问:
Run angularjs front-end web app on codenvy
How do I run an angularjs front-end web app on codenvy? The app uses angular-route.js for routing between pages. I have tried using the preview function, but that one seems to not work due to the routing...</p>

答: Another thing to try is to unbound the app from localhost, i.e. use host as 0.0.0.0</p>


来源: stackexchange

问:
Kotlin internal classes in Java visible publicly
I am developing an Android crypto library in Kotlin. I have a couple of internal classes which become publicly visible in a Java app. Found this in documentations.

internal declarations become public in Java. Members of internal classes go through name mangling, to make it harder to accidentally use them from Java and to allow overloading for members with the same signature that don't see each other according to Kotlin rules;

Is there a way to get around this?

答:
Apart from @JvmSynthetic, you can use @JvmName with an illegal Java identifier, like adding a space.

As an example, I added a space in the @JvmName param, so any languages except Kotlin will not be able to invoke your method:

```<code>@JvmName(" example")
internal fun example() {
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Apart from @JvmSynthetic, you can use @JvmName with an illegal Java identifier, like adding a space.

As an example, I added a space in the @JvmName param, so any languages except Kotlin will not be able to invoke your method:

@JvmName(" example")
internal fun example() {
}

ContentLicense: CC BY-SA 4.0


问:
iterate through multiple lists with python
Hi I've searched through Stackoverflow and have been struggling with the following list-related challenge, but as a Python novice I'm stumped.

I currently have 2 lists of test data, one with user info, (both new and old user ID followed by name data) and the other a list of lists with user and page numbers (eeIDlist). I want to check if the page numbers associated with a particular user matches either the new or old ID , and if either ID matches, append the page numbers back to the original list.

I've gotten as far as matching and appending a list to the CompanyName list, but the list seems to grown exponentially and represents all of the user page data, rather than just the page numbers associated with the individuals.

Advice warmly welcomed!

My code is as follows:

```<code>pagenumbers=[]

for i in CompanyNameList:

    for ee in i:
        for eeid in eeIDlist:
            try:
                if (str(eeid[1]) in ee):
                    pagenumbers.extend([eeid[0]])
                    i.append(pagenumbers)
                    i.append([eeid[0]])
            except ValueError:
                print "Not a valid number"

print i
</code>```

My source data is as follows:

```<code>CompanyNameList:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]
</code>```

UserID and Page Number
eeIDlist:

```<code>[[144128,1],[144138,12],[144130,6],[144131,9],[40013,153],[40074,310],[40023, 210],
[40050,250]]
</code>```

Desired Output List:

```<code>[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ',[1,153]],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ',[6,210]],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG',[9,250]],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE',[12,310]]]
</code>```

答:
I have corrected your code</p>

```<code>CompanyNameList = [['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]
eeIDlist = [[144128,1],[144138,12],[144130,6],[144131,9],[40013,153],[40074,310],[40023, 210], [40050,250]]

for CompanyName in CompanyNameList:
    pageList = []
    newID = int(CompanyName[0])
    oldID = int(CompanyName[1])
    for eeID in eeIDlist:
        if eeID[0] == newID or eeID[0] == oldID:
            pageList.append(eeID[1])
    CompanyName.append(pageList)

print(CompanyNameList)
</code>```

Body:
Hi I've searched through Stackoverflow and have been struggling with the following list-related challenge, but as a Python novice I'm stumped.

I currently have 2 lists of test data, one with user info, (both new and old user ID followed by name data) and the other a list of lists with user and page numbers (eeIDlist). I want to check if the page numbers associated with a particular user matches either the new or old ID , and if either ID matches, append the page numbers back to the original list.

I've gotten as far as matching and appending a list to the CompanyName list, but the list seems to grown exponentially and represents all of the user page data, rather than just the page numbers associated with the individuals.

Advice warmly welcomed!

My code is as follows:

pagenumbers=[]

for i in CompanyNameList:

    for ee in i:
        for eeid in eeIDlist:
            try:
                if (str(eeid[1]) in ee):
                    pagenumbers.extend([eeid[0]])
                    i.append(pagenumbers)
                    i.append([eeid[0]])
            except ValueError:
                print "Not a valid number"

print i

My source data is as follows:

CompanyNameList:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]

UserID and Page Number
eeIDlist:

[[144128,1],[144138,12],[144130,6],[144131,9],[40013,153],[40074,310],[40023, 210],
[40050,250]]

Desired Output List:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ',[1,153]],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ',[6,210]],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG',[9,250]],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE',[12,310]]]

Body:
I have corrected your code

CompanyNameList = [['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]
eeIDlist = [[144128,1],[144138,12],[144130,6],[144131,9],[40013,153],[40074,310],[40023, 210], [40050,250]]

for CompanyName in CompanyNameList:
    pageList = []
    newID = int(CompanyName[0])
    oldID = int(CompanyName[1])
    for eeID in eeIDlist:
        if eeID[0] == newID or eeID[0] == oldID:
            pageList.append(eeID[1])
    CompanyName.append(pageList)

print(CompanyNameList)


问:
Searching an arraylist for the index of an object with a specific value
I'm writing a program to take and organize class info, including the students in a class, recorded by ID and Grade. I'm able to add the students as desired, and they print as desired (so I know the entries are correct), but when I go to search for a student, the search method is only able to find the last entered student ID. Why is my search function breaking down?

The search function:

```<code>public static int studentFinder(ClassSection classOne) {
      int studentIndex = 0;
      boolean searchAgain = false;
      boolean correctStudent = false;
     do {
      studentIndex = idFinder(classOne);
        if (studentIndex == -1) {
            System.out.println("That student was not found in the class");
            System.out.println("Would you like to search again?");
                searchAgain = yesNoBool();
        } else {
            System.out.println("You have selected student ID# " +classOne.getStudentIDByIndex(studentIndex));
                System.out.println("Is this correct?");
                    correctStudent = yesNoBool();
                        if (!correctStudent) {
                            System.out.println("Would you like to search again?");
                                searchAgain = yesNoBool();
                        }
        }
     } while(searchAgain);
     return studentIndex;
  }
</code>```

ID Finder module:

```<code>public static int idFinder(ClassSection classOne) {
      int studentID = 0;
      String intString = "a Student ID to search for:";
      int studentIndex = 0;
      System.out.println("Please enter a Student ID to search for:");
        studentID = intChecker(intString);
      for (int i = 0; i < classOne.students.size(); i++) {
          int studentIdTest = classOne.students.get(i).getStudentID();
            if (studentIdTest == studentID) {
                studentIndex = i;
            } else if (studentIdTest != studentID){
                studentIndex = -1;
            }
      }
        return studentIndex;
  }
</code>```

The ClassSection class:

```<code>import java.util.*;

public class ClassSection {
    //instance variables
     protected int crnNum = 0;
     protected String deptCode = "null";
     protected int courseNum = 0;
     protected String instructMode = "null";
     protected String meetingDays = "null";
     protected String meetingTimesStart = "null";
     protected String meetingTimesEnd = "null";
     protected int classCapacity = 0;
     protected int classEnrollment = 0;
     protected int instructorID = 0;
     protected ArrayList<StudentEnrollee> students = new ArrayList<StudentEnrollee>();

    //constructors
        public ClassSection(int crnNum, String deptCode, int courseNum, String instructMode, String meetingDays,
                String meetingTimesStart, String meetingTimesEnd, int classCapacity, int classEnrollment,
                int instructorID) {
            super();
            this.crnNum = crnNum;
            this.deptCode = deptCode;
            this.courseNum = courseNum;
            this.instructMode = instructMode;
            this.meetingDays = meetingDays;
            this.meetingTimesStart = meetingTimesStart;
            this.meetingTimesEnd = meetingTimesEnd;
            this.classCapacity = classCapacity;
            this.classEnrollment = classEnrollment;
            this.instructorID = instructorID;
        }

    public ClassSection() {
        super();
        this.crnNum = 0;
        this.deptCode = "";
        this.courseNum = 0;
        this.instructMode = "";
        this.meetingDays = "";
        this.meetingTimesStart = "";
        this.meetingTimesEnd = "";
        this.classCapacity = 0;
        this.classEnrollment = 0;
        this.instructorID = 0;
    }

    //getters and setters
        public void getStudents() {
            this.students.forEach(System.out::println);
        }

        public int getStudentIDByIndex(int index) {
            return this.students.get(index).getStudentID();
        }

        public void addStudent(StudentEnrollee student) {
            this.students.add(student);
        }

        public void removeStudent(int removalIndex) {
            this.students.remove(removalIndex);
        }

        public void changeAddStudentGrade(int studentIndex, int studentGrade) {
            this.students.get(studentIndex).setStudentGrade(studentGrade);
        }

        public int getCrnNum() {
            return crnNum;
        }

        public void setCrnNum(int crnNum) {
            this.crnNum = crnNum;
        }
        public String getDeptCode() {
            return deptCode;
        }
        public void setDeptCode(String deptCode) {
            this.deptCode = deptCode;
        }
        public int getCourseNum() {
            return courseNum;
        }
        public void setCourseNum(int courseNum) {
            this.courseNum = courseNum;
        }
        public String getInstructMode() {
            return instructMode;
        }
        public void setInstructMode(String instructMode) {
            this.instructMode = instructMode;
        }
        public String getMeetingDays() {
            return meetingDays;
        }
        public void setMeetingDays(String meetingDays) {
            this.meetingDays = meetingDays;
        }

        public String getMeetingTimesStart() {
            return meetingTimesStart;
        }

        public void setMeetingTimesStart(String meetingTimesStart) {
            this.meetingTimesStart = meetingTimesStart;
        }

        public String getMeetingTimesEnd() {
            return meetingTimesEnd;
        }

        public void setMeetingTimesEnd(String meetingTimesEnd) {
            this.meetingTimesEnd = meetingTimesEnd;
        }

        public int getClassCapacity() {
            return classCapacity;
        }
        public void setClassCapacity(int classCapacity) {
            this.classCapacity = classCapacity;
        }
        public int getClassEnrollment() {
            return classEnrollment;
        }
        public void setClassEnrollment(int classEnrollment) {
            this.classEnrollment = classEnrollment;
        }
        public int getInstructorID() {
            return instructorID;
        }
        public void setInstructorID(int instructorID) {
            this.instructorID = instructorID;
        }

        //mutators
        @Override
        public String toString() {
            return String.format("Crn Number: %20s \nDept Code: %20s \nInstruction Mode: %20s"
                    + " \nCourse Number: %20s \nClass Capacity: %20s \nClass Enrollment: %20s"
                    + " \nMeeting Days: %20s \nMeeting Times: %8$20s - %9$2s \nInstructor ID: %10$20s \n" + Arrays.toString(students.toArray()).replace("[", "").replace(", S","S").replace("]", "").trim(),
                    crnNum, deptCode, instructMode, courseNum, classCapacity, classEnrollment, meetingDays,
                    meetingTimesStart, meetingTimesEnd, instructorID);
        }

}
</code>```

The student enrollee class (where the objects in the arraylist are from):

```<code>public class StudentEnrollee {
    protected int studentID = 0;
    protected int studentGrade = 0;

    public StudentEnrollee() {
        super();
        studentID = 0;
        studentGrade = 0;
    }

    public StudentEnrollee(int studentID, int studentGrade) {
        super();
        this.studentID = studentID;
        this.studentGrade = studentGrade;
    }

    //setters & getters
    public int getStudentID() {
        return studentID;
    }
    public void setStudentID(int studentID) {
        this.studentID = studentID;
    }
    public int getStudentGrade() {
        return studentGrade;
    }
    public void setStudentGrade(int studentGrade) {
        this.studentGrade = studentGrade;
    }

    @Override
    public String toString() {
        return String.format("Student ID: %20s  \nStudent Grade: %20s \n", studentID, studentGrade);
    }

}
</code>```

The intchecker and yesNoBool methods are just error checking and confirmation functions, but here they are just in case:

```<code>  public static int intChecker(String object) {
    boolean correctInput = false;
    int userInput = 0;

    while (!correctInput) {
        try {
            userInput = scanner.nextInt();
            correctInput = true;
        } catch(InputMismatchException e) {
            System.out.println("I'm sorry, that doesn't seem to be a number");
            System.out.println("Please enter " +object);
            scanner.next();
        }
    }

    return userInput;
}

  public static boolean yesNoBool() {
      String yesNo = "";
      boolean yesNoBool = false;
      System.out.println("Please enter Y/N");
        yesNo = scanner.next();
      while ((!yesNo.equalsIgnoreCase("n") && !yesNo.equalsIgnoreCase("y"))){
            System.out.println("I'm sorry, please enter Y/N");
                yesNo = scanner.next();
        }
      if (yesNo.equalsIgnoreCase("y")) {
          yesNoBool = true;
      } else if (yesNo.equalsIgnoreCase("n")) {
          yesNoBool = false;
      }

      return yesNoBool;
  }
</code>```

答:
Once you found the match you have to break the loop, otherwise studentIndex gets overwritten for rest of the records for which loop iterating. Also you don't need if(studentIdTest != studentID) just else is also work same.

Add Break in loop in idFinder method as follows:

```<code>for (int i = 0; i < classOne.students.size(); i++) {
      int studentIdTest = classOne.students.get(i).getStudentID();
        if (studentIdTest == studentID) {
            studentIndex = i;
            break;
        } else{
            studentIndex = -1;
        }
  }
</code>```

Suggestion: you can intialize studentIndex with -1 instead of setting it in each iteration where match not found.

I hope this will solve your problem.

Body:
I'm writing a program to take and organize class info, including the students in a class, recorded by ID and Grade. I'm able to add the students as desired, and they print as desired (so I know the entries are correct), but when I go to search for a student, the search method is only able to find the last entered student ID. Why is my search function breaking down?

The search function:

public static int studentFinder(ClassSection classOne) {
      int studentIndex = 0;
      boolean searchAgain = false;
      boolean correctStudent = false;
     do {
      studentIndex = idFinder(classOne);
        if (studentIndex == -1) {
            System.out.println("That student was not found in the class");
            System.out.println("Would you like to search again?");
                searchAgain = yesNoBool();
        } else {
            System.out.println("You have selected student ID# " +classOne.getStudentIDByIndex(studentIndex));
                System.out.println("Is this correct?");
                    correctStudent = yesNoBool();
                        if (!correctStudent) {
                            System.out.println("Would you like to search again?");
                                searchAgain = yesNoBool();
                        }
        }
     } while(searchAgain);
     return studentIndex;
  }

ID Finder module:

public static int idFinder(ClassSection classOne) {
      int studentID = 0;
      String intString = "a Student ID to search for:";
      int studentIndex = 0;
      System.out.println("Please enter a Student ID to search for:");
        studentID = intChecker(intString);
      for (int i = 0; i < classOne.students.size(); i++) {
          int studentIdTest = classOne.students.get(i).getStudentID();
            if (studentIdTest == studentID) {
                studentIndex = i;
            } else if (studentIdTest != studentID){
                studentIndex = -1;
            }
      }
        return studentIndex;
  }

The ClassSection class:

import java.util.*;

public class ClassSection {
    //instance variables
     protected int crnNum = 0;
     protected String deptCode = "null";
     protected int courseNum = 0;
     protected String instructMode = "null";
     protected String meetingDays = "null";
     protected String meetingTimesStart = "null";
     protected String meetingTimesEnd = "null";
     protected int classCapacity = 0;
     protected int classEnrollment = 0;
     protected int instructorID = 0;
     protected ArrayList<StudentEnrollee> students = new ArrayList<StudentEnrollee>();

    //constructors
        public ClassSection(int crnNum, String deptCode, int courseNum, String instructMode, String meetingDays,
                String meetingTimesStart, String meetingTimesEnd, int classCapacity, int classEnrollment,
                int instructorID) {
            super();
            this.crnNum = crnNum;
            this.deptCode = deptCode;
            this.courseNum = courseNum;
            this.instructMode = instructMode;
            this.meetingDays = meetingDays;
            this.meetingTimesStart = meetingTimesStart;
            this.meetingTimesEnd = meetingTimesEnd;
            this.classCapacity = classCapacity;
            this.classEnrollment = classEnrollment;
            this.instructorID = instructorID;
        }

    public ClassSection() {
        super();
        this.crnNum = 0;
        this.deptCode = "";
        this.courseNum = 0;
        this.instructMode = "";
        this.meetingDays = "";
        this.meetingTimesStart = "";
        this.meetingTimesEnd = "";
        this.classCapacity = 0;
        this.classEnrollment = 0;
        this.instructorID = 0;
    }

    //getters and setters
        public void getStudents() {
            this.students.forEach(System.out::println);
        }

        public int getStudentIDByIndex(int index) {
            return this.students.get(index).getStudentID();
        }

        public void addStudent(StudentEnrollee student) {
            this.students.add(student);
        }

        public void removeStudent(int removalIndex) {
            this.students.remove(removalIndex);
        }

        public void changeAddStudentGrade(int studentIndex, int studentGrade) {
            this.students.get(studentIndex).setStudentGrade(studentGrade);
        }

        public int getCrnNum() {
            return crnNum;
        }

        public void setCrnNum(int crnNum) {
            this.crnNum = crnNum;
        }
        public String getDeptCode() {
            return deptCode;
        }
        public void setDeptCode(String deptCode) {
            this.deptCode = deptCode;
        }
        public int getCourseNum() {
            return courseNum;
        }
        public void setCourseNum(int courseNum) {
            this.courseNum = courseNum;
        }
        public String getInstructMode() {
            return instructMode;
        }
        public void setInstructMode(String instructMode) {
            this.instructMode = instructMode;
        }
        public String getMeetingDays() {
            return meetingDays;
        }
        public void setMeetingDays(String meetingDays) {
            this.meetingDays = meetingDays;
        }

        public String getMeetingTimesStart() {
            return meetingTimesStart;
        }

        public void setMeetingTimesStart(String meetingTimesStart) {
            this.meetingTimesStart = meetingTimesStart;
        }

        public String getMeetingTimesEnd() {
            return meetingTimesEnd;
        }

        public void setMeetingTimesEnd(String meetingTimesEnd) {
            this.meetingTimesEnd = meetingTimesEnd;
        }

        public int getClassCapacity() {
            return classCapacity;
        }
        public void setClassCapacity(int classCapacity) {
            this.classCapacity = classCapacity;
        }
        public int getClassEnrollment() {
            return classEnrollment;
        }
        public void setClassEnrollment(int classEnrollment) {
            this.classEnrollment = classEnrollment;
        }
        public int getInstructorID() {
            return instructorID;
        }
        public void setInstructorID(int instructorID) {
            this.instructorID = instructorID;
        }

        //mutators
        @Override
        public String toString() {
            return String.format("Crn Number: %20s \nDept Code: %20s \nInstruction Mode: %20s"
                    + " \nCourse Number: %20s \nClass Capacity: %20s \nClass Enrollment: %20s"
                    + " \nMeeting Days: %20s \nMeeting Times: %8$20s - %9$2s \nInstructor ID: %10$20s \n" + Arrays.toString(students.toArray()).replace("[", "").replace(", S","S").replace("]", "").trim(),
                    crnNum, deptCode, instructMode, courseNum, classCapacity, classEnrollment, meetingDays,
                    meetingTimesStart, meetingTimesEnd, instructorID);
        }

}

The student enrollee class (where the objects in the arraylist are from):

public class StudentEnrollee {
    protected int studentID = 0;
    protected int studentGrade = 0;

    public StudentEnrollee() {
        super();
        studentID = 0;
        studentGrade = 0;
    }

    public StudentEnrollee(int studentID, int studentGrade) {
        super();
        this.studentID = studentID;
        this.studentGrade = studentGrade;
    }

    //setters & getters
    public int getStudentID() {
        return studentID;
    }
    public void setStudentID(int studentID) {
        this.studentID = studentID;
    }
    public int getStudentGrade() {
        return studentGrade;
    }
    public void setStudentGrade(int studentGrade) {
        this.studentGrade = studentGrade;
    }

    @Override
    public String toString() {
        return String.format("Student ID: %20s  \nStudent Grade: %20s \n", studentID, studentGrade);
    }

}

The intchecker and yesNoBool methods are just error checking and confirmation functions, but here they are just in case:

  public static int intChecker(String object) {
    boolean correctInput = false;
    int userInput = 0;

    while (!correctInput) {
        try {
            userInput = scanner.nextInt();
            correctInput = true;
        } catch(InputMismatchException e) {
            System.out.println("I'm sorry, that doesn't seem to be a number");
            System.out.println("Please enter " +object);
            scanner.next();
        }
    }

    return userInput;
}

  public static boolean yesNoBool() {
      String yesNo = "";
      boolean yesNoBool = false;
      System.out.println("Please enter Y/N");
        yesNo = scanner.next();
      while ((!yesNo.equalsIgnoreCase("n") && !yesNo.equalsIgnoreCase("y"))){
            System.out.println("I'm sorry, please enter Y/N");
                yesNo = scanner.next();
        }
      if (yesNo.equalsIgnoreCase("y")) {
          yesNoBool = true;
      } else if (yesNo.equalsIgnoreCase("n")) {
          yesNoBool = false;
      }

      return yesNoBool;
  }

Body:
Once you found the match you have to break the loop, otherwise studentIndex gets overwritten for rest of the records for which loop iterating. Also you don't need if(studentIdTest != studentID) just else is also work same.

Add Break in loop in idFinder method as follows:

for (int i = 0; i < classOne.students.size(); i++) {
      int studentIdTest = classOne.students.get(i).getStudentID();
        if (studentIdTest == studentID) {
            studentIndex = i;
            break;
        } else{
            studentIndex = -1;
        }
  }

Suggestion: you can intialize studentIndex with -1 instead of setting it in each iteration where match not found.

I hope this will solve your problem.


问:
How to print call responce in Log message into json format
I Used retrofit 2.0 for server calls becaue consuming json and sending json. I am getting return responce with status code. but, my values are not inserted into server. i think my json data wrong. but, how can I print our client side json means Callrespose in Log.d(). I tried but no solution.
Main.java :

```<code> ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
        UserDTO userDTO=new UserDTO();
        userDTO.setUserid(userId);
        userDTO.setFile(file);
        userDTO.setUsers(adapter.usersList);

       Call<UserDTO> response = getResponse.ShareFiles(userDTO);

        Log.d("Shared Files : ",userDTO.toString());

        response.enqueue(new Callback<UserDTO>() {
            @Override
            public void onResponse(Call<UserDTO> call, Response<UserDTO> response) {
                Log.d("Shared Friends Responce call : ", String.valueOf(call.isExecuted())+"\n"+call.toString()+"\n"+call.clone());

                Log.d("Shared Friends Responce : ",response.message()+" "+response.code());

            }

            @Override
            public void onFailure(Call<UserDTO> call, Throwable t) {
                Log.d("Shared Friends Error : ",t.getMessage());
            }
        });
</code>```

API Config:

```<code>public class AppConfig {
private static String BASE_URL = "http://104.236.67.117:8000/";
    static Retrofit getRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(AppConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
}
</code>```

答:
Find the solution

Step 1:
   OK HTTP Add dependencies in Build.gradle

```<code>    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
</code>```

Step 2: In Appconfig

```<code> HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(logging); // this is for log interceptor
    Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(httpClient.build())
    .build();
</code>```

Body:
I Used retrofit 2.0 for server calls becaue consuming json and sending json. I am getting return responce with status code. but, my values are not inserted into server. i think my json data wrong. but, how can I print our client side json means Callrespose in Log.d(). I tried but no solution.
Main.java :

 ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
        UserDTO userDTO=new UserDTO();
        userDTO.setUserid(userId);
        userDTO.setFile(file);
        userDTO.setUsers(adapter.usersList);

       Call<UserDTO> response = getResponse.ShareFiles(userDTO);

        Log.d("Shared Files : ",userDTO.toString());

        response.enqueue(new Callback<UserDTO>() {
            @Override
            public void onResponse(Call<UserDTO> call, Response<UserDTO> response) {
                Log.d("Shared Friends Responce call : ", String.valueOf(call.isExecuted())+"\n"+call.toString()+"\n"+call.clone());

                Log.d("Shared Friends Responce : ",response.message()+" "+response.code());

            }

            @Override
            public void onFailure(Call<UserDTO> call, Throwable t) {
                Log.d("Shared Friends Error : ",t.getMessage());
            }
        });

API Config:

public class AppConfig {
private static String BASE_URL = "http://104.236.67.117:8000/";
    static Retrofit getRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(AppConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
}

Body:
Find the solution

Step 1:
   OK HTTP Add dependencies in Build.gradle

    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'

Step 2: In Appconfig

 HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
    httpClient.addInterceptor(logging); // this is for log interceptor
    Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(httpClient.build())
    .build();


问:
Applescript results to txt file
I'm trying to write an apple script that gets the unwatched TVShows and puts the filename (preferably without the full path, just "whatever.m4v") in a text file.

Here is the code I have:

```<code>tell application "iTunes"
    set watchedEpisodes to tracks of playlist "TV Shows" whose unplayed is false and played count > 0
    set unwatchedEpisodes to tracks of playlist "TV Shows" whose unplayed is true
    if (count unwatchedEpisodes) > 0 then
        set trackNames to {}
        repeat with anEpisode in unwatchedEpisodes
            set end of trackNames to ((name of anEpisode) as text) & " of show " & show of anEpisode & " Filename: " & location of anEpisode
        end repeat

        set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}

        set unwatchedTVShows to trackNames as text
        do shell script "echo " & unwatchedTVShows & " > /Volumes/Data/Media/Kodi/unwatchedTVShows.txt"

        #display dialog trackNames as text

        set AppleScript's text item delimiters to TID
    end if
end tell
</code>```

I get the following error:

```<code>error "iTunes got an error: sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file" number 2
</code>```

If I replace the "unwatchedTVShows" varible in the do shell statement like this:

```<code>do shell script "echo " & "test" & " > /Volumes/Data/Media/Kodi/unwatchedTVShows.txt"
</code>```

it works as I expect (I have a filename called "unwatchedTVShows.txt" and it contains the word "test".  I can use the "Display dialog trackNames as text" line that I currently have commented and it works fine.  What am I missing?

答:
The list of shows contains quotes and spaces. Just escape the entire list with quoted form of:

```<code>do shell script "echo " & quoted form of unwatchedTVShows & " > /Volumes/Data/Media/Kodi/unwatchedTVShows.txt"
</code>```

Title: Applescript results to txt file

Body:
I'm trying to write an apple script that gets the unwatched TVShows and puts the filename (preferably without the full path, just "whatever.m4v") in a text file.

Here is the code I have:

tell application "iTunes"
    set watchedEpisodes to tracks of playlist "TV Shows" whose unplayed is false and played count > 0
    set unwatchedEpisodes to tracks of playlist "TV Shows" whose unplayed is true
    if (count unwatchedEpisodes) > 0 then
        set trackNames to {}
        repeat with anEpisode in unwatchedEpisodes
            set end of trackNames to ((name of anEpisode) as text) & " of show " & show of anEpisode & " Filename: " & location of anEpisode
        end repeat

        set {TID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}

        set unwatchedTVShows to trackNames as text
        do shell script "echo " & unwatchedTVShows & " > /Volumes/Data/Media/Kodi/unwatchedTVShows.txt"

        #display dialog trackNames as text

        set AppleScript's text item delimiters to TID
    end if
end tell

I get the following error:

error "iTunes got an error: sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file" number 2

If I replace the "unwatchedTVShows" varible in the do shell statement like this:

do shell script "echo " & "test" & " > /Volumes/Data/Media/Kodi/unwatchedTVShows.txt"

it works as I expect (I have a filename called "unwatchedTVShows.txt" and it contains the word "test".  I can use the "Display dialog trackNames as text" line that I currently have commented and it works fine.  What am I missing?

Body:
The list of shows contains quotes and spaces. Just escape the entire list with quoted form of:

do shell script "echo " & quoted form of unwatchedTVShows & " > /Volumes/Data/Media/Kodi/unwatchedTVShows.txt"


问:
cannot able to verify the twitter details in nodejs?
I used this link  https://dev.twitter.com/apps I followed the procedure and I got the consumer key,consumer secret key,access token key,access token secret details.I put it in my code.I ran in localhost It shows  **twitter.verifyCredentials is not a function.**I enclosed the code can anyone tell me what is the problem in the code.Thanks in advance...

var twitter=require("twitter");
var tweeter = new twitter(
    {
    consumer_key:'xyz',
    consumer_secret:'abx',
    access_token_key:'asd',
    access_token_secret:'www'
});
app.get('/twitterCheck', function (req, res) {
    twitter.verifyCredentials(function (error, data)
    {
        res.send("Hello, " + data.name + ".  I am in your          twitters.");
    });
});
app.listen(8086,function()
{
    console.log("port is listen on 8086");
});```

答:
This is from node-twitter-api package. Try using node-twitter-api, This will work:

```<code>const express = require('express')
const app = express()
const twitterAPI = require('node-twitter-api');
const twitter = new twitterAPI({
    consumerKey: '*****',
    consumerSecret: '******',
});
const accessToken = "***********";
const accessTokenSecret = "***********";
const params = {};

app.get('/twitterCheck', function (req, res) {
    twitter.verifyCredentials(accessToken, accessTokenSecret, params, function (error, data, response) {
        if (error) {
            console.log(error);
        } else {
            console.log(data["screen_name"]);
        }
    });
});
app.listen(8086, function () {
    console.log("port is listen on 8086");
});
</code>```

Body:
This is from node-twitter-api package. Try using node-twitter-api, This will work:

const express = require('express')
const app = express()
const twitterAPI = require('node-twitter-api');
const twitter = new twitterAPI({
    consumerKey: '*****',
    consumerSecret: '******',
});
const accessToken = "***********";
const accessTokenSecret = "***********";
const params = {};

app.get('/twitterCheck', function (req, res) {
    twitter.verifyCredentials(accessToken, accessTokenSecret, params, function (error, data, response) {
        if (error) {
            console.log(error);
        } else {
            console.log(data["screen_name"]);
        }
    });
});
app.listen(8086, function () {
    console.log("port is listen on 8086");
});


问:
Get array within an object
I am trying to get the array value from the object I created but seems like that obj.item is not working to me. It always saying undefined here's my code::

```<code>$.each(componentSentenceArray, function(index,item) {
          conole.log(item.item_name)

});
</code>```

and here is my object

```<code>ingredient:
Array(3)
0:{item_name: "Albenza", uom_code: "", uom_desc: "", amount: ""}
1:{item_name: "Baclofen", uom_code: "", uom_desc: "", amount: ""}
2:{item_name: "Lasix", uom_code: "", uom_desc: "", amount: ""}

main_component:
Array(1)
0 :{item_name: "Lasix", uom_code: "", uom_desc: "", amount: ""}
</code>```

答:
```<code>$.each(componentSentenceArray, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log('index', data)
    })
})
</code>```

this will work!

Title: Get array within an object

Body:
I am trying to get the array value from the object I created but seems like that obj.item is not working to me. It always saying undefined here's my code::

$.each(componentSentenceArray, function(index,item) {
          conole.log(item.item_name)

});

and here is my object

ingredient:
Array(3)
0:{item_name: "Albenza", uom_code: "", uom_desc: "", amount: ""}
1:{item_name: "Baclofen", uom_code: "", uom_desc: "", amount: ""}
2:{item_name: "Lasix", uom_code: "", uom_desc: "", amount: ""}

main_component:
Array(1)
0 :{item_name: "Lasix", uom_code: "", uom_desc: "", amount: ""}

Body:
$.each(componentSentenceArray, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log('index', data)
    })
})

this will work!


问:
getScript function working but doesn't get some of the css
So every time I am loading my getScript function on ajax success some of the js are working some of it are not. but if i'm loading trying to load it on my footer.php it's working. but I need to load it dynamically since I am using ajax to load my pages and I need my js files to load everytime I change content and also it looks like my .js files aren't getting the css from the page. Here's my code to load the scripts.

JS

```<code>var base_url = window.location.origin;

if (window.location.pathname.split('/')[1] === 'music' ||
  window.location.pathname.split('/')[1] === 'musicsystem')
  base_url = base_url + '/' + window.location.pathname.split('/')[1];
$(document).ready(function() {
  $.ajax({
    async: false,
    url: base_url + '/dashboard/index',
    success: function(data) {
      var getScript = jQuery.getScript;
      jQuery.getScript = function(resources, callback) {
        var length = resources.length,
          handler = function() {
            counter++;
          },
          deferreds = [],
          counter = 0,
          idx = 0;

        for (idx; idx < length; idx++) {
          deferreds.push(getScript(resources[idx], handler));
        }

        jQuery.when.apply(null, deferreds).then(function() {
          callback && callback();
        });
      };

      var scripts = [
        base_url + "/assets/bower_components/jquery/dist/jquery.min.js",
        base_url + "/assets/bower_components/bootstrap/dist/js/bootstrap.min.js",
        base_url + "/assets/bower_components/jquery-ui/jquery-ui.min.js",
        base_url + "/assets/bower_components/datatables.net/js/jquery.dataTables.min.js",
        base_url + "/assets/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js",
        base_url + "/assets/bower_components/jquery-sparkline/dist/jquery.sparkline.min.js",
        base_url + "/assets/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js",
        base_url + "/assets/plugins/jvectormap/jquery-jvectormap-world-mill-en.js",
        base_url + "/assets/bower_components/jquery-knob/dist/jquery.knob.min.js",
        base_url + "/assets/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js",
        base_url + "/assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js",
        base_url + "/assets/bower_components/jquery-slimscroll/jquery.slimscroll.min.js",
        base_url + "/assets/bower_components/fastclick/lib/fastclick.js",
        base_url + "/assets/dist/js/adminlte.min.js",
        base_url + "/assets/dist/js/pages/dashboard.js",
        base_url + "/assets/plugins/iCheck/icheck.min.js",
        base_url + "/assets/dist/js/demo.js",
        base_url + "/assets/js/dataTables.colReorder.min.js",
        base_url + "/assets/dist/js/clipboard.js",
        base_url + "/assets/js/audio.min.js",
        base_url + "/assets/js/config.js",
        base_url + "/assets/js/dropzone.js",
        base_url + "/assets/js/howler.js",
        base_url + "/assets/js/upload.js",
        base_url + "/assets/js/player.js",
        base_url + "/assets/js/songdraganddrop.js",
        base_url + "/assets/js/pitching.js",
        base_url + "/assets/js/share.js",
        base_url + "/assets/js/alertify.js",
        base_url + "/assets/bower_components/select2/dist/js/select2.full.min.js",
        base_url + "/assets/js/newscript.js"
      ];

      $.getScript(scripts, function(data, textStatus) {
        $('#inside').html(data);
      });
    }
  });
});
</code>```

答:
Maybe the following will work better, even though it's not documented the function getScript of jQuery returns a promise, you can use that. $.ajax returns a promise too so you can use that.

var base_url = window.location.origin;

```<code>if (window.location.pathname.split('/')[1] === 'music' ||
  window.location.pathname.split('/')[1] === 'musicsystem')
  base_url = base_url + '/' + window.location.pathname.split('/')[1];

const getScripts =
  resources => {
    return jQuery.when.apply(
      null
      ,resources.map(
        resource =>
          $.getScript(base_url + resource)
        )
    )
;

}
$(document).ready(function() {
  $.ajax({
    //async: false,//are you kidding? async false is still a thing???? I assume you'd like someone to hire you at some point in time right?
    url: base_url + '/dashboard/index'
  })
  .then(
    data => {
      const scripts = [
        //are you sure you'd want to load all the scripts?
        //I'm pretty sure you don't need to load your libraries again
        //would be simpler to write a js function that will initialize
        //the new content that's on the page instead of this
        "/assets/bower_components/jquery/dist/jquery.min.js",
        "/assets/bower_components/bootstrap/dist/js/bootstrap.min.js",
        "/assets/bower_components/jquery-ui/jquery-ui.min.js",
        "/assets/bower_components/datatables.net/js/jquery.dataTables.min.js",
        "/assets/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js",
        "/assets/bower_components/jquery-sparkline/dist/jquery.sparkline.min.js",
        "/assets/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js",
        "/assets/plugins/jvectormap/jquery-jvectormap-world-mill-en.js",
        "/assets/bower_components/jquery-knob/dist/jquery.knob.min.js",
        "/assets/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js",
        "/assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js",
        "/assets/bower_components/jquery-slimscroll/jquery.slimscroll.min.js",
        "/assets/bower_components/fastclick/lib/fastclick.js",
        "/assets/dist/js/adminlte.min.js",
        "/assets/dist/js/pages/dashboard.js",
        "/assets/plugins/iCheck/icheck.min.js",
        "/assets/dist/js/demo.js",
        "/assets/js/dataTables.colReorder.min.js",
        "/assets/dist/js/clipboard.js",
        "/assets/js/audio.min.js",
        "/assets/js/config.js",
        "/assets/js/dropzone.js",
        "/assets/js/howler.js",
        "/assets/js/upload.js",
        "/assets/js/player.js",
        "/assets/js/songdraganddrop.js",
        "/assets/js/pitching.js",
        "/assets/js/share.js",
        "/assets/js/alertify.js",
        "/assets/bower_components/select2/dist/js/select2.full.min.js",
        "/assets/js/newscript.js"
      ];
      $('#inside').html(data);//set the html before loading the scripts
      return getScripts(scripts)
      .then(x=>data);//return data after getscript is done
    }
  )
  .then(
    undefined
    ,err => console.warn("Failed:",err)//handle the error
  );

});
</code>```

Body:
So every time I am loading my getScript function on ajax success some of the js are working some of it are not. but if i'm loading trying to load it on my footer.php it's working. but I need to load it dynamically since I am using ajax to load my pages and I need my js files to load everytime I change content and also it looks like my .js files aren't getting the css from the page. Here's my code to load the scripts.

JS

var base_url = window.location.origin;

if (window.location.pathname.split('/')[1] === 'music' ||
  window.location.pathname.split('/')[1] === 'musicsystem')
  base_url = base_url + '/' + window.location.pathname.split('/')[1];
$(document).ready(function() {
  $.ajax({
    async: false,
    url: base_url + '/dashboard/index',
    success: function(data) {
      var getScript = jQuery.getScript;
      jQuery.getScript = function(resources, callback) {
        var length = resources.length,
          handler = function() {
            counter++;
          },
          deferreds = [],
          counter = 0,
          idx = 0;

        for (idx; idx < length; idx++) {
          deferreds.push(getScript(resources[idx], handler));
        }

        jQuery.when.apply(null, deferreds).then(function() {
          callback && callback();
        });
      };

      var scripts = [
        base_url + "/assets/bower_components/jquery/dist/jquery.min.js",
        base_url + "/assets/bower_components/bootstrap/dist/js/bootstrap.min.js",
        base_url + "/assets/bower_components/jquery-ui/jquery-ui.min.js",
        base_url + "/assets/bower_components/datatables.net/js/jquery.dataTables.min.js",
        base_url + "/assets/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js",
        base_url + "/assets/bower_components/jquery-sparkline/dist/jquery.sparkline.min.js",
        base_url + "/assets/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js",
        base_url + "/assets/plugins/jvectormap/jquery-jvectormap-world-mill-en.js",
        base_url + "/assets/bower_components/jquery-knob/dist/jquery.knob.min.js",
        base_url + "/assets/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js",
        base_url + "/assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js",
        base_url + "/assets/bower_components/jquery-slimscroll/jquery.slimscroll.min.js",
        base_url + "/assets/bower_components/fastclick/lib/fastclick.js",
        base_url + "/assets/dist/js/adminlte.min.js",
        base_url + "/assets/dist/js/pages/dashboard.js",
        base_url + "/assets/plugins/iCheck/icheck.min.js",
        base_url + "/assets/dist/js/demo.js",
        base_url + "/assets/js/dataTables.colReorder.min.js",
        base_url + "/assets/dist/js/clipboard.js",
        base_url + "/assets/js/audio.min.js",
        base_url + "/assets/js/config.js",
        base_url + "/assets/js/dropzone.js",
        base_url + "/assets/js/howler.js",
        base_url + "/assets/js/upload.js",
        base_url + "/assets/js/player.js",
        base_url + "/assets/js/songdraganddrop.js",
        base_url + "/assets/js/pitching.js",
        base_url + "/assets/js/share.js",
        base_url + "/assets/js/alertify.js",
        base_url + "/assets/bower_components/select2/dist/js/select2.full.min.js",
        base_url + "/assets/js/newscript.js"
      ];

      $.getScript(scripts, function(data, textStatus) {
        $('#inside').html(data);
      });
    }
  });
});

Body:
Maybe the following will work better, even though it's not documented the function getScript of jQuery returns a promise, you can use that. $.ajax returns a promise too so you can use that.

var base_url = window.location.origin;

if (window.location.pathname.split('/')[1] === 'music' ||
  window.location.pathname.split('/')[1] === 'musicsystem')
  base_url = base_url + '/' + window.location.pathname.split('/')[1];

const getScripts =
  resources => {
    return jQuery.when.apply(
      null
      ,resources.map(
        resource =>
          $.getScript(base_url + resource)
        )
    )
;

}
$(document).ready(function() {
  $.ajax({
    //async: false,//are you kidding? async false is still a thing???? I assume you'd like someone to hire you at some point in time right?
    url: base_url + '/dashboard/index'
  })
  .then(
    data => {
      const scripts = [
        //are you sure you'd want to load all the scripts?
        //I'm pretty sure you don't need to load your libraries again
        //would be simpler to write a js function that will initialize
        //the new content that's on the page instead of this
        "/assets/bower_components/jquery/dist/jquery.min.js",
        "/assets/bower_components/bootstrap/dist/js/bootstrap.min.js",
        "/assets/bower_components/jquery-ui/jquery-ui.min.js",
        "/assets/bower_components/datatables.net/js/jquery.dataTables.min.js",
        "/assets/bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js",
        "/assets/bower_components/jquery-sparkline/dist/jquery.sparkline.min.js",
        "/assets/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js",
        "/assets/plugins/jvectormap/jquery-jvectormap-world-mill-en.js",
        "/assets/bower_components/jquery-knob/dist/jquery.knob.min.js",
        "/assets/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js",
        "/assets/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js",
        "/assets/bower_components/jquery-slimscroll/jquery.slimscroll.min.js",
        "/assets/bower_components/fastclick/lib/fastclick.js",
        "/assets/dist/js/adminlte.min.js",
        "/assets/dist/js/pages/dashboard.js",
        "/assets/plugins/iCheck/icheck.min.js",
        "/assets/dist/js/demo.js",
        "/assets/js/dataTables.colReorder.min.js",
        "/assets/dist/js/clipboard.js",
        "/assets/js/audio.min.js",
        "/assets/js/config.js",
        "/assets/js/dropzone.js",
        "/assets/js/howler.js",
        "/assets/js/upload.js",
        "/assets/js/player.js",
        "/assets/js/songdraganddrop.js",
        "/assets/js/pitching.js",
        "/assets/js/share.js",
        "/assets/js/alertify.js",
        "/assets/bower_components/select2/dist/js/select2.full.min.js",
        "/assets/js/newscript.js"
      ];
      $('#inside').html(data);//set the html before loading the scripts
      return getScripts(scripts)
      .then(x=>data);//return data after getscript is done
    }
  )
  .then(
    undefined
    ,err => console.warn("Failed:",err)//handle the error
  );

});


问:
Render multilpe times - Double render in rails
How to avoid this double render issue, i have been trying to replicate but couldn't. So is there any issue with this below code?

```<code>def check_count
  assign_values_from_params
  if count >= failed_count
    render partial: params[:view_name], layout: false and return
  else
    render text: 'works' and return
  end
end

def assign_values_from_params
  # code
  # code
  # code
  if @date.blank?
    redirect_to main_index_path and return
  end

  if @counted_obj != 5
    # call one function
  end
end
</code>```

Also should i try something this way Double render error rails ?

答:
According to me first, check whether any render is being called. As going through your code it is not showing but maybe internally it is being called. So You can call performed? in your controller to check if render  was already called:

```<code>performed?               # => false
render partial: params[:view_name], layout: false
performed?               # => true
</code>```

If calling performed? says true for the first time then you have to check your code.

Body:
How to avoid this double render issue, i have been trying to replicate but couldn't. So is there any issue with this below code?

def check_count
  assign_values_from_params
  if count >= failed_count
    render partial: params[:view_name], layout: false and return
  else
    render text: 'works' and return
  end
end

def assign_values_from_params
  # code
  # code
  # code
  if @date.blank?
    redirect_to main_index_path and return
  end

  if @counted_obj != 5
    # call one function
  end
end

Also should i try something this way Double render error rails ?

Body:
According to me first, check whether any render is being called. As going through your code it is not showing but maybe internally it is being called. So You can call performed? in your controller to check if render  was already called:

performed?               # => false
render partial: params[:view_name], layout: false
performed?               # => true

If calling performed? says true for the first time then you have to check your code.


问:
Which unit does JTS LineString.getLength() use
I'm trying to figure out which unit JTS LineString.getLength() return.

for example:

```<code>LineString foo = (initialize line string somehow)
foo.getLength() -> 7.025667228118838E-4
</code>```

Are these Kilometers?, Meters?, Feet?

答: It depends in which unit your coordinate geometries are expressed. If your coordinates are in meters, the perimeter will also be in meters.</p>

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to figure out which unit JTS LineString.getLength() return.

for example:

LineString foo = (initialize line string somehow)
foo.getLength() -> 7.025667228118838E-4

Are these Kilometers?, Meters?, Feet?


问:
Thymeleaf spring loop n item
I am quite new to spring framework.

I try to iterate 10 item in a list. I use thymeleaf template.

This is my code for ;

```<code><li th:each="item,iter : ${list}">
        <span th:if="${iter.index} <=10  " th:text="${item}"/>
</li>
</code>```

This code is not working and I could not find a way to run the code.

Thanks for your interest.

答: This <span th:if="${iter.index} <=10  " th:text="${item}"/> not the correct Thymeleaf syntax. The complete expression has to be within the ${} like ${iter.index <= 10 }

Title: Thymeleaf spring loop n item

Body:
I am quite new to spring framework.

I try to iterate 10 item in a list. I use thymeleaf template.

This is my code for ;

        <span th:if="${iter.index} <=10  " th:text="${item}"/>

This code is not working and I could not find a way to run the code.

Thanks for your interest.


问:
Making my integer go up by 1 every second
I'm extremely new to c# and I'm wondering how I can make a basic timer that counts up by one using an integer. So far I only have

```<code>int timer = 0;
int max = 10000;

        while ( timer < max )
        {
          timer += 1;

        }
</code>```

I'm assuming this will automatically boost the timer straight to 1000 because there's no speed set. I'm wondering how I can set a speed to this. Thank you.

答:
You can use  System.Threading.Thread.Sleep(1000);  But the whole system is stopping. another solution is timer. Timer = new Timer();</p>

```<code>int timer = 0;
int max = 10000;

        while ( timer < max )
        {
          timer += 1;
          System.Threading.Thread.Sleep(1000);
        }
</code>```

Body:
I'm extremely new to c# and I'm wondering how I can make a basic timer that counts up by one using an integer. So far I only have

int timer = 0;
int max = 10000;

        while ( timer < max )
        {
          timer += 1;

        }

I'm assuming this will automatically boost the timer straight to 1000 because there's no speed set. I'm wondering how I can set a speed to this. Thank you.

Body:
You can use  System.Threading.Thread.Sleep(1000);  But the whole system is stopping. another solution is timer. Timer = new Timer();

int timer = 0;
int max = 10000;

        while ( timer < max )
        {
          timer += 1;
          System.Threading.Thread.Sleep(1000);
        }


问:
Angularjs rootscope data loss in refreshing
i got a situation in angularjs1.x
when i am save a value in   $rootScope after pass the next page/router

The $rootScope value is lost in  Refresh f5/reload (window reload)

without using localStorage

答:
You can avoid that by using localStorage to store your data.

$rootScope.data = localStorage.data; // get data from localStorage and assign it to rootScope
var data = {a : 1, b: 2}; // update your data
localStorage.data = data; // set it in localStorage
$rootScope.data = data;```

Note You'll need to update your localStroage data every time you update $rootScope.data .

Body:
You can avoid that by using localStorage to store your data.

$rootScope.data = localStorage.data; // get data from localStorage and assign it to rootScope
var data = {a : 1, b: 2}; // update your data
localStorage.data = data; // set it in localStorage
$rootScope.data = data;

Note You'll need to update your localStroage data every time you update $rootScope.data .


问:
ValueError: operands could not be broadcast together with shapes (5,) (30,)
I am trying to merge arrays like this:

If:

```<code>a = [1.2, 1, 3, 4]
b = [0.0 , 0.0]
c = [0.0 , 0.0]
a = a + b + c
</code>```

Then the result should be:

```<code>[0.0 , 0.0 , 1.2 , 1 ,3 ,4 , 0.0 ,0.0]
</code>```

what I do is that extract histogram of array
  and merge it with normal array.

```<code>x1, bins, patch = plt.hist(array1, bins = round(max(array1) - min(array1)))
x1 = b + x1 + c

but the form of x1 is
x1 = [  2.   0.   0.   1.   0.   2.   5.   0.   1.   1.   0.   1.   5.]
</code>```

and maybe that cause the error like this

ValueError: operands could not be broadcast together with shapes (5,) (30,)

please help me.
  I don't know what to do

答:
NumPy arrays behave differently with the + operator: with Python lists, adding lists together means concatenation (which is what you wanted).

However, in NumPy, adding arrays together means element-wise addition (and if the dimensions don't match, broadcasting first).

To get what you wanted, use np.concatenate, e.g.

```<code>import numpy as np
np.concatenate((b,x1,c))
</code>```

Body:
I am trying to merge arrays like this:

If:

a = [1.2, 1, 3, 4]
b = [0.0 , 0.0]
c = [0.0 , 0.0]
a = a + b + c

Then the result should be:

[0.0 , 0.0 , 1.2 , 1 ,3 ,4 , 0.0 ,0.0]

what I do is that extract histogram of array
  and merge it with normal array.

x1, bins, patch = plt.hist(array1, bins = round(max(array1) - min(array1)))
x1 = b + x1 + c

but the form of x1 is
x1 = [  2.   0.   0.   1.   0.   2.   5.   0.   1.   1.   0.   1.   5.]

and maybe that cause the error like this

ValueError: operands could not be broadcast together with shapes (5,) (30,)

please help me.
  I don't know what to do

Body:
NumPy arrays behave differently with the + operator: with Python lists, adding lists together means concatenation (which is what you wanted).

However, in NumPy, adding arrays together means element-wise addition (and if the dimensions don't match, broadcasting first).

To get what you wanted, use np.concatenate, e.g.

import numpy as np
np.concatenate((b,x1,c))


问:
I need to include a triangle as background on a div using css.

Need to add the triangle to the top right corner of a div and make text flow over it. Can we achieve this with plain css without using an image?

答:
you can try adding pseudo element to the box, and then using borders create triangle, check below snippet:

.box{
  width: 500px;
  height: 300px;
  background: #233058;
  padding: 20px 40px;
  position: relative;
  z-index:-1;
}

.box:before{
  content: '';
  width: 0px;
  height: 0px;
  background: transparent;
  position: absolute;
  right: 0px;
  top: 0px;
  display: block;
  z-index: 100;
  border-left: 80px solid transparent;
  border-bottom: 150px solid transparent;
  border-right: 150px solid rgba(70, 88, 158, .5);
  border-top: 80px solid rgba(70, 88, 158, .5);
  z-index: 0;
}

h1, P{
  color: white;
  font-family: Arial;
  font-weight: lighter;
  position: relative;
  z-index: 999;
}

p{
 font: 1.5em sans-serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box">
  <h1>Request and instance</h1>
  <p>Need to add the triangle to the top right corner of a div and make text flow over it. </p>
</div></code>```

Body:
you can try adding pseudo element to the box, and then using borders create triangle, check below snippet:

.box{
  width: 500px;
  height: 300px;
  background: #233058;
  padding: 20px 40px;
  position: relative;
  z-index:-1;
}

.box:before{
  content: '';
  width: 0px;
  height: 0px;
  background: transparent;
  position: absolute;
  right: 0px;
  top: 0px;
  display: block;
  z-index: 100;
  border-left: 80px solid transparent;
  border-bottom: 150px solid transparent;
  border-right: 150px solid rgba(70, 88, 158, .5);
  border-top: 80px solid rgba(70, 88, 158, .5);
  z-index: 0;
}

h1, P{
  color: white;
  font-family: Arial;
  font-weight: lighter;
  position: relative;
  z-index: 999;
}

p{
 font: 1.5em sans-serif;
}

<div class="box">
  <h1>Request and instance</h1>
  <p>Need to add the triangle to the top right corner of a div and make text flow over it. </p>
</div>


答:
There are number of options:

while + Thread.Sleep in synchronous code

while + Task.Delay in asynchronous code

System.Threading.Timer in synchronous code

First one is the inefficient one from resources point, because it blocks calling thread.

Second one actually uses third one inside, and is intended for TAP code.

There also are:

System.Timers.Timer, but you should avoid it since it's a IComponent API wrapper over System.Threading.Timer and just adds some IComponent-specific trash in your code;

UI frameworks timers like DispatcherTimer, but they are not general purpose timers and must be used with particular UI framework.

Title: Making my integer go up by 1 every second


答:
```<code>$.each(componentSentenceArray, function(index,item) {
     $.each(item, function(index, arrayItem) {
       console.log(arrayItem.item_name)
     })
});
</code>```

This should help

Title: Get array within an object

Body:
$.each(componentSentenceArray, function(index,item) {
     $.each(item, function(index, arrayItem) {
       console.log(arrayItem.item_name)
     })
});

This should help


问:
ArrayIndexOutOfBoundsException when read from buffer
My app send data (string or bytes) to another app copy via Bluetooth.
I try to send big text or bytes[] and get this error:

```<code>FATAL EXCEPTION: Thread-8297
        java.lang.ArrayIndexOutOfBoundsException: length=1024; index=1024
            at com.ramimartin.multibluetooth.bluetooth.BluetoothRunnable.run(BluetoothRunnable.java:147)
            at java.lang.Thread.run(Thread.java:841)
</code>```

So, why?
Code from line

BluetoothRunnable.java:147

is:

```<code>while(bytesRead == bufferSize && buffer[bufferSize] != 0) {
</code>```

Full code:

```<code>        int bufferSize = 1024;
        int bytesRead;
        byte[] buffer = new byte[bufferSize];
                    try {
                        if(this.mInputStream != null) {
                            bytesRead = this.mInputStream.read(buffer);
                            ByteBuffer bbuf = ByteBuffer.allocate(bytesRead);
                            if(bytesRead != -1) {
                                while(bytesRead == bufferSize && buffer[bufferSize] != 0) {
                                    bbuf.put(buffer, 0, bytesRead);
                                    if(this.mInputStream == null) {
                                        return;
                                    }

                                    bytesRead = this.mInputStream.read(buffer);
                                }

                                bbuf.put(buffer, 0, bytesRead);
                            }

                            EventBus.getDefault().post(new BluetoothCommunicatorBytes(bbuf.array()));
                            continue;
                        }
                    } catch (IOException var8) {
                        Log.e(TAG, "===> Error Received Bytes IOException  : " + var8.getMessage());
                        continue;
                    }
</code>```

答:
This should be:

```<code>while(bytesRead == bufferSize && buffer[bufferSize - 1] != 0)
</code>```

Also there might be times when bufferSize is than 1.

And the way to read an array is:

```<code>int arr[] = new int[10];
</code>```

The max index in the above case will be:

```<code>arr[9]
</code>```

as index starts from 0.

Body:
My app send data (string or bytes) to another app copy via Bluetooth.
I try to send big text or bytes[] and get this error:

FATAL EXCEPTION: Thread-8297
        java.lang.ArrayIndexOutOfBoundsException: length=1024; index=1024
            at com.ramimartin.multibluetooth.bluetooth.BluetoothRunnable.run(BluetoothRunnable.java:147)
            at java.lang.Thread.run(Thread.java:841)

So, why?
Code from line

BluetoothRunnable.java:147

is:

while(bytesRead == bufferSize && buffer[bufferSize] != 0) {

Full code:

        int bufferSize = 1024;
        int bytesRead;
        byte[] buffer = new byte[bufferSize];
                    try {
                        if(this.mInputStream != null) {
                            bytesRead = this.mInputStream.read(buffer);
                            ByteBuffer bbuf = ByteBuffer.allocate(bytesRead);
                            if(bytesRead != -1) {
                                while(bytesRead == bufferSize && buffer[bufferSize] != 0) {
                                    bbuf.put(buffer, 0, bytesRead);
                                    if(this.mInputStream == null) {
                                        return;
                                    }

                                    bytesRead = this.mInputStream.read(buffer);
                                }

                                bbuf.put(buffer, 0, bytesRead);
                            }

                            EventBus.getDefault().post(new BluetoothCommunicatorBytes(bbuf.array()));
                            continue;
                        }
                    } catch (IOException var8) {
                        Log.e(TAG, "===> Error Received Bytes IOException  : " + var8.getMessage());
                        continue;
                    }

Body:
This should be:

while(bytesRead == bufferSize && buffer[bufferSize - 1] != 0)

Also there might be times when bufferSize is than 1.

And the way to read an array is:

int arr[] = new int[10];

The max index in the above case will be:

arr[9]

as index starts from 0.


问:
Replace bookmark text in Word file using Open XML SDK
I assume v2.0 is better... they have some nice "how to:..." examples but bookmarks don't seem to act as obviously as say a Table... a bookmark is defined by two XML elements BookmarkStart & BookmarkEnd. We have some templates with text in as bookmarks and we simply want to replace bookmarks with some other text... no weird formatting is going on but how do I select/replace bookmark text?

答:
Here is how i do it and VB to add/replace text between bookmarkStart and BookmarkEnd.</p>

```<code><w:bookmarkStart w:name="forbund_kort" w:id="0" />
        - <w:r>
          <w:t>forbund_kort</w:t>
          </w:r>
<w:bookmarkEnd w:id="0" />

Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Wordprocessing

    Public Class PPWordDocx

        Public Sub ChangeBookmarks(ByVal path As String)
            Try
                Dim doc As WordprocessingDocument = WordprocessingDocument.Open(path, True)
                 'Read the entire document contents using the GetStream method:

                Dim bookmarkMap As IDictionary(Of String, BookmarkStart) = New Dictionary(Of String, BookmarkStart)()
                Dim bs As BookmarkStart
                For Each bs In doc.MainDocumentPart.RootElement.Descendants(Of BookmarkStart)()
                    bookmarkMap(bs.Name) = bs
                Next
                For Each bs In bookmarkMap.Values
                    Dim bsText As DocumentFormat.OpenXml.OpenXmlElement = bs.NextSibling
                    If Not bsText Is Nothing Then
                        If TypeOf bsText Is BookmarkEnd Then
                            'Add Text element after start bookmark
                            bs.Parent.InsertAfter(New Run(New Text(bs.Name)), bs)
                        Else
                            'Change Bookmark Text
                            If TypeOf bsText Is Run Then
                                If bsText.GetFirstChild(Of Text)() Is Nothing Then
                                    bsText.InsertAt(New Text(bs.Name), 0)
                                End If
                                bsText.GetFirstChild(Of Text)().Text = bs.Name
                            End If
                        End If

                    End If
                Next
                doc.MainDocumentPart.RootElement.Save()
                doc.Close()
            Catch ex As Exception
                Throw ex
            End Try
        End Sub

    End Class
</code>```

Body:
Here is how i do it and VB to add/replace text between bookmarkStart and BookmarkEnd.

<w:bookmarkStart w:name="forbund_kort" w:id="0" />
        - <w:r>
          <w:t>forbund_kort</w:t>
          </w:r>
<w:bookmarkEnd w:id="0" />

Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Wordprocessing

    Public Class PPWordDocx

        Public Sub ChangeBookmarks(ByVal path As String)
            Try
                Dim doc As WordprocessingDocument = WordprocessingDocument.Open(path, True)
                 'Read the entire document contents using the GetStream method:

                Dim bookmarkMap As IDictionary(Of String, BookmarkStart) = New Dictionary(Of String, BookmarkStart)()
                Dim bs As BookmarkStart
                For Each bs In doc.MainDocumentPart.RootElement.Descendants(Of BookmarkStart)()
                    bookmarkMap(bs.Name) = bs
                Next
                For Each bs In bookmarkMap.Values
                    Dim bsText As DocumentFormat.OpenXml.OpenXmlElement = bs.NextSibling
                    If Not bsText Is Nothing Then
                        If TypeOf bsText Is BookmarkEnd Then
                            'Add Text element after start bookmark
                            bs.Parent.InsertAfter(New Run(New Text(bs.Name)), bs)
                        Else
                            'Change Bookmark Text
                            If TypeOf bsText Is Run Then
                                If bsText.GetFirstChild(Of Text)() Is Nothing Then
                                    bsText.InsertAt(New Text(bs.Name), 0)
                                End If
                                bsText.GetFirstChild(Of Text)().Text = bs.Name
                            End If
                        End If

                    End If
                Next
                doc.MainDocumentPart.RootElement.Save()
                doc.Close()
            Catch ex As Exception
                Throw ex
            End Try
        End Sub

    End Class


问:
Get object thymelaf
I have a for:each like this:

```<code><tbody>
    <tr th:each="bill : ${bills}" id="bill">
        <td th:text="${bill.bill_id}"></td>
        <td th:text="${bill.client.phone}"></td>
        <td th:text="${bill.date}"></td>
        <td><a href="#" class="btn btn-info btn-xs" data-toggle="modal"
    id="open-modal">Ver detalles</a></td>
    </tr>
</tbody>
</code>```

The question is how can I get the entire ${bill} to a variable in JavaScript or jQuery because I need more information. I saw the documentation and it said:

```<code> <script th:inline="javascript">
   /*<![CDATA[*/
   ...

    var user  name = /*[[${bill}]]*/ '';

    ...
   /*]]>*/
 </script>
</code>```

I have tried this on a external JavaScript file and it does not work.

答:
If you are using Thymeleaf 3, this should be enough

```<code><script th:inline="javascript">
    var user  name = [[${bill}]];
</script>
</code>```

And you have to put it in .html file because by default it process .html file. You can add it in your .html file and it will be available in the scripts included after the above code in the .html file

Title: Get object thymelaf

Body:
I have a for:each like this:

        Ver detalles

The question is how can I get the entire ${bill} to a variable in JavaScript or jQuery because I need more information. I saw the documentation and it said:

I have tried this on a external JavaScript file and it does not work.

Body:
If you are using Thymeleaf 3, this should be enough

<script th:inline="javascript">
    var user  name = [[${bill}]];
</script>

And you have to put it in .html file because by default it process .html file. You can add it in your .html file and it will be available in the scripts included after the above code in the .html file


问:
Bulk Inserting CSV file to Oracle DB using sqlloader nodeJS
I am trying to load csv file using nodeJS on oracle database.

From documentation here https://docs.oracle.com/cd/B19306_01/server.102/b14215/ldr_concepts.htm it seems to be possible to load the entire csv file and pass on to Oracle by implementing the below.

```<code>load data
infile 'example.dat'  "str '|\n'"
into table example
fields terminated by ',' optionally enclosed by '"'
(col1 char(5),
 col2 char(7))
</code>```

where data looks something like

```<code>hello,world,|
james,bond,|
</code>```

However when I implement it using oracledb library on nodeJS, it throws ORA-00900 invalid SQL statement error

The below is how I implement the query.

```<code>oracledb.getConnection(
    {
        user: userId,
        password: password,
        connectString: `(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = ${host})(PORT = ${port}))(CONNECT_DATA = (SID = ${sid})))`
    },
    function (err, connection) {
        if (err) {
            errorHandler(err);
            return;
        }
        connection.execute(
            query,
            function (err, result) {
                if (err) {
                    errorHandler(err);
                    oracleFunctions.connection.doRelease(connection, errorHandler);
                    return;
                }

                successHandler(result);
                oracleFunctions.connection.doRelease(connection, errorHandler);
            });
    });
</code>```

my query is as below

```<code>LOAD DATA
infile 'path\to\the\file.csv' "str '\n'"
INTO TABLE e1_000090000_ADS_R_PPLaps
FIELDS TERMINATED BY ',' optionally enclosed by '"'
</code>```

What am I doing wrong?

答: You are mixing the SQL*Loader utility, a separate binary provided by Oracle for data loading, with actual valid SQL syntax. You cannot just pass on SQL*Loader parameters as SQL statements, they are not! If you want to load a file via Node.js you will have to read the file, parse the contents and translate that to actual INSERT INTO statement, which is exactly what SQL*Loader does for you.

Body:
I am trying to load csv file using nodeJS on oracle database.

From documentation here https://docs.oracle.com/cd/B19306_01/server.102/b14215/ldr_concepts.htm it seems to be possible to load the entire csv file and pass on to Oracle by implementing the below.

load data
infile 'example.dat'  "str '|\n'"
into table example
fields terminated by ',' optionally enclosed by '"'
(col1 char(5),
 col2 char(7))

where data looks something like

hello,world,|
james,bond,|

However when I implement it using oracledb library on nodeJS, it throws ORA-00900 invalid SQL statement error

The below is how I implement the query.

oracledb.getConnection(
    {
        user: userId,
        password: password,
        connectString: `(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = ${host})(PORT = ${port}))(CONNECT_DATA = (SID = ${sid})))`
    },
    function (err, connection) {
        if (err) {
            errorHandler(err);
            return;
        }
        connection.execute(
            query,
            function (err, result) {
                if (err) {
                    errorHandler(err);
                    oracleFunctions.connection.doRelease(connection, errorHandler);
                    return;
                }

                successHandler(result);
                oracleFunctions.connection.doRelease(connection, errorHandler);
            });
    });

my query is as below

LOAD DATA
infile 'path\to\the\file.csv' "str '\n'"
INTO TABLE e1_000090000_ADS_R_PPLaps
FIELDS TERMINATED BY ',' optionally enclosed by '"'

What am I doing wrong?


问:
JavaScript smooth scroll - iphone
Are there any plugins or does anyone know of a good way to achieve the iPhone elastic band scroll?
working example in flash
http://www.shinedraw.com/text-effect/silverlight-3-and-flash-iphone-dragging-effect/

I'm looking to drag and scroll a div, but if it goes past a certain point it bounces back.

Thanks

答:
Once you have figured out how to scroll it, it's very simple in mootools to obtain that "bounce" effect.

For example, you can apply a particular bounce effect in this way:

```<code>//element is supposed to be the main div you want to drag on iPhone
var element = $('elementID');

//instantiate a morph fx referred to that element
var bounceEffect = new Fx.Morph(element,{duration:1000, transition:Fx.Transitions.Bounce.easeOut});

//...then, when you want it to bounce back (e.g. at the release, or when it goes below a certain position) you can do:

bounceEffect.start({'top':0});
</code>```

Edit: take a look @ mootouch too, it's a very interesting project

Title: JavaScript smooth scroll - iphone

Body:
Once you have figured out how to scroll it, it's very simple in mootools to obtain that "bounce" effect.

For example, you can apply a particular bounce effect in this way:

//element is supposed to be the main div you want to drag on iPhone
var element = $('elementID');

//instantiate a morph fx referred to that element
var bounceEffect = new Fx.Morph(element,{duration:1000, transition:Fx.Transitions.Bounce.easeOut});

//...then, when you want it to bounce back (e.g. at the release, or when it goes below a certain position) you can do:

bounceEffect.start({'top':0});

Edit: take a look @ mootouch too, it's a very interesting project