问:
how to create image slider with left and right arrow buttons in bootstrap
I need create image slider to move left and right with arrow buttons. please see my existing images here

```<code><div class="col-md-3  animated fadeInUp" >
          <div class="tourbox">
            <div style="background-image:url(); width:100%; height:100%;" class="zoom" >
            </div>
            </div>
                <div class="col-md-12 text-center tourboxInner1"><img src="img/icons/info.png" width="30px"></div>
                <div class="col-md-12 text-center tourboxInner">CLASSICAL TOUR</div>

            </div>

            <div class="col-md-3 animated fadeInUp">
            <div class="tourbox">
            <div style="background-image:url(); width:100%; height:100%;" class="zoom" >
            </div>
            </div>
                <div class="col-md-12 text-center tourboxInner1"><img src="img/icons/info.png" width="30px"></div>
                <div class="col-md-12 text-center tourboxInner">TEA COUNTRY TOUR</div>
                </div>
</code>```

my image slider example link here

I need show four images in the page at one time and need move left and right one by one with new images. I am using bootstrap here. how can I do this please help me?

答:
hey hello Brother may be my answer helped you totally using bootstrap no custom css and js

```<code><div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="carousel-item active">
  <img class="d-block img-fluid" src="http://www.planwallpaper.com/static/images/desktop-year-of-the-tiger-images-wallpaper.jpg" alt="First slide">
</div>
<div class="carousel-item">
  <img class="d-block img-fluid" src="http://www.gettyimages.com/gi-resources/images/Embed/new/embed2.jpg" alt="Second slide">
</div>
<div class="carousel-item">
  <img class="d-block img-fluid" src="https://www.w3schools.com/w3css/img_fjords.jpg" alt="Third slide">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</code>```

here is working fiddle

Body:
I need create image slider to move left and right with arrow buttons. please see my existing images here

CLASSICAL TOUR

TEA COUNTRY TOUR

my image slider example link here

I need show four images in the page at one time and need move left and right one by one with new images. I am using bootstrap here. how can I do this please help me?

Body:
hey hello Brother may be my answer helped you totally using bootstrap no custom css and js

<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="carousel-item active">
  <img class="d-block img-fluid" src="http://www.planwallpaper.com/static/images/desktop-year-of-the-tiger-images-wallpaper.jpg" alt="First slide">
</div>
<div class="carousel-item">
  <img class="d-block img-fluid" src="http://www.gettyimages.com/gi-resources/images/Embed/new/embed2.jpg" alt="Second slide">
</div>
<div class="carousel-item">
  <img class="d-block img-fluid" src="https://www.w3schools.com/w3css/img_fjords.jpg" alt="Third slide">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>

here is working fiddle


来源: stackexchange

问:
How do I access a private member from a subclass
Trying to print the username in the method printShortSummary in the MessagePost class. The username is private in the Post class. Doing this for educational purposes. Still getting error that the username is private in Post. </p>

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

/**
 * This class stores information about a news feed post in a
 * social network. Posts can be stored and displayed. This class
 * serves as a superclass for more specific post types.
 *
 * @author Michael Kölling and David J. Barnes
 * @version 0.2
 */
public class Post
{
    private String username;  // username of the post's author
    private long timestamp;
    private int likes;
    private ArrayList<String> comments;

    /**
     * Constructor for objects of class Post.
     *
     * @param author    The username of the author of this post.
     */
    public Post(String author)
    {
        username = author;
        timestamp = System.currentTimeMillis();
        likes = 0;
        comments = new ArrayList<>();
    }

    public void getUserName()
    {

      getUserName();

    }
    /**
     * Record one more 'Like' indication from a user.
     */
    public void like()
    {
        likes++;
    }

    /**
     * Record that a user has withdrawn his/her 'Like' vote.
     */
    public void unlike()
    {
        if (likes > 0) {
            likes--;
        }
    }

    /**
     * Add a comment to this post.
     *
     * @param text  The new comment to add.
     */
    public void addComment(String text)
    {
        comments.add(text);
    }

    /**
     * Return the time of creation of this post.
     *
     * @return The post's creation time, as a system time value.
     */
    public long getTimeStamp()
    {
        return timestamp;
    }

    /**
     * Display the details of this post.
     *
     * (Currently: Print to the text terminal. This is simulating display
     * in a web browser for now.)
     */
    public void display()
    {
        System.out.println(username);
        System.out.print(timeString(timestamp));

        if(likes > 0) {
            System.out.println("  -  " + likes + " people like this.");
        }
        else {
            System.out.println();
        }

        if(comments.isEmpty()) {
            System.out.println("   No comments.");
        }
        else {
            System.out.println("   " + comments.size() + " comment(s). Click here to view.");
        }
    }

    /**
     * Create a string describing a time point in the past in terms
     * relative to current time, such as "30 seconds ago" or "7 minutes ago".
     * Currently, only seconds and minutes are used for the string.
     *
     * @param time  The time value to convert (in system milliseconds)
     * @return      A relative time string for the given time
     */

    private String timeString(long time)
    {
        long current = System.currentTimeMillis();
        long pastMillis = current - time;      // time passed in milliseconds
        long seconds = pastMillis/1000;
        long minutes = seconds/60;
        if(minutes > 0) {
            return minutes + " minutes ago";
        }
        else {
            return seconds + " seconds ago";
        }
    }
}

import java.util.ArrayList;

/**
 * This class stores information about a post in a social network news feed.
 * The main part of the post consists of a (possibly multi-line)
 * text message. Other data, such as author and time, are also stored.
 *
 * @author Michael Kölling and David J. Barnes
 * @version 0.2
 */
public class MessagePost extends Post
{
    private String message;  // an arbitrarily long, multi-line message

    /**
     * Constructor for objects of class MessagePost.
     *
     * @param author    The username of the author of this post.
     * @param text      The text of this post.
     */
    public MessagePost(String author, String text)
    {
        super(author);
        message = text;
    }

    public static void printShortSummary()
    {
      Post.getUserName();
      System.out.print ("Message postfrom" + username);

    }

    /**
     * Return the text of this post.
     *
     * @return The post's message text.
     */
    public String getText()
    {
        return message;
    }
}
</code>```

答:
If you don't have access to Post class or you don't wanna change Post class, you can use java Reflection API to access private members in any class

Ex:

```<code>public void printShortSummary() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    Field field = Post.class.getDeclaredField("username");
    field.setAccessible(true);
    System.out.print("Message post from " + field.get(this).toString());
}
</code>```

Note : Anyway this not the object oriented way

ContentLicense: CC BY-SA 3.0

Body:
Trying to print the username in the method printShortSummary in the MessagePost class. The username is private in the Post class. Doing this for educational purposes. Still getting error that the username is private in Post.

import java.util.ArrayList;

/**
 * This class stores information about a news feed post in a
 * social network. Posts can be stored and displayed. This class
 * serves as a superclass for more specific post types.
 *
 * @author Michael Kölling and David J. Barnes
 * @version 0.2
 */
public class Post
{
    private String username;  // username of the post's author
    private long timestamp;
    private int likes;
    private ArrayList<String> comments;

    /**
     * Constructor for objects of class Post.
     *
     * @param author    The username of the author of this post.
     */
    public Post(String author)
    {
        username = author;
        timestamp = System.currentTimeMillis();
        likes = 0;
        comments = new ArrayList<>();
    }

    public void getUserName()
    {

      getUserName();

    }
    /**
     * Record one more 'Like' indication from a user.
     */
    public void like()
    {
        likes++;
    }

    /**
     * Record that a user has withdrawn his/her 'Like' vote.
     */
    public void unlike()
    {
        if (likes > 0) {
            likes--;
        }
    }

    /**
     * Add a comment to this post.
     *
     * @param text  The new comment to add.
     */
    public void addComment(String text)
    {
        comments.add(text);
    }

    /**
     * Return the time of creation of this post.
     *
     * @return The post's creation time, as a system time value.
     */
    public long getTimeStamp()
    {
        return timestamp;
    }

    /**
     * Display the details of this post.
     *
     * (Currently: Print to the text terminal. This is simulating display
     * in a web browser for now.)
     */
    public void display()
    {
        System.out.println(username);
        System.out.print(timeString(timestamp));

        if(likes > 0) {
            System.out.println("  -  " + likes + " people like this.");
        }
        else {
            System.out.println();
        }

        if(comments.isEmpty()) {
            System.out.println("   No comments.");
        }
        else {
            System.out.println("   " + comments.size() + " comment(s). Click here to view.");
        }
    }

    /**
     * Create a string describing a time point in the past in terms
     * relative to current time, such as "30 seconds ago" or "7 minutes ago".
     * Currently, only seconds and minutes are used for the string.
     *
     * @param time  The time value to convert (in system milliseconds)
     * @return      A relative time string for the given time
     */

    private String timeString(long time)
    {
        long current = System.currentTimeMillis();
        long pastMillis = current - time;      // time passed in milliseconds
        long seconds = pastMillis/1000;
        long minutes = seconds/60;
        if(minutes > 0) {
            return minutes + " minutes ago";
        }
        else {
            return seconds + " seconds ago";
        }
    }
}

import java.util.ArrayList;

/**
 * This class stores information about a post in a social network news feed.
 * The main part of the post consists of a (possibly multi-line)
 * text message. Other data, such as author and time, are also stored.
 *
 * @author Michael Kölling and David J. Barnes
 * @version 0.2
 */
public class MessagePost extends Post
{
    private String message;  // an arbitrarily long, multi-line message

    /**
     * Constructor for objects of class MessagePost.
     *
     * @param author    The username of the author of this post.
     * @param text      The text of this post.
     */
    public MessagePost(String author, String text)
    {
        super(author);
        message = text;
    }

    public static void printShortSummary()
    {
      Post.getUserName();
      System.out.print ("Message postfrom" + username);

    }

    /**
     * Return the text of this post.
     *
     * @return The post's message text.
     */
    public String getText()
    {
        return message;
    }
}

Body:
If you don't have access to Post class or you don't wanna change Post class, you can use java Reflection API to access private members in any class

Ex:

public void printShortSummary() throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    Field field = Post.class.getDeclaredField("username");
    field.setAccessible(true);
    System.out.print("Message post from " + field.get(this).toString());
}

Note : Anyway this not the object oriented way


问:
SQL subquery that gets sum of alias column
I am new to SQL and trying to create a subquery within my SQL statement that finds the sum of all the totals in my alias column. I'm a bit confused on how to format a subquery and every time I've tried it says that I am formatting it incorrectly.

```<code> cmd.CommandText = "SELECT ProductName, OD.UnitPrice, Quantity, OD.UnitPrice * Quantity AS total, SUM(SELECT(total)) AS finalTotal " +
            "FROM Products, [Order Details] AS OD " +
            "WHERE OD.ProductID = Products.ProductID AND orderID = @OrderID";
</code>```

If I try the code above I get an error saying I have incorrect syntax near the SELECT statement. Any help is appreciated!

答:
If you need to get sum for all the rows you can use SUM with OVER

```<code>SELECT *,SUM(total)OVER() AS finalTotal
FROM
  (
    SELECT P.ProductName, OD.UnitPrice, Quantity, OD.UnitPrice * OD.Quantity AS total
    FROM Products P
    JOIN [Order Details] OD ON OD.ProductID = Products.ProductID
    WHERE OD.orderID = @OrderID
  ) q
</code>```

Body:
I am new to SQL and trying to create a subquery within my SQL statement that finds the sum of all the totals in my alias column. I'm a bit confused on how to format a subquery and every time I've tried it says that I am formatting it incorrectly.

 cmd.CommandText = "SELECT ProductName, OD.UnitPrice, Quantity, OD.UnitPrice * Quantity AS total, SUM(SELECT(total)) AS finalTotal " +
            "FROM Products, [Order Details] AS OD " +
            "WHERE OD.ProductID = Products.ProductID AND orderID = @OrderID";

If I try the code above I get an error saying I have incorrect syntax near the SELECT statement. Any help is appreciated!

Body:
If you need to get sum for all the rows you can use SUM with OVER

SELECT *,SUM(total)OVER() AS finalTotal
FROM
  (
    SELECT P.ProductName, OD.UnitPrice, Quantity, OD.UnitPrice * OD.Quantity AS total
    FROM Products P
    JOIN [Order Details] OD ON OD.ProductID = Products.ProductID
    WHERE OD.orderID = @OrderID
  ) q


问:
Calling methods within methods, Calling methods with multiple parameters to main. Mixing String and double
I'm struggling with an assignment. I need help figuring out how to call the right methods within each other and eventually in main. My whole code might need work at this point, what am I doing wrong? I've been stuck on this for a week..  (Guidelines at the bottom) Thanks!

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

public class AverageWithMethods {
static Scanner in = new Scanner(System.in);

  public static void main(String[]args)
  {
   userPrompt(); //Can't figure out how I'm supposed to set this up.
  }

  public static String userPrompt()
  {
   System.out.println("Enter 5 to 10 numbers separated by spaces, then press enter: ");
   String num = in.nextLine();

   return num; //I think I'm supposed to call the averager method here somehow?
  }

  public static double averager(String userPrompt)
  {
  double nums = Double.parseDouble(userPrompt);
  double average = 0;
  int counter = 0;
  char c = ' ';
       for (int i = 0; i < userPrompt.length(); i++)
       {
                if(userPrompt.charAt(i) == c)
            {
                counter++;
            }
            average = nums / counter;
        }

    return average;
  }

      public static void result(double average, String userPrompt)
  {
      System.out.println("The average of the numbers" + userPrompt + "is" + average);
  }

}
</code>```

GUIDELINES:

The program prompts the user for five to ten numbers, all on one line, and separated by spaces.   Then the user calculates the average of those numbers, and displays the numbers and their average to the user.

The program uses methods to:

Get the numbers entered by the user Calculate the average of the numbers entered by the user Print the results with the whole number, a decimal, and two decimal positions The first method should take no arguments and return a String of numbers separated by spaces.

The second method should take a String as its only argument and return a double (the average).

The third method should take a String and a double as arguments but have no return value.

For example, if the user input is... 20 40 60 80 100
...the program should give as output... The average of the numbers 20 40 60 80 100 is 60.00.

答:
I will not exactly provide complete solution to your questions but guide you in solving the problem:

User input : 1 2 3 4 5
Thus, now you need to read it in a String which you are already doing in your userPrompt() method.

Post that you need to call your averager() method to get the average
of the numbers. In that averager method you can need to split the
String to get the numbers. Check : String.split() method
documentation on how to achieve that. Then, you need to call
Double.parseDouble() for your String array of numbers.

Finally , you need to make a call to result method in you main()
method.

I hope it helps you on how to approach the problems and has sufficient hints to get the correct solution

Body:
I'm struggling with an assignment. I need help figuring out how to call the right methods within each other and eventually in main. My whole code might need work at this point, what am I doing wrong? I've been stuck on this for a week..  (Guidelines at the bottom) Thanks!

import java.util.Scanner;

public class AverageWithMethods {
static Scanner in = new Scanner(System.in);

  public static void main(String[]args)
  {
   userPrompt(); //Can't figure out how I'm supposed to set this up.
  }

  public static String userPrompt()
  {
   System.out.println("Enter 5 to 10 numbers separated by spaces, then press enter: ");
   String num = in.nextLine();

   return num; //I think I'm supposed to call the averager method here somehow?
  }

  public static double averager(String userPrompt)
  {
  double nums = Double.parseDouble(userPrompt);
  double average = 0;
  int counter = 0;
  char c = ' ';
       for (int i = 0; i < userPrompt.length(); i++)
       {
                if(userPrompt.charAt(i) == c)
            {
                counter++;
            }
            average = nums / counter;
        }

    return average;
  }

      public static void result(double average, String userPrompt)
  {
      System.out.println("The average of the numbers" + userPrompt + "is" + average);
  }

}

GUIDELINES:

The program prompts the user for five to ten numbers, all on one line, and separated by spaces.   Then the user calculates the average of those numbers, and displays the numbers and their average to the user.

The program uses methods to:

Get the numbers entered by the user Calculate the average of the numbers entered by the user Print the results with the whole number, a decimal, and two decimal positions The first method should take no arguments and return a String of numbers separated by spaces.

The second method should take a String as its only argument and return a double (the average).

The third method should take a String and a double as arguments but have no return value.

For example, if the user input is... 20 40 60 80 100
...the program should give as output... The average of the numbers 20 40 60 80 100 is 60.00.


问:
What to write so that when "enter" is pressed, then code proceeds further?
Please help me in the below code :

```<code>import java.util.Scanner;
class A
{
    public static void main(String args[])
    {
        Scanner Sc = new Scanner(System.in);
        System.out.print("Enter first number : ");
        a = Sc.nextInt();
        System.out.print("Enter second number : ");
        b = Sc.nextInt();
        System.out.print("Sum is : " + (a + b));
        System.out.print("Press enter to continue...");
        /* HERE IS MY DOUBT */
        /* WHAT TO WRITE HERE SO THAT WHEN "ENTER" IS PRESSED THEN CODE PROCEEDS */
    }
}
</code>```

Like in C language we can use getch() to hold a program. Is there something similar in Java too?

I have already tried Sc.nextLine(). The problem with Sc.nextLine() is that, in it first I have to enter a value and then press enter and then the code proceeds.
But what I want is to just press enter and proceed.

答:
Robot or Actions Class
Press the desired Key by making the object of actions or Robot class.
Like
Actions act=New Action(webdriver Dr)
Act.PressyourKey
Use the auto suggestions.This is how we press any desired Key you can use this Act.pressyourKey if true in a loop and it should execute your code</p>

Body:
Please help me in the below code :

import java.util.Scanner;
class A
{
    public static void main(String args[])
    {
        Scanner Sc = new Scanner(System.in);
        System.out.print("Enter first number : ");
        a = Sc.nextInt();
        System.out.print("Enter second number : ");
        b = Sc.nextInt();
        System.out.print("Sum is : " + (a + b));
        System.out.print("Press enter to continue...");
        /* HERE IS MY DOUBT */
        /* WHAT TO WRITE HERE SO THAT WHEN "ENTER" IS PRESSED THEN CODE PROCEEDS */
    }
}

Like in C language we can use getch() to hold a program. Is there something similar in Java too?

I have already tried Sc.nextLine(). The problem with Sc.nextLine() is that, in it first I have to enter a value and then press enter and then the code proceeds.
But what I want is to just press enter and proceed.


问:
Efficiently convert an unsigned short to a char*
What would be an efficient, portable way to convert a unsigned short to a char* (i.e. convert 25 to '25').

I'd like to avoid things such as getting (std::string) strings involved.  Performance is important in this case since this conversion will need to happen quickly and often.

I was looking into things such as using sprintf but would like to explorer any and all ideas.

ContentLicense: CC BY-SA 2.5

Body:
try this:

int convert(unsigned short val, char* dest)
{
  int i = 0;
  if (val > 10000)
  {
    dest[i++] = (val / 10000) | 0x30;
    val %= 10000;
  }
  if (val > 1000)
  {
    dest[i++] = (val / 1000) | 0x30;
    val %= 1000;
  }
  if (val > 100)
  {
    dest[i++] = (val / 100) | 0x30;
    val %= 100;
  }
  if (val > 10)
  {
    dest[i++] = (val / 10) | 0x30;
    val %= 10;
  }
  dest[i++] = (val) | 0x30;
  dest[i] = 0;
  return i;
}


问:
Heroku: deploying minio server with Dockerfile CMD failure
I am trying to deploy my minio server to heroku.  This is my Dockerfile:

```<code>FROM minio/minio
ENV MINIO_ACCESS_KEY="xxxxxx"
ENV MINIO_SECRET_KEY="xxxxxxxx"
CMD ["server", "/data"]
EXPOSE 9000
</code>```

This works locally when I build and run it through docker (using these commands:)

```<code>docker build . -t testheroku
sudo docker run -p 8080:8080 testheroku
</code>```

The Dockerfile is the only file in the directory.

Then, I try to push it to heroku.  I followed the commands on the heroku docker instruction page to install the heroku container plugin, login, etc.  Then, I pushed my app with: heroku container:push web --app APP_NAME

When I visit the app, I get an application error in browser.  This is what the heroku logs display:

```<code>2017-09-21T02:24:47.589576+00:00 app[api]: Deployed web (26b84915ed48) by user []
2017-09-21T02:24:47.589576+00:00 app[api]: Release v28 created by user []
2017-09-21T02:24:48.241050+00:00 heroku[web.1]: State changed from crashed to starting
2017-09-21T02:24:49.480733+00:00 heroku[web.1]: Starting process with command `server /data`
2017-09-21T02:24:51.961825+00:00 app[web.1]: ‘server /data’ is not a minio sub-command. See ‘minio --help’.
2017-09-21T02:24:52.056706+00:00 heroku[web.1]: Process exited with status 1
2017-09-21T02:24:52.064400+00:00 heroku[web.1]: State changed from starting to crashed
2017-09-21T02:24:52.938136+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=APP_NAME.herokuapp.com request_id=80ddd6f8-c053-4ff6-b4c9-fdb0ce8a48a5 fwd="67.245.14.153" dyno= connect= service= status=503 bytes= protocol=https
2017-09-21T02:24:54.319660+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=APP_NAME.herokuapp.com request_id=9988b6af-8a91-4e77-9bd4-c79c9e2ec24c fwd="67.245.14.153" dyno= connect= service= status=503 bytes= protocol=https
</code>```

For those unfamiliar with minio, some explanation of ‘server /data’ is not a minio sub-command. See ‘minio --help’.: this shows when you run the minio command with an argument that isn't a minio command. For example,

```<code>./minio sadf
‘sadf’ is not a minio sub-command. See ‘minio --help’.
</code>```

So what heroku is telling me is that it's interpreting the CMD line from my Dockerfile, not as it should (which is with server as the minio subcommand and /data as its argument) but instead, if you notice the quotation marks, heroku is smashing the two pieces together and attempting to use the whole string as a minio subcommand - hence the error message.  It's trying to run the command minio 'server /data' instead of minio server /data

Has anyone seen this kind of behavior from heroku before with a Dockerfile?  How can I make sure that the CMD line gets interpreted correctly, and not as one full string?  I assume this is a heroku issue because it runs fine locally.  Any advice would be welcome.

答: I had a similar issue that seemed to be caused by having other ENTRYPOINTS in the parent layers. To solve this, I added ENTRYPOINT [] above my CMD and everything worked fine.

Body:
I am trying to deploy my minio server to heroku.  This is my Dockerfile:

FROM minio/minio
ENV MINIO_ACCESS_KEY="xxxxxx"
ENV MINIO_SECRET_KEY="xxxxxxxx"
CMD ["server", "/data"]
EXPOSE 9000

This works locally when I build and run it through docker (using these commands:)

docker build . -t testheroku
sudo docker run -p 8080:8080 testheroku

The Dockerfile is the only file in the directory.

Then, I try to push it to heroku.  I followed the commands on the heroku docker instruction page to install the heroku container plugin, login, etc.  Then, I pushed my app with: heroku container:push web --app APP_NAME

When I visit the app, I get an application error in browser.  This is what the heroku logs display:

2017-09-21T02:24:47.589576+00:00 app[api]: Deployed web (26b84915ed48) by user []
2017-09-21T02:24:47.589576+00:00 app[api]: Release v28 created by user []
2017-09-21T02:24:48.241050+00:00 heroku[web.1]: State changed from crashed to starting
2017-09-21T02:24:49.480733+00:00 heroku[web.1]: Starting process with command `server /data`
2017-09-21T02:24:51.961825+00:00 app[web.1]: ‘server /data’ is not a minio sub-command. See ‘minio --help’.
2017-09-21T02:24:52.056706+00:00 heroku[web.1]: Process exited with status 1
2017-09-21T02:24:52.064400+00:00 heroku[web.1]: State changed from starting to crashed
2017-09-21T02:24:52.938136+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=APP_NAME.herokuapp.com request_id=80ddd6f8-c053-4ff6-b4c9-fdb0ce8a48a5 fwd="67.245.14.153" dyno= connect= service= status=503 bytes= protocol=https
2017-09-21T02:24:54.319660+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=APP_NAME.herokuapp.com request_id=9988b6af-8a91-4e77-9bd4-c79c9e2ec24c fwd="67.245.14.153" dyno= connect= service= status=503 bytes= protocol=https

For those unfamiliar with minio, some explanation of ‘server /data’ is not a minio sub-command. See ‘minio --help’.: this shows when you run the minio command with an argument that isn't a minio command. For example,

./minio sadf
‘sadf’ is not a minio sub-command. See ‘minio --help’.

So what heroku is telling me is that it's interpreting the CMD line from my Dockerfile, not as it should (which is with server as the minio subcommand and /data as its argument) but instead, if you notice the quotation marks, heroku is smashing the two pieces together and attempting to use the whole string as a minio subcommand - hence the error message.  It's trying to run the command minio 'server /data' instead of minio server /data

Has anyone seen this kind of behavior from heroku before with a Dockerfile?  How can I make sure that the CMD line gets interpreted correctly, and not as one full string?  I assume this is a heroku issue because it runs fine locally.  Any advice would be welcome.


问:
What is InputStream & Output Stream? Why and when do we use them?
Someone explain to me what InputStream and OutputStream are?

I am confused about the use cases for both InputStream and OutputStream.

If you could also include a snippet of code to go along with your explanation, that would be great. Thanks!

答:
Stream: In laymen terms stream is data , most generic stream is binary representation of data.

Input Stream : If you are reading data from a file or any other source , stream used is input stream. In a simpler terms input stream acts as a channel to read data.

Output Stream : If you want to read and process data from a source (file etc) you first need to save the data , the mean to store data is output stream .


问:
How do i display an input in Python within a print statement
```<code>name = input('What is You name ')
</code>```

this shows me only the input, I need to display 'hello' as well!!

```<code>print ('Hello', input(name))
</code>```

When I try to type this :-

```<code>name = input('What is You name ')
print ('Hello')
input(name)
</code>```

Why is that it displays the name directly and not the hello keyword. Could anyone please update on the same and share a coed that might be helpful.

答:
This is even the exact example in the docs</p>

```<code>person = input('Enter your name: ')
print('Hello', person)
</code>```

Body:
name = input('What is You name ')

this shows me only the input, I need to display 'hello' as well!!

print ('Hello', input(name))

When I try to type this :-

name = input('What is You name ')
print ('Hello')
input(name)

Why is that it displays the name directly and not the hello keyword. Could anyone please update on the same and share a coed that might be helpful.

Body:
This is even the exact example in the docs

person = input('Enter your name: ')
print('Hello', person)


问:
Laravel 5.5 - multiple images upload
I have this function in my controller:

```<code>use File;
use Image; //image intervention library
...
public function upload(Request $request)
    {
        //make sure there is a folder in public with the username
        $username = Auth::user()->name;
        $folderpath = public_path('images/' . $username . '/');
        File::makeDirectory($folderpath, $mode = 0777, true, true);

        $files = $request->file;

        if(!empty($files)):
            foreach($files as $file):
                $filename = 'post_' . time() . '.' . $file->getClientOriginalExtension();
                $path = $folderpath . $filename;
                Image::make($file)->resize(800,400)->save($path);
            endforeach;
        endif;

        return 'success';
    }
</code>```

which only save the last image if I upload multiple.

and I tried:

```<code>public function upload(Request $request)
    {
        //make sure there is a folder in public with the username
        $username = Auth::user()->name;
        $folderpath = public_path('images/' . $username . '/');
        File::makeDirectory($folderpath, $mode = 0777, true, true);

        $files = $request->file;

        if(!empty($files)):
            foreach($files as $file):
                $filename = 'post_' . time() . '.' . $file->getClientOriginalExtension();
                $path = $folderpath . $filename;
                $file->save($path);
            endforeach;
        endif;

        return ''success;
    }
</code>```

which throw me error:

Method save does not exist.

I goggled and it seems like I did not instantiate it with model. But in this case, how can I instantiate it with model if it is just a direct file upload?

What is the best way for multiple images upload in laravel?

Update

After reading @kunal's answer, I managed to solve the issue by adding a unique number for the file name:

```<code>public function upload(Request $request)
    {
        //make sure there is a folder in public with the username
        $username = Auth::user()->name;
        $folderpath = public_path('images/' . $username . '/');
        File::makeDirectory($folderpath, $mode = 0777, true, true);

        $files = $request->file;
        $count = 0;//<-- add a counter
        if(!empty($files)):
            foreach($files as $file):
                $filename = 'post_' . time() . '_' . $count . '.' . $file->getClientOriginalExtension();//<-- add counter to the file name
                $path = $folderpath . $filename;
                Image::make($file)->resize(800,400)->save($path);
                $count ++;//<-- increase the value
            endforeach;
        endif;

        return 'success';
    }
</code>```

答:
I am thinking u may missed this part

```<code><input type="file" id="gallery" name="file[]" />
</code>```

note the file[] it must be array otherwise it will only save the last image if upload multiple image

If u did ur html part correct, then use like this,

```<code>foreach ($file as $photo) {
    $path = Storage::putFile('foldername', $photo);
}
</code>```

Title: Laravel 5.5 - multiple images upload

Body:
I have this function in my controller:

use File;
use Image; //image intervention library
...
public function upload(Request $request)
    {
        //make sure there is a folder in public with the username
        $username = Auth::user()->name;
        $folderpath = public_path('images/' . $username . '/');
        File::makeDirectory($folderpath, $mode = 0777, true, true);

        $files = $request->file;

        if(!empty($files)):
            foreach($files as $file):
                $filename = 'post_' . time() . '.' . $file->getClientOriginalExtension();
                $path = $folderpath . $filename;
                Image::make($file)->resize(800,400)->save($path);
            endforeach;
        endif;

        return 'success';
    }

which only save the last image if I upload multiple.

and I tried:

public function upload(Request $request)
    {
        //make sure there is a folder in public with the username
        $username = Auth::user()->name;
        $folderpath = public_path('images/' . $username . '/');
        File::makeDirectory($folderpath, $mode = 0777, true, true);

        $files = $request->file;

        if(!empty($files)):
            foreach($files as $file):
                $filename = 'post_' . time() . '.' . $file->getClientOriginalExtension();
                $path = $folderpath . $filename;
                $file->save($path);
            endforeach;
        endif;

        return ''success;
    }

which throw me error:

Method save does not exist.

I goggled and it seems like I did not instantiate it with model. But in this case, how can I instantiate it with model if it is just a direct file upload?

What is the best way for multiple images upload in laravel?

Update

After reading @kunal's answer, I managed to solve the issue by adding a unique number for the file name:

public function upload(Request $request)
    {
        //make sure there is a folder in public with the username
        $username = Auth::user()->name;
        $folderpath = public_path('images/' . $username . '/');
        File::makeDirectory($folderpath, $mode = 0777, true, true);

        $files = $request->file;
        $count = 0;//<-- add a counter
        if(!empty($files)):
            foreach($files as $file):
                $filename = 'post_' . time() . '_' . $count . '.' . $file->getClientOriginalExtension();//<-- add counter to the file name
                $path = $folderpath . $filename;
                Image::make($file)->resize(800,400)->save($path);
                $count ++;//<-- increase the value
            endforeach;
        endif;

        return 'success';
    }

Body:
I am thinking u may missed this part

<input type="file" id="gallery" name="file[]" />

note the file[] it must be array otherwise it will only save the last image if upload multiple image

If u did ur html part correct, then use like this,

foreach ($file as $photo) {
    $path = Storage::putFile('foldername', $photo);
}


问:
Simple Python AES decryption for longer ciphertexts
I am not an expert in AES and moreover I have to deliver the deciphering function to a very limited Python 2 environment.

I have a 32-byte key and a 16-byte initialisation vector along with a 64-byte test cipher message - all of type str. AES operates in a cipher-block chaining mode.

With pycrypto it all works and I get a 64-symbol decrypted message of type unicode.

```<code>from Crypto.Cipher import AES

cipher = AES.new(key, AES.MODE_CBC, vector)
decryption = cipher.decrypt(message).decode()
print(decryption)
</code>```

Unfortunately the pycrypto itself is not supported in the final environment as I believe it has some fancy compiled dependencies for AES.
There is a purely Python alternative called pyaes:

```<code>import pyaes

cipher = pyaes.AESModeOfOperationCBC(key, vector)
decryption = cipher.decrypt(message[0:16]).decode()
print(decryption)
</code>```

Notice that I sliced the first 16 bytes and got the first 16 symbols of the decrypted message (of type unicode) correctly.

However, once I try the full message I get
ValueError: ciphertext block must be 16 bytes.

Even if I slice message[16:32], I get
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb8 in position 0: ordinal not in range(128).

So how to use the pyaes and decrypt longer ciphertexts in my case?

The secret plaintext looks like this

```<code>{"valueInt":123, "valueFloat":1.23, "valueString":"123"}
</code>```

with trailing (padded) spaces.

答:
Possibility 1. The case of the message[16:32] is that the first part of your unencrypted text could have multibyte characters, so after taking 16 bytes, 1+ byte is leaking to the second part of your original/unencrypted string. Though this is only if you are using multibyte characters.

If you are also encrypting them, you could try converting the text to binary first if your encoding is utf8:

```<code>cipher.encrypt(mystring.encode('utf8'))
</code>```

and in reverse

```<code>cipher.decrypt(mystring.decode('utf8'))
</code>```

Possiblity 2. If you are decrypting with the same AESModeOfOperationCFB you should try with a new instance for decryption. The following code fails to decrypt the correct text which contains non valid ascii bytes.

```<code>cipher = pyaes.AESModeOfOperationCBC(key, vector)
encrypted = cipher.decrypt('Hello world')
print(encrypted)
# ?Eg?m??K?(|
decrypted = cipher.decrypt(encrypted)
print(decrypted)
# ?XL=?-QE??Y?=k
</code>```

But if you do this way:

```<code>encrypter = pyaes.AESModeOfOperationCBC(key, vector)
encrypted = cipher.encrypt('Hello world !!!!')
print(encrypted)
# ?Eg?m??K?(|
decrypter = pyaes.AESModeOfOperationCBC(key, vector)
decrypted = decrypter.decrypt(encrypted)
# Hello world !!!!
</code>```

If you are encrypting 2 blocks with same instance and then concatenate them, you need a new instance which decrypt 2 new blocks. Or encrypt/decrypt each block with a new instance each.

Body:
I am not an expert in AES and moreover I have to deliver the deciphering function to a very limited Python 2 environment.

I have a 32-byte key and a 16-byte initialisation vector along with a 64-byte test cipher message - all of type str. AES operates in a cipher-block chaining mode.

With pycrypto it all works and I get a 64-symbol decrypted message of type unicode.

from Crypto.Cipher import AES

cipher = AES.new(key, AES.MODE_CBC, vector)
decryption = cipher.decrypt(message).decode()
print(decryption)

Unfortunately the pycrypto itself is not supported in the final environment as I believe it has some fancy compiled dependencies for AES.
There is a purely Python alternative called pyaes:

import pyaes

cipher = pyaes.AESModeOfOperationCBC(key, vector)
decryption = cipher.decrypt(message[0:16]).decode()
print(decryption)

Notice that I sliced the first 16 bytes and got the first 16 symbols of the decrypted message (of type unicode) correctly.

However, once I try the full message I get
ValueError: ciphertext block must be 16 bytes.

Even if I slice message[16:32], I get
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb8 in position 0: ordinal not in range(128).

So how to use the pyaes and decrypt longer ciphertexts in my case?

The secret plaintext looks like this

{"valueInt":123, "valueFloat":1.23, "valueString":"123"}

with trailing (padded) spaces.

Body:
Possibility 1. The case of the message[16:32] is that the first part of your unencrypted text could have multibyte characters, so after taking 16 bytes, 1+ byte is leaking to the second part of your original/unencrypted string. Though this is only if you are using multibyte characters.

If you are also encrypting them, you could try converting the text to binary first if your encoding is utf8:

cipher.encrypt(mystring.encode('utf8'))

and in reverse

cipher.decrypt(mystring.decode('utf8'))

Possiblity 2. If you are decrypting with the same AESModeOfOperationCFB you should try with a new instance for decryption. The following code fails to decrypt the correct text which contains non valid ascii bytes.

cipher = pyaes.AESModeOfOperationCBC(key, vector)
encrypted = cipher.decrypt('Hello world')
print(encrypted)
# ?Eg?m??K?(|
decrypted = cipher.decrypt(encrypted)
print(decrypted)
# ?XL=?-QE??Y?=k

But if you do this way:

encrypter = pyaes.AESModeOfOperationCBC(key, vector)
encrypted = cipher.encrypt('Hello world !!!!')
print(encrypted)
# ?Eg?m??K?(|
decrypter = pyaes.AESModeOfOperationCBC(key, vector)
decrypted = decrypter.decrypt(encrypted)
# Hello world !!!!

If you are encrypting 2 blocks with same instance and then concatenate them, you need a new instance which decrypt 2 new blocks. Or encrypt/decrypt each block with a new instance each.


问:
convert radio buttons into stars
I have some radio buttons that I'm trying to convert into stars and I'm following these example to create a star-rating component: https://codepen.io/muhammad_mabrouk/pen/bWybwX

I am still learning react, so I do not know how to import bootstrap in this component. What I need to import is:

```<code>    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</code>```

Here is the code:

import { Component } from 'react'
import React from 'react';
import PageTemplate from './PageTemplate'
import '../css/starRating.css';

class Rating extends Component {

    render(){
        return (

            <input id="star-5" type="radio" name="rating" value="star-5"></input>

            <input id="star-4" type="radio" name="rating" value="star-4"></input>

            <input id="star-3" type="radio" name="rating" value="star-3"></input>

            <input id="star-2" type="radio" name="rating" value="star-2"></input>

            <input id="star-1" type="radio" name="rating" value="star-1"></input>

        );
    }
}

export default Rating;```

I will appreciate all your help.

答:
You need to place this :

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</code>```

inside public folder , index.html file.

OR

Download that file and store it locally, then place it with your starRating.css

Then import same as starRating.css

```<code>import '../css/starRating.css';
import '../css/font-awesome.min.css';
</code>```

Title: convert radio buttons into stars

Body:
I have some radio buttons that I'm trying to convert into stars and I'm following these example to create a star-rating component: https://codepen.io/muhammad_mabrouk/pen/bWybwX

I am still learning react, so I do not know how to import bootstrap in this component. What I need to import is:

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

Here is the code:

import { Component } from 'react'
import React from 'react';
import PageTemplate from './PageTemplate'
import '../css/starRating.css';

class Rating extends Component {

    render(){
        return (

            <input id="star-5" type="radio" name="rating" value="star-5"></input>

            <input id="star-4" type="radio" name="rating" value="star-4"></input>

            <input id="star-3" type="radio" name="rating" value="star-3"></input>

            <input id="star-2" type="radio" name="rating" value="star-2"></input>

            <input id="star-1" type="radio" name="rating" value="star-1"></input>

        );
    }
}

export default Rating;

I will appreciate all your help.

Body:
You need to place this :

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

inside public folder , index.html file.

OR

Download that file and store it locally, then place it with your starRating.css

Then import same as starRating.css

import '../css/starRating.css';
import '../css/font-awesome.min.css';


问:
DriveResourceClient in Drive API not found
While working with Google Drive API in Android, I found lots of contents mentioning DriveResourceClient (class or interface). However, in my Android I didn't find the same class.

I confirmed about the version mentioned in COMPILE Section of build.gradle file too, and found that it has the same version which was mentioned in those contents.

following is the dependency used in build.gradle

```<code>compile 'com.google.android.gms:play-services-drive:11.4.2'
</code>```

I am building app having minSdkVersion 23 (i.e. Android 6) and targetSdkVersion is 26 (i.e. Android 8.0).

I guess, I am missing some settings.

Any guidance would be very helpful to me.

Thanks

答: Per the Google Play services release notes, DriveResourceClient was only added in version 11.6.0 of Google Play services. Update your dependency if you'd like to use the new API.

Body:
While working with Google Drive API in Android, I found lots of contents mentioning DriveResourceClient (class or interface). However, in my Android I didn't find the same class.

I confirmed about the version mentioned in COMPILE Section of build.gradle file too, and found that it has the same version which was mentioned in those contents.

following is the dependency used in build.gradle

compile 'com.google.android.gms:play-services-drive:11.4.2'

I am building app having minSdkVersion 23 (i.e. Android 6) and targetSdkVersion is 26 (i.e. Android 8.0).

I guess, I am missing some settings.

Any guidance would be very helpful to me.

Thanks


问:
Tensorflow v1.4: Layer.input not supported in Eager mode
I understand that Eager mode is a new alpha feature on the nightly builds and that it is not perfect yet, but I do not know if there are any tf.keras workarounds for this problem.

The error Layer.input not supported in Eager mode. triggers on the block

```<code>model = tf.keras.models.Sequential()
model.add(tf.layers.Dense(2, input_shape = (None, 1)))
model.add(tf.layers.Dense(units = 1))
model.compile(optimizer = "sgd", loss = "mean_squared_error")
</code>```

I do not know anything about keras or the keras tensorflow API and I was wondering if there was a way to avoid Layer.input with keras techniques so as to stay within Eager mode. Following a tutorial in the tf.Eager docs I have confirmed that model = tf.layers.Dense(1) works but I don't know how to add another layer.

Any help is very much appreciated.

EDIT
As of tensorflow v1.10, keras is supported in eager mode.

答:
Keras Models are not yet supported with eager execution, but Keras layers are. Which means that while you can't use tf.keras.models.Sequential yet, you could combine layers yourself. See the user guide.

Hope that helps.

ContentLicense: CC BY-SA 4.0

Body:
I understand that Eager mode is a new alpha feature on the nightly builds and that it is not perfect yet, but I do not know if there are any tf.keras workarounds for this problem.

The error Layer.input not supported in Eager mode. triggers on the block

model = tf.keras.models.Sequential()
model.add(tf.layers.Dense(2, input_shape = (None, 1)))
model.add(tf.layers.Dense(units = 1))
model.compile(optimizer = "sgd", loss = "mean_squared_error")

I do not know anything about keras or the keras tensorflow API and I was wondering if there was a way to avoid Layer.input with keras techniques so as to stay within Eager mode. Following a tutorial in the tf.Eager docs I have confirmed that model = tf.layers.Dense(1) works but I don't know how to add another layer.

Any help is very much appreciated.

EDIT
As of tensorflow v1.10, keras is supported in eager mode.


问:
Express.js View "globals"
I'm using Express.js (on Node.js) and I know that you can render a view with custom data via the "locals" parameter. (res.render("template", { locals: { foo: "bar" } });)

Is there any way to have "globals"? (ie. data that's accessible to every view)

I saw view options, but that isn't recursive, so it replaces the locals I set if I use any locals with my template.

This is my use case: I want to make it so that CSS/JS files can be added on a per-page basis, and that is part of my main layout. The problem is, if I don't explicitly set those arrays on every render, I get an undefined error, so in my template I always have to do the typeof css !== "undefined" dance. Additionally, I have other select box option lists that I don't want to have to explicitly add to each of my forms.

答:
The simplest way to accomplish this is to create a variable that represents the default set of locals for your views.  Then create a function that accepts an object, merges it with the locals, and returns the merged object.

I also pass ALL my locals inside a container object i.e. {locals:{g:{prop:val}}}  so in my views I can refernce g.prop which will just return null when it isn't set, instead of throwing an undefined error.

```<code>function default_page_vars(custom_vars){
    var vars = {
        footer: true,
        host: req.headers.host.split(':')[0],
        config: this.config
    };

    if(custom_vars){
        for(var k in custom_vars){
            vars[k] = custom_vars[k];
        }
    }
    return {
        g:vars
    };
}

//within your handler
response.render(view, {
    locals: default_page_vars(other_locals)
});
</code>```

Title: Express.js View "globals"

Body:
The simplest way to accomplish this is to create a variable that represents the default set of locals for your views.  Then create a function that accepts an object, merges it with the locals, and returns the merged object.

I also pass ALL my locals inside a container object i.e. {locals:{g:{prop:val}}}  so in my views I can refernce g.prop which will just return null when it isn't set, instead of throwing an undefined error.

function default_page_vars(custom_vars){
    var vars = {
        footer: true,
        host: req.headers.host.split(':')[0],
        config: this.config
    };

    if(custom_vars){
        for(var k in custom_vars){
            vars[k] = custom_vars[k];
        }
    }
    return {
        g:vars
    };
}

//within your handler
response.render(view, {
    locals: default_page_vars(other_locals)
});


问:
What is gitlab runner
I think I'm fundamentally missing something. I'm new to CI/CD and trying to set up my first pipeline ever with gitlab.

The project is a pre-existing PHP project.

I don't want to clean it up just yet, at the moment I've pushed the whole thing into a docker container and it's running fine talking to google cloud's mysql databases etc as it should locally and also on a remote google cloud testing VM.
The dream is to be able to push to the development branch, and then merge the dev banch into the test branch which then TRIGGERS automated tests (easy part), and also causes the remote test VM (hosted on google cloud), to PULL the newest changes, rebuild the image from the latest docker file (or pull the latest image from gitlab image register)... and then rebuild the container with the newest image.

I'm playing around with gitlab's runner but I'm not understanding what it's actually for, despite looking through almost all the online content for it.
Do I just install it in the google cloud VM, and then when I push to gitlab from my development machine.. the repo will 'signal' the runner (which is running on the VM, to execute a bunch of scripts (which might include git pull on the newest changes?).

Because I already pre-package my app into a container locally (and push the image to the image registry) do I need to use docker as my executor on the runner? or can i just use shell and shell the commands in?

What am I missing?

TLDR and extra:

Questions:

What is runner actually for,
where is it meant to be installed?

Does it care which directory it is run in?

If it doesn't care which directory it's run,
where does it execute it's script commands? At root?

If I am locally building my own images and uploading them to gitlab's registry,

Do I need to set my executor to docker? Shouldn't I just set it to shell, pull the image, and build it? (Assuming the runner is runing on the remote VM).

答:
What is runner actually for?

You have your project along with a .gitlab-ci.yml file. .gitlab-ci.yml defines what stages your CI/CD pipeline has and what to do in each stage. This typically consists of a build,test,deploy stages. Within each stage you can define multiple job. For example in build stage you may have 3 jobs to build on debian, centos and windows (in GitLab glossary build:debian, build:centos, build:windows). A GitLab runner clones the project read the gitlab-ci.yaml file and do what he is instructed to do. So basically GitLab runner is a Golang process that executes some instructed tasks.

where is it meant to be installed?

You can install a runner in your desired environment listed here. https://docs.gitlab.com/runner/install/
or
you can use a shared runner that is already installed on GitLab's infrastructure.

Does it care which directory it is run in?

Yes. Every task executed by runner is relativly to CI_PROJECT_DIR defined in https://gitlab.com/help/ci/variables/README. But you can alter this behaviour.

where does it execute it's script commands? At root?

Do I need to set my executor to docker? Shouldn't I just set it to shell, pull the image, and build it?

A runner can have mutiple executors such as docker, shell, virtualbox etc but docker being the most common one. If you use docker as the executor you can pull any image from docker hub or your configured registry and you can do loads of stff with docker images. In a docker environment normally you run them as the root user.
https://docs.gitlab.com/runner/executors/README.html

Title: What is gitlab runner


问:
installing scrapy mac os 10.7.5
I'm trying to install scrapy, but when I enter scrapy startproject tutorial at the command line it gives me an error. I installed with

sudo easy_install scrapy

I have searched Google and stackoverflow and a lot of answers suggest that scrapy hasn't been properly added to my PATH. Well, I can find scrapy at

```<code>/Library/Python/2.7/site-packages/scrapy
</code>```

But even after adding the following line to my ~/.bash_profile, scrapy still doesn't work:

```<code> export PATH=/Library/Python/2.7/site-packages:$PATH
</code>```

I'm not that confident that I've done this right. Any help would be greatly appreciated!

答: “pip3 install scrapy” has solved my problem. Can you try this?</p>

Title: installing scrapy mac os 10.7.5

Body:
I'm trying to install scrapy, but when I enter scrapy startproject tutorial at the command line it gives me an error. I installed with

sudo easy_install scrapy

I have searched Google and stackoverflow and a lot of answers suggest that scrapy hasn't been properly added to my PATH. Well, I can find scrapy at

/Library/Python/2.7/site-packages/scrapy

But even after adding the following line to my ~/.bash_profile, scrapy still doesn't work:

 export PATH=/Library/Python/2.7/site-packages:$PATH

I'm not that confident that I've done this right. Any help would be greatly appreciated!


问:
Powershell KML Generation Manipulate Timestamp in Loop
I have a block of powershell code that looks like this:

```<code>$(
foreach ($csv in $csvfiles) {
 $fname = (Get-Item $csv).Basename
 '<Folder>
  <name>{0}</name>' -f $fname
    $(
    Import-Csv $csv |
    foreach {
    '<Placemark>
     <name>{0} - {1}</name>
     <TimeStamp>
      <begin>{1}</begin>
      <end>{1}</end>
     </TimeStamp>
     <description>Information - {4}</description>
     <styleUrl>#{5}</styleUrl>
     <Point>
      <coordinates>{2},{3}</coordinates>
     </Point>
    </Placemark>

      ' -f $_.Variable, $_.Timestamp, $_.Variable2, $_.Variable3, $_.Variable4, $_.Color
     }
     )
'</Folder>'
   }
)
</code>```

The above code works.  I am trying to make my placemarkers last a longer period so they do not disappear if the slider moves off of the seconds field.  Timestamp is of the format:

2017-07-26T19:03:40Z

Sometimes the timestamp will shift to the 41 or 39 second, and when moving the slider in Google Earth, you will lose the placemark because it is moving in 1 minute increments...which is what I want.  I want to set a begin and end timestamp for the placemark by subtracting and adding 20 seconds to the actual timestamp.  How can I do this using the code below?  Is there an easy way for me to just subtract and add seconds to the timestamp and still use it as an input to the KML file in that loop?

答:
Perhaps you can try the following to just strip the seconds:

```<code>-f $_.Variable, $($_.Timestamp -replace '^(.*)(\d\d)(.*)$','${1}00$3'), $_.Variable2, $_.Variable3, $_.Variable4, $_.Color
</code>```

$() : allow to compute the new value first.

-replace regex, newvalue : reple the seconds by 00.

I use ${1} for the first capture to avoid the $100 wich means nothing, the second capture is replaced by 00 the third capture is kept as is.

Body:
I have a block of powershell code that looks like this:

$(
foreach ($csv in $csvfiles) {
 $fname = (Get-Item $csv).Basename
 '<Folder>
  <name>{0}</name>' -f $fname
    $(
    Import-Csv $csv |
    foreach {
    '<Placemark>
     <name>{0} - {1}</name>
     <TimeStamp>
      <begin>{1}</begin>
      <end>{1}</end>
     </TimeStamp>
     <description>Information - {4}</description>

     <Point>
      <coordinates>{2},{3}</coordinates>
     </Point>
    </Placemark>

      ' -f $_.Variable, $_.Timestamp, $_.Variable2, $_.Variable3, $_.Variable4, $_.Color
     }
     )
'</Folder>'
   }
)

The above code works.  I am trying to make my placemarkers last a longer period so they do not disappear if the slider moves off of the seconds field.  Timestamp is of the format:

2017-07-26T19:03:40Z

Sometimes the timestamp will shift to the 41 or 39 second, and when moving the slider in Google Earth, you will lose the placemark because it is moving in 1 minute increments...which is what I want.  I want to set a begin and end timestamp for the placemark by subtracting and adding 20 seconds to the actual timestamp.  How can I do this using the code below?  Is there an easy way for me to just subtract and add seconds to the timestamp and still use it as an input to the KML file in that loop?

Body:
Perhaps you can try the following to just strip the seconds:

-f $_.Variable, $($_.Timestamp -replace '^(.*)(\d\d)(.*)$','${1}00$3'), $_.Variable2, $_.Variable3, $_.Variable4, $_.Color

$() : allow to compute the new value first.

-replace regex, newvalue : reple the seconds by 00.

I use ${1} for the first capture to avoid the $100 wich means nothing, the second capture is replaced by 00 the third capture is kept as is.


问:
How to remove item from an array on condition using JavaScript
I have an an array which is mentioned below. I would like to remove an item from the array which has empty property value using JavaScript.

Actual array:

```<code>[
    {
        "href":"/client",
        "methods":[]
    },
    {
        "href":"/home",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    },
    {
        "href":"/about",
        "methods":[]
    },
    {
        "href":"/contact",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    }
]
</code>```

Expecting result:

```<code>[
    {
        "href":"/home",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    },
    {
        "href":"/contact",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    }
]
</code>```

答:
Iterate over the object array and filter based on methods property length.

```<code>var obj = [...];
obj = obj.filter((val) => val.methods && val.methods.length !== 0);
</code>```

Body:
I have an an array which is mentioned below. I would like to remove an item from the array which has empty property value using JavaScript.

Actual array:

[
    {
        "href":"/client",
        "methods":[]
    },
    {
        "href":"/home",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    },
    {
        "href":"/about",
        "methods":[]
    },
    {
        "href":"/contact",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    }
]

Expecting result:

[
    {
        "href":"/home",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    },
    {
        "href":"/contact",
        "methods":
            {
                "type1":"GET",
                "type2":"POST",
            }
    }
]

Body:
Iterate over the object array and filter based on methods property length.

var obj = [...];
obj = obj.filter((val) => val.methods && val.methods.length !== 0);


问:
XSD attribute cannot equal value?
How can I restrict an attribute to not allow a particular value?

For instance, I have an <xs:key/> on an Id attribute of an element, but some yahoo has gone and thrown a magic number in there so now I cannot allow 3, but 1, 2, and 5 are perfectly acceptable.

答:
Have you tried having a look at the restriction tag link text, the code below, it should give you a tag called Id which only allows integers that doesn't start with a 3</p>

```<code><xs:key name="Id">
    <xs:simpleType>
        <xs:restriction base="xs:integer">
            <xs:pattern value="[^3]\d*"/>
       </xs:restriction>
  </xs:simpleType>
</xs:key>
</code>```

Title: XSD attribute cannot equal value?

Body:
Have you tried having a look at the restriction tag link text, the code below, it should give you a tag called Id which only allows integers that doesn't start with a 3

<xs:key name="Id">
    <xs:simpleType>
        <xs:restriction base="xs:integer">
            <xs:pattern value="[^3]\d*"/>
       </xs:restriction>
  </xs:simpleType>
</xs:key>


问:
SQL subquery that gets sum of alias column
I am new to SQL and trying to create a subquery within my SQL statement that finds the sum of all the totals in my alias column. I'm a bit confused on how to format a subquery and every time I've tried it says that I am formatting it incorrectly.

```<code> cmd.CommandText = "SELECT ProductName, OD.UnitPrice, Quantity, OD.UnitPrice * Quantity AS total, SUM(SELECT(total)) AS finalTotal " +
            "FROM Products, [Order Details] AS OD " +
            "WHERE OD.ProductID = Products.ProductID AND orderID = @OrderID";
</code>```

If I try the code above I get an error saying I have incorrect syntax near the SELECT statement. Any help is appreciated!

答:
The issue is here SUM(SELECT(total)), you cannot call select in this way, you have to specify from clause to make a subquery.

If you need to get the sum of all the rows (unit price * Quantity), Then:

```<code>SELECT Sum (UnitPrice * Quantity) AS total FROM Products
JOIN [Order Details] OD ON OD.ProductID = Products.ProductID
WHERE OD.orderID = @OrderID
</code>```

If you need to repeat that for the record set then:

```<code>SELECT *,SUM(total)OVER() AS OverAllTotal
FROM
  (
    SELECT P.ProductName, OD.UnitPrice, Quantity, OD.UnitPrice * OD.Quantity AS total
    FROM Products P
    JOIN [Order Details] OD ON OD.ProductID = Products.ProductID
    WHERE OD.orderID = @OrderID
  ) subQuery
</code>```

Body:
I am new to SQL and trying to create a subquery within my SQL statement that finds the sum of all the totals in my alias column. I'm a bit confused on how to format a subquery and every time I've tried it says that I am formatting it incorrectly.

 cmd.CommandText = "SELECT ProductName, OD.UnitPrice, Quantity, OD.UnitPrice * Quantity AS total, SUM(SELECT(total)) AS finalTotal " +
            "FROM Products, [Order Details] AS OD " +
            "WHERE OD.ProductID = Products.ProductID AND orderID = @OrderID";

If I try the code above I get an error saying I have incorrect syntax near the SELECT statement. Any help is appreciated!

Body:
The issue is here SUM(SELECT(total)), you cannot call select in this way, you have to specify from clause to make a subquery.

If you need to get the sum of all the rows (unit price * Quantity), Then:

SELECT Sum (UnitPrice * Quantity) AS total FROM Products
JOIN [Order Details] OD ON OD.ProductID = Products.ProductID
WHERE OD.orderID = @OrderID

If you need to repeat that for the record set then:

SELECT *,SUM(total)OVER() AS OverAllTotal
FROM
  (
    SELECT P.ProductName, OD.UnitPrice, Quantity, OD.UnitPrice * OD.Quantity AS total
    FROM Products P
    JOIN [Order Details] OD ON OD.ProductID = Products.ProductID
    WHERE OD.orderID = @OrderID
  ) subQuery


问:
pandas column containing list of objects, split this column based upon keynames and store values as comma separated values
I have a dataframe which contains column:

```<code>A
[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}]
[{"A": 31, "B": "hij"},{"A": 32, "B": "abc"}]
[{"A": 28, "B": "abc"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "klm"},{"A": 30, "B": "nop"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "xyz"}]
</code>```

Output should be such that:

```<code>A              B
28,29,30       abc,def,hij
31,32          hij,abc
28             abc
28,29,30       abc,def,hij
28,29,30       abc,klm,nop
28,29          abc,xyz
</code>```

How do i split the list of objects into columns depending on key names and have them stored as comma separated values as shown above.

答:
By using stack then groupby

```<code>df.A.apply(pd.Series).stack().\
     apply(pd.Series).groupby(level=0).\
        agg(lambda x :','.join(x.astype(str)))
Out[457]:
          A            B
0  28,29,30  abc,def,hij
1     31,32      hij,abc
2        28          abc
3  28,29,30  abc,def,hij
4  28,29,30  abc,klm,nop
</code>```

Data input:

```<code>df=pd.DataFrame({'A':[[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}],
[{"A": 31, "B": "hij"},{"A": 32, "B": "abc"}],
[{"A": 28, "B": "abc"}],[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}],
[{"A": 28, "B": "abc"},{"A": 29, "B": "klm"},{"A": 30, "B": "nop"}]]})
</code>```

For your additional question read from csv

```<code>import ast
df=pd.read_csv(r'your.csv',dtype={'A':object})

df['A'] = df['A'].apply(ast.literal_eval)
</code>```

Body:
I have a dataframe which contains column:

A
[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}]
[{"A": 31, "B": "hij"},{"A": 32, "B": "abc"}]
[{"A": 28, "B": "abc"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "klm"},{"A": 30, "B": "nop"}]
[{"A": 28, "B": "abc"},{"A": 29, "B": "xyz"}]

Output should be such that:

A              B
28,29,30       abc,def,hij
31,32          hij,abc
28             abc
28,29,30       abc,def,hij
28,29,30       abc,klm,nop
28,29          abc,xyz

How do i split the list of objects into columns depending on key names and have them stored as comma separated values as shown above.

Body:
By using stack then groupby

df.A.apply(pd.Series).stack().\
     apply(pd.Series).groupby(level=0).\
        agg(lambda x :','.join(x.astype(str)))
Out[457]:
          A            B
0  28,29,30  abc,def,hij
1     31,32      hij,abc
2        28          abc
3  28,29,30  abc,def,hij
4  28,29,30  abc,klm,nop

Data input:

df=pd.DataFrame({'A':[[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}],
[{"A": 31, "B": "hij"},{"A": 32, "B": "abc"}],
[{"A": 28, "B": "abc"}],[{"A": 28, "B": "abc"},{"A": 29, "B": "def"},{"A": 30, "B": "hij"}],
[{"A": 28, "B": "abc"},{"A": 29, "B": "klm"},{"A": 30, "B": "nop"}]]})

For your additional question read from csv

import ast
df=pd.read_csv(r'your.csv',dtype={'A':object})

df['A'] = df['A'].apply(ast.literal_eval)


问:
Python Regex: how to parse repeated groups in a string?
I want to match a pattern with a string including pure numbers, such as '2324235235980980' with a pattern like as described below:

The pattern is '2-6-8-7-4', in which the pattern starts with 2, transit to 6, either self-loop at 6 or transit to 8, then it could go back and forth between 6 and 8, could self-loop at 8, or could transit to 7. And the same thing for 7. One more thing for 7 is 7-8-6-8-7 could happen. Finally, 7 could reach 4, once it reaches 4, the pattern is done. During the process, if it reaches out to other points, then it has to start with 2 again to be counted.
I use

```<code>import re
re.findall(r'(2((6+8+)+)7)', test_string)
</code>```

the output includes '2666686888668887', but when I add 4, I don't know the syntax to compile this. Has anyone an idea? Thanks a lot!

答:
I think this is easier achieved than initially expected:

26[68]+?[687]+?4

2-followed-by-6-followed-by-6|8-followed-by-6|8|7-followed-by-4.

The only not so obvious part is to make the pattern lazy.

Here is an even better pattern:

\b26?([^7]6|8|[^6]7)+?4\b

2-followed-by-(not7)6|8|(not6)7-followed-by-4.

Body:
I want to match a pattern with a string including pure numbers, such as '2324235235980980' with a pattern like as described below:

The pattern is '2-6-8-7-4', in which the pattern starts with 2, transit to 6, either self-loop at 6 or transit to 8, then it could go back and forth between 6 and 8, could self-loop at 8, or could transit to 7. And the same thing for 7. One more thing for 7 is 7-8-6-8-7 could happen. Finally, 7 could reach 4, once it reaches 4, the pattern is done. During the process, if it reaches out to other points, then it has to start with 2 again to be counted.
I use

import re
re.findall(r'(2((6+8+)+)7)', test_string)

the output includes '2666686888668887', but when I add 4, I don't know the syntax to compile this. Has anyone an idea? Thanks a lot!


问:
Python webdriver switch from main window to popup screen (not Java alert) and login
Here is the window I need to enter new password and repeat it again and click 'create'.

My code so far:

```<code>        createLogin = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="Item.MessageUniqueBody"]/div/div/div/div/div[2]/div[2]/a')))
        createLogin.click()
        time.sleep(10)
        try:
            newPassword = self.driver.find_elements_by_xpath('//*[@id="editNewUser_newPassword"]')
            newPassword1 = self.driver.find_elements_by_xpath('//*[@id="editNewUser_newPasswordRepeat"]')
            newPasswordForm = self.driver.find_elements_by_xpath('//*[@id="editNewUserPasswordForm"]/table/tbody/tr[1]/td[1]')
            self.driver.switch_to.active_element(newPasswordForm)
            time.sleep(3)
            newPassword.send_keys('123')
            newPassword1.send_keys('123')
            time.sleep(2)

            # createLog = wait.until(
            #     EC.presence_of_element_located((By.XPATH, '//*[@id="editNewUserPassword_save"]')))
            # createLog.click()
            # time.sleep(5)
        except NoAlertPresentException as e:
            time.sleep(2)
        myAccount = wait.until(
            EC.presence_of_element_located((By.XPATH, '//*[@id="easMyAccount1"]')))
        myAccount.click()
        time.sleep(5)
</code>```

答:
@gauurang Answer is right, But You have to used find_element_by_xpath, also as your xpath suggested you have id to locate the webelements so it is always better to use id over xpath

Also your xpath are correct

```<code>newPassword = self.driver.find_element_by_id('editNewUser_newPassword')
    newPassword1 = self.driver.find_element_by_id('editNewUser_newPasswordRepeat')
    newPasswordForm = self.driver.find_element_by_xpath('//*[@id="editNewUserPasswordForm"]/table/tbody/tr[1]/td[1]')
</code>```

Body:
Here is the window I need to enter new password and repeat it again and click 'create'.

My code so far:

        createLogin = wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="Item.MessageUniqueBody"]/div/div/div/div/div[2]/div[2]/a')))
        createLogin.click()
        time.sleep(10)
        try:
            newPassword = self.driver.find_elements_by_xpath('//*[@id="editNewUser_newPassword"]')
            newPassword1 = self.driver.find_elements_by_xpath('//*[@id="editNewUser_newPasswordRepeat"]')
            newPasswordForm = self.driver.find_elements_by_xpath('//*[@id="editNewUserPasswordForm"]/table/tbody/tr[1]/td[1]')
            self.driver.switch_to.active_element(newPasswordForm)
            time.sleep(3)
            newPassword.send_keys('123')
            newPassword1.send_keys('123')
            time.sleep(2)

            # createLog = wait.until(
            #     EC.presence_of_element_located((By.XPATH, '//*[@id="editNewUserPassword_save"]')))
            # createLog.click()
            # time.sleep(5)
        except NoAlertPresentException as e:
            time.sleep(2)
        myAccount = wait.until(
            EC.presence_of_element_located((By.XPATH, '//*[@id="easMyAccount1"]')))
        myAccount.click()
        time.sleep(5)

Body:
@gauurang Answer is right, But You have to used find_element_by_xpath, also as your xpath suggested you have id to locate the webelements so it is always better to use id over xpath

Also your xpath are correct

newPassword = self.driver.find_element_by_id('editNewUser_newPassword')
    newPassword1 = self.driver.find_element_by_id('editNewUser_newPasswordRepeat')
    newPasswordForm = self.driver.find_element_by_xpath('//*[@id="editNewUserPasswordForm"]/table/tbody/tr[1]/td[1]')


问:
Evaluating lm where training data has been automatically transformaed with dummy variables
I'm trying to use statisticalmodeling package to evaluate a model and also look at effect sizes:

```<code>library(caret)
library(statisticalModeling)

a_model <- train(
  Sepal.Length ~ Species + Sepal.Width,
  data = iris,
  method = "lm"
)

statisticalModeling::effect_size(a_model$finalModel, ~ Species, data = iris)
</code>```

During fitting the model, r automatically converts categorical variable Species to a dummy variable - great, I don't have to worry about that.

However, this is throwing an error when I try to evaluate the model. The last line above gives:

Error in eval(expr, envir, enclos) : object 'Speciesversicolor' not found

Putting my question another way, is it possible to retrive the transformed data that r used to build the model? I culd then pass this into the data parameter of the statisticalmodeling functions.

I tried switching data = iris to data = a_model$trainingData but encountered the same message.

I don't encounter this issue using base r linear model, only with the caret derived one.

答:
You can avoid it using default S3 method of train.

```<code>b_model <- train(x = iris[, c("Species", "Sepal.Width")],
                 y = iris$Sepal.Length,
                 method = "lm")

identical(a_model$finalModel$coefficients, b_model$finalModel$coefficients)  # TRUE

statisticalModeling::effect_size(b_model$finalModel, ~ Species, data = iris)
</code>```

Body:
I'm trying to use statisticalmodeling package to evaluate a model and also look at effect sizes:

library(caret)
library(statisticalModeling)

a_model <- train(
  Sepal.Length ~ Species + Sepal.Width,
  data = iris,
  method = "lm"
)

statisticalModeling::effect_size(a_model$finalModel, ~ Species, data = iris)

During fitting the model, r automatically converts categorical variable Species to a dummy variable - great, I don't have to worry about that.

However, this is throwing an error when I try to evaluate the model. The last line above gives:

Error in eval(expr, envir, enclos) : object 'Speciesversicolor' not found

Putting my question another way, is it possible to retrive the transformed data that r used to build the model? I culd then pass this into the data parameter of the statisticalmodeling functions.

I tried switching data = iris to data = a_model$trainingData but encountered the same message.

I don't encounter this issue using base r linear model, only with the caret derived one.

Body:
You can avoid it using default S3 method of train.

b_model <- train(x = iris[, c("Species", "Sepal.Width")],
                 y = iris$Sepal.Length,
                 method = "lm")

identical(a_model$finalModel$coefficients, b_model$finalModel$coefficients)  # TRUE

statisticalModeling::effect_size(b_model$finalModel, ~ Species, data = iris)


问:
Multiple DomainSite: when one domain site admin login in Umbraco, he can't see other Domain Site user
I have one use case in Umbraco. My project is Multidomain site (India, China, Greece). When I create a USER (India admin and group-adminIndia) from main administrator and in adminIndia group I give permission all along with user.

I did same thing with China and Greece admin. Now when I log in from India admin I can also disable other admin and vice versa.

This is the problem. My requirement is this: when India admin logs in, he shouldn't be able to see admins from others groups. Can anyone help with this issue?. Can I do it with Javascript or Jquery?

Check images: 1) Admin china group screen 2) admin india group 3)Login from indian admin now he can disable china admin. This is the problem. 4)Login from main admin . 5) content in umbraco backoffice

答: You have to give permission to both groups to the Users section in addition to their respective content nodes root:


答:
enter var json = {};

var key = "giveitakeyvalue";

json[key] = null;

delete json[key];

Title: How to remove item from an array on condition using JavaScript


答:
This is the job for filter. however filter does not modify the existing array so you need to assign it to a different array/overwrite the current variable</p>

```<code>a = a.filter(item => Object.keys(item.methods).length > 0)
</code>```

Body:
This is the job for filter. however filter does not modify the existing array so you need to assign it to a different array/overwrite the current variable

a = a.filter(item => Object.keys(item.methods).length > 0)


问:
Nullpointerexception in accessing interface method in retrofit calling
Nullpointerexception in accessing interface method in retrofit calling

Userservice.class

```<code>public interface UserService {

    @POST("login")
    Call<ResUser> login(@Body login login);
}
</code>```

RetrofitClient.class

```<code>public class RetrofitClient {

    private static Retrofit retrofit=null;

    public static Retrofit getClient(String url){

        if(retrofit==null){
            retrofit=new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }

        return retrofit;
    }
}
</code>```

login.class

```<code>    private void doLogin(String username,String password){
    Call<ResUser> call=userService.login(new login(username,password));
    call.enqueue(new Callback<ResUser>() {
        @Override
        public void onResponse(Call<ResUser> call, Response<ResUser> response) {
            if(response.isSuccessful()){
             Log.e("succes");
            }
        }

        @Override
        public void onFailure(Call<ResUser> call, Throwable t) {

        }
    });

}
</code>```

ApiUtils.class

```<code>public class ApiUtils {

    public static final String BASE_URL="";

    public static UserService getUserService(){
        return RetrofitClient.getClient(BASE_URL).create(UserService.class);
    }
}
</code>```

i have nullpointerexception in this line

```<code>  Call<ResUser> call=userService.login(new login(username,password));
</code>```

答:
i think your problem in login method and you should check null username and password before call:

Call call=userService.login(new login(username,password));

Accept my answer if it helpful for you.

Body:
Nullpointerexception in accessing interface method in retrofit calling

Userservice.class

public interface UserService {

    @POST("login")
    Call<ResUser> login(@Body login login);
}

RetrofitClient.class

public class RetrofitClient {

    private static Retrofit retrofit=null;

    public static Retrofit getClient(String url){

        if(retrofit==null){
            retrofit=new Retrofit.Builder()
                    .baseUrl(url)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }

        return retrofit;
    }
}

login.class

    private void doLogin(String username,String password){
    Call<ResUser> call=userService.login(new login(username,password));
    call.enqueue(new Callback<ResUser>() {
        @Override
        public void onResponse(Call<ResUser> call, Response<ResUser> response) {
            if(response.isSuccessful()){
             Log.e("succes");
            }
        }

        @Override
        public void onFailure(Call<ResUser> call, Throwable t) {

        }
    });

}

ApiUtils.class

public class ApiUtils {

    public static final String BASE_URL="";

    public static UserService getUserService(){
        return RetrofitClient.getClient(BASE_URL).create(UserService.class);
    }
}

i have nullpointerexception in this line

  Call<ResUser> call=userService.login(new login(username,password));


问:
What steps are required to create a custom Android version?

Background

We are handing out phones for people to use while visiting our exhibition, and in those phones we are running a j2me app. The people will be using the device on their own while walking around, and returning it when leaving.

Problem

While our app is made specifically to be easy to use and understand for someone who has never used it before, the phone OS is not... (Currently HTCs with Brew MP)

People are accidentally pressing the front buttons and are thrown back into the menus, or the screen locks and they dont know how to get back.

Solution?

The only solution I can think of is to create a custom Android version that we can use in our phones.

The thing I would like to change is to disable all hardware buttons and special swipes. So people are essentially locked into our app when it is launched.

A few questions comes to mind:

How hard it is to get a custom built android version up and running on a device?

Does disabling buttons mean I have to dig deep into the kernel, or is it easily accessible?

Are some handsets better suited for running custom android? (We are currently planning on using ZTE Blade)

Does android come with drivers for GSM/camera/GPS etc for most chipsets, or will that be a problem?

Am I over-complicating things? Perhaps regular apps can override what the buttons do already?

答:
Have a look at the link below for how to download and compile the android source, as for getting it on the device, I've not worked that bit out yet...

http://source.android.com/source/download.html

My guess is that you're gonna have to hack your device to be able to put your own firmware/rom on it. Ask on the #android-root irc on freenode for advice on that. I've heard of people putting their own roms on that phone so it is possible.

In my personal opinion I think you are hugely over complicating things. You can override the default action of the back button, and obviously the menu button. Not too sure about the home button.

Maybe just go for something super simple and give out / attach a piece of card to the phone with 'How to get back to the app if you're silly enough to quit it' instructions on it? That, or give everyone that leaves the app a bit of a slap and hopefully they shouldn't do it again ;)


问:
Daterangepicker / Moment JS - Wrong timestamp
I've been scratching my head over this for a while now. I am using daterangepicker.js (http://tamble.github.io/jquery-ui-daterangepicker/) in the front end of my UI. My implementation is pretty basic and can be found below. The issue is that whenever I convert the extensions time using moment.unix() the timestamp returns one hour before the date entered

```<code><script type="text/javascript">
    $("#date-range").daterangepicker({
        datepickerOptions : {
            numberOfMonths : 1,
        },
        presetRanges: [{
           text: 'Last 7 Days',
           dateStart: function(){return moment().subtract('days', 7)},
           dateEnd: function() { return moment() }
        },{
           text: 'Last 30 Days',
           dateStart: function(){return moment().subtract('days', 30)},
           dateEnd: function() { return moment() }
        },{
           text: 'Last 3 months',
           dateStart: function(){return moment().subtract('days', 90)},
           dateEnd: function() { return moment() }
        },{
           text: 'Last 6 months',
           dateStart: function(){return moment().subtract('days', 180)},
           dateEnd: function() { return moment() }
        },{
           text: 'This Year',
           dateStart: function(){return moment().startOf('year')},
           dateEnd: function() { return moment() }
        }],
        change:function(event, data){

            // gets inputted dates
            var inputData = $('#date-range').daterangepicker('getRange');

            console.log(inputData);

            // formats dates into unix time stamps
            var start = moment(inputData.start).unix();
            var end   = moment(inputData.end).unix();

            console.log(start);

            // get current URL of the page (without query string)
            var currentUrl = location.protocol+'//'+location.host+location.pathname;

            // create new url
            var newUrl = currentUrl+'?start='+start+'&end='+end;

            // redirect to new URL
            //window.location.href = newUrl;
        }
    });
</script>
</code>```

An example out put is here: as you can see the start stamp passed to my moment js is Mon 2nd October 2017 at midnight (this is correct and reflects what I selected in the UI)

start: Mon Oct 02 2017 00:00:00 GMT+0100 (GMT Daylight Time) {}

When I use

```<code>var start = moment(inputData.start).unix();
</code>```

It is converted to 1506898800 which reflects 10/01/2017 @ 11:00pm (UTC)

I have tried moment().utc().

Any pointers here ?

PS I am aware I could add 3600 to the timestamps but would prefer not to do it this way as I'm sure I am missing something relatively simple.

Thanks

答:
First of all, Mon Oct 02 2017 00:00:00 GMT+0100 (GMT Daylight Time) equals to
Sun Oct 01 2017 23:00:00 GMT+0000 (UTC) when converted to UTC.

Seconds, .unix() will return the seconds from 1970 relative to UTC time. Timestamps don't have timezones.

The solution is fixing the time zone to a specified one, and by doing that using the most safe one (UTC, no DST switches). To do that, try including moment-timezone to the page and run this code once before initializing the datepicker:

```<code>moment.tz.setDefault("UTC");
</code>```

This way all of your dates will be compatible with unix timestamps.

Body:
I've been scratching my head over this for a while now. I am using daterangepicker.js (http://tamble.github.io/jquery-ui-daterangepicker/) in the front end of my UI. My implementation is pretty basic and can be found below. The issue is that whenever I convert the extensions time using moment.unix() the timestamp returns one hour before the date entered

An example out put is here: as you can see the start stamp passed to my moment js is Mon 2nd October 2017 at midnight (this is correct and reflects what I selected in the UI)

start: Mon Oct 02 2017 00:00:00 GMT+0100 (GMT Daylight Time) {}

When I use

var start = moment(inputData.start).unix();

It is converted to 1506898800 which reflects 10/01/2017 @ 11:00pm (UTC)

I have tried moment().utc().

Any pointers here ?

PS I am aware I could add 3600 to the timestamps but would prefer not to do it this way as I'm sure I am missing something relatively simple.

Thanks

Body:
First of all, Mon Oct 02 2017 00:00:00 GMT+0100 (GMT Daylight Time) equals to
Sun Oct 01 2017 23:00:00 GMT+0000 (UTC) when converted to UTC.

Seconds, .unix() will return the seconds from 1970 relative to UTC time. Timestamps don't have timezones.

The solution is fixing the time zone to a specified one, and by doing that using the most safe one (UTC, no DST switches). To do that, try including moment-timezone to the page and run this code once before initializing the datepicker:

moment.tz.setDefault("UTC");

This way all of your dates will be compatible with unix timestamps.