问:
Using get() and set() in Java
I have seen several get() and set() methods used for private fields. And I also understand why its being used.

But what I dont understand is that, I have my Student class with private fields in them. So why is it when I remove the get() and set(), it still works (for example, method to print).

Or is it still working because its in the same file class? but say if I try calling the private field without defining the get() and set() method from an external class. It wont work?

This is my code with the get() and set()

```<code>public class Student {
    private String name;
    private String address;
    private String degreeName;
    private String department;
    private String yearCommence;
    private long studentID;
    private static int nextID = 901000 ;

    public String getName() {
        return name;
    }
    public String getAddress() {
        return address;
    }
    public String getDegreeName() {
        return degreeName;
    }
    public String getDepartment() {
        return department;
    }
    public String getYearCommence() {
        return yearCommence;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAddress(String address) {
        this.name = address;
    }
    public void setDegreeName(String degreeName) {
        this.degreeName = degreeName;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
    public void setYearCommence(String yearCommence) {
        this.department = yearCommence;
    }

    public Student(String name, String address, String degreeName, String department, String yearCommence, long StudentID) {
        this.name = name;
        this.address = address;
        this.degreeName = degreeName;
        this.department = department;
        this.yearCommence = yearCommence;
        this.studentID = nextID++;
    }

    public Student(String name, String address, String degreeName, String department, long studentID) {
        this(name, address, degreeName, department, null, studentID);
    }
    public Student(String name, String address, String degreeName, long studentID) {
        this(name, address, degreeName, null, null, studentID);
    }
    public Student(String name, String address, long studentID) {
        this(name, address, null, null, null, studentID);
    }
    public Student(String name, long studentID) {
        this(name, null, null, null, null, studentID);
    }
    public Student(long studentID) {
        this(null, null, null, null, null, studentID);
    }

    @Override
    public String toString() {
        return "StudentInfo {" + "name=" + name + ", address=" + address + ", degreeName=" + degreeName + ", department=" + department + ", commence = " + yearCommence +", "+ " "+ "studentID = " + studentID+ "}";
    }

    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<>();

        Student student1 = new Student("Yusuf", "jl.ANU", "IT", "CECS", null, Student.nextID);
        students.add(student1);
        System.out.println(student1);

        Student student2 = new Student("Ning", "jl.Cikini","IT", null, null, Student.nextID);
        students.add(student2);
        System.out.println(student2);

        Student student3 = new Student("Boris", "jl.Babi", Student.nextID);
        students.add(student3);
        System.out.println(student3);

        Student student4 = new Student(null, null, null, null, null, Student.nextID);
        students.add(student4);
        System.out.println(student4);
    }
}
</code>```

答: All of your functions are in the class that owns the private attributes and can therefore access all of them without needing a getter function. It should also be noted that because the main function is static it can only access other static members.

Title: Using get() and set() in Java

Body:
I have seen several get() and set() methods used for private fields. And I also understand why its being used.

But what I dont understand is that, I have my Student class with private fields in them. So why is it when I remove the get() and set(), it still works (for example, method to print).

Or is it still working because its in the same file class? but say if I try calling the private field without defining the get() and set() method from an external class. It wont work?

This is my code with the get() and set()

public class Student {
    private String name;
    private String address;
    private String degreeName;
    private String department;
    private String yearCommence;
    private long studentID;
    private static int nextID = 901000 ;

    public String getName() {
        return name;
    }
    public String getAddress() {
        return address;
    }
    public String getDegreeName() {
        return degreeName;
    }
    public String getDepartment() {
        return department;
    }
    public String getYearCommence() {
        return yearCommence;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAddress(String address) {
        this.name = address;
    }
    public void setDegreeName(String degreeName) {
        this.degreeName = degreeName;
    }
    public void setDepartment(String department) {
        this.department = department;
    }
    public void setYearCommence(String yearCommence) {
        this.department = yearCommence;
    }

    public Student(String name, String address, String degreeName, String department, String yearCommence, long StudentID) {
        this.name = name;
        this.address = address;
        this.degreeName = degreeName;
        this.department = department;
        this.yearCommence = yearCommence;
        this.studentID = nextID++;
    }

    public Student(String name, String address, String degreeName, String department, long studentID) {
        this(name, address, degreeName, department, null, studentID);
    }
    public Student(String name, String address, String degreeName, long studentID) {
        this(name, address, degreeName, null, null, studentID);
    }
    public Student(String name, String address, long studentID) {
        this(name, address, null, null, null, studentID);
    }
    public Student(String name, long studentID) {
        this(name, null, null, null, null, studentID);
    }
    public Student(long studentID) {
        this(null, null, null, null, null, studentID);
    }

    @Override
    public String toString() {
        return "StudentInfo {" + "name=" + name + ", address=" + address + ", degreeName=" + degreeName + ", department=" + department + ", commence = " + yearCommence +", "+ " "+ "studentID = " + studentID+ "}";
    }

    public static void main(String[] args) {
        ArrayList<Student> students = new ArrayList<>();

        Student student1 = new Student("Yusuf", "jl.ANU", "IT", "CECS", null, Student.nextID);
        students.add(student1);
        System.out.println(student1);

        Student student2 = new Student("Ning", "jl.Cikini","IT", null, null, Student.nextID);
        students.add(student2);
        System.out.println(student2);

        Student student3 = new Student("Boris", "jl.Babi", Student.nextID);
        students.add(student3);
        System.out.println(student3);

        Student student4 = new Student(null, null, null, null, null, Student.nextID);
        students.add(student4);
        System.out.println(student4);
    }
}


来源: stackexchange

问:
Go GOTRACEBACK=crash with no core file
go version go1.8.3 darwin/amd64

```<code>ulimit -c unlimited
env GOTRACEBACK=crash ./testgotraceback.go
ls -al
no core file generated.
</code>```

testgotraceback.go source file

```<code>package main

import (
    "fmt"
    "time"
)

func saferoutine(c chan bool) {
    for i := 0; i < 10; i++ {
        fmt.Println("Count:", i)
        time.Sleep(1 * time.Second)
    }
    c <- true
}
func panicgoroutine(c chan bool) {
    time.Sleep(5 * time.Second)
    panic("Panic, omg ...")
    c <- true
}
func main() {
    c := make(chan bool, 2)
    go saferoutine(c)
    go panicgoroutine(c)
    for i := 0; i < 2; i++ {
        <-c
    }
}
</code>```

I want to use core file to trace some error.But use the GOTRACEBACK=crash command,I find no core file.use golang1.7 as well.
so ,what's the problem?thanks for help.

答:
If you are expecting a core dump file to be created in the directory where you program is being run, you not only need to use ulimit and set GOTRACEBACK but also change settings on your operating system to save core file in the current directory.

Assuming you are using Linux, this is distribution-specific. You need to find relevant sysfs entry and save core value to it. For example, a core pattern sysfs entry on Fedora is /proc/sys/kernel/core_pattern and to setup you OS to save core files in the current directory, you would need to execute:

```<code>echo core > /proc/sys/kernel/core_pattern
</code>```

ContentLicense: CC BY-SA 3.0

Title: Go GOTRACEBACK=crash with no core file

Body:
go version go1.8.3 darwin/amd64

ulimit -c unlimited
env GOTRACEBACK=crash ./testgotraceback.go
ls -al
no core file generated.

testgotraceback.go source file

package main

import (
    "fmt"
    "time"
)

func saferoutine(c chan bool) {
    for i := 0; i < 10; i++ {
        fmt.Println("Count:", i)
        time.Sleep(1 * time.Second)
    }
    c <- true
}
func panicgoroutine(c chan bool) {
    time.Sleep(5 * time.Second)
    panic("Panic, omg ...")
    c <- true
}
func main() {
    c := make(chan bool, 2)
    go saferoutine(c)
    go panicgoroutine(c)
    for i := 0; i < 2; i++ {
        <-c
    }
}

I want to use core file to trace some error.But use the GOTRACEBACK=crash command,I find no core file.use golang1.7 as well.
so ,what's the problem?thanks for help.

Body:
If you are expecting a core dump file to be created in the directory where you program is being run, you not only need to use ulimit and set GOTRACEBACK but also change settings on your operating system to save core file in the current directory.

Assuming you are using Linux, this is distribution-specific. You need to find relevant sysfs entry and save core value to it. For example, a core pattern sysfs entry on Fedora is /proc/sys/kernel/core_pattern and to setup you OS to save core files in the current directory, you would need to execute:

echo core > /proc/sys/kernel/core_pattern


问:
Font Rendering between Mozilla and webkit
I'm not sure if this has anything to do with the recent Safari update, but I'm beginning to notice this a lot. There is a drastic difference in the way each browser is rendering fonts.

for instance, I took screenshots of what I am seeing here on stackoverflow...
http://twitpic.com/q43eh

I have verified that this is a trend via my co-workers machines.

has anyone noticed this or have any thoughts on non-hack solutions?

答: I first noticed this in OSX in October 2010. It is especially noticeable with Helvetica Neue. I suspect that an OSX update broke font anti-aliasing in font sizes above 12 pixels. I've posted an Apple Support message here. </p>

ContentLicense: CC BY-SA 2.5


问:
SQL Server query help... super slow query
My query is taking too long to execute, do anyone know how to optimize the query below? P.S. The 'temp_db' has 1'024'912'779 rows.

Here is the query:

```<code>SELECT
    CASE
       WHEN user_agent LIKE '%Mobile%'
          THEN 'Mobile'
          ELSE 'Desktop'
    END AS DEVICE,
    CAST(DATEADD(hour, +8, timestamp_gmt) AS Date) AS HKDate,
    DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)) AS HKHour,
    pixel_name AS Pixel,
    COUNT(id) AS Fires,
    COUNT(DISTINCT id) AS Uu
FROM
    temp_db
WHERE
    CONVERT(date, timestamp_gmt) BETWEEN DATEADD(day, -3, GETDATE())
                                     AND CONVERT(date, GETDATE())
    AND advertiser_name LIKE '%TimCompany%'
GROUP BY
    CASE
       WHEN user_agent LIKE '%Mobile%'
          THEN 'Mobile'
          ELSE 'Desktop'
    END,
    CAST(DATEADD(hour, +8, timestamp_gmt) AS Date),
    DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)),
    pixel_name;
</code>```

答:
The date in where clause is not sargable. try below:</p>

```<code>SELECT
    CASE
       WHEN user_agent LIKE '%Mobile%'
          THEN 'Mobile'
          ELSE 'Desktop'
    END AS DEVICE,
    CAST(DATEADD(hour, +8, timestamp_gmt) AS Date) AS HKDate,
    DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)) AS HKHour,
    pixel_name AS Pixel,
    COUNT(id) AS Fires,
    COUNT(DISTINCT id) AS Uu
FROM
    temp_db
WHERE
    timestamp_gmt >= convert(date, DATEADD(day, -3, GETDATE()))
                 and timestamp_gmt < convert(date, DATEADD(day, 1, GETDATE()) )
    AND advertiser_name LIKE '%TimCompany%'
GROUP BY
    CASE
       WHEN user_agent LIKE '%Mobile%'
          THEN 'Mobile'
          ELSE 'Desktop'
    END,
    CAST(DATEADD(hour, +8, timestamp_gmt) AS Date),
    DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)),
    pixel_name;
</code>```

Body:
My query is taking too long to execute, do anyone know how to optimize the query below? P.S. The 'temp_db' has 1'024'912'779 rows.

Here is the query:

SELECT
    CASE
       WHEN user_agent LIKE '%Mobile%'
          THEN 'Mobile'
          ELSE 'Desktop'
    END AS DEVICE,
    CAST(DATEADD(hour, +8, timestamp_gmt) AS Date) AS HKDate,
    DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)) AS HKHour,
    pixel_name AS Pixel,
    COUNT(id) AS Fires,
    COUNT(DISTINCT id) AS Uu
FROM
    temp_db
WHERE
    CONVERT(date, timestamp_gmt) BETWEEN DATEADD(day, -3, GETDATE())
                                     AND CONVERT(date, GETDATE())
    AND advertiser_name LIKE '%TimCompany%'
GROUP BY
    CASE
       WHEN user_agent LIKE '%Mobile%'
          THEN 'Mobile'
          ELSE 'Desktop'
    END,
    CAST(DATEADD(hour, +8, timestamp_gmt) AS Date),
    DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)),
    pixel_name;

Body:
The date in where clause is not sargable. try below:

SELECT
    CASE
       WHEN user_agent LIKE '%Mobile%'
          THEN 'Mobile'
          ELSE 'Desktop'
    END AS DEVICE,
    CAST(DATEADD(hour, +8, timestamp_gmt) AS Date) AS HKDate,
    DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)) AS HKHour,
    pixel_name AS Pixel,
    COUNT(id) AS Fires,
    COUNT(DISTINCT id) AS Uu
FROM
    temp_db
WHERE
    timestamp_gmt >= convert(date, DATEADD(day, -3, GETDATE()))
                 and timestamp_gmt < convert(date, DATEADD(day, 1, GETDATE()) )
    AND advertiser_name LIKE '%TimCompany%'
GROUP BY
    CASE
       WHEN user_agent LIKE '%Mobile%'
          THEN 'Mobile'
          ELSE 'Desktop'
    END,
    CAST(DATEADD(hour, +8, timestamp_gmt) AS Date),
    DATEPART(Hour, DATEADD(hour, +8, timestamp_gmt)),
    pixel_name;


答: Private attributes are, by definition, only accessible by the same class. This means that methods in the class itself can access the private attributes. Methods in any other classes won't be able to access such private attributes and thus would need get/set methods. </p>

Title: Using get() and set() in Java


答: There can be private fields in an class which have no get or set method. Your are able to use your class, but can't set or get the values of this fields from outside this class. If you have a constructer which have these private fields as parameters, these fields will be set on initialization, but can't be change afterwards on that instance. </p>

Title: Using get() and set() in Java


问:
Jboss 7 AS - combine standalone.xml loggin configuration and per deployment logging configuration
i am using JBoss 7 AS,i have few ear deployed in this JBoss.
standalone.xml has configured with following logging configuration

```<code><subsystem xmlns="urn:jboss:domain:logging:3.0">
.
.
.
.
            <console-handler name="CONSOLE">
                <level name="INFO"/>
                <formatter>
                    <pattern-formatter pattern="%K{level}%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
                </formatter>
            </console-handler>
.
.
.
.
            <size-rotating-file-handler autoflush="true" name="MAINLOGFILE">
                <formatter>
                    <pattern-formatter pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
                </formatter>
                <file path="mainlog.log" relative-to="jboss.server.log.dir"/>
                <append value="true"/>
                <rotate-size value="1m"/>
                <max-backup-index value="1000"/>
            </size-rotating-file-handler>
</code>```

Then i tried to add a logging.properties file into one ear META-INF,it woks as expected.
again i wanted to refer a handler (MAINLOGFILE defined in the stanalone.xml) from that logging.properties file (which i have placed in to META-INF of one of ear ).
this is the logging.properties looks like:

```<code>loggers=my.testpackage

logger.my.testpackage.level=INFO
logger.my.testpackage.handlers=EXTFILE,MAINLOGFILE
logger.my.testpackage.useParentHandlers=true

    handler.EXTFILE=org.jboss.logmanager.handlers.PeriodicRotatingFileHandler
    handler.EXTFILE.level=ALL
    handler.EXTFILE.formatter=PATTERN
    handler.EXTFILE.properties=autoFlush,append,fileName,suffix
    handler.EXTFILE.constructorProperties=fileName,append
    handler.EXTFILE.autoFlush=true
    handler.EXTFILE.append=true
    handler.EXTFILE.fileName=${jboss.server.log.dir}/mytest.log
    handler.EXTFILE.suffix=.yyyy-MM-dd

    formatter.COLOR-PATTERN=org.jboss.logmanager.formatters.PatternFormatter
    formatter.COLOR-PATTERN.properties=pattern
    formatter.COLOR-PATTERN.pattern=%K{level}%d{HH\:mm\:ss,SSS} %-5p [%c] (%t) %s%E%n

    formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter
    formatter.PATTERN.properties=pattern
    formatter.PATTERN.pattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS} %-5p [%c] (%t) %s%E%n
</code>```

But the entries log into the EXTFILE are not logged into the MAINLOGFILE.
My expectation is that each and every entry which is logged into EXTFILE should be visible in the MAINLOGFILE as well

Please help me o find out a way to refer a log handler defined in the standalone.xml from per deployment loggign.properties file.

Thank you.

答:
Do you really need the logging config in your app? You can easily define the logger handlers in jboss logging subsystem that target specific packages or even classes in the apps the are deployed:  </p>

```<code><!-- all classes in `my.testpackage` package should only print INFO and up into mainlog.-->
<logger category="my.testpackage" use-parent-handlers="true">
   <level name="INFO"/>
   <handlers>
      <handler name="MAINLOGFILE"/>
   </handlers>
</logger>
 <!-- This class should print DEBUG and up into mainlog.-->
<logger category="my.testpackage.SuperImportantClass" use-parent-handlers="true">
   <level name="DEBUG"/>
   <handlers>
      <handler name="MAINLOGFILE"/>
   </handlers>
</logger>
</code>```

<p>Advantages: you can easily add this configuration via cli or web admin interface of JBoss and as a great bonus, you can change it at runtime without having to restart the server or your webapp. If you want, you can then make the configuration part of your distribution process e.g. create your own docker image with jboss, with your app deployment and your cli/config. </p>

Body:
i am using JBoss 7 AS,i have few ear deployed in this JBoss.
standalone.xml has configured with following logging configuration

<subsystem xmlns="urn:jboss:domain:logging:3.0">
.
.
.
.
            <console-handler name="CONSOLE">
                <level name="INFO"/>
                <formatter>
                    <pattern-formatter pattern="%K{level}%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
                </formatter>
            </console-handler>
.
.
.
.
            <size-rotating-file-handler autoflush="true" name="MAINLOGFILE">
                <formatter>
                    <pattern-formatter pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5p [%c] (%t) %s%E%n"/>
                </formatter>
                <file path="mainlog.log" relative-to="jboss.server.log.dir"/>
                <append value="true"/>
                <rotate-size value="1m"/>
                <max-backup-index value="1000"/>
            </size-rotating-file-handler>

Then i tried to add a logging.properties file into one ear META-INF,it woks as expected.
again i wanted to refer a handler (MAINLOGFILE defined in the stanalone.xml) from that logging.properties file (which i have placed in to META-INF of one of ear ).
this is the logging.properties looks like:

loggers=my.testpackage

logger.my.testpackage.level=INFO
logger.my.testpackage.handlers=EXTFILE,MAINLOGFILE
logger.my.testpackage.useParentHandlers=true

    handler.EXTFILE=org.jboss.logmanager.handlers.PeriodicRotatingFileHandler
    handler.EXTFILE.level=ALL
    handler.EXTFILE.formatter=PATTERN
    handler.EXTFILE.properties=autoFlush,append,fileName,suffix
    handler.EXTFILE.constructorProperties=fileName,append
    handler.EXTFILE.autoFlush=true
    handler.EXTFILE.append=true
    handler.EXTFILE.fileName=${jboss.server.log.dir}/mytest.log
    handler.EXTFILE.suffix=.yyyy-MM-dd

    formatter.COLOR-PATTERN=org.jboss.logmanager.formatters.PatternFormatter
    formatter.COLOR-PATTERN.properties=pattern
    formatter.COLOR-PATTERN.pattern=%K{level}%d{HH\:mm\:ss,SSS} %-5p [%c] (%t) %s%E%n

    formatter.PATTERN=org.jboss.logmanager.formatters.PatternFormatter
    formatter.PATTERN.properties=pattern
    formatter.PATTERN.pattern=%d{yyyy-MM-dd HH\:mm\:ss,SSS} %-5p [%c] (%t) %s%E%n

But the entries log into the EXTFILE are not logged into the MAINLOGFILE.
My expectation is that each and every entry which is logged into EXTFILE should be visible in the MAINLOGFILE as well

Please help me o find out a way to refer a log handler defined in the standalone.xml from per deployment loggign.properties file.

Thank you.

Body:
Do you really need the logging config in your app? You can easily define the logger handlers in jboss logging subsystem that target specific packages or even classes in the apps the are deployed:

<!-- all classes in `my.testpackage` package should only print INFO and up into mainlog.-->
<logger category="my.testpackage" use-parent-handlers="true">
   <level name="INFO"/>
   <handlers>
      <handler name="MAINLOGFILE"/>
   </handlers>
</logger>
 <!-- This class should print DEBUG and up into mainlog.-->
<logger category="my.testpackage.SuperImportantClass" use-parent-handlers="true">
   <level name="DEBUG"/>
   <handlers>
      <handler name="MAINLOGFILE"/>
   </handlers>
</logger>

Advantages: you can easily add this configuration via cli or web admin interface of JBoss and as a great bonus, you can change it at runtime without having to restart the server or your webapp. If you want, you can then make the configuration part of your distribution process e.g. create your own docker image with jboss, with your app deployment and your cli/config.


问:
Getting descriptive login error messages in iOS app using AWS Cognito
I am developing an iOS app in Swift using AWS Cognito to handle user login and registration. I've found that when users do something that Cognito doesn't allow (entering the wrong username/password on login, trying to create a password that doesn't match the requirements, etc.) the app will display error messages such asThe operation couldn't be completed. (Com.amazonaws.AWSCognitoIdentityProviderErrorDomain error 0.). I've noticed that different actions can result in different error codes, but I'd like to make the error messages more descriptive so that my users will actually know what they did wrong.

Currently, I get the error message by checking if task.error != nil for the login/registration/etc. task, and if this check return true, I get the string task.error!.localizedDescription for the error message. I realize I could grab the error code from this string by getting the substring corresponding to the 1 digit code, but this seems like a really terrible long-term solution. At the very least, I would like to get the error code as an integer, or preferably get a description of the error that will make sense to the average user. Is there some way to do this?

答:
Try using the AWSCognitoIdentityProviderErrorType Enum (see AWSCognitoIdentityProviderModel.h).
Its rawValues represent the ErrorCodes in the NSErrors with the AWSCognitoIdentityProviderErrorDomain.


问:
JSON Parsing using Swift 3
I am calling a soap service in my application. I am getting this response in JSON from server

```<code>{
  "CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "IsCorporate":false,
  "ID":48,
  "Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "GroupID":null,
  "GroupName":null,
  "CustomerID":48
}
</code>```

I have tried what online tutorial suggests but I am not able to parse data. It gives me error that "Invalid value around character 0." My Code is this

```<code> let is_URL: String = "http://labs2.unitedtracker.com/WTService.asmx?op=GetTerminalNumber"

    let lobj_Request = NSMutableURLRequest(url: NSURL(string: is_URL)! as URL)
    let session = URLSession.shared

    lobj_Request.httpMethod = "POST"
    lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
    lobj_Request.addValue("labs2.unitedtracker.com", forHTTPHeaderField: "Host")
    lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
    lobj_Request.addValue(String(is_SoapMessage.characters.count), forHTTPHeaderField: "Content-Length")
    lobj_Request.addValue("http://tempuri.org/GetTerminalNumber", forHTTPHeaderField: "SOAPAction")

    let task = session.dataTask(with: lobj_Request as URLRequest, completionHandler: {data, response, error -> Void in

        do {
            if let data = data,
                let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                let customerID = json["CustomerID"] as? [[String: Any]] {
                print(customerID)
            }
        } catch {
            print("Error deserializing JSON: \(error)")
        }

        if error != nil
        {
            print("Error: " + String(describing: error))
        }
    })
    task.resume()
</code>```

Can anyone suggest me what is wrong i m doing. And how should be such JSON response from Soap Service should be parsed.

Here is complete response from my Server.

```<code><?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetAuthenticateUserResponse xmlns="http://tempuri.org/"><GetAuthenticateUserResult>[{"CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ","IsCorporate":false,"ID":48,"Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ","GroupID":null,"GroupName":null,"CustomerID":48}]</GetAuthenticateUserResult></GetAuthenticateUserResponse></soap:Body></soap:Envelope>
</code>```

答:
Your code:

```<code>let customerID = json["CustomerID"] as? [[String: Any]] {
    print(customerID)
}
</code>```

treats the customerID as dictionary instead of string.

It should be:

```<code>let customerID = json["CustomerID"] as? String {
    print(customerID)
}
</code>```

You should use another way of network request and JSON parser, like Alamofire and AlamofireObjectMapper.

Title: JSON Parsing using Swift 3

Body:
I am calling a soap service in my application. I am getting this response in JSON from server

{
  "CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "IsCorporate":false,
  "ID":48,
  "Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ",
  "GroupID":null,
  "GroupName":null,
  "CustomerID":48
}

I have tried what online tutorial suggests but I am not able to parse data. It gives me error that "Invalid value around character 0." My Code is this

 let is_URL: String = "http://labs2.unitedtracker.com/WTService.asmx?op=GetTerminalNumber"

    let lobj_Request = NSMutableURLRequest(url: NSURL(string: is_URL)! as URL)
    let session = URLSession.shared

    lobj_Request.httpMethod = "POST"
    lobj_Request.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
    lobj_Request.addValue("labs2.unitedtracker.com", forHTTPHeaderField: "Host")
    lobj_Request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
    lobj_Request.addValue(String(is_SoapMessage.characters.count), forHTTPHeaderField: "Content-Length")
    lobj_Request.addValue("http://tempuri.org/GetTerminalNumber", forHTTPHeaderField: "SOAPAction")

    let task = session.dataTask(with: lobj_Request as URLRequest, completionHandler: {data, response, error -> Void in

        do {
            if let data = data,
                let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                let customerID = json["CustomerID"] as? [[String: Any]] {
                print(customerID)
            }
        } catch {
            print("Error deserializing JSON: \(error)")
        }

        if error != nil
        {
            print("Error: " + String(describing: error))
        }
    })
    task.resume()

Can anyone suggest me what is wrong i m doing. And how should be such JSON response from Soap Service should be parsed.

Here is complete response from my Server.

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><GetAuthenticateUserResponse xmlns="http://tempuri.org/"><GetAuthenticateUserResult>[{"CustomerName":"Muneer Ahmad/ Ejaz Ahmad (User)  ","IsCorporate":false,"ID":48,"Name":"Muneer Ahmad/ Ejaz Ahmad (User)  ","GroupID":null,"GroupName":null,"CustomerID":48}]</GetAuthenticateUserResult></GetAuthenticateUserResponse></soap:Body></soap:Envelope>

Body:
Your code:

let customerID = json["CustomerID"] as? [[String: Any]] {
    print(customerID)
}

treats the customerID as dictionary instead of string.

It should be:

let customerID = json["CustomerID"] as? String {
    print(customerID)
}

You should use another way of network request and JSON parser, like Alamofire and AlamofireObjectMapper.


问:
jquery - get elements by tag within a specific div?
I'm trying to get all input elements within a certain div, but it seems to return all inputs on any given page... is there a way to do this?</p>

```<code>if($('#umi-form')) {
          var inputs = document.getElementsByTagName('input');
}
</code>```

答:
It can be done like this:</p>

```<code>var $inputs = $('#umi-form input');
</code>```

Body:
I'm trying to get all input elements within a certain div, but it seems to return all inputs on any given page... is there a way to do this?

if($('#umi-form')) {
          var inputs = document.getElementsByTagName('input');
}

Body:
It can be done like this:

var $inputs = $('#umi-form input');


问:
How To add Gmail Account Credentials in Static way to Access that account in Android App
I am doing an android app which uses only my Google account. I want to integrate my Gmail Account in my Android app. So each user who uses my app can use my Google account only .  I want to set my Google account in static without using AccountManager Obj to display all email in their Mobiles.

Please Help me.

答:
You can't do this. Gmail account cannot be bind to multiple device (there is a limit ... i don't know exactly but i know it)
Google keep rights to disable those account, check in google account android policy. </p>

<p>You got to let people use their own google play account. </p>

Body:
You can't do this. Gmail account cannot be bind to multiple device (there is a limit ... i don't know exactly but i know it)
Google keep rights to disable those account, check in google account android policy.

You got to let people use their own google play account.


答:
Too many is the correct answer. However, if you want to use them try this trick:

```<code>Set myRange2 = Range("C6:C9,E7:E9,G7:G9,J6:J9,L7:L9,N7:N9,Q6:Q9,S7:S9,U7:U9,X6:X9,Z7:Z9,AB7:AB9")
Set myRange2 = Union(myRange2,range("C12:C15,E13:E15,G13:G15,J12:J15,L13:L15,N13:N15,Q12:Q15,S13:S15,U13:U15,X12:X15,Z13:Z15,AB13:AB15,C18:C21,E19:E21,G19:G21,J18:J21,L19:L21,N19:N21,Q18:Q21,S19:S21,U19:U21,X18:X21,Z19:Z21,AB19:AB21"))
</code>```

You can have up to 30 arguments in a Union:

https://msdn.microsoft.com/en-us/library/office/ff834621.aspx

But if you increment like in the code above, you can go like this forever.

Title: excel vba error 1004 Range

Body:
So i've got 2 Range() items:

Set myRange1 = Range("E2:E8,D9:D12,F9:F12,J2:J8,I9:I12,K9:K12,O2:O8,N9:N12,P9:P12,E14:E20,D21:D24,F21:F24,J14:J20,I21:I24,K21:K24,O14:O20,N21:N24,P21:P24,E26:E32,D33:D36,F33:F36,J26:J32,I33:I36,K33:K36,O26:O32,N33:N36,P33:P36")
Set myRange2 = Range("C6:C9,E7:E9,G7:G9,J6:J9,L7:L9,N7:N9,Q6:Q9,S7:S9,U7:U9,X6:X9,Z7:Z9,AB7:AB9,C12:C15,E13:E15,G13:G15,J12:J15,L13:L15,N13:N15,Q12:Q15,S13:S15,U13:U15,X12:X15,Z13:Z15,AB13:AB15,C18:C21,E19:E21,G19:G21,J18:J21,L19:L21,N19:N21,Q18:Q21,S19:S21,U19:U21,X18:X21,Z19:Z21,AB19:AB21")

myRange1 is fine, myRange2 throws Run-time Error 1004 Method 'Range' of Object '_Global' Failed.

Does anyone know why? Is there too many ranges in a range? In my opinion they're both pretty long.

Body:
Too many is the correct answer. However, if you want to use them try this trick:

Set myRange2 = Range("C6:C9,E7:E9,G7:G9,J6:J9,L7:L9,N7:N9,Q6:Q9,S7:S9,U7:U9,X6:X9,Z7:Z9,AB7:AB9")
Set myRange2 = Union(myRange2,range("C12:C15,E13:E15,G13:G15,J12:J15,L13:L15,N13:N15,Q12:Q15,S13:S15,U13:U15,X12:X15,Z13:Z15,AB13:AB15,C18:C21,E19:E21,G19:G21,J18:J21,L19:L21,N19:N21,Q18:Q21,S19:S21,U19:U21,X18:X21,Z19:Z21,AB19:AB21"))

You can have up to 30 arguments in a Union:

https://msdn.microsoft.com/en-us/library/office/ff834621.aspx

But if you increment like in the code above, you can go like this forever.


问:
how to add a circle at the top middle of tab in html?
I am design a circle at the top middle of my tab but my tab will automatic increase based on the content i am using md-tab for creating the tab

I have created a circle  with css

```<code>.bubble_circle {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        font-size: 20px;
        line-height: 15px;
    }
</code>```

Please help me out from this problem .past one day i am trying to set the circle in the top middle of the tab but i am enable to do this .

答:
You can also solve this very easy with flexbox. Use display: flex; on the tab and justify-content: center; to center your child bubble on the top of the tab. No positions etc. needed.

.tab {
  width: 100%;
  height: 50px;
  background: grey;
  display: flex;
  flex-direction: column;
}

.centered {
  display: flex;
  justify-content: center;
}

.bubble_circle {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  font-size: 20px;
  line-height: 15px;
  background-color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="tab">
  <div class="centered">
      <div class="bubble_circle"></div>
  </div>
  <div class="centered ">
      <p>Tab</p>
  </div>
</div></code>```

Body:
I am design a circle at the top middle of my tab but my tab will automatic increase based on the content i am using md-tab for creating the tab

I have created a circle  with css

.bubble_circle {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        font-size: 20px;
        line-height: 15px;
    }

Please help me out from this problem .past one day i am trying to set the circle in the top middle of the tab but i am enable to do this .

Body:
You can also solve this very easy with flexbox. Use display: flex; on the tab and justify-content: center; to center your child bubble on the top of the tab. No positions etc. needed.

.tab {
  width: 100%;
  height: 50px;
  background: grey;
  display: flex;
  flex-direction: column;
}

.centered {
  display: flex;
  justify-content: center;
}

.bubble_circle {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  font-size: 20px;
  line-height: 15px;
  background-color: white;
}

<div class="tab">
  <div class="centered">
      <div class="bubble_circle"></div>
  </div>
  <div class="centered ">
      <p>Tab</p>
  </div>
</div>


问:
javascript object error
This is my situation:

```<code>

var r = {"id":"test","files":[],"code":""};

var Page = Class.create({

 initialize: function(json) {
  this.id = json.id;
  this.json = json;

 },
        start: function() {
  this.json.files.each(function(x) {
   var cssResource = this.pageResource(x, 'css');
   this.attachCssResource(cssResource);

  }.bind(this));
        },

//etc....

});

var P = new Page(r);
P.start();

</code>```

Hi have this.json.files.each is not a function.. why?

I use prototype 1.7 library.

if i use this

```<code>
var P = new Page({"id":"test","files":[],"code":""});
</code>```

i have NO error??....

答:
If you are targeting only ECMAScript 5 platforms you will want to use Array.forEach.

15.4.4.18 Array.prototype.forEach ( callbackfn [ , thisArg ] )

callbackfn should be a function that accepts three arguments. forEach calls callbackfn once for each element present in the array, in ascending order. callbackfn is called only for elements of the array which actually exist; it is not called for missing elements of the array.

If a thisArg parameter is provided, it will be used as the this value for each invocation of callbackfn. If it is not provided, undefined is used instead.

callbackfn is called with three arguments: the value of the element, the index of the element, and the object being traversed.

forEach does not directly mutate the object on which it is called but the object may be mutated by the calls to callbackfn.

The range of elements processed by forEach is set before the first call to callbackfn. Elements which are appended to the array after the call to forEach begins will not be visited by callbackfn. If existing elements of the array are changed, their value as passed to callback will be the value at the time forEach visits them; elements that are deleted after the call to forEach begins and before being visited are not visited.

Title: javascript object error

Body:
This is my situation:

var r = {"id":"test","files":[],"code":""};

var Page = Class.create({

 initialize: function(json) {
  this.id = json.id;
  this.json = json;

 },
        start: function() {
  this.json.files.each(function(x) {
   var cssResource = this.pageResource(x, 'css');
   this.attachCssResource(cssResource);

  }.bind(this));
        },

//etc....

});

var P = new Page(r);
P.start();

Hi have this.json.files.each is not a function.. why?

I use prototype 1.7 library.

if i use this

var P = new Page({"id":"test","files":[],"code":""});

i have NO error??....


问:
Get Bitmap image details (such as width and height)
How to get the image detail (name, width, height, size, etc) which is selected in image view

I Generate ImageViewXML

```<code><ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent"/>
</code>```

and get a function to put selected image from folder to that ImageView

```<code>Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

            //Log.d(TAG, String.valueOf(bitmap));

            ImageView imageView = (ImageView) findViewById(R.id.imageView);
            imageView.setImageBitmap(bitmap);

        } catch (IOException e) {
            e.printStackTrace();
        }
</code>```

Its all working correctly without bug, when i want to get the image detail, such as name by using String.valueOf(bitmap) but it return with : android.graphics.Bitmap@5280fcb4

How to get that image detail ?

答:
```<code>String path = (String) imageView .getTag();
</code>```

<p>you can get the path of the image by this getTag() from that should get the name of image </p>

Body:
How to get the image detail (name, width, height, size, etc) which is selected in image view

I Generate ImageViewXML

<ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="match_parent"/>

and get a function to put selected image from folder to that ImageView

Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

            //Log.d(TAG, String.valueOf(bitmap));

            ImageView imageView = (ImageView) findViewById(R.id.imageView);
            imageView.setImageBitmap(bitmap);

        } catch (IOException e) {
            e.printStackTrace();
        }

Its all working correctly without bug, when i want to get the image detail, such as name by using String.valueOf(bitmap) but it return with : android.graphics.Bitmap@5280fcb4

How to get that image detail ?

Body:
String path = (String) imageView .getTag();

you can get the path of the image by this getTag() from that should get the name of image


问:
MySql SELECT index benefits
Are there significant benefits between the two SQL select ?

```<code>SELECT * FROM table USE INDEX (cod_clie) WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1;

SELECT * FROM table WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1;
</code>```

cod_clie is an INDEX field, of course!

答:
By default query analyzer find best index to improve query performance. But due to many manual indexing or heavily modified tables (INSERT or DELETE for example), over time the key distributions (Cardinality) diverge from the true state.

If an Optimizer that picks the wrong plan can cause severe performance issues. This means that your server can hit a performance problem at the most unexpected time.

Lucky for us, we can force the Optimizer to pick a particular plan (index) with the 'USE INDEX' hint.

Title: MySql SELECT index benefits

Body:
Are there significant benefits between the two SQL select ?

SELECT * FROM table USE INDEX (cod_clie) WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1;

SELECT * FROM table WHERE cod_clie = "example" AND pwd_clie = "example" LIMIT 1;

cod_clie is an INDEX field, of course!


问:
sql position of subquery's name
I don't know where is the right position of subquery

my query is

```<code>SELECT *
FROM (
            SELECT *
            FROM ESMBLNK
            UNION ALL
            SELECT *
            FROM ESMVDGL
            WHERE condition1
              AND condition2
        )
</code>```

I have to put the name of subquery but don't know how to insert it

答:
As Jarlh said, the name must go after the end of the FROM ( ), for example, I call the subquery A. By the way, your WHERE clause will only affect ESMVDGL.</p>

```<code>SELECT *
FROM (
        SELECT *
        FROM ESMBLNK
        UNION ALL
        SELECT *
        FROM ESMVDGL
        WHERE condition1
          AND condition2
    ) A
</code>```

Title: sql position of subquery's name

Body:
I don't know where is the right position of subquery

my query is

SELECT *
FROM (
            SELECT *
            FROM ESMBLNK
            UNION ALL
            SELECT *
            FROM ESMVDGL
            WHERE condition1
              AND condition2
        )

I have to put the name of subquery but don't know how to insert it

Body:
As Jarlh said, the name must go after the end of the FROM ( ), for example, I call the subquery A. By the way, your WHERE clause will only affect ESMVDGL.

SELECT *
FROM (
        SELECT *
        FROM ESMBLNK
        UNION ALL
        SELECT *
        FROM ESMVDGL
        WHERE condition1
          AND condition2
    ) A


问:
override delete_selected to check for records that exist in other tables in django 1.10
I am using the default admin dashboard of django. Basically, i want to override the delete_selected method on a model by model basis so I can check for records before allowing the deletion to take place.

My models.py is:

```<code>class Kind(models.Model):

    name = models.CharField(max_length=50, unique=True)
    addedby = models.ForeignKey(User,related_name='admin_kind')
    createdon = models.DateTimeField(auto_now_add=True)
    updatedon = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name',)

class Item(models.Model):

    name = models.CharField(max_length=50)
    kind = models.ForeignKey(Kind,related_name="item_kind")
    createdon = models.DateTimeField(auto_now_add=True)
    updatedon = models.DateTimeField(auto_now=True)

    def __str__(self):
        return ' , '.join([self.kind.name, self.name])

    class Meta:
        ordering = ('kind', 'name',)
        unique_together = (('name','kind'))
</code>```

Now what I want is before a kind could be deleted, I want to check if there is a related record in items. If there is, do not delete it.

But i am stuck at how to go about overriding delete_selected method in admin.py.

```<code>def delete_selected(self, request, obj):
    '''
    Delete Kind only if there are no items under it.
    '''
    for o in obj.all():
        featuredItems = Item.objects.filter(kind=o).count()
        if featuredItems == 0:
            o.delete()
</code>```

However, django shows the warning and when i click yes, it deletes the kind even though there are records for it. I want to absolutely block the deletion.

答:
Actually you are trying to write a lot of code for something that can be done merely by adding an attribute to your model field

PROTECT
Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

```<code>class Item(models.Model):

    name=models.CharField(max_length=50)
    kind=models.ForeignKey(Kind,related_name="item_kind", on_delete=models.PROTECT)
</code>```

What you are trying to achieve is made even more difficult by the fact that django displays a confirmation page on delete.

Body:
I am using the default admin dashboard of django. Basically, i want to override the delete_selected method on a model by model basis so I can check for records before allowing the deletion to take place.

My models.py is:

class Kind(models.Model):

    name = models.CharField(max_length=50, unique=True)
    addedby = models.ForeignKey(User,related_name='admin_kind')
    createdon = models.DateTimeField(auto_now_add=True)
    updatedon = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ('name',)

class Item(models.Model):

    name = models.CharField(max_length=50)
    kind = models.ForeignKey(Kind,related_name="item_kind")
    createdon = models.DateTimeField(auto_now_add=True)
    updatedon = models.DateTimeField(auto_now=True)

    def __str__(self):
        return ' , '.join([self.kind.name, self.name])

    class Meta:
        ordering = ('kind', 'name',)
        unique_together = (('name','kind'))

Now what I want is before a kind could be deleted, I want to check if there is a related record in items. If there is, do not delete it.

But i am stuck at how to go about overriding delete_selected method in admin.py.

def delete_selected(self, request, obj):
    '''
    Delete Kind only if there are no items under it.
    '''
    for o in obj.all():
        featuredItems = Item.objects.filter(kind=o).count()
        if featuredItems == 0:
            o.delete()

However, django shows the warning and when i click yes, it deletes the kind even though there are records for it. I want to absolutely block the deletion.

Body:
Actually you are trying to write a lot of code for something that can be done merely by adding an attribute to your model field

PROTECT
Prevent deletion of the referenced object by raising ProtectedError, a subclass of django.db.IntegrityError.

class Item(models.Model):

    name=models.CharField(max_length=50)
    kind=models.ForeignKey(Kind,related_name="item_kind", on_delete=models.PROTECT)

What you are trying to achieve is made even more difficult by the fact that django displays a confirmation page on delete.


问:
LocationProvider costAllowed
When you choose a locationProvider by Criteria you can choose to allowCost or not.
But of which cost we are talking about?
If I choose to don't allow cost I allow the network provider?
Which providers can have a cost?</p>

答: I think it means that if you allow costs, that the application can/will connect to the internet via 3G to get a location. Otherwise GPS or Wi-Fi will be selected.</p>

Title: LocationProvider costAllowed


问:
Cucmber.js step is getting passed even though expect should have failed
My Cucumber step is getting passed even though expect statement is failing. It seems steps is running before expect statement is completed.

Please let me know how can I instruct the cucumber step to fail if expect is getting failed.

[Folder Structure]  Following is my Feature file

```<code>    #features/test.feature

 Feature: Running Cucumber with Protractor
    As a user of Protractor
    I should be able to use Cucumber
    In order to run my E2E tests

    Scenario: Protractor and Cucumber Test
        Given I go to "https://angularjs.org/"
        When I add "Be Awesome" in the task field
        And I click the add button
        Then I should see my new task in the list
</code>```

Following is Step Definition

```<code>var chai = require('chai'),
    expect = chai.expect,
    chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

chai.should();

var {defineSupportCode} = require('cucumber');
let scenarioTimeout = 200 * 1000;

defineSupportCode(({setDefaultTimeout}) => {
    setDefaultTimeout(scenarioTimeout);
});

defineSupportCode(function({Given, When, Then}) {
  Given(/^I go to "([^"]*)"$/, function(site) {
    return browser.get(site);
  });

  When(/^I add "([^"]*)" in the task field$/, function(task) {
    return element(by.model('todoList.todoText')).sendKeys(task);
  });

  When(/^I click the add button$/, function() {
  var el = element(by.css('[value="add"]'));
   return el.click();
  });

  Then(/^I should see my new task in the list$/, function() {
    var todoList = element.all(by.repeater('todo in todoList.todos'));
    return expect(todoList.get(2).getText()).to.eventually.equal('Not Awesome');

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

All works well If I write Then step as below :

Solution 1:

```<code>    element.all(by.repeater('todo in todoList.todos')).then(function(items){
expect(items[2].getText()).to.eventually.equal('Not Awesome').and.notify(callback);
});
</code>```

Solution2:

```<code>return element.all(by.repeater('todo in todoList.todos')).then(function(items){
return expect(items[2].getText()).to.eventually.equal('Not Awesome');
});
</code>```

I really want to understand why it did not work if I have written Then step in the below way:

```<code>Then(/^I should see my new task in the list$/, function() {
</code>```

```<code>var todoList = element.all(by.repeater('todo in todoList.todos'));
    return expect(todoList.get(2).getText()).to.eventually.equal('Not Awesome');
</code>```

答:
I finally managed to solve the issue.

Chai-as-promised version was 6.0 and it peer dependency is Chai version >=2.1.2 and < 4.
I was having the chai version > 4 so I downgraded to version 2.1.2 and it all worked smoothly.

Body:
My Cucumber step is getting passed even though expect statement is failing. It seems steps is running before expect statement is completed.

Please let me know how can I instruct the cucumber step to fail if expect is getting failed.

[Folder Structure]  Following is my Feature file

    #features/test.feature

 Feature: Running Cucumber with Protractor
    As a user of Protractor
    I should be able to use Cucumber
    In order to run my E2E tests

    Scenario: Protractor and Cucumber Test
        Given I go to "https://angularjs.org/"
        When I add "Be Awesome" in the task field
        And I click the add button
        Then I should see my new task in the list

Following is Step Definition

var chai = require('chai'),
    expect = chai.expect,
    chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);

chai.should();

var {defineSupportCode} = require('cucumber');
let scenarioTimeout = 200 * 1000;

defineSupportCode(({setDefaultTimeout}) => {
    setDefaultTimeout(scenarioTimeout);
});

defineSupportCode(function({Given, When, Then}) {
  Given(/^I go to "([^"]*)"$/, function(site) {
    return browser.get(site);
  });

  When(/^I add "([^"]*)" in the task field$/, function(task) {
    return element(by.model('todoList.todoText')).sendKeys(task);
  });

  When(/^I click the add button$/, function() {
  var el = element(by.css('[value="add"]'));
   return el.click();
  });

  Then(/^I should see my new task in the list$/, function() {
    var todoList = element.all(by.repeater('todo in todoList.todos'));
    return expect(todoList.get(2).getText()).to.eventually.equal('Not Awesome');

  });
});

All works well If I write Then step as below :

Solution 1:

    element.all(by.repeater('todo in todoList.todos')).then(function(items){
expect(items[2].getText()).to.eventually.equal('Not Awesome').and.notify(callback);
});

Solution2:

return element.all(by.repeater('todo in todoList.todos')).then(function(items){
return expect(items[2].getText()).to.eventually.equal('Not Awesome');
});

I really want to understand why it did not work if I have written Then step in the below way:

Then(/^I should see my new task in the list$/, function() {

var todoList = element.all(by.repeater('todo in todoList.todos'));
    return expect(todoList.get(2).getText()).to.eventually.equal('Not Awesome');


问:
Android different databases for different users
I want to see if there is a way to assign different database names to different users that login to an app. I'm trying to write a small app that assigns a DB to a user based on their username/email.

I tried setting DATABASE_NAME that is passed into

```<code>public SQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
</code>```

to the users' email addresses but it doesn't work. It loads the same data for all users.

On logout, I close the database and clean up and on startup, everytime I start a new database connection with the name already properly assigned...

Can someone help me understand what I'm missing?

答:
You can just pass the name of the database to your SQLiteOpenHelper class constructor (along with required Context instance) instead of hardcoding it as did DATABASE_NAME:

```<code>public class DBOpenHelper extends SQLiteOpenHelper {

    public DBOpenHelper(Context context, String dbName, int dbVersion) {
        super(context, dbName, null, dbVersion);
    }
...
}
</code>```

Body:
I want to see if there is a way to assign different database names to different users that login to an app. I'm trying to write a small app that assigns a DB to a user based on their username/email.

I tried setting DATABASE_NAME that is passed into

public SQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

to the users' email addresses but it doesn't work. It loads the same data for all users.

On logout, I close the database and clean up and on startup, everytime I start a new database connection with the name already properly assigned...

Can someone help me understand what I'm missing?

Body:
You can just pass the name of the database to your SQLiteOpenHelper class constructor (along with required Context instance) instead of hardcoding it as did DATABASE_NAME:

public class DBOpenHelper extends SQLiteOpenHelper {

    public DBOpenHelper(Context context, String dbName, int dbVersion) {
        super(context, dbName, null, dbVersion);
    }
...
}


问:
Python 3.6 - Accessing what key a number is
I have been making a game using pygame, in which a user can customize their controls. I want to be able to tell the user which key they have set to each variable, however, I am not sure how do do this, as when setting the variable I use int(event.key), which returns the number of that key, which works fine. I want to be able to use this number and tell the user which key corresponds to that number.  I have in mind something that is like print(key(number))Thanks in advance!

答: Ok guys I found the answer, pygame.key.name(number) works nicely! This returns values such as space, up, down, etc.


答:
Hope this helps

* {
padding: 0;
margin: 0;
}

.tab {
background-color: lightgray;
border-left: thin solid darkgray;
border-right: thin solid darkgray;
border-top: thin solid darkgray;
border-radius: 5px;
display: inline-block;
padding-top: 1em;
position: relative;
}
.bubble-circle {
position: absolute;
top: 1px;
left: 50%;
transform: translate(-50%, 0);
width: 15px;
height: 15px;
border-radius: 50%;
background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='tab'>
<div class='bubble-circle'></div>
<p>Tab 1</p>
</div></code>```

Title: how to add a circle at the top middle of tab in html?

Body:
Hope this helps

* {
padding: 0;
margin: 0;
}

.tab {
background-color: lightgray;
border-left: thin solid darkgray;
border-right: thin solid darkgray;
border-top: thin solid darkgray;
border-radius: 5px;
display: inline-block;
padding-top: 1em;
position: relative;
}
.bubble-circle {
position: absolute;
top: 1px;
left: 50%;
transform: translate(-50%, 0);
width: 15px;
height: 15px;
border-radius: 50%;
background-color: red;
}

<div class='tab'>
<div class='bubble-circle'></div>
<p>Tab 1</p>
</div>


问:
Not work search in active directory
I have a problem with novell.ldap. The connection is successful. I used the test server server http://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server. In ldap browser successfully applied test mask "(cn=italians)". But not in my code.. What am I doing wrong ?

```<code>LdapConnection conn = new LdapConnection();
conn.Connect("ldap.forumsys.com", 389);
conn.Bind("cn=read-only-admin,dc=example,dc=com", "password");
LdapSearchResults searchResults_ = conn.Search("dc=example,dc=com", LdapConnection.SCOPE_SUB, "(cn=italians)", null, false);
conn.Disconnect();
</code>```

答: You are searching for cn=italians but the DIT has ou=italians.

Title: Not work search in active directory

Body:
I have a problem with novell.ldap. The connection is successful. I used the test server server http://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server. In ldap browser successfully applied test mask "(cn=italians)". But not in my code.. What am I doing wrong ?

LdapConnection conn = new LdapConnection();
conn.Connect("ldap.forumsys.com", 389);
conn.Bind("cn=read-only-admin,dc=example,dc=com", "password");
LdapSearchResults searchResults_ = conn.Search("dc=example,dc=com", LdapConnection.SCOPE_SUB, "(cn=italians)", null, false);
conn.Disconnect();


问:
Packaging java project
I have one java project with two class. One of them is with main method. I also have two files one of them is a.properties and second one i b.xls. The way I want to export this project is in one executable jar but withour these two files(a.properties and b.xls) being compressed inside this executable jar. The reason for this is, user who run this project should able to change the properties file(a.properties) and also excel file(b.xls). I also want to include the libraries I have used for this project.

I am using Eclipse helios and jdk 1.6.

I really appreciate if somebody will provide me the steps for this. I already tried the Export option with executable jar but it compress everything including two files.

Thanks

答:
You'd need to exclude the files from the jar </p>

```<code><jar jarfile="some.jar" excludes="some.properties,some.properties">
        <fileset dir="${build}" />
        <manifest>
            <attribute name="Main-Class" value="some.class"/>
            <attribute name="Class-Path" value="."/>
        </manifest>
    </jar>
</code>```

Title: Packaging java project

Body:
You'd need to exclude the files from the jar

<jar jarfile="some.jar" excludes="some.properties,some.properties">
        <fileset dir="${build}" />
        <manifest>
            <attribute name="Main-Class" value="some.class"/>
            <attribute name="Class-Path" value="."/>
        </manifest>
    </jar>


问:
FirebaseDatabase: Model is missing a constructor with no arguments
So I've added Firebase data like this:

and I called the data inside a ListView:

```<code>private void displayStudentChatMessages() {
    listofMessages = (ListView) findViewById(R.id.list_msg);
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference(String.valueOf(generateChatID));

    adapter = new FirebaseListAdapter<StudentMessageModel>(this, StudentMessageModel.class, R.layout.item_chat_right, ref) {
        @Override
        protected void populateView(View v, StudentMessageModel model, int position) {
            TextView messageUsername = (TextView) findViewById(R.id.message_user_sender);
            TextView messageText = (TextView) findViewById(R.id.message_user);
            TextView messageTime = (TextView) findViewById(R.id.message_usertime);

            messageUsername.setText(model.getStudentName());
            messageText.setText(model.getStudentMessage());
            messageTime.setText(DateFormat.format("yyyy-MM-dd (HH:mm:ss)", model.getStudentTime()));
        }
    };

    listofMessages.setAdapter(adapter);
    listofMessages.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
}
</code>```

But I got the error:

com.google.firebase.database.DatabaseException: Class com.androidports.autosiskola.StudentMessageModel is missing a constructor with no arguments

I need those data where the root's child is the generated-name (test-testteacher-student-teacher).

Here is how I added the constructor:

```<code>public class StudentMessageModel {

private String studentUsername;
private String studentName;
private String studentMessage;
private String generatedChatID;
private long studentTime;

public StudentMessageModel(String studentUsername, String studentName, String studentMessage, String generatedChatID) {
    this.studentUsername = studentUsername;
    this.studentName = studentName;
    this.studentMessage = studentMessage;
    this.generatedChatID = generatedChatID;

    studentTime = new Date().getTime();
}
</code>```

and getters and setters.

答:
I believe the error is self-explanatory. You must have a constructor with no arguments. Like this:</p>

```<code>public class StudentMessageModel {

private String studentUsername;
private String studentName;
private String studentMessage;
private String generatedChatID;
private long studentTime;

public StudentMessageModel(String studentUsername, String studentName, String studentMessage, String generatedChatID) {
    this.studentUsername = studentUsername;
    this.studentName = studentName;
    this.studentMessage = studentMessage;
    this.generatedChatID = generatedChatID;

    studentTime = new Date().getTime();
}

public StudentMessageModel(){}
</code>```

Body:
So I've added Firebase data like this:

and I called the data inside a ListView:

private void displayStudentChatMessages() {
    listofMessages = (ListView) findViewById(R.id.list_msg);
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference(String.valueOf(generateChatID));

    adapter = new FirebaseListAdapter<StudentMessageModel>(this, StudentMessageModel.class, R.layout.item_chat_right, ref) {
        @Override
        protected void populateView(View v, StudentMessageModel model, int position) {
            TextView messageUsername = (TextView) findViewById(R.id.message_user_sender);
            TextView messageText = (TextView) findViewById(R.id.message_user);
            TextView messageTime = (TextView) findViewById(R.id.message_usertime);

            messageUsername.setText(model.getStudentName());
            messageText.setText(model.getStudentMessage());
            messageTime.setText(DateFormat.format("yyyy-MM-dd (HH:mm:ss)", model.getStudentTime()));
        }
    };

    listofMessages.setAdapter(adapter);
    listofMessages.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
}

But I got the error:

com.google.firebase.database.DatabaseException: Class com.androidports.autosiskola.StudentMessageModel is missing a constructor with no arguments

I need those data where the root's child is the generated-name (test-testteacher-student-teacher).

Here is how I added the constructor:

public class StudentMessageModel {

private String studentUsername;
private String studentName;
private String studentMessage;
private String generatedChatID;
private long studentTime;

public StudentMessageModel(String studentUsername, String studentName, String studentMessage, String generatedChatID) {
    this.studentUsername = studentUsername;
    this.studentName = studentName;
    this.studentMessage = studentMessage;
    this.generatedChatID = generatedChatID;

    studentTime = new Date().getTime();
}

and getters and setters.

Body:
I believe the error is self-explanatory. You must have a constructor with no arguments. Like this:

public class StudentMessageModel {

private String studentUsername;
private String studentName;
private String studentMessage;
private String generatedChatID;
private long studentTime;

public StudentMessageModel(String studentUsername, String studentName, String studentMessage, String generatedChatID) {
    this.studentUsername = studentUsername;
    this.studentName = studentName;
    this.studentMessage = studentMessage;
    this.generatedChatID = generatedChatID;

    studentTime = new Date().getTime();
}

public StudentMessageModel(){}


问:
Hash Ciphers and check with Signature in C
I have three binary files: cipher01.bin, cipher02.bin and cipher03.bin.
Additionally I have a sign.bin and a pubkey.pem file. The task is to hash all three ciphers and compare it to the signature. Therefore I used RSA to decrypt the sign.bin with the public key from pubkey.pem.

The result looks good but none of the cipher-hashes belongs to the signature. But I know, that there is at least one cipher which belongs to the signature because it is a task from our university. Maybe I forgot something but I can't figure out what.

Here is my code so far:

```<code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/rsa.h>
#include <openssl/bio.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/** converts unsigned character to readble string*/
char *pt(unsigned char *md) {
  int i;
  char *buf = (char*)malloc(sizeof(char)*80);

  for(int i = 0; i < SHA_DIGEST_LENGTH;i++) {
    sprintf(&(buf[i*2]),"%02x",md[i]);
  }

  return (buf);
}

/** returns error */
void err_exit(void) {
  printf("%s\n",ERR_error_string(ERR_get_error(),NULL));

  ERR_free_strings();
  exit(EXIT_FAILURE);
}

/** reads a file */
char * readFile(char * filename,long int * filesize) {
  FILE *fin;
  char *buf;

  if((fin=fopen(filename,"r"))==NULL) {
    printf("Error opening %s.\n",filename);
    exit(EXIT_FAILURE);
  }

  fseek(fin,0L,SEEK_END);
  *filesize = ftell(fin);
  rewind(fin);

  if(!(buf=malloc(*filesize))) {
    printf("Memory exhausted. Stop.\n");
    exit(EXIT_FAILURE);
  }

  fread(buf,*filesize,1,fin);
  fclose(fin);

  return buf;
}

/** hash a file with sha1 */
char * hashBinaryFile(char * filename) {
  long int filesize = 0;

  EVP_MD_CTX c;
  unsigned char md[SHA_DIGEST_LENGTH];

  ERR_load_crypto_strings();

  EVP_MD_CTX_init(&c);

  /** reads files into buf */
  char * buf = readFile(filename,&filesize);

  if((EVP_DigestInit(&c,EVP_sha1()))==0) {
    err_exit();
  }

  if((EVP_DigestUpdate(&c,buf,filesize))==0) {
    err_exit();
  }

  if((EVP_DigestFinal(&c,md,NULL))==0) {
    err_exit();
  }

  //printf("%s\n",pt(md));

  EVP_MD_CTX_cleanup(&c);
  free(buf);
  ERR_free_strings();

  return pt(md);

}

int padding = RSA_PKCS1_PADDING;

/** loads public key and creates rsa */
RSA * createRSAWithFilename(char * filename,int public) {
  FILE * fp = fopen(filename,"rb");

  if(fp == NULL) {
    printf("Unable to open file %s \n",filename);
    return NULL;
  }

  RSA *rsa= RSA_new() ;

  if(public) {
    rsa = PEM_read_RSA_PUBKEY(fp, &rsa,NULL, NULL);
  } else {
    rsa = PEM_read_RSAPrivateKey(fp, &rsa,NULL, NULL);
  }

  return rsa;
}

/** decrypt signature */
char * public_decrypt(unsigned char * enc_data,int data_len, unsigned char *decrypted) {
  RSA * rsa = createRSAWithFilename("archieve/pubkey.pem",1);
  int  result = RSA_public_decrypt(data_len,enc_data,decrypted,rsa,padding);
  return pt(decrypted);
}

int main(int argc,char *argv[]) {
  /** decrypt signature */
  long int encrypted_length;
  long int decrypted_length;
  unsigned char decrypted[4098]={};
  char * encrypted = readFile("archieve/s72897-sig.bin",&encrypted_length);
  char * sign = public_decrypt(encrypted,encrypted_length, decrypted);

  char * cipher01 = hashBinaryFile("archieve/s72897-cipher01.bin");
  char * cipher02 = hashBinaryFile("archieve/s72897-cipher02.bin");
  char * cipher03 = hashBinaryFile("archieve/s72897-cipher03.bin");

  if(strcmp(sign,cipher01)==0) {
    printf("cipher01\n");
  } else if(strcmp(sign,cipher02)==0) {
    printf("cipher02\n");
  } else if(strcmp(sign,cipher03)==0) {
    printf("cipher03\n");
  } else {
    printf("No cipher matches the signature\n");
  }

  return 0;
}
</code>```

Thanks for any kind of help.

Edit: fixed some code

Edit2: link to the *.zip https://ufile.io/tqwoh

答:
You transform your files in human readable format twice:

```<code>char * public_decrypt(...)
{
    return pt(decrypted);
    //     ^
}

int main(int argc,char *argv[])
{
    char * sign = pt(public_decrypt(encrypted,encrypted_length, decrypted));
    //            ^
</code>```

Additionally, you actually have some memory leaks: You do not free the rsa instance in public_decrypt neither do you free the strings returned (encrypted, sign, cypher0x)...

Further recommendation in for pt:

```<code>char *buf = (char*)malloc(sizeof(char) * 2 * SHA_DIGEST_LENGTH);
</code>```

If you have an appropriate constant already, use it... sizeof(char) always is 1 by definition, so you could drop it...

Body:
I have three binary files: cipher01.bin, cipher02.bin and cipher03.bin.
Additionally I have a sign.bin and a pubkey.pem file. The task is to hash all three ciphers and compare it to the signature. Therefore I used RSA to decrypt the sign.bin with the public key from pubkey.pem.

The result looks good but none of the cipher-hashes belongs to the signature. But I know, that there is at least one cipher which belongs to the signature because it is a task from our university. Maybe I forgot something but I can't figure out what.

Here is my code so far:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/rsa.h>
#include <openssl/bio.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/** converts unsigned character to readble string*/
char *pt(unsigned char *md) {
  int i;
  char *buf = (char*)malloc(sizeof(char)*80);

  for(int i = 0; i < SHA_DIGEST_LENGTH;i++) {
    sprintf(&(buf[i*2]),"%02x",md[i]);
  }

  return (buf);
}

/** returns error */
void err_exit(void) {
  printf("%s\n",ERR_error_string(ERR_get_error(),NULL));

  ERR_free_strings();
  exit(EXIT_FAILURE);
}

/** reads a file */
char * readFile(char * filename,long int * filesize) {
  FILE *fin;
  char *buf;

  if((fin=fopen(filename,"r"))==NULL) {
    printf("Error opening %s.\n",filename);
    exit(EXIT_FAILURE);
  }

  fseek(fin,0L,SEEK_END);
  *filesize = ftell(fin);
  rewind(fin);

  if(!(buf=malloc(*filesize))) {
    printf("Memory exhausted. Stop.\n");
    exit(EXIT_FAILURE);
  }

  fread(buf,*filesize,1,fin);
  fclose(fin);

  return buf;
}

/** hash a file with sha1 */
char * hashBinaryFile(char * filename) {
  long int filesize = 0;

  EVP_MD_CTX c;
  unsigned char md[SHA_DIGEST_LENGTH];

  ERR_load_crypto_strings();

  EVP_MD_CTX_init(&c);

  /** reads files into buf */
  char * buf = readFile(filename,&filesize);

  if((EVP_DigestInit(&c,EVP_sha1()))==0) {
    err_exit();
  }

  if((EVP_DigestUpdate(&c,buf,filesize))==0) {
    err_exit();
  }

  if((EVP_DigestFinal(&c,md,NULL))==0) {
    err_exit();
  }

  //printf("%s\n",pt(md));

  EVP_MD_CTX_cleanup(&c);
  free(buf);
  ERR_free_strings();

  return pt(md);

}

int padding = RSA_PKCS1_PADDING;

/** loads public key and creates rsa */
RSA * createRSAWithFilename(char * filename,int public) {
  FILE * fp = fopen(filename,"rb");

  if(fp == NULL) {
    printf("Unable to open file %s \n",filename);
    return NULL;
  }

  RSA *rsa= RSA_new() ;

  if(public) {
    rsa = PEM_read_RSA_PUBKEY(fp, &rsa,NULL, NULL);
  } else {
    rsa = PEM_read_RSAPrivateKey(fp, &rsa,NULL, NULL);
  }

  return rsa;
}

/** decrypt signature */
char * public_decrypt(unsigned char * enc_data,int data_len, unsigned char *decrypted) {
  RSA * rsa = createRSAWithFilename("archieve/pubkey.pem",1);
  int  result = RSA_public_decrypt(data_len,enc_data,decrypted,rsa,padding);
  return pt(decrypted);
}

int main(int argc,char *argv[]) {
  /** decrypt signature */
  long int encrypted_length;
  long int decrypted_length;
  unsigned char decrypted[4098]={};
  char * encrypted = readFile("archieve/s72897-sig.bin",&encrypted_length);
  char * sign = public_decrypt(encrypted,encrypted_length, decrypted);

  char * cipher01 = hashBinaryFile("archieve/s72897-cipher01.bin");
  char * cipher02 = hashBinaryFile("archieve/s72897-cipher02.bin");
  char * cipher03 = hashBinaryFile("archieve/s72897-cipher03.bin");

  if(strcmp(sign,cipher01)==0) {
    printf("cipher01\n");
  } else if(strcmp(sign,cipher02)==0) {
    printf("cipher02\n");
  } else if(strcmp(sign,cipher03)==0) {
    printf("cipher03\n");
  } else {
    printf("No cipher matches the signature\n");
  }

  return 0;
}

Thanks for any kind of help.

Edit: fixed some code

Edit2: link to the *.zip https://ufile.io/tqwoh

Body:
You transform your files in human readable format twice:

char * public_decrypt(...)
{
    return pt(decrypted);
    //     ^
}

int main(int argc,char *argv[])
{
    char * sign = pt(public_decrypt(encrypted,encrypted_length, decrypted));
    //            ^

Additionally, you actually have some memory leaks: You do not free the rsa instance in public_decrypt neither do you free the strings returned (encrypted, sign, cypher0x)...

Further recommendation in for pt:

char *buf = (char*)malloc(sizeof(char) * 2 * SHA_DIGEST_LENGTH);

If you have an appropriate constant already, use it... sizeof(char) always is 1 by definition, so you could drop it...


问:
how to combine 2 array values into single one by common value
1.fetching the values from a same table with different date

```<code> <?php
    $date= date("Y-m-d");;
    $prev_date = date('Y-m-d', strtotime($date .' -1 day'));
    $result_yest=mysql_query("SELECT isp,sum(sent) AS `sent_yest` FROM red_global WHERE status_date='$prev_date' and sent > 0 group by 1",$link1);
    $data_yest = array(); // create a variable to hold the information
    while (($row_yest = mysql_fetch_array($result_yest, MYSQL_ASSOC)) !== false){
      $data_yest[] = $row_yest; // add the row in to the results (data) array
    }
    print_r($data_yest);
    $result_today=mysql_query("SELECT isp,sum(sent) AS `sent_today` FROM red_global WHERE status_date='$date' and sent > 0 group by 1",$link1);
    $data_today = array(); // create a variable to hold the information
    while (($row_today = mysql_fetch_array($result_today, MYSQL_ASSOC)) !== false){
      $data_today[] = $row_today; // add the row in to the results (data) array
    }
    print_r($data_today);
    exit;
?>
</code>```

2.Array results in which one array contains yesterday's sent count and another one aray contains today's sent count both array having the common isp

```<code>Array (
  [0] => Array ( [isp] => aol [sent_yest] => 46838 )
  [1] => Array ( [isp] => gmail [sent_yest] => 33015 )
  [2] => Array ( [isp] => juno [sent_yest] => 93544 )
  [3] => Array ( [isp] => roadrunner [sent_yest] => 6181 )
  [4] => Array ( [isp] => yahoo [sent_yest] => 71444 )
)

Array (
  [0] => Array ( [isp] => aol [sent_today] => 14135 )
  [1] => Array ( [isp] => att [sent_today] => 624 )
  [2] => Array ( [isp] => gmail [sent_today] => 21263 )
  [3] => Array ( [isp] => juno [sent_today] => 74934 )
  [4] => Array ( [isp] => roadrunner [sent_today] => 939 )
  [5] => Array ( [isp] => yahoo [sent_today] => 22059 )
)
</code>```

Now i need a result like this isp name, yesterday's sent count, today's sent count

```<code>[isp, sent_yest, sent_today],
[aol, 46838,  14135],
[att, 0,  624],
[gmail, 33015,  21263],
</code>```

Anyone help me to solve this.. Thanks in advance

答:
Do it like below:-

```<code>$final_array = array();

if(count($arr1)>=count($arr2)){
  foreach ($arr1 as $arr){
      $key='';
      foreach ($arr2 as $ar2){
         if($arr['isp'] == $ar2['isp']){
            $final_array[$arr['isp']] = array($arr['isp'],$arr['sent_yest'],$ar2['sent_today']);
            $key ='';break;
         }else{
             $key = $arr['isp'];
         }
      }
      if($key!==''){
            $final_array[$key] = array($arr['isp'],$arr['sent_yest'],0);
            $key ='';
      }
  }
}

if(count($arr2)>count($arr1)){
   foreach ($arr2 as $ar2){
       $key='';
      foreach ($arr1 as $arr){
         if($ar2['isp'] == $arr['isp']){
            $final_array[$ar2['isp']] = array($ar2['isp'],$arr['sent_yest'],$ar2['sent_today']);
             $key ='';break;
         }else{
             $key = $ar2['isp'];
         }
      }
      if($key!==''){
            $final_array[$key] = array($ar2['isp'],0,$ar2['sent_today']);
            $key ='';
      }
   }
}

echo "<pre/>";print_r($final_array);
</code>```

Output:-https://eval.in/814625

Body:
1.fetching the values from a same table with different date

 <?php
    $date= date("Y-m-d");;
    $prev_date = date('Y-m-d', strtotime($date .' -1 day'));
    $result_yest=mysql_query("SELECT isp,sum(sent) AS `sent_yest` FROM red_global WHERE status_date='$prev_date' and sent > 0 group by 1",$link1);
    $data_yest = array(); // create a variable to hold the information
    while (($row_yest = mysql_fetch_array($result_yest, MYSQL_ASSOC)) !== false){
      $data_yest[] = $row_yest; // add the row in to the results (data) array
    }
    print_r($data_yest);
    $result_today=mysql_query("SELECT isp,sum(sent) AS `sent_today` FROM red_global WHERE status_date='$date' and sent > 0 group by 1",$link1);
    $data_today = array(); // create a variable to hold the information
    while (($row_today = mysql_fetch_array($result_today, MYSQL_ASSOC)) !== false){
      $data_today[] = $row_today; // add the row in to the results (data) array
    }
    print_r($data_today);
    exit;
?>

2.Array results in which one array contains yesterday's sent count and another one aray contains today's sent count both array having the common isp

Array (
  [0] => Array ( [isp] => aol [sent_yest] => 46838 )
  [1] => Array ( [isp] => gmail [sent_yest] => 33015 )
  [2] => Array ( [isp] => juno [sent_yest] => 93544 )
  [3] => Array ( [isp] => roadrunner [sent_yest] => 6181 )
  [4] => Array ( [isp] => yahoo [sent_yest] => 71444 )
)

Array (
  [0] => Array ( [isp] => aol [sent_today] => 14135 )
  [1] => Array ( [isp] => att [sent_today] => 624 )
  [2] => Array ( [isp] => gmail [sent_today] => 21263 )
  [3] => Array ( [isp] => juno [sent_today] => 74934 )
  [4] => Array ( [isp] => roadrunner [sent_today] => 939 )
  [5] => Array ( [isp] => yahoo [sent_today] => 22059 )
)

Now i need a result like this isp name, yesterday's sent count, today's sent count

[isp, sent_yest, sent_today],
[aol, 46838,  14135],
[att, 0,  624],
[gmail, 33015,  21263],

Anyone help me to solve this.. Thanks in advance

Body:
Do it like below:-

$final_array = array();

if(count($arr1)>=count($arr2)){
  foreach ($arr1 as $arr){
      $key='';
      foreach ($arr2 as $ar2){
         if($arr['isp'] == $ar2['isp']){
            $final_array[$arr['isp']] = array($arr['isp'],$arr['sent_yest'],$ar2['sent_today']);
            $key ='';break;
         }else{
             $key = $arr['isp'];
         }
      }
      if($key!==''){
            $final_array[$key] = array($arr['isp'],$arr['sent_yest'],0);
            $key ='';
      }
  }
}

if(count($arr2)>count($arr1)){
   foreach ($arr2 as $ar2){
       $key='';
      foreach ($arr1 as $arr){
         if($ar2['isp'] == $arr['isp']){
            $final_array[$ar2['isp']] = array($ar2['isp'],$arr['sent_yest'],$ar2['sent_today']);
             $key ='';break;
         }else{
             $key = $ar2['isp'];
         }
      }
      if($key!==''){
            $final_array[$key] = array($ar2['isp'],0,$ar2['sent_today']);
            $key ='';
      }
   }
}

echo "<pre/>";print_r($final_array);

Output:-https://eval.in/814625


问:
I'm trying to echo an image in a PHP variable in CodeIgniter
Hello I'm trying to echo an image on a view page in CodeIgniter but nothing is displayed on the page.

Here I'm making the variable:

```<code><?php $image = "<img src='../../images/stoel.jpg' alt='img' />";  ?>
</code>```

And here I'm trying to echo the image:

```<code><img src="<?php echo $image;?>">
</code>```

答:
Intro

This is the most basic php, so what's the addition of this question? Please read the basics of echo here: http://php.net/manual/en/function.echo.php (Example 1).

Learn the basics first!

Solution

1. Assign full html tag to variable and echo full html:

```<code><?php
    $image = '<img src="../../images/stoel.jpg" alt="Foo">';

    echo $image;
?>
</code>```

2. Or assign image path to variable and echo concat string:

```<code><?php
    $path = '../../images/stoel.jpg';

    echo '<img src="' . $path . '" alt="Foo">';
?>
</code>```

3. Or assign image path to variable and echo only this with php:

```<code><?php
    $path = '../../images/stoel.jpg';
?>

<img src="<?= $path; ?>" alt="Foo">
</code>```

Body:
Hello I'm trying to echo an image on a view page in CodeIgniter but nothing is displayed on the page.

Here I'm making the variable:

<?php $image = "";  ?>

And here I'm trying to echo the image:

<img src="<?php echo $image;?>">

Body:
Intro

This is the most basic php, so what's the addition of this question? Please read the basics of echo here: http://php.net/manual/en/function.echo.php (Example 1).

Learn the basics first!

Solution

1. Assign full html tag to variable and echo full html:

<?php
    $image = '<img src="../../images/stoel.jpg" alt="Foo">';

    echo $image;
?>

2. Or assign image path to variable and echo concat string:

<?php
    $path = '../../images/stoel.jpg';

    echo '<img src="' . $path . '" alt="Foo">';
?>

3. Or assign image path to variable and echo only this with php:

<?php
    $path = '../../images/stoel.jpg';
?>

<img src="<?= $path; ?>" alt="Foo">


问:
Python unable to find lxml module
I wrote a script some times ago that contain

```<code>from lxml import etree
</code>```

But, unfortunatly it is not working anymore.
In doubt i checked installation with :

```<code>sudo apt-get install python-lxml
sudo pip install lxml
sudo apt-get install libxml2-dev
sudo apt-get install libxslt1-dev
</code>```

I checked if it could be my python version with :

```<code>me@pc:~$ python
Python 2.7.3 (default, Sep 14 2012, 14:11:57)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import lxml
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named lxml
</code>```

My os is ubuntu 12.04.1 LTS with Python 2.7.3.

All seems fine. I can't see what could be the problem.

答:
For Python 3.6, it is very tricky.

I have the same problem and try to install the latest version, lxml 3.8. But I still get the error. And then I use lxml 3.7.3, then it is ok.

ContentLicense: CC BY-SA 4.0

Title: Python unable to find lxml module

Body:
I wrote a script some times ago that contain

from lxml import etree

But, unfortunatly it is not working anymore.
In doubt i checked installation with :

sudo apt-get install python-lxml
sudo pip install lxml
sudo apt-get install libxml2-dev
sudo apt-get install libxslt1-dev

I checked if it could be my python version with :

me@pc:~$ python
Python 2.7.3 (default, Sep 14 2012, 14:11:57)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import lxml
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named lxml

My os is ubuntu 12.04.1 LTS with Python 2.7.3.

All seems fine. I can't see what could be the problem.


问:
Can I use JOIN instead of a subquery to get COUNT() across tables in MySQL?
I have one table that stores posts. Each post object has a postTypeId that denotes if it's a question post or an answer post. I would like to get question posts and count the number of answer posts each question post has. Can I do this using a JOIN instead of a subquery as shown below? The schema assumes the following: postsTable(id, postTypeId, parentId, title)

```<code>SELECT
    posts.id, posts.postTypeId, posts.parentId, posts.title
    , (SELECT COUNT(answers.id) AS answerCount FROM posts AS answers WHERE posts.id = answers.parentId GROUP BY posts.postTypeId)
    FROM posts
    WHERE posts.postTypeId = '1'
</code>```

Also, is the GROUP By necessary in the subquery?

答:
```<code>SELECT
        p.id, count(answers.id) answerCount, p.title
FROM posts p
     LEFT JOIN posts answers
    ON posts.id = answers.parentId
WHERE
    p.postTypeId = '1'
GROUP BY

p.id, p.title
</code>```

Take a look at this query to see it for SO

The main advantages to this is that its typically faster and more readable but it also allows you to get more data from "Answers".

E.g.

```<code>SELECT
        p.id, count(answers.id) answerCount, p.title, MAX(Answers.Score) HighScore,
FROM posts p
     LEFT JOIN posts answers
    ON posts.id = answers.parentId
WHERE
    p.postTypeId = '1'
GROUP BY

p.id, p.title
</code>```

Body:
I have one table that stores posts. Each post object has a postTypeId that denotes if it's a question post or an answer post. I would like to get question posts and count the number of answer posts each question post has. Can I do this using a JOIN instead of a subquery as shown below? The schema assumes the following: postsTable(id, postTypeId, parentId, title)

SELECT
    posts.id, posts.postTypeId, posts.parentId, posts.title
    , (SELECT COUNT(answers.id) AS answerCount FROM posts AS answers WHERE posts.id = answers.parentId GROUP BY posts.postTypeId)
    FROM posts
    WHERE posts.postTypeId = '1'

Also, is the GROUP By necessary in the subquery?

Body:
SELECT
        p.id, count(answers.id) answerCount, p.title
FROM posts p
     LEFT JOIN posts answers
    ON posts.id = answers.parentId
WHERE
    p.postTypeId = '1'
GROUP BY

p.id, p.title

Take a look at this query to see it for SO

The main advantages to this is that its typically faster and more readable but it also allows you to get more data from "Answers".

E.g.

SELECT
        p.id, count(answers.id) answerCount, p.title, MAX(Answers.Score) HighScore,
FROM posts p
     LEFT JOIN posts answers
    ON posts.id = answers.parentId
WHERE
    p.postTypeId = '1'
GROUP BY

p.id, p.title


问:
Custom code to combine all types of lucene query type
I am building a project that can generate custom queries for searching a lucene index. I did some research and found out many ways to query a lucene index like:

boolean Search: field: white cloths AND field shoes

term Query Search: field: i am a boy

proximity Query search: 5/5/2016-10/6/2017

What am confused about is: Can QueryParser do all this querying or do you have to write a method to do individual queries like in Tutorialspoint query programming, where they gave examples of each kind of query and how to implement it.

Here is my code so far:

```<code>/** Setting the searcher method to search the index passed **/
    private void indexSearch(String indexDir, String queryX, int repeat, int hitsPerPage, String field, boolean raw) throws Exception{
        /*** starting the method process ***/
        // Here we process the searcher data
        reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexDir)));
        searcher = new IndexSearcher(reader);
        Analyzer analyzer = new StandardAnalyzer();
        // BufferedReader
        BufferedReader in = null;
        boolean checkQ=false;
        // Lets check if query is a file
        File cfile=new File(queryX);
        // Now lets check
        if(cfile.isFile()){
        // We process queryX as a file
        in = Files.newBufferedReader(Paths.get(queryX), StandardCharsets.UTF_8);
        checkQ=true;
        }
        else{
        checkQ=false;
        }

       /** We pass query in different query types **/
       parser = new QueryParser(field, analyzer);
       // Here we are going to select the data we use for line
       String line = checkQ != true ? queryX : in.readLine();
       // Now lets trim the line

          line = line.trim();

          /******* NOW LETS CALL FUNCTION TO PASS QUERY ******/
          search(line);

    }

  /** Making complex query priviledge to get data **/
    public TopDocs search( String searchQuery) throws Exception{
        // Lets pass query
        query = parser.parse(searchQuery);
        // Now lets return
        return searcher.search(query, 100);
        }

    public TopDocs search(Query query) throws IOException{
        return searcher.search(query, 100);
        }

  /**** Making the getDocument for the search ****/
    public Document getDocument(ScoreDoc scoreDoc) throws CorruptIndexException, IOException{
        return searcher.doc(scoreDoc.doc);
        }

  /** Simple command-line based search demo. */
  public void close() throws Exception {
  // Lets close reader
      reader.close();
  }
</code>```

Here is the Tutorials point example in using a different query type:

```<code>    private void searchUsingTermQuery(String searchQuery)throws IOException, ParseException{
 searcher = new Searcher(indexDir); long startTime = System.currentTimeMillis(); //create a term to search file name
Term term = new Term(LuceneConstants.FILE_NAME, searchQuery);
//create the term query object
Query query = new TermQuery(term);
//do the search
TopDocs hits = searcher.search(query);
 long endTime = System.currentTimeMillis();
 System.out.println(hits.totalHits + " documents found. Time :" + (endTime - startTime) + "ms");
for(ScoreDoc scoreDoc : hits.scoreDocs) {
Document doc = searcher.getDocument(scoreDoc);
 System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH));
 }
searcher.close();
</code>```

I want to be able to combine all the lucene Query Types so I can query my indexes like described in this tutorial: http://www.javaranch.com/journal/2004/04/Lucene.html

My project creates dynamic fields from xml files and uses it to store indexes, so I know the fields, and I also want to be able to get the fields that got hits.

答:
If I am not wrong, it seems like you want to read query strings from a file and then execute them. And you want to be able to write all sorts of queries in the file. Correct?

It is possible. While coding the queries gives you flexibility, all queries can be written in text format with trial and error.

I would suggest looking at this. It is Lucene's documentation for Query Parser Syntax.

Also I would suggest to write all queries using code, and print the String representation of the final Query. This would give you insight as to how to write queries in String format.

Body:
I am building a project that can generate custom queries for searching a lucene index. I did some research and found out many ways to query a lucene index like:

boolean Search: field: white cloths AND field shoes

term Query Search: field: i am a boy

proximity Query search: 5/5/2016-10/6/2017

What am confused about is: Can QueryParser do all this querying or do you have to write a method to do individual queries like in Tutorialspoint query programming, where they gave examples of each kind of query and how to implement it.

Here is my code so far:

/** Setting the searcher method to search the index passed **/
    private void indexSearch(String indexDir, String queryX, int repeat, int hitsPerPage, String field, boolean raw) throws Exception{
        /*** starting the method process ***/
        // Here we process the searcher data
        reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexDir)));
        searcher = new IndexSearcher(reader);
        Analyzer analyzer = new StandardAnalyzer();
        // BufferedReader
        BufferedReader in = null;
        boolean checkQ=false;
        // Lets check if query is a file
        File cfile=new File(queryX);
        // Now lets check
        if(cfile.isFile()){
        // We process queryX as a file
        in = Files.newBufferedReader(Paths.get(queryX), StandardCharsets.UTF_8);
        checkQ=true;
        }
        else{
        checkQ=false;
        }

       /** We pass query in different query types **/
       parser = new QueryParser(field, analyzer);
       // Here we are going to select the data we use for line
       String line = checkQ != true ? queryX : in.readLine();
       // Now lets trim the line

          line = line.trim();

          /******* NOW LETS CALL FUNCTION TO PASS QUERY ******/
          search(line);

    }

  /** Making complex query priviledge to get data **/
    public TopDocs search( String searchQuery) throws Exception{
        // Lets pass query
        query = parser.parse(searchQuery);
        // Now lets return
        return searcher.search(query, 100);
        }

    public TopDocs search(Query query) throws IOException{
        return searcher.search(query, 100);
        }

  /**** Making the getDocument for the search ****/
    public Document getDocument(ScoreDoc scoreDoc) throws CorruptIndexException, IOException{
        return searcher.doc(scoreDoc.doc);
        }

  /** Simple command-line based search demo. */
  public void close() throws Exception {
  // Lets close reader
      reader.close();
  }

Here is the Tutorials point example in using a different query type:

    private void searchUsingTermQuery(String searchQuery)throws IOException, ParseException{
 searcher = new Searcher(indexDir); long startTime = System.currentTimeMillis(); //create a term to search file name
Term term = new Term(LuceneConstants.FILE_NAME, searchQuery);
//create the term query object
Query query = new TermQuery(term);
//do the search
TopDocs hits = searcher.search(query);
 long endTime = System.currentTimeMillis();
 System.out.println(hits.totalHits + " documents found. Time :" + (endTime - startTime) + "ms");
for(ScoreDoc scoreDoc : hits.scoreDocs) {
Document doc = searcher.getDocument(scoreDoc);
 System.out.println("File: "+ doc.get(LuceneConstants.FILE_PATH));
 }
searcher.close();

I want to be able to combine all the lucene Query Types so I can query my indexes like described in this tutorial: http://www.javaranch.com/journal/2004/04/Lucene.html

My project creates dynamic fields from xml files and uses it to store indexes, so I know the fields, and I also want to be able to get the fields that got hits.


问:
iOS Calculate correct WKWebview height for html string with embeded tweet
I am using wkwebview to load given HTML strings using loadHTMLString method. After wkwebview didFinishNavigation I am updating height of wkwebview to content height by evaluating javascript "document.height".
This is working for plain html string.

but for html string with embeded tweet height calculation goes wrong.
here is tweet content

```<code></p>
<blockquote class="twitter-tweet">
<p lang="fr" dir="ltr">Union Cabinet approves civil aviation policy.</p>— Press Trust of India (@PTI_News)
<a href="https://twitter.com/PTI_News/status/742990663495647232">June 15, 2016</a></blockquote>
<p>
<script>window.twttr = (function(d, s, id)
{var js, fjs = d.getElementsByTagName(s)[0],t = window.twttr || {};if (d.getElementById(id)) return t;js = d.createElement(s);js.id = id;
js.src = "https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js, fjs);t._e = [];
t.ready = function(f)
{t._e.push(f);};return t;}(document, "script", "twitter-wjs"));</script>
</code>```

So after webview loads twitter feeds completely, we do not get callback in wkwebviewdelegate methods .

答:
```<code>    //Add some Scheme tag in your HTML string.

    let urlwithScheme = 'widget.twitter.myapp://url’

    let strTwitter = "<script> twttr.ready(function(e){ twttr.events.bind('rendered', function (event) { window.location = \(urlwithScheme); } ); }) </script>"
    let strHTML = "<!DOCTYPE html><html>\(strTwitter)</html>"

    // After load HTML check url scheme, if it belongs to twitter rendered action or not

    @available(iOS 8.0, *)

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void){
        // If twitter feed finished renderin
        if(navigationAction.request.url?.scheme == "widget.twitter.myapp"){
            // Don’t update frame here
            decisionHandler(.cancel)
        }

        decisionHandler(.allow)
}
</code>```

Body:
I am using wkwebview to load given HTML strings using loadHTMLString method. After wkwebview didFinishNavigation I am updating height of wkwebview to content height by evaluating javascript "document.height".
This is working for plain html string.

but for html string with embeded tweet height calculation goes wrong.
here is tweet content

Union Cabinet approves civil aviation policy.
— Press Trust of India (@PTI_News)
June 15, 2016

So after webview loads twitter feeds completely, we do not get callback in wkwebviewdelegate methods .