问:
Error while connecting to facebook server through the proxy
I am having problems connecting to gtalk/facebook server from behind a proxy .In my loginservlet under doPost I specify the proxy settings before making a connection with the servers.The code is as follows:

```<code>package web;

import java.io.IOException;
import java.io.PrintWriter;

  import javax.servlet.ServletException;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;

  import org.jivesoftware.smack.ConnectionConfiguration;
  import org.jivesoftware.smack.SASLAuthentication;
  import org.jivesoftware.smack.XMPPConnection;
  import org.jivesoftware.smack.XMPPException;
  import org.jivesoftware.smack.proxy.ProxyInfo;

  import dao.MySASLDigestMD5Mechanism;

   public class LoginFacebookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

   public LoginFacebookServlet() {
    super();

  }
 XMPPConnection connection;
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String userName = request.getParameter("usrnm_fb");
    String password = request.getParameter("password_fb");

    response.setContentType("text/html");
    PrintWriter pw=response.getWriter();

    SASLAuthentication.registerSASLMechanism("DIGEST-MD5", MySASLDigestMD5Mechanism.class);
    //SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 0);

  ProxyInfo proxyInfo = new ProxyInfo(ProxyInfo.ProxyType.HTTP,"proxy.xxx.com"  "talk.google.com",   port, "username", "password");
    ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com",5222,proxyInfo);
    connection = new XMPPConnection(config);
   config.setSASLAuthenticationEnabled(true);
    try {
        connection.connect();
    } catch (XMPPException e) {
        e.printStackTrace();
    }
    try {
        connection.login(userName, password);
    } catch (XMPPException e) {
        e.printStackTrace();
    }
    System.out.println(connection.isAuthenticated());
   // System.out.println("Welcome!!you are now connected to facebook");
}
</code>```

}

When I run the application it still gives me 500 status error.Following is the stack trace

```<code> XMPPError connecting to chat.facebook.com:5222.: remote-server-error(502) XMPPError      connecting to chat.facebook.com:5222.
  -- caused by: java.net.ConnectException: Connection timed out: connect
at org.jivesoftware.smack.XMPPConnection.connectUsingConfiguration(XMPPConnection.java:900)
at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:1415)
at web.LoginFacebookServlet.doPost(LoginFacebookServlet.java:52)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
Nested Exception:
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at              org.jivesoftware.smack.proxy.DirectSocketFactory.createSocket(DirectSocketFactory.java:28)
at org.jivesoftware.smack.XMPPConnection.connectUsingConfiguration(XMPPConnection.java:888)
at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:1415)
at web.LoginFacebookServlet.doPost(LoginFacebookServlet.java:52)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at       org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
 Apr 26, 2011 11:32:24 AM org.apache.catalina.core.StandardWrapperValve invoke
 SEVERE: Servlet.service() for servlet LoginFacebookServlet threw exception
java.lang.IllegalStateException: Not connected to server.
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:382)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:349)
at web.LoginFacebookServlet.doPost(LoginFacebookServlet.java:57)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
</code>```

I checked to see  if any thing more was there to add for by passing proxy but am unable to understand as to where am I going wrong?

Thanks:)

答:
XMPP != HTTP so there's no reason to expect that an HTTP proxy will be used by an XMPP client. However, it seems like Smack has added HTTP proxy support (in addition to SOCKS4 and SOCKS5 proxy support they had earlier). The ConnectionConfiguration can accept a ProxyInfo parameter.

As far as I can tell from the JavaDocs, this is what you need to do:

```<code>ProxyInfo proxyInfo = new ProxyInfo(ProxyInfo.ProxyType.HTTP, "proxy.xxx.com", 8080, "username", "password")
ConnectionConfiguration config = new ConnectionConfiguration("facebook.com", 5222, proxyInfo);
XMPPConnection conn = new XMPPConnection(config);
conn.connect();
</code>```

Also, for future questions, please note

Although your question is tagged 'Smack' you posted no Smack specific code. The lines showing use of the URLConnection are pointless since that's not where your connection is failing.

Your question title indicates Google Talk, however everything else refers to Facebook. This is confusing and unclear questions or code that is NOT what you're actually working with will most likely lead to frustration for you and other members. As far as possible, you should post an SSCCE.

Body:
I am having problems connecting to gtalk/facebook server from behind a proxy .In my loginservlet under doPost I specify the proxy settings before making a connection with the servers.The code is as follows:

package web;

import java.io.IOException;
import java.io.PrintWriter;

  import javax.servlet.ServletException;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;

  import org.jivesoftware.smack.ConnectionConfiguration;
  import org.jivesoftware.smack.SASLAuthentication;
  import org.jivesoftware.smack.XMPPConnection;
  import org.jivesoftware.smack.XMPPException;
  import org.jivesoftware.smack.proxy.ProxyInfo;

  import dao.MySASLDigestMD5Mechanism;

   public class LoginFacebookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

   public LoginFacebookServlet() {
    super();

  }
 XMPPConnection connection;
/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String userName = request.getParameter("usrnm_fb");
    String password = request.getParameter("password_fb");

    response.setContentType("text/html");
    PrintWriter pw=response.getWriter();

    SASLAuthentication.registerSASLMechanism("DIGEST-MD5", MySASLDigestMD5Mechanism.class);
    //SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 0);

  ProxyInfo proxyInfo = new ProxyInfo(ProxyInfo.ProxyType.HTTP,"proxy.xxx.com"  "talk.google.com",   port, "username", "password");
    ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com",5222,proxyInfo);
    connection = new XMPPConnection(config);
   config.setSASLAuthenticationEnabled(true);
    try {
        connection.connect();
    } catch (XMPPException e) {
        e.printStackTrace();
    }
    try {
        connection.login(userName, password);
    } catch (XMPPException e) {
        e.printStackTrace();
    }
    System.out.println(connection.isAuthenticated());
   // System.out.println("Welcome!!you are now connected to facebook");
}

}

When I run the application it still gives me 500 status error.Following is the stack trace

 XMPPError connecting to chat.facebook.com:5222.: remote-server-error(502) XMPPError      connecting to chat.facebook.com:5222.
  -- caused by: java.net.ConnectException: Connection timed out: connect
at org.jivesoftware.smack.XMPPConnection.connectUsingConfiguration(XMPPConnection.java:900)
at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:1415)
at web.LoginFacebookServlet.doPost(LoginFacebookServlet.java:52)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
Nested Exception:
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at              org.jivesoftware.smack.proxy.DirectSocketFactory.createSocket(DirectSocketFactory.java:28)
at org.jivesoftware.smack.XMPPConnection.connectUsingConfiguration(XMPPConnection.java:888)
at org.jivesoftware.smack.XMPPConnection.connect(XMPPConnection.java:1415)
at web.LoginFacebookServlet.doPost(LoginFacebookServlet.java:52)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at       org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
 Apr 26, 2011 11:32:24 AM org.apache.catalina.core.StandardWrapperValve invoke
 SEVERE: Servlet.service() for servlet LoginFacebookServlet threw exception
java.lang.IllegalStateException: Not connected to server.
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:382)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:349)
at web.LoginFacebookServlet.doPost(LoginFacebookServlet.java:57)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)

I checked to see  if any thing more was there to add for by passing proxy but am unable to understand as to where am I going wrong?

Thanks:)

Body:
XMPP != HTTP so there's no reason to expect that an HTTP proxy will be used by an XMPP client. However, it seems like Smack has added HTTP proxy support (in addition to SOCKS4 and SOCKS5 proxy support they had earlier). The ConnectionConfiguration can accept a ProxyInfo parameter.

As far as I can tell from the JavaDocs, this is what you need to do:

ProxyInfo proxyInfo = new ProxyInfo(ProxyInfo.ProxyType.HTTP, "proxy.xxx.com", 8080, "username", "password")
ConnectionConfiguration config = new ConnectionConfiguration("facebook.com", 5222, proxyInfo);
XMPPConnection conn = new XMPPConnection(config);
conn.connect();

Also, for future questions, please note

Although your question is tagged 'Smack' you posted no Smack specific code. The lines showing use of the URLConnection are pointless since that's not where your connection is failing.

Your question title indicates Google Talk, however everything else refers to Facebook. This is confusing and unclear questions or code that is NOT what you're actually working with will most likely lead to frustration for you and other members. As far as possible, you should post an SSCCE.


来源: stackexchange

问:
Spring boot rest response gives 1 result on OneToMany when there are multiple objects in database
For a school project, we have to make a spring boot rest server that communicates to our MySQL database. Here is a screenshot of the database:

For my user model I have the following:

```<code>@Entity
@Table(name = "User")
@Setter
public class User extends ResourceSupport implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_user", updatable = false, nullable = false)
    @JsonSerialize
    private Long id;
    @Getter
    private String firstName;
    @Getter
    private String lastName;
    @Getter
    private String email;
    @Getter
    private String password;
    @Getter
    private Double hourlyWage;
    @Getter
    private String adress;
    @Getter
    private String city;
    @Getter
    private Boolean isManager;
    @Getter
    @OneToMany
    @JoinTable(name = "user_to_project", joinColumns = @JoinColumn(name = "id"), inverseJoinColumns = @JoinColumn(name = "project_id"))
    private List<Project> projects;

</code>```

Then for my project class:

```<code>@Entity
@Table(name = "project")
@Setter
public class Project extends ResourceSupport {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_project")
    @JsonSerialize
    private Long id;
    @Getter
    @OneToOne
    @JoinColumn(name = "owner", referencedColumnName = "id")
    private Company owner;
    @Getter
    private String description;
    @Getter
    private String name;
    @Getter
    private double payout;
    @Getter
    private boolean internal;
    @Getter
    @OneToMany
    @JoinTable(name = "user_to_project", joinColumns = @JoinColumn(name = "id"), inverseJoinColumns = @JoinColumn(name = "user_id"))
    private List<User> users;
</code>```

I don't know what I'm doing wrong because this is the result I am getting:

while I have this in my link table:

I Hope someone has an answer to my question because I'm getting sick of spring boot and this school project.

答:
I don't know will it help you or not, but below is my code:

```<code>// Role
@LazyCollection(LazyCollectionOption.FALSE)
@ManyToMany(mappedBy = "roles")
@JsonIgnoreProperties("roles")
@OrderBy("id")
private List<User> users;

// User
@LazyCollection(LazyCollectionOption.FALSE)
@ManyToMany
@JoinTable(name = "users_roles",
        joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")
)
@JsonIgnoreProperties("users")
@OrderBy("id")
private List<Role> roles;
</code>```

Also, take attention - instead of SQL where m2m tables are equals, in JPA one table is "master" (User in my example) and other one "slave". "Slave" should have modifier mappedBy in @ManyToMany annotation.

Table DDLs (postgres):

```<code>create table roles
(
  id               serial                not null
    constraint roles_pkey
    primary key,
  version          bigint default 0
);

create table users
(
  id               serial                not null
    constraint users_pkey
    primary key,
  version          bigint  default 0
);

create table users_roles
(
  user_id integer not null
    constraint fk_users
    references users,
  role_id integer not null
    constraint fk_roles
    references roles,
  constraint users_roles_pkey
  primary key (user_id, role_id)
);
</code>```

I hope it will be helpful. Good luck.

ContentLicense: CC BY-SA 4.0

Body:
For a school project, we have to make a spring boot rest server that communicates to our MySQL database. Here is a screenshot of the database:

For my user model I have the following:

@Entity
@Table(name = "User")
@Setter
public class User extends ResourceSupport implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_user", updatable = false, nullable = false)
    @JsonSerialize
    private Long id;
    @Getter
    private String firstName;
    @Getter
    private String lastName;
    @Getter
    private String email;
    @Getter
    private String password;
    @Getter
    private Double hourlyWage;
    @Getter
    private String adress;
    @Getter
    private String city;
    @Getter
    private Boolean isManager;
    @Getter
    @OneToMany
    @JoinTable(name = "user_to_project", joinColumns = @JoinColumn(name = "id"), inverseJoinColumns = @JoinColumn(name = "project_id"))
    private List<Project> projects;

Then for my project class:

@Entity
@Table(name = "project")
@Setter
public class Project extends ResourceSupport {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_project")
    @JsonSerialize
    private Long id;
    @Getter
    @OneToOne
    @JoinColumn(name = "owner", referencedColumnName = "id")
    private Company owner;
    @Getter
    private String description;
    @Getter
    private String name;
    @Getter
    private double payout;
    @Getter
    private boolean internal;
    @Getter
    @OneToMany
    @JoinTable(name = "user_to_project", joinColumns = @JoinColumn(name = "id"), inverseJoinColumns = @JoinColumn(name = "user_id"))
    private List<User> users;

I don't know what I'm doing wrong because this is the result I am getting:

while I have this in my link table:

I Hope someone has an answer to my question because I'm getting sick of spring boot and this school project.

Body:
I don't know will it help you or not, but below is my code:

// Role
@LazyCollection(LazyCollectionOption.FALSE)
@ManyToMany(mappedBy = "roles")
@JsonIgnoreProperties("roles")
@OrderBy("id")
private List<User> users;

// User
@LazyCollection(LazyCollectionOption.FALSE)
@ManyToMany
@JoinTable(name = "users_roles",
        joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")
)
@JsonIgnoreProperties("users")
@OrderBy("id")
private List<Role> roles;

Also, take attention - instead of SQL where m2m tables are equals, in JPA one table is "master" (User in my example) and other one "slave". "Slave" should have modifier mappedBy in @ManyToMany annotation.

Table DDLs (postgres):

create table roles
(
  id               serial                not null
    constraint roles_pkey
    primary key,
  version          bigint default 0
);

create table users
(
  id               serial                not null
    constraint users_pkey
    primary key,
  version          bigint  default 0
);

create table users_roles
(
  user_id integer not null
    constraint fk_users
    references users,
  role_id integer not null
    constraint fk_roles
    references roles,
  constraint users_roles_pkey
  primary key (user_id, role_id)
);

I hope it will be helpful. Good luck.


问:
How to create a program that converts binary to decimal
I'm trying to convert binary to decimal, how do I change my code to be able to do that? Where did I mess up?

i tried looking at other examples, looking at java api and watching videos but i still can't figure out what mistake i have made.

```<code>package Calculator;
import java.util.Scanner;
public class Calculator {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
            System.out.println("(2) Convert binary to decimal");
            System.out.println("\n\n Please enter your choice: ");
            int choice = scan.nextInt();
            if(choice == 2){
                scan.nextLine();
                //prompt for user input
                System.out.println("Please enter a binary number: ");
                String binary = scan.nextLine();
                char[] binaryArray = binary.toCharArray();
                int i=1;
                int integer=0;
            //potential problem somewhere around here?
            while(i<8){
                if(binaryArray[i]==0) {
                    ++i;
                }else if(binaryArray[i]==1) {
                    switch(i) {
                    case 1:
                        integer+=128;
                        ++i;
                        break;
                    case 2:
                        integer+=64;
                        ++i;
                        break;
                    case 3:
                        integer+=32;
                        ++i;
                        break;
                    case 4:
                        integer+=16;
                        ++i;
                        break;
                    case 5:
                        integer+=8;
                        ++i;
                        break;
                    case 6:
                        integer+=4;
                        ++i;
                        break;
                    case 7:
                        integer+=2;
                        ++i;
                        break;
                    case 8:
                        integer+=1;
                        ++i;
                        break;
                    }
            }
        }
            System.out.println("The decimal value of the binary number is: "+ integer);
            scan.close();
    }
}
</code>```

}

The input is always 0. I've tried 11010110, 11111111,and 01010111. Always 0. I know the problem lies somewhere with my integer value not changing but I can't figure out what it specifically is.

答:
Others have already pointed out that you have got confused between 0 and 1, and '0' and'1'`.

Other problems:

Your i starts at 1, so you miss the most significant bit;

You will never actually hit case 8: in the switch because of the while (i < 8) loop guard.

This doesn't work unless you enter exactly 8 bits.

You can write the entire while loop in a much more concise way:

```<code>for (int i = 0; i < binaryArray.length; i++) {
  integer *= 2; // shift the digits along by 1 place
  if (binaryArray[i] == '1') {
    integer += 1; // set the least significant bit.
  }
}
</code>```

Body:
I'm trying to convert binary to decimal, how do I change my code to be able to do that? Where did I mess up?

i tried looking at other examples, looking at java api and watching videos but i still can't figure out what mistake i have made.

package Calculator;
import java.util.Scanner;
public class Calculator {
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
            System.out.println("(2) Convert binary to decimal");
            System.out.println("\n\n Please enter your choice: ");
            int choice = scan.nextInt();
            if(choice == 2){
                scan.nextLine();
                //prompt for user input
                System.out.println("Please enter a binary number: ");
                String binary = scan.nextLine();
                char[] binaryArray = binary.toCharArray();
                int i=1;
                int integer=0;
            //potential problem somewhere around here?
            while(i<8){
                if(binaryArray[i]==0) {
                    ++i;
                }else if(binaryArray[i]==1) {
                    switch(i) {
                    case 1:
                        integer+=128;
                        ++i;
                        break;
                    case 2:
                        integer+=64;
                        ++i;
                        break;
                    case 3:
                        integer+=32;
                        ++i;
                        break;
                    case 4:
                        integer+=16;
                        ++i;
                        break;
                    case 5:
                        integer+=8;
                        ++i;
                        break;
                    case 6:
                        integer+=4;
                        ++i;
                        break;
                    case 7:
                        integer+=2;
                        ++i;
                        break;
                    case 8:
                        integer+=1;
                        ++i;
                        break;
                    }
            }
        }
            System.out.println("The decimal value of the binary number is: "+ integer);
            scan.close();
    }
}

}

The input is always 0. I've tried 11010110, 11111111,and 01010111. Always 0. I know the problem lies somewhere with my integer value not changing but I can't figure out what it specifically is.

Body:
Others have already pointed out that you have got confused between 0 and 1, and '0' and'1'`.

Other problems:

Your i starts at 1, so you miss the most significant bit;

You will never actually hit case 8: in the switch because of the while (i < 8) loop guard.

This doesn't work unless you enter exactly 8 bits.

You can write the entire while loop in a much more concise way:

for (int i = 0; i < binaryArray.length; i++) {
  integer *= 2; // shift the digits along by 1 place
  if (binaryArray[i] == '1') {
    integer += 1; // set the least significant bit.
  }
}


问:
Summary of knapsack solve in CPLEX
So I'm have trouble in python version of CPLEX. I would think it would be pretty easy to get like a summary of what the solver did i.e number of branches, etc.

Anyone know how to do this?

```<code>import cplex
from cplex.exceptions import CplexError
class knapsack:
    def __init__(self,N,g,square_list):
        self.N = N
        self.square_list= square_list
        self.g = g
    def solve_problem(self):
        try:
            my_prob = cplex.Cplex()
            prob =my_prob
            prob.set_log_stream(None)
            prob.set_error_stream(None)
            prob.set_warning_stream(None)
            prob.set_results_stream(None)
            my_obj = self.g
            my_ctype = "B"
            number_of_one = self.square_list.count(1.0)
            my_ctype = my_ctype*len(self.square_list)
            val = self.N  -number_of_one
            rhs=[val]
            my_sense="L"
            my_rownames = ["r1"]

            counter =0
            variable_list=[]
            coiff_list=[]
            for i in self.square_list:
                if i==0:
                    coiff_list.append(1.0)
                else:
                    coiff_list.append(-1.0)
                variable_list.append("w" + str(counter))
                counter+=1

            rows = [[variable_list, coiff_list]]
            prob.objective.set_sense(prob.objective.sense.minimize)

            prob.variables.add(obj=my_obj, types=my_ctype,
                        names=variable_list)
            prob.linear_constraints.add(lin_expr=rows, senses=my_sense,
                                    rhs=rhs)
            my_prob.solve()
            x = my_prob.solution.get_values()
            print(my_prob.solution.get_status())
            print("---")
            print(my_prob.solution.status())
            return x
        except CplexError as exc:
            print(exc)
            return
</code>```

When I look at the methods associated with my_prob and myprob.solution I see

```<code>['MIP_starts', 'SOS', '_Cplex__copy_init', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_aborter', '_disposed', '_env', '_env_lp_ptr', '_invoke_generic_callback', '_is_MIP', '_is_special_filetype', '_lp', 'advanced', 'cleanup', 'conflict', 'copy_vmconfig', 'del_vmconfig', 'double_annotations', 'end', 'feasopt', 'get_aborter', 'get_dettime', 'get_num_cores', 'get_problem_name', 'get_problem_type', 'get_stats', 'get_time', 'get_version', 'get_versionnumber', 'has_vmconfig', 'indicator_constraints', 'linear_constraints', 'long_annotations', 'objective', 'order', 'parameters', 'populate_solution_pool', 'presolve', 'problem_type', 'pwl_constraints', 'quadratic_constraints', 'read', 'read_annotations', 'read_copy_vmconfig', 'register_callback', 'remove_aborter', 'runseeds', 'set_callback', 'set_error_stream', 'set_log_stream', 'set_problem_name', 'set_problem_type', 'set_results_stream', 'set_warning_stream', 'solution', 'solve', 'start', 'unregister_callback', 'use_aborter', 'variables', 'write', 'write_annotations', 'write_benders_annotation']
['MIP', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_add_iter', '_add_single', '_conv', '_cplex', '_env', '_get_index', '_get_index_function', 'advanced', 'basis', 'get_activity_levels', 'get_dual_values', 'get_float_quality', 'get_indicator_slacks', 'get_indices', 'get_integer_quality', 'get_linear_slacks', 'get_method', 'get_objective_value', 'get_quadratic_activity_levels', 'get_quadratic_dualslack', 'get_quadratic_slacks', 'get_quality_metrics', 'get_reduced_costs', 'get_solution_type', 'get_status', 'get_status_string', 'get_values', 'infeasibility', 'is_dual_feasible', 'is_primal_feasible', 'method', 'pool', 'progress', 'quality_metric', 'sensitivity', 'status', 'type', 'write']
</code>```

答:
Found that there is a write function on the solution object

```<code>my_prob.solution.write("myanswer")
</code>```

This contains all relevant information on the CPLEX run.

Title: Summary of knapsack solve in CPLEX

Body:
So I'm have trouble in python version of CPLEX. I would think it would be pretty easy to get like a summary of what the solver did i.e number of branches, etc.

Anyone know how to do this?

import cplex
from cplex.exceptions import CplexError
class knapsack:
    def __init__(self,N,g,square_list):
        self.N = N
        self.square_list= square_list
        self.g = g
    def solve_problem(self):
        try:
            my_prob = cplex.Cplex()
            prob =my_prob
            prob.set_log_stream(None)
            prob.set_error_stream(None)
            prob.set_warning_stream(None)
            prob.set_results_stream(None)
            my_obj = self.g
            my_ctype = "B"
            number_of_one = self.square_list.count(1.0)
            my_ctype = my_ctype*len(self.square_list)
            val = self.N  -number_of_one
            rhs=[val]
            my_sense="L"
            my_rownames = ["r1"]

            counter =0
            variable_list=[]
            coiff_list=[]
            for i in self.square_list:
                if i==0:
                    coiff_list.append(1.0)
                else:
                    coiff_list.append(-1.0)
                variable_list.append("w" + str(counter))
                counter+=1

            rows = [[variable_list, coiff_list]]
            prob.objective.set_sense(prob.objective.sense.minimize)

            prob.variables.add(obj=my_obj, types=my_ctype,
                        names=variable_list)
            prob.linear_constraints.add(lin_expr=rows, senses=my_sense,
                                    rhs=rhs)
            my_prob.solve()
            x = my_prob.solution.get_values()
            print(my_prob.solution.get_status())
            print("---")
            print(my_prob.solution.status())
            return x
        except CplexError as exc:
            print(exc)
            return

When I look at the methods associated with my_prob and myprob.solution I see

['MIP_starts', 'SOS', '_Cplex__copy_init', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_aborter', '_disposed', '_env', '_env_lp_ptr', '_invoke_generic_callback', '_is_MIP', '_is_special_filetype', '_lp', 'advanced', 'cleanup', 'conflict', 'copy_vmconfig', 'del_vmconfig', 'double_annotations', 'end', 'feasopt', 'get_aborter', 'get_dettime', 'get_num_cores', 'get_problem_name', 'get_problem_type', 'get_stats', 'get_time', 'get_version', 'get_versionnumber', 'has_vmconfig', 'indicator_constraints', 'linear_constraints', 'long_annotations', 'objective', 'order', 'parameters', 'populate_solution_pool', 'presolve', 'problem_type', 'pwl_constraints', 'quadratic_constraints', 'read', 'read_annotations', 'read_copy_vmconfig', 'register_callback', 'remove_aborter', 'runseeds', 'set_callback', 'set_error_stream', 'set_log_stream', 'set_problem_name', 'set_problem_type', 'set_results_stream', 'set_warning_stream', 'solution', 'solve', 'start', 'unregister_callback', 'use_aborter', 'variables', 'write', 'write_annotations', 'write_benders_annotation']
['MIP', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_add_iter', '_add_single', '_conv', '_cplex', '_env', '_get_index', '_get_index_function', 'advanced', 'basis', 'get_activity_levels', 'get_dual_values', 'get_float_quality', 'get_indicator_slacks', 'get_indices', 'get_integer_quality', 'get_linear_slacks', 'get_method', 'get_objective_value', 'get_quadratic_activity_levels', 'get_quadratic_dualslack', 'get_quadratic_slacks', 'get_quality_metrics', 'get_reduced_costs', 'get_solution_type', 'get_status', 'get_status_string', 'get_values', 'infeasibility', 'is_dual_feasible', 'is_primal_feasible', 'method', 'pool', 'progress', 'quality_metric', 'sensitivity', 'status', 'type', 'write']

Body:
Found that there is a write function on the solution object

my_prob.solution.write("myanswer")

This contains all relevant information on the CPLEX run.


问:
Solving for the upper bound and lower bound of liars, in liar-truth teller problem
I am trying to solve a truth teller/ Liar problem. A survey of a class is taken. Answers are in the form of a Matrix A, where A[i][j] represents the reply given by the i-th student about the j-th student. If that character is ‘L’ – it means he/she is a liar; if it’s ‘T’ – then it means that, that student is a truth speaker.

Truth-Speaker (‘T’): All his/her replies are true.
Liar (‘L’) : (S)he has made at least one false reply.

ex. 1

```<code>TLLL

LTLL

LLTL

LLLT
</code>```

Class contains at least 3 and at most 4 liars, 3 is the lower bound of liars, and 4 is the upper bound.

ex. 2

```<code>TLTLT

TTTTT

LLTLL

LLLLL

TLTLT
</code>```

Class contains at least 4 and at most 4 liars

I am not sure how the lower and upper bound was found, any help would be appreciated.

答:
For the examples you give you can just follow the logic and see what follows from assuming that a particular person is T. In general you can set up a mixed integer programming problem.

Let x_i=1 if person i is L, and x_i=0 if he is T. Then create a linear function from the statements of every person. For example, from TLTLT create:

```<code>f_1 = (x_1) + (1-x_2) + (x_3) + (1-x_4) + (x_5)
</code>```

You can see the pattern. For any feasible assignment (that is, a setting of the x variables where there is no contradiction between the x values and the people's statements) you must have that x_1=0 if and only if f_1=0, and x_1=1 if and only if f_1>0, or, since everything is integer, f_1>=1. This is equivalent to f_i>=x_i and f_i<=(N+1)x_i (where N is the number of people). So now you have the system:

```<code>For all i=1,...,N
    f_i>=x_i
    f_i<=(N+1)x_i
    x_i is 0 or 1
</code>```

and every feasible solution to this system corresponds to a feasible assignment and vice versa.

With these constraints simply minimize and maximize sum x_i to get the lower and upper bound on the number of liars.

Body:
I am trying to solve a truth teller/ Liar problem. A survey of a class is taken. Answers are in the form of a Matrix A, where A[i][j] represents the reply given by the i-th student about the j-th student. If that character is ‘L’ – it means he/she is a liar; if it’s ‘T’ – then it means that, that student is a truth speaker.

Truth-Speaker (‘T’): All his/her replies are true.
Liar (‘L’) : (S)he has made at least one false reply.

ex. 1

TLLL

LTLL

LLTL

LLLT

Class contains at least 3 and at most 4 liars, 3 is the lower bound of liars, and 4 is the upper bound.

ex. 2

TLTLT

TTTTT

LLTLL

LLLLL

TLTLT

Class contains at least 4 and at most 4 liars

I am not sure how the lower and upper bound was found, any help would be appreciated.

Body:
For the examples you give you can just follow the logic and see what follows from assuming that a particular person is T. In general you can set up a mixed integer programming problem.

Let x_i=1 if person i is L, and x_i=0 if he is T. Then create a linear function from the statements of every person. For example, from TLTLT create:

f_1 = (x_1) + (1-x_2) + (x_3) + (1-x_4) + (x_5)

You can see the pattern. For any feasible assignment (that is, a setting of the x variables where there is no contradiction between the x values and the people's statements) you must have that x_1=0 if and only if f_1=0, and x_1=1 if and only if f_1>0, or, since everything is integer, f_1>=1. This is equivalent to f_i>=x_i and f_i<=(N+1)x_i (where N is the number of people). So now you have the system:

For all i=1,...,N
    f_i>=x_i
    f_i<=(N+1)x_i
    x_i is 0 or 1

and every feasible solution to this system corresponds to a feasible assignment and vice versa.

With these constraints simply minimize and maximize sum x_i to get the lower and upper bound on the number of liars.


问:
Locally installed executable dependencies fail using npm run/yarn run on Windows
I am using a Windows machine as my primary development machine. I usually use WSL for most of my projects, but one of my electron projects requires me to work in the Windows environment. So I've set up node, npm, yarn & git on the Windows side as well. But I am having troubles with locally installed dependencies.
Say, I have added concurrently to my project using yarn add concurrently. Now if I do yarn run concurrently, it fails saying that 'C:\Users\Praneet\Projects\my-project\node_modules\.bin\concurrently' is not recognized as an internal or external command. But if I do yarn run concurrently.cmd, it works. Same thing happens for scripts in package.json. I have to change react-scripts start to react-scripts.cmd start to make it work. But I don't want to do this for every script, because there are other devs working with me who use MacOS. I will be really grateful if someone could help me with this.

答:
Have you tried running these commands using Windows Powershell? It might work.

Another option (the one I use when I must code in a Windows environment) is to use Git Bash: https://gitforwindows.org/

It simulates a BASH for Windows, so the commands you are trying to run should work without the .cmd.


问:
Persistence file operations in background
Currently I'm developing a persistence library for Android in Kotlin. Now I am at the point where I've to handle  file operations (read, write, etc.) and I wonder what is the best way to do this? First I don't have to do this on the main thread to block the UI. Second I have to be sure that all operations are executed immediately and no one gets lost at process kills or device restarts.

I looked at the background guide on the developer site but now I am a bit confused. As I don't want to start a forground service for each persist operation it looks like WorkManager is the best solution for me. The documentation states:

WorkManager is intended for tasks that are deferrable - that is, not required to run immediately - and required to run reliably even if the app exits or the device restarts.

But here is the problem: My work should be executed immediately and does not depend on system events so I am not sure if this is the best way to go. What do you thing is the best solution for me?

答:
You can have a repository expose suspend functions that handle the I/O. Here is a TextRepository that reads and writes text from a Uri (as this is adapted from a future book sample that supports files and Storage Access Framework Uri values):

```<code>class TextRepository(context: Context) {
  private val resolver: ContentResolver = context.contentResolver

  suspend fun read(source: Uri) = withContext(Dispatchers.IO) {
    try {
      resolver.openInputStream(source)?.use { stream ->
        StreamResult.Content(source, stream.readText())
      } ?: throw IllegalStateException("could not open $source")
    } catch (e: FileNotFoundException) {
      StreamResult.Content(source, "")
    } catch (t: Throwable) {
      StreamResult.Error(t)
    }
  }

  suspend fun write(source: Uri, text: String): StreamResult =
    withContext(Dispatchers.IO) {
      try {
        resolver.openOutputStream(source)?.use { stream ->
          stream.writeText(text)
          StreamResult.Content(source, text)
        } ?: throw IllegalStateException("could not open $source")
      } catch (t: Throwable) {
        StreamResult.Error(t)
      }
    }
}

private fun InputStream.readText(charset: Charset = Charsets.UTF_8): String =
  readBytes().toString(charset)

private fun OutputStream.writeText(
  text: String,
  charset: Charset = Charsets.UTF_8
): Unit = write(text.toByteArray(charset))

sealed class StreamResult {
  object Loading : StreamResult()
  data class Content(val source: Uri, val text: String) : StreamResult()
  data class Error(val throwable: Throwable) : StreamResult()
}
</code>```

In this case, I am using the loading-content-error (LCE) pattern, where the suspend functions are returning a StreamResult. StreamResult.Content wraps the read-in text or the text that was just written.

Then, you can have a ViewModel of some sort call the suspend functions:

```<code>class MainMotor(repo: TextRepository) : ViewModel {
  private val _results = MutableLiveData<StreamResult>()
  val results: LiveData<StreamResult> = _results

  fun read(source: Uri) {
    _results.value = StreamResult.Loading

    viewModelScope.launch(Dispatchers.Main) {
      _results.value = repo.read(source)
    }
  }

  fun write(source: Uri, text: String) {
    _results.value = StreamResult.Loading

    viewModelScope.launch(Dispatchers.Main) {
      _results.value = repo.write(source, text)
    }
  }
}
</code>```

In my case, I route the StreamResult unmodified through a MutableLiveData for the UI to consume, following an MVI-style pattern. In practice, a ViewModel probably transforms the repo result into something more directly usable by the UI, and so the LiveData would be of some other type, with the ViewModel performing the conversion.

Body:
You can have a repository expose suspend functions that handle the I/O. Here is a TextRepository that reads and writes text from a Uri (as this is adapted from a future book sample that supports files and Storage Access Framework Uri values):

class TextRepository(context: Context) {
  private val resolver: ContentResolver = context.contentResolver

  suspend fun read(source: Uri) = withContext(Dispatchers.IO) {
    try {
      resolver.openInputStream(source)?.use { stream ->
        StreamResult.Content(source, stream.readText())
      } ?: throw IllegalStateException("could not open $source")
    } catch (e: FileNotFoundException) {
      StreamResult.Content(source, "")
    } catch (t: Throwable) {
      StreamResult.Error(t)
    }
  }

  suspend fun write(source: Uri, text: String): StreamResult =
    withContext(Dispatchers.IO) {
      try {
        resolver.openOutputStream(source)?.use { stream ->
          stream.writeText(text)
          StreamResult.Content(source, text)
        } ?: throw IllegalStateException("could not open $source")
      } catch (t: Throwable) {
        StreamResult.Error(t)
      }
    }
}

private fun InputStream.readText(charset: Charset = Charsets.UTF_8): String =
  readBytes().toString(charset)

private fun OutputStream.writeText(
  text: String,
  charset: Charset = Charsets.UTF_8
): Unit = write(text.toByteArray(charset))

sealed class StreamResult {
  object Loading : StreamResult()
  data class Content(val source: Uri, val text: String) : StreamResult()
  data class Error(val throwable: Throwable) : StreamResult()
}

In this case, I am using the loading-content-error (LCE) pattern, where the suspend functions are returning a StreamResult. StreamResult.Content wraps the read-in text or the text that was just written.

Then, you can have a ViewModel of some sort call the suspend functions:

class MainMotor(repo: TextRepository) : ViewModel {
  private val _results = MutableLiveData<StreamResult>()
  val results: LiveData<StreamResult> = _results

  fun read(source: Uri) {
    _results.value = StreamResult.Loading

    viewModelScope.launch(Dispatchers.Main) {
      _results.value = repo.read(source)
    }
  }

  fun write(source: Uri, text: String) {
    _results.value = StreamResult.Loading

    viewModelScope.launch(Dispatchers.Main) {
      _results.value = repo.write(source, text)
    }
  }
}

In my case, I route the StreamResult unmodified through a MutableLiveData for the UI to consume, following an MVI-style pattern. In practice, a ViewModel probably transforms the repo result into something more directly usable by the UI, and so the LiveData would be of some other type, with the ViewModel performing the conversion.


问:
Wordpress Images not displaying on Mobile
Wordpress Images will display correctly on Desktop but not on Mobile. Sometimes upon refreshing, a different set of images will display each time?

I have attempting in uninstalling all plugins already, and am not sure if anyone can inspect the issue using their mobile device or offer some additional options

.htaccess:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
# BEGIN WP-HUMMINGBIRD-CACHING
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault A0
<FilesMatch "\.(txt|xml|js)$">
ExpiresDefault A691200
</FilesMatch>
<FilesMatch "\.(css)$">
ExpiresDefault A691200
</FilesMatch>
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav|mp4|m4v|ogg|webm|aac|eot|ttf|otf|woff|svg)$">
ExpiresDefault A691200
</FilesMatch>
<FilesMatch "\.(jpg|jpeg|png|gif|swf|webp)$">
ExpiresDefault A691200
</FilesMatch>
</IfModule>
<IfModule mod_headers.c>
  <FilesMatch "\.(txt|xml|js)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
  <FilesMatch "\.(css)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
  <FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav|mp4|m4v|ogg|webm|aac|eot|ttf|otf|woff|svg)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
  <FilesMatch "\.(jpg|jpeg|png|gif|swf|webp)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
</IfModule>
# END WP-HUMMINGBIRD-CACHING
# BEGIN ShortPixelWebp

# END ShortPixelWebp
</code>```

答:
Not enough information here. You have only given us the code for the htaccess file and you state

and am not sure if anyone can inspect the issue using their mobile device or offer some additional options

but you have not given us any address

Body:
Wordpress Images will display correctly on Desktop but not on Mobile. Sometimes upon refreshing, a different set of images will display each time?

I have attempting in uninstalling all plugins already, and am not sure if anyone can inspect the issue using their mobile device or offer some additional options

.htaccess:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
# BEGIN WP-HUMMINGBIRD-CACHING
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault A0
<FilesMatch "\.(txt|xml|js)$">
ExpiresDefault A691200
</FilesMatch>
<FilesMatch "\.(css)$">
ExpiresDefault A691200
</FilesMatch>
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav|mp4|m4v|ogg|webm|aac|eot|ttf|otf|woff|svg)$">
ExpiresDefault A691200
</FilesMatch>
<FilesMatch "\.(jpg|jpeg|png|gif|swf|webp)$">
ExpiresDefault A691200
</FilesMatch>
</IfModule>
<IfModule mod_headers.c>
  <FilesMatch "\.(txt|xml|js)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
  <FilesMatch "\.(css)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
  <FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav|mp4|m4v|ogg|webm|aac|eot|ttf|otf|woff|svg)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
  <FilesMatch "\.(jpg|jpeg|png|gif|swf|webp)$">
   Header set Cache-Control "max-age=691200"
  </FilesMatch>
</IfModule>
# END WP-HUMMINGBIRD-CACHING
# BEGIN ShortPixelWebp

# END ShortPixelWebp


问:
No space left on device due to docker/cron
I have a basic server on google cloud that just runs a docker container via cron once every 30 minutes. I noticed that the docker command stopped working and I got an error saying

```<code>docker: Error response from daemon: no space left on device.
</code>```

I then noticed that I got this error even when I trying to autocomplete in bash by typing cd path/ and hitting tab. I figured out something was probably wrong with the storage so I tried df -h and it showed this:

```<code>Filesystem      Size  Used Avail Use% Mounted on
udev            860M     0  860M   0% /dev
tmpfs           175M   19M  157M  11% /run
/dev/sda1       9.7G  9.7G     0 100% /
tmpfs           871M     0  871M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           871M     0  871M   0% /sys/fs/cgroup
tmpfs           175M     0  175M   0% /run/user/1001
</code>```

As you can see /dev/sda1 is 100% full for some reason. Why is this happening and how can I fix it?

I noticed there were several thousand exited docker containers so I removed this with this command:

```<code>docker rm -v $(docker ps -a -q -f status=exited)
</code>```

Now the storage usage is 61%, which is still too high.

答:
When running containers that you do not need to keep in a stopped state, it's a good practice to use docker run --rm ... to automatically cleanup the stopped container.

If the container generates volumes, visible in docker volume ls, you'll likely want to clean these once the data is no longer needed. with the --rm flag on run, anonymous volumes (which appear as a long unique id) will be automatically deleted.

Docker also provides the command:

```<code>docker system prune
</code>```

which you can automate to cleanup images, containers, networks, and even volumes. Note that you should take time to understand what this command does before running it, and especially before automating it. When scripting this command, you can use the -f flag to bypass the prompt.

Before running a prune, you can check:

```<code>docker system df
</code>```

to see how much disk is being used by each component, and each component has it's own prune command, e.g. docker container prune and docker volume prune, should you want to clean just one area.

For more details on the prune command, see: https://docs.docker.com/engine/reference/commandline/system_prune/

Body:
I have a basic server on google cloud that just runs a docker container via cron once every 30 minutes. I noticed that the docker command stopped working and I got an error saying

docker: Error response from daemon: no space left on device.

I then noticed that I got this error even when I trying to autocomplete in bash by typing cd path/ and hitting tab. I figured out something was probably wrong with the storage so I tried df -h and it showed this:

Filesystem      Size  Used Avail Use% Mounted on
udev            860M     0  860M   0% /dev
tmpfs           175M   19M  157M  11% /run
/dev/sda1       9.7G  9.7G     0 100% /
tmpfs           871M     0  871M   0% /dev/shm
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           871M     0  871M   0% /sys/fs/cgroup
tmpfs           175M     0  175M   0% /run/user/1001

As you can see /dev/sda1 is 100% full for some reason. Why is this happening and how can I fix it?

I noticed there were several thousand exited docker containers so I removed this with this command:

docker rm -v $(docker ps -a -q -f status=exited)

Now the storage usage is 61%, which is still too high.

Body:
When running containers that you do not need to keep in a stopped state, it's a good practice to use docker run --rm ... to automatically cleanup the stopped container.

If the container generates volumes, visible in docker volume ls, you'll likely want to clean these once the data is no longer needed. with the --rm flag on run, anonymous volumes (which appear as a long unique id) will be automatically deleted.

Docker also provides the command:

docker system prune

which you can automate to cleanup images, containers, networks, and even volumes. Note that you should take time to understand what this command does before running it, and especially before automating it. When scripting this command, you can use the -f flag to bypass the prompt.

Before running a prune, you can check:

docker system df

to see how much disk is being used by each component, and each component has it's own prune command, e.g. docker container prune and docker volume prune, should you want to clean just one area.

For more details on the prune command, see: https://docs.docker.com/engine/reference/commandline/system_prune/


问:
How does laravel redirect first to public folder?
I am looking at a stock laravel 5.8 project and I am trying to understand how does Laravel redirect all the requests from the / to the /public folder.

There is no index.php file in the root and no .htaccess to redirect traffic to public?

答:
laravel 5.8 i use the following

root .htaccess

```<code>RewriteEngine On

RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L,QSA]
</code>```

public/.htaccess

```<code><IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
</code>```

Body:
laravel 5.8 i use the following

root .htaccess

RewriteEngine On

RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L,QSA]

public/.htaccess

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>


问:
Calling super().method() in a subclass that does not override method
The Python documentation of super states:

This is useful for accessing inherited methods that have been overridden in a class.

Is there a point in calling super().method() in a subclass that does not override method?

To me there is not, since calling self.method() would be equivalent, that is to say inheritance would look method up in self's superclasses using the same type(self).__mro__ method resolution order (given by the C3 linearization of self's superclass hierarchy) than super.

So to me, super is useful in this situation:

```<code>class A:
    def f(self):
        print("A")

class B:
    pass

class C(B, A):
    def f(self):
        super().f()
        print("C")

C().f()  # prints A C
</code>```

but not in this one:

```<code>class A:
    def f(self):
        print("A")

class B:
    pass

class C(B, A):
    def g(self):
        super().f()  # should be just self.f()
        print("C")

C().g()  # prints A C
</code>```

答:
As noted by @chepner, calling super().method() in a subclass that does not override method is not equivalent to calling self.method(). The difference appears in subclasses of that subclass that override method.

Compare:

```<code>class A:
    def f(self):
        print("A")

class B:
    pass

class C(B, A):
    def g(self):
        super().f()  # == super(C, self).f(), so lookup starts after C in type(self).__mro__
        print("C")

class D(C):
    def f(self):
        print("D")

D().g()  # prints A C, since D.__mro__ == (D, C, B, A, object)
</code>```

with:

```<code>class A:
    def f(self):
        print("A")

class B:
    pass

class C(B, A):
    def g(self):
        self.f()  # lookup starts at the beginning in type(self).__mro__
        print("C")

class D(C):
    def f(self):
        print("D")

D().g()  # prints D C, since D.__mro__ == (D, C, B, A, object)
</code>```

Body:
The Python documentation of super states:

This is useful for accessing inherited methods that have been overridden in a class.

Is there a point in calling super().method() in a subclass that does not override method?

To me there is not, since calling self.method() would be equivalent, that is to say inheritance would look method up in self's superclasses using the same type(self).__mro__ method resolution order (given by the C3 linearization of self's superclass hierarchy) than super.

So to me, super is useful in this situation:

class A:
    def f(self):
        print("A")

class B:
    pass

class C(B, A):
    def f(self):
        super().f()
        print("C")

C().f()  # prints A C

but not in this one:

class A:
    def f(self):
        print("A")

class B:
    pass

class C(B, A):
    def g(self):
        super().f()  # should be just self.f()
        print("C")

C().g()  # prints A C

Body:
As noted by @chepner, calling super().method() in a subclass that does not override method is not equivalent to calling self.method(). The difference appears in subclasses of that subclass that override method.

Compare:

class A:
    def f(self):
        print("A")

class B:
    pass

class C(B, A):
    def g(self):
        super().f()  # == super(C, self).f(), so lookup starts after C in type(self).__mro__
        print("C")

class D(C):
    def f(self):
        print("D")

D().g()  # prints A C, since D.__mro__ == (D, C, B, A, object)

with:

class A:
    def f(self):
        print("A")

class B:
    pass

class C(B, A):
    def g(self):
        self.f()  # lookup starts at the beginning in type(self).__mro__
        print("C")

class D(C):
    def f(self):
        print("D")

D().g()  # prints D C, since D.__mro__ == (D, C, B, A, object)


问:
Passing data from Edit Text to Java Object,
I am trying to register users using SQLLite 3, and I need help getting information from EditText to user object then registering users.

I tried this:

```<code>        private EditText inputLastname;
        private EditText inputEmail;
        private EditText inputPassword;
        private EditText inputCity;
        private EditText inputPhone;
        register_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    User user = new User();
                    user.setFirstname(inputFirstname.getText().toString());
                    user.setLastname(inputLastname.getText().toString());
                    user.setEmail(inputEmail.getText().toString());
                    user.setPassword(inputPassword.getText().toString());
                    user.setPhone(Integer.parseInt(inputPhone.getText().toString()));
                    user.setCity(inputCity.getText().toString());

                    if (user != null) {

                        Log.d("message", user.toString().trim());// check if user is populated
                        databaseManager.createUser(user);// create user method
                        Toast toast =
                                Toast.makeText(getApplicationContext(), user.toString().trim(), Toast.LENGTH_LONG);
                        toast.setMargin(50, 50);
                        toast.show();
                        Intent intent = new Intent(getApplicationContext(), login.class);
                        startActivity(intent);
                    }
                } catch (Exception ex) {
                    Toast.makeText(register.this, "Registration Failed", Toast.LENGTH_SHORT).show();
                    System.out.print(ex.toString());
                }
            }
        });
</code>```

Does anyone know a better/working way of doing this?

答:
Looks like you are missing the initialization of pointing your EditText variables to the widgets in the layout. You should do this in your onCreate method. Once you do that you can use the getText().toString() on those variables to get the strings.

For example

    private EditText inputLastname;
    private EditText inputEmail;
    private EditText inputPassword;
    private EditText inputCity;
    private EditText inputPhone;

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_groups, container, false);

        // Do this for every view
        inputEmail = view.findViewById(R.id.email_edit_text_id);
        ...

        return view;
    }

```

Body:
I am trying to register users using SQLLite 3, and I need help getting information from EditText to user object then registering users.

I tried this:

        private EditText inputLastname;
        private EditText inputEmail;
        private EditText inputPassword;
        private EditText inputCity;
        private EditText inputPhone;
        register_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    User user = new User();
                    user.setFirstname(inputFirstname.getText().toString());
                    user.setLastname(inputLastname.getText().toString());
                    user.setEmail(inputEmail.getText().toString());
                    user.setPassword(inputPassword.getText().toString());
                    user.setPhone(Integer.parseInt(inputPhone.getText().toString()));
                    user.setCity(inputCity.getText().toString());

                    if (user != null) {

                        Log.d("message", user.toString().trim());// check if user is populated
                        databaseManager.createUser(user);// create user method
                        Toast toast =
                                Toast.makeText(getApplicationContext(), user.toString().trim(), Toast.LENGTH_LONG);
                        toast.setMargin(50, 50);
                        toast.show();
                        Intent intent = new Intent(getApplicationContext(), login.class);
                        startActivity(intent);
                    }
                } catch (Exception ex) {
                    Toast.makeText(register.this, "Registration Failed", Toast.LENGTH_SHORT).show();
                    System.out.print(ex.toString());
                }
            }
        });

Does anyone know a better/working way of doing this?


问:
Why would one ever want to compile with -O2 instead of -O3
We usually compile with -O2 because -O3 would "trigger subtle bugs".

For our GCC version -O3 enables more aggressive inlining which would actually reveal bugs otherwise unnoticed (e.g. use of uninitialized values from functions taking them as reference arguments or out-of-bounds access for arrays). It seems to me this aggressive inlining also allows a more expressive way of coding with smaller functions and -funswitch-loops helps keeping variable definitions more local in loops.

Given that bugs in our code are orders of magnitude more likely than compiler bugs and that we use -Wall -Wextra without any issues what kind of bugs should we be looking for?

If it matters we use gcc-4.3.2. Compile time is not a major issue for us.

答: Size. Of course if size does really matters (sometimes is does, like embedded), one would use -Os. But main difference at O3 is the (from you already mentioned) inlining. This can increase the generated code size (but it is faster). Maybe you want speed, but not at all (space) cost? Otherwise  I would see no reason why not to use O3 (except you know of a gcc compiler bug that only occurs in your code at O3, but as long as you dont have an error, you cant reproduce at O2, I would not care).

ContentLicense: CC BY-SA 3.0


问:
Dplyr - Mean for multiple columns
I want to calculate the mean for several columns and thus create a new column for the mean using dplyr and without melting + merging.

```<code>> head(growth2)
  CODE_COUNTRY CODE_PLOT IV12_ha_yr IV23_ha_yr IV34_ha_yr IV14_ha_yr IV24_ha_yr IV13_ha_yr
1            1         6       4.10       6.97         NA         NA         NA       4.58
2            1        17       9.88       8.75         NA         NA         NA       8.25
3            1        30         NA         NA         NA         NA         NA         NA
4            1        37      15.43      15.07      11.89      10.00      12.09      14.33
5            1        41      20.21      15.01      14.72      11.31      13.27      17.09
6            1        46      12.64      14.36      13.65       9.07      12.47      12.36
>
</code>```

I need a new column within the dataset with the mean of all the IV columns.
I tried this:

```<code>growth2 %>%
  group_by(CODE_COUNTRY, CODE_PLOT) %>%
  summarise(IVmean=mean(IV12_ha_yr:IV13_ha_yr, na.rm=TRUE))
</code>```

And returned several errors depending on the example used, such as:

```<code>Error in NA_real_:NA_real_ : NA/NaN argument
</code>```

or

```<code>Error in if (trim > 0 && n) { : missing value where TRUE/FALSE needed
</code>```

答:
I tried to comment on Rick Scriven's answer but don't have the experience points for it. Anyway, wanted to contribute. His answer said to do this:

```<code>    library(dplyr)
    mutate(df, IVMean = rowMeans(select(df, starts_with("IV")), na.rm = TRUE))
</code>```

That works, but if all columns don't start with "IV", which was my case, how do you do it? Turns out, that select does not want a logical vector, so you can't use AND or OR. For example, you cannot say "starts_with('X') | starts_with('Y')". You have to build a numeric vector. Here is how it is done.

```<code>    mutate(df, IVMean = rowMeans(select(df, c(starts_with("IV"), starts_with("IX"))), na.rm = TRUE))
</code>```

Title: Dplyr - Mean for multiple columns

Body:
I want to calculate the mean for several columns and thus create a new column for the mean using dplyr and without melting + merging.

> head(growth2)
  CODE_COUNTRY CODE_PLOT IV12_ha_yr IV23_ha_yr IV34_ha_yr IV14_ha_yr IV24_ha_yr IV13_ha_yr
1            1         6       4.10       6.97         NA         NA         NA       4.58
2            1        17       9.88       8.75         NA         NA         NA       8.25
3            1        30         NA         NA         NA         NA         NA         NA
4            1        37      15.43      15.07      11.89      10.00      12.09      14.33
5            1        41      20.21      15.01      14.72      11.31      13.27      17.09
6            1        46      12.64      14.36      13.65       9.07      12.47      12.36
>

I need a new column within the dataset with the mean of all the IV columns.
I tried this:

growth2 %>%
  group_by(CODE_COUNTRY, CODE_PLOT) %>%
  summarise(IVmean=mean(IV12_ha_yr:IV13_ha_yr, na.rm=TRUE))

And returned several errors depending on the example used, such as:

Error in NA_real_:NA_real_ : NA/NaN argument

or

Error in if (trim > 0 && n) { : missing value where TRUE/FALSE needed

Body:
I tried to comment on Rick Scriven's answer but don't have the experience points for it. Anyway, wanted to contribute. His answer said to do this:

    library(dplyr)
    mutate(df, IVMean = rowMeans(select(df, starts_with("IV")), na.rm = TRUE))

That works, but if all columns don't start with "IV", which was my case, how do you do it? Turns out, that select does not want a logical vector, so you can't use AND or OR. For example, you cannot say "starts_with('X') | starts_with('Y')". You have to build a numeric vector. Here is how it is done.

    mutate(df, IVMean = rowMeans(select(df, c(starts_with("IV"), starts_with("IX"))), na.rm = TRUE))


问:
Rails installation with MySQL2 failing on Mojave
```<code>OS: Mojave 10.14.2
Ruby v 2.6.0
Rails v 2.5.2
Mysql 8 Server (installed standalone, not through homebrew, and tested through phpmyadmin)
</code>```

In my Gemfile, I have:

```<code>gem 'mysql2', '>= 0.4.4', '< 0.6.0'
</code>```

I did:

```<code>bundle config build.mysql2 --with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include
bundle install --path .bundle
</code>```

And I am receiving the following error message:

```<code>Fetching mysql2 0.5.2
Installing mysql2 0.5.2 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Users/test_guy/Dropbox/Development/Rails/TestAppMac/.bundle/ruby/2.6.0/gems/mysql2-0.5.2/ext/mysql2
/Users/test_guy/.rbenv/versions/2.6.0/bin/ruby -I /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0 -r ./siteconf20190128-82406-1b5c8qc.rb extconf.rb --with-ldflags\=-L/usr/local/opt/openssl/lib\ --with-cppflags\=-I/usr/local/opt/openssl/include
checking for rb_absint_size()... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/Users/test_guy/.rbenv/versions/2.6.0/bin/$(RUBY_BASE_NAME)
/Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:467:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:552:in `try_link0'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:570:in `try_link'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:782:in `try_func'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:1069:in `block in have_func'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:959:in `block in checking_for'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:361:in `block (2 levels) in postpone'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:331:in `open'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:361:in `block in postpone'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:331:in `open'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:357:in `postpone'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:958:in `checking_for'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:1068:in `have_func'
    from extconf.rb:25:in `<main>'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /Users/test_guy/Dropbox/Development/Rails/TestAppMac/.bundle/ruby/2.6.0/extensions/x86_64-darwin-18/2.6.0-static/mysql2-0.5.2/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /Users/test_guy/Dropbox/Development/Rails/TestAppMac/.bundle/ruby/2.6.0/gems/mysql2-0.5.2 for inspection.
Results logged to /Users/test_guy/Dropbox/Development/Rails/TestAppMac/.bundle/ruby/2.6.0/extensions/x86_64-darwin-18/2.6.0-static/mysql2-0.5.2/gem_make.out

An error occurred while installing mysql2 (0.5.2), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.5.2' --source 'https://rubygems.org/'` succeeds before bundling.

In Gemfile:
  mysql2
</code>```

Any ideas?

答:
Make sure you have the command line development tools

```<code>xcode-select --install
</code>```

Make sure openssl is installed on Mac via Homebrew.

```<code>brew install openssl
</code>```

Install mysql2 gem with the options.

```<code>gem install mysql2 -v '0.5.2' -- --with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include
</code>```

ref: Install mysql2 on MacOS Mojave

Body:
OS: Mojave 10.14.2
Ruby v 2.6.0
Rails v 2.5.2
Mysql 8 Server (installed standalone, not through homebrew, and tested through phpmyadmin)

In my Gemfile, I have:

gem 'mysql2', '>= 0.4.4', '< 0.6.0'

I did:

bundle config build.mysql2 --with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include
bundle install --path .bundle

And I am receiving the following error message:

Fetching mysql2 0.5.2
Installing mysql2 0.5.2 with native extensions
Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Users/test_guy/Dropbox/Development/Rails/TestAppMac/.bundle/ruby/2.6.0/gems/mysql2-0.5.2/ext/mysql2
/Users/test_guy/.rbenv/versions/2.6.0/bin/ruby -I /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0 -r ./siteconf20190128-82406-1b5c8qc.rb extconf.rb --with-ldflags\=-L/usr/local/opt/openssl/lib\ --with-cppflags\=-I/usr/local/opt/openssl/include
checking for rb_absint_size()... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/Users/test_guy/.rbenv/versions/2.6.0/bin/$(RUBY_BASE_NAME)
/Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:467:in `try_do': The compiler failed to generate an executable file. (RuntimeError)
You have to install development tools first.
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:552:in `try_link0'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:570:in `try_link'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:782:in `try_func'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:1069:in `block in have_func'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:959:in `block in checking_for'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:361:in `block (2 levels) in postpone'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:331:in `open'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:361:in `block in postpone'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:331:in `open'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:357:in `postpone'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:958:in `checking_for'
    from /Users/test_guy/.rbenv/versions/2.6.0/lib/ruby/2.6.0/mkmf.rb:1068:in `have_func'
    from extconf.rb:25:in `'

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  /Users/test_guy/Dropbox/Development/Rails/TestAppMac/.bundle/ruby/2.6.0/extensions/x86_64-darwin-18/2.6.0-static/mysql2-0.5.2/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in /Users/test_guy/Dropbox/Development/Rails/TestAppMac/.bundle/ruby/2.6.0/gems/mysql2-0.5.2 for inspection.
Results logged to /Users/test_guy/Dropbox/Development/Rails/TestAppMac/.bundle/ruby/2.6.0/extensions/x86_64-darwin-18/2.6.0-static/mysql2-0.5.2/gem_make.out

An error occurred while installing mysql2 (0.5.2), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.5.2' --source 'https://rubygems.org/'` succeeds before bundling.

In Gemfile:
  mysql2

Any ideas?

Body:
Make sure you have the command line development tools

xcode-select --install

Make sure openssl is installed on Mac via Homebrew.

brew install openssl

Install mysql2 gem with the options.

gem install mysql2 -v '0.5.2' -- --with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include

ref: Install mysql2 on MacOS Mojave


问:
Suppress redirect on API URLs in ASP.NET Core
I have an ASP.NET Core site that uses cookie authentication for most pages. For those pages, the default server response of providing a 302 redirect for an unauthorized client is desirable. However, the site also accepts API requests; they use API keys and have no use for cookies.

Ideally, I'd like to turn off cookie processing for the API URLs altogether, but minimally, I need to ensure that if an API client is unauthorized, the server doesn't respond with a 302 redirect.

答:
Other simple way </p>

```<code> .AddCookie(options =>
            {
                options.AccessDeniedPath = "/Home/401";
                options.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToAccessDenied = context =>
                    {
                        if (context.Request.Path.StartsWithSegments("/api"))
                        {
                            context.Response.StatusCode = (int)(HttpStatusCode.Unauthorized);
                        }
                        return Task.CompletedTask;
                    },
                };
            })
</code>```

Body:
Other simple way

 .AddCookie(options =>
            {
                options.AccessDeniedPath = "/Home/401";
                options.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToAccessDenied = context =>
                    {
                        if (context.Request.Path.StartsWithSegments("/api"))
                        {
                            context.Response.StatusCode = (int)(HttpStatusCode.Unauthorized);
                        }
                        return Task.CompletedTask;
                    },
                };
            })


答:
If you are familiar with the CPLEX interactive, you may be used to seeing something like the following summary after the optimization:

```<code>MIP - Integer optimal, tolerance (0.0001/1e-06):  Objective = -2.0183208990e+02
Current MIP best bound = -2.0181209207e+02 (gap = 0.0199978, 0.01%)
Solution time =    1.43 sec.  Iterations = 25361  Nodes = 4335 (21)
Deterministic time = 686.22 ticks  (479.17 ticks/sec)
</code>```

As suggested in the comments section, all of this information can be queried if you look through the documentation here. Most of it comes from the Cplex.solution interface as you suggested.

For example, consider the following interactive session:

```<code>>>> c.problem_type[c.get_problem_type()]
'MILP'
>>> c.solution.get_status_string()
'integer optimal, tolerance'
>>> c.parameters.mip.tolerances.mipgap.get()
0.0001
>>> c.parameters.mip.tolerances.absmipgap.get()
1e-06
>>> c.solution.get_objective_value()
-201.83208990000034
>>> c.solution.MIP.get_best_objective()
-201.8120920681663
>>> c.solution.MIP.get_mip_relative_gap()
9.908152783804216e-05
>>> print(c.solution.get_quality_metrics())
Incumbent solution:
MILP objective                                -2.0183208990e+02
MILP solution norm |x| (Total, Max)            4.65432e+02  2.02051e+02
MILP solution error (Ax=b) (Total, Max)        5.24512e-11  2.34035e-12
MILP x bound error (Total, Max)                0.00000e+00  0.00000e+00
MILP x integrality error (Total, Max)          0.00000e+00  0.00000e+00
MILP slack bound error (Total, Max)            4.54747e-13  4.54747e-13
>>> c.solution.MIP.get_incumbent_node()
4266
>>> c.solution.MIP.get_num_cuts(c.solution.MIP.cut_type.GUB_cover)
3
</code>```

Title: Summary of knapsack solve in CPLEX

Body:
So I'm have trouble in python version of CPLEX. I would think it would be pretty easy to get like a summary of what the solver did i.e number of branches, etc.

Anyone know how to do this?

import cplex
from cplex.exceptions import CplexError
class knapsack:
    def __init__(self,N,g,square_list):
        self.N = N
        self.square_list= square_list
        self.g = g
    def solve_problem(self):
        try:
            my_prob = cplex.Cplex()
            prob =my_prob
            prob.set_log_stream(None)
            prob.set_error_stream(None)
            prob.set_warning_stream(None)
            prob.set_results_stream(None)
            my_obj = self.g
            my_ctype = "B"
            number_of_one = self.square_list.count(1.0)
            my_ctype = my_ctype*len(self.square_list)
            val = self.N  -number_of_one
            rhs=[val]
            my_sense="L"
            my_rownames = ["r1"]

            counter =0
            variable_list=[]
            coiff_list=[]
            for i in self.square_list:
                if i==0:
                    coiff_list.append(1.0)
                else:
                    coiff_list.append(-1.0)
                variable_list.append("w" + str(counter))
                counter+=1

            rows = [[variable_list, coiff_list]]
            prob.objective.set_sense(prob.objective.sense.minimize)

            prob.variables.add(obj=my_obj, types=my_ctype,
                        names=variable_list)
            prob.linear_constraints.add(lin_expr=rows, senses=my_sense,
                                    rhs=rhs)
            my_prob.solve()
            x = my_prob.solution.get_values()
            print(my_prob.solution.get_status())
            print("---")
            print(my_prob.solution.status())
            return x
        except CplexError as exc:
            print(exc)
            return

When I look at the methods associated with my_prob and myprob.solution I see

['MIP_starts', 'SOS', '_Cplex__copy_init', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_aborter', '_disposed', '_env', '_env_lp_ptr', '_invoke_generic_callback', '_is_MIP', '_is_special_filetype', '_lp', 'advanced', 'cleanup', 'conflict', 'copy_vmconfig', 'del_vmconfig', 'double_annotations', 'end', 'feasopt', 'get_aborter', 'get_dettime', 'get_num_cores', 'get_problem_name', 'get_problem_type', 'get_stats', 'get_time', 'get_version', 'get_versionnumber', 'has_vmconfig', 'indicator_constraints', 'linear_constraints', 'long_annotations', 'objective', 'order', 'parameters', 'populate_solution_pool', 'presolve', 'problem_type', 'pwl_constraints', 'quadratic_constraints', 'read', 'read_annotations', 'read_copy_vmconfig', 'register_callback', 'remove_aborter', 'runseeds', 'set_callback', 'set_error_stream', 'set_log_stream', 'set_problem_name', 'set_problem_type', 'set_results_stream', 'set_warning_stream', 'solution', 'solve', 'start', 'unregister_callback', 'use_aborter', 'variables', 'write', 'write_annotations', 'write_benders_annotation']
['MIP', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_add_iter', '_add_single', '_conv', '_cplex', '_env', '_get_index', '_get_index_function', 'advanced', 'basis', 'get_activity_levels', 'get_dual_values', 'get_float_quality', 'get_indicator_slacks', 'get_indices', 'get_integer_quality', 'get_linear_slacks', 'get_method', 'get_objective_value', 'get_quadratic_activity_levels', 'get_quadratic_dualslack', 'get_quadratic_slacks', 'get_quality_metrics', 'get_reduced_costs', 'get_solution_type', 'get_status', 'get_status_string', 'get_values', 'infeasibility', 'is_dual_feasible', 'is_primal_feasible', 'method', 'pool', 'progress', 'quality_metric', 'sensitivity', 'status', 'type', 'write']

Body:
If you are familiar with the CPLEX interactive, you may be used to seeing something like the following summary after the optimization:

MIP - Integer optimal, tolerance (0.0001/1e-06):  Objective = -2.0183208990e+02
Current MIP best bound = -2.0181209207e+02 (gap = 0.0199978, 0.01%)
Solution time =    1.43 sec.  Iterations = 25361  Nodes = 4335 (21)
Deterministic time = 686.22 ticks  (479.17 ticks/sec)

As suggested in the comments section, all of this information can be queried if you look through the documentation here. Most of it comes from the Cplex.solution interface as you suggested.

For example, consider the following interactive session:

>>> c.problem_type[c.get_problem_type()]
'MILP'
>>> c.solution.get_status_string()
'integer optimal, tolerance'
>>> c.parameters.mip.tolerances.mipgap.get()
0.0001
>>> c.parameters.mip.tolerances.absmipgap.get()
1e-06
>>> c.solution.get_objective_value()
-201.83208990000034
>>> c.solution.MIP.get_best_objective()
-201.8120920681663
>>> c.solution.MIP.get_mip_relative_gap()
9.908152783804216e-05
>>> print(c.solution.get_quality_metrics())
Incumbent solution:
MILP objective                                -2.0183208990e+02
MILP solution norm |x| (Total, Max)            4.65432e+02  2.02051e+02
MILP solution error (Ax=b) (Total, Max)        5.24512e-11  2.34035e-12
MILP x bound error (Total, Max)                0.00000e+00  0.00000e+00
MILP x integrality error (Total, Max)          0.00000e+00  0.00000e+00
MILP slack bound error (Total, Max)            4.54747e-13  4.54747e-13
>>> c.solution.MIP.get_incumbent_node()
4266
>>> c.solution.MIP.get_num_cuts(c.solution.MIP.cut_type.GUB_cover)
3


问:
Learning or Training on Microservices
Can anyone please suggest good learning or paid training site for good understanding on microservice including CI/CD and deploying to kubernates /docker using circuit breaker , auto-scaling and deploying to any cloud provider.</p>

答:
There are some good sources from where you can learn these things.
If you are looking for a Online Course/Learning platform the most popular ones are
Udemy and Pluralsight. There are some others but I used these and they where very helpful.

Now if all this topics are in one course and if you will find a guide which includes all them in one course is possible but I did
not fine one.

Instead what you can do is have a couple of separate courses to cover these topics:

Microservices archticture - which is actually a big topic on its own
Here is one from Udemy:
https://www.udemy.com/microservices-software-architecture-patterns-and-techniques/
Here is one from Pluralsight:
https://app.pluralsight.com/library/courses/microservices-architecture/table-of-contents

Kubernetes(includes some docker, autoscaling)
Here is one from Udemy:
https://www.udemy.com/kubernetes-microservices/
Here is one from Pluralsight:
https://app.pluralsight.com/library/courses/docker-kubernetes-big-picture/table-of-contents

These are just examples. There are plenty more courses which you can pick depending on your
experience level on those topics.

Title: Learning or Training on Microservices


问:
How do I transform special values into Option::None when using Serde to deserialize?
I'm parsing data into:

```<code>struct Data {
    field1: Option<f32>,
    field2: Option<u64>,
    // more ...
}
</code>```

The problem is that my input data format formats what would be a None in Rust as "n/a".

How do tell Serde that an Option<T> should be None for the specific string n/a, as opposed to an error? We can assume that this doesn't apply to a String.

This isn't the same question as How to deserialize "NaN" as `nan` with serde_json? because that's creating an f32 from a special value whereas my question is creating an Option<Anything> from a special value. It's also not How to transform fields during deserialization using Serde? as that still concerns a specific type.

答:
You can write your own deserialization function that handles this case:

use serde::de::Deserializer;
use serde::Deserialize;

// custom deserializer function
fn deserialize_maybe_nan<'de, D, T: Deserialize<'de>>(
    deserializer: D,
) -> Result<Option<T>, D::Error>
where
    D: Deserializer<'de>,
{
    // we define a local enum type inside of the function
    // because it is untagged, serde will deserialize as the first variant
    // that it can
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum MaybeNA {
        // if it can be parsed as Option<T>, it will be
        Value(Option),
        // otherwise try parsing as a string
        NAString(String),
    }

    // deserialize into local enum
    let value: MaybeNA<T> = Deserialize::deserialize(deserializer)?;
    match value {
        // if parsed as T or None, return that
        MaybeNA::Value(value) => Ok(value),

        // otherwise, if value is string an "n/a", return None
        // (and fail if it is any other string)
        MaybeNA::NAString(string) => {
            if string == "n/a" {
                Ok(None)
            } else {
                Err(serde::de::Error::custom("Unexpected string"))
            }
        }
    }
}
```
<p>Then you can mark your fields with <code>#[serde(default, deserialize_with = "deserialize_maybe_nan")]</code> to use this function instead of the default function:</p>
```#[derive(Deserialize)]
struct Data {
    #[serde(default, deserialize_with = "deserialize_maybe_nan")]
    field1: Option<f32>,
    #[serde(default, deserialize_with = "deserialize_maybe_nan")]
    field2: Option<u64>,
    // more ...
}
```

Working playground example

More information in the documentation:

deserialize_with serde attribute

Untagged enum representation

Body:
I'm parsing data into:

struct Data {
    field1: Option<f32>,
    field2: Option<u64>,
    // more ...
}

The problem is that my input data format formats what would be a None in Rust as "n/a".

How do tell Serde that an Option<T> should be None for the specific string n/a, as opposed to an error? We can assume that this doesn't apply to a String.

This isn't the same question as How to deserialize "NaN" as `nan` with serde_json? because that's creating an f32 from a special value whereas my question is creating an Option<Anything> from a special value. It's also not How to transform fields during deserialization using Serde? as that still concerns a specific type.

Body:
You can write your own deserialization function that handles this case:

use serde::de::Deserializer;
use serde::Deserialize;

// custom deserializer function
fn deserialize_maybe_nan<'de, D, T: Deserialize<'de>>(
    deserializer: D,
) -> Result<Option<T>, D::Error>
where
    D: Deserializer<'de>,
{
    // we define a local enum type inside of the function
    // because it is untagged, serde will deserialize as the first variant
    // that it can
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum MaybeNA<U> {
        // if it can be parsed as Option<T>, it will be
        Value(Option<U>),
        // otherwise try parsing as a string
        NAString(String),
    }

    // deserialize into local enum
    let value: MaybeNA<T> = Deserialize::deserialize(deserializer)?;
    match value {
        // if parsed as T or None, return that
        MaybeNA::Value(value) => Ok(value),

        // otherwise, if value is string an "n/a", return None
        // (and fail if it is any other string)
        MaybeNA::NAString(string) => {
            if string == "n/a" {
                Ok(None)
            } else {
                Err(serde::de::Error::custom("Unexpected string"))
            }
        }
    }
}

Then you can mark your fields with #[serde(default, deserialize_with = "deserialize_maybe_nan")] to use this function instead of the default function:

#[derive(Deserialize)]
struct Data {
    #[serde(default, deserialize_with = "deserialize_maybe_nan")]
    field1: Option<f32>,
    #[serde(default, deserialize_with = "deserialize_maybe_nan")]
    field2: Option<u64>,
    // more ...
}

Working playground example

More information in the documentation:

deserialize_with serde attribute

Untagged enum representation