问:
java.net sockets, readline and line terminators (VNC connection)
I am using x11vnc and I want to develop simple client for it.
So, the work is:

recieve info from socket

send info

recieve next data

send another info

and etc.

So, for example, I am using the next simple code:
```
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(socket.getInputStream()));
String test = null;</p>

```    try {
        test = lnr.readLine();
        System.out.println(test);
        test = lnr.readLine();
        System.out.println(test);
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.exit(0);
```

<p>```
The first message from server I got without errors (first readLine). The next message is empty (or without any line terminator for readLine) and I have infinite loop.
lnr.ready() not works for me.

So, how can I read from socket when data from socket sometimes have no "\n", "\r", "\r\n" or if the socket buffer is empty?

答:
The only RFB/VNC message that is terminated by a newline is the initial version exchange. In fact the RFB/VNC protocol is somewhat deficient in that it does not have any unique message framing; you have to process every message or you will lose your place. You probably will need to read directly from the socket or from the InputStreamReader. Wrapping it with LineNumberReader won't work.

The best reference I have found on the RFB/VNC protocol: http://tigervnc.org/cgi-bin/rfbproto

Body:
I am using x11vnc and I want to develop simple client for it.
So, the work is:

recieve info from socket

send info

recieve next data

send another info

and etc.

So, for example, I am using the next simple code:

LineNumberReader lnr = new LineNumberReader(new InputStreamReader(socket.getInputStream()));
String test = null;

    try {
        test = lnr.readLine();
        System.out.println(test);
        test = lnr.readLine();
        System.out.println(test);
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.exit(0);

The first message from server I got without errors (first readLine). The next message is empty (or without any line terminator for readLine) and I have infinite loop.
lnr.ready() not works for me.

So, how can I read from socket when data from socket sometimes have no "\n", "\r", "\r\n" or if the socket buffer is empty?


来源: stackexchange

问:
SQL query to insert more than one value for same atribute
I want to make a web page to update scores of some students. This page should have following features :
After opening the page it should start with all the roll numbers facing a box which is already filled with the previous scores. Now we can edit any score and put new score in the box we want and then after pressing 'Done' button, score of all the students should be updated using one query. Please someone write that query</p>

答:
```<code>UPDATE table_name
SET score1 = value1
WHERE codition to specify a row;
</code>```

Table_name in your database. After that write a new score value with their column name and also in the where condition write a condition which will specify your score row which you want to update.

ContentLicense: CC BY-SA 3.0

Body:
UPDATE table_name
SET score1 = value1
WHERE codition to specify a row;

Table_name in your database. After that write a new score value with their column name and also in the where condition write a condition which will specify your score row which you want to update.


问:
Lambda expression to convert array/List of String to array/List of Integers
Since Java 8 comes with powerful lambda expressions,

I would like to write a function to convert a List/array of Strings to array/List of Integers, Floats, Doubles etc..

In normal Java, it would be as simple as

```<code>for(String str : strList){
   intList.add(Integer.valueOf(str));
}
</code>```

But how do I achieve the same with a lambda, given an array of Strings to be converted to an array of Integers.

答:
You can also use, </p>

```<code>List<String> list = new ArrayList<>();
    list.add("1");
    list.add("2");
    list.add("3");

    Integer[] array = list.stream()
        .map( v -> Integer.valueOf(v))
        .toArray(Integer[]::new);
</code>```

Body:
Since Java 8 comes with powerful lambda expressions,

I would like to write a function to convert a List/array of Strings to array/List of Integers, Floats, Doubles etc..

In normal Java, it would be as simple as

for(String str : strList){
   intList.add(Integer.valueOf(str));
}

But how do I achieve the same with a lambda, given an array of Strings to be converted to an array of Integers.

Body:
You can also use,

List<String> list = new ArrayList<>();
    list.add("1");
    list.add("2");
    list.add("3");

    Integer[] array = list.stream()
        .map( v -> Integer.valueOf(v))
        .toArray(Integer[]::new);


问:
TCP Service & REST APIs
I have a GPS Tracker Device, I have run a TCP/IP Server Code which Successfully establishes connection with each device in a separate Thread and Device Keep sending its heart beat after one minute and server replies ON. When I send a command to get device location it gives me location and everything is working fine.

Now I want to get location from an android device using web service, Now I'm confuse how can I use running thread of a specific device from an Android App?

答:
```<code>class Server
{
    TcpListener server = null;
    public Server(string ip, int port)
    {
        IPAddress localAddr = IPAddress.Parse(ip);
        server = new TcpListener(localAddr, port);
        server.Start();
        StartListener();
    }

    public void StartListener()
    {
        try
        {
            while (true)
            {
                Console.WriteLine("Waiting for a connection... ");
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Connected!");

                Thread t = new Thread(new ParameterizedThreadStart(HandleDeivce));
                t.Start(client);
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
    }

    public void HandleDeivce(Object obj)
    {
        TcpClient client = (TcpClient)obj;
        NetworkStream stream = client.GetStream();

        string data = null;
        Byte[] bytes = new Byte[256];
        int i;

        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
        {
            data = Encoding.ASCII.GetString(bytes, 0, i);
            Console.WriteLine("{1}: Received: {0}", data, Thread.CurrentThread.ManagedThreadId);

            if (data.StartsWith("##"))
            {
                data = "LOAD";
            }
            else
            {
                data = "ON";
            }

            byte[] msg = Encoding.ASCII.GetBytes(data);
            stream.Write(msg, 0, msg.Length);

            Console.WriteLine("{1}: Sent: {0}", data, Thread.CurrentThread.ManagedThreadId);
        }
        client.Close();
    }
}
</code>```

Title: TCP Service & REST APIs


问:
Convert a JSON into CSV using jq
I have a json file, which is stored in an environment variable temp.

{
  "users": [
    {
      "username": "jack",
      "email": "jack@somewhere.com",
      "total running apps": "1",
      "api-mock-app": "0",
      "flogo": "1",
      "ipaas": "0",
      "nodejs-app": "0"
    },
    {
      "username": "jill",
      "email": "jill@somewhere.com",
      "total running apps": "1",
      "api-mock-app": "0",
      "flogo": "1",
      "ipaas": "0",
      "nodejs-app": "0"
    }
  ]
}

When i am converting this JSON into CSV using this command

```<code>jq -r '.users[] | [.username, .email, .total running apps, .api-mock-app, .flogo, .ipaas, .nodejs-app] | @csv' <<< $temp
</code>```

I am getting following error.

jq: error: syntax error, unexpected IDENT (Unix shell quoting issues?) at , line 1:
.users[] | [.username, .email, .total running apps, .api-mock-app, .flogo, .ipaas, .nodejs-app] | @csv

jq: 1 compile error

Any help Please?

答:
You need to quote your column names, especially since they contain spaces and dashes. However you need to escape the quotes for bash:</p>

```<code>jq --raw-output '.users[] | [.username, .email, ."total running apps", ."api-mock-app", ."flogo", ."ipaas", ."nodejs-app"] | @csv'
</code>```

Title: Convert a JSON into CSV using jq

Body:
I have a json file, which is stored in an environment variable temp.

{
  "users": [
    {
      "username": "jack",
      "email": "jack@somewhere.com",
      "total running apps": "1",
      "api-mock-app": "0",
      "flogo": "1",
      "ipaas": "0",
      "nodejs-app": "0"
    },
    {
      "username": "jill",
      "email": "jill@somewhere.com",
      "total running apps": "1",
      "api-mock-app": "0",
      "flogo": "1",
      "ipaas": "0",
      "nodejs-app": "0"
    }
  ]
}

When i am converting this JSON into CSV using this command

jq -r '.users[] | [.username, .email, .total running apps, .api-mock-app, .flogo, .ipaas, .nodejs-app] | @csv' <<< $temp

I am getting following error.

jq: error: syntax error, unexpected IDENT (Unix shell quoting issues?) at , line 1:
.users[] | [.username, .email, .total running apps, .api-mock-app, .flogo, .ipaas, .nodejs-app] | @csv

jq: 1 compile error

Any help Please?

Body:
You need to quote your column names, especially since they contain spaces and dashes. However you need to escape the quotes for bash:

jq --raw-output '.users[] | [.username, .email, ."total running apps", ."api-mock-app", ."flogo", ."ipaas", ."nodejs-app"] | @csv'


问:
How can I subscribe to incoming SSE events using Spring
I wrote a Spring RestController that returns a SseEmitter (for server-sent-event), and adds HATEOAS links to each event. Here is a simplified but working example of this controller:

```<code>package hello;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import hello.Greeting.Status;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestController
public class GreetingController {

    private static final Logger log = LoggerFactory.getLogger(GreetingController.class);

    private static final String template = "Hello, %s!";

    class GreetingRequestHandler implements Runnable {

        private ResponseBodyEmitter emitter;
        private Greeting greeting;

        public GreetingRequestHandler(final ResponseBodyEmitter emitter, final Greeting greeting) {
            this.emitter = emitter;
            this.greeting = greeting;
        }

        @Override
        public void run() {
            try {
                log.info(this.greeting.toString());
                this.emitter.send(this.greeting);
                Thread.sleep(5000);
                if (Status.COMPLETE.equals(this.greeting.getStatus())) {
                    this.emitter.complete();
                } else {
                    this.greeting.incrementStatus();
                    new Thread(new GreetingRequestHandler(this.emitter, this.greeting)).start();
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping(path = "/greeting")
    public SseEmitter greeting(@RequestParam(value = "name", defaultValue = "World") final String name) {
        SseEmitter emitter = new SseEmitter();
        Greeting greeting = new Greeting(String.format(template, name));
        greeting.add(linkTo(methodOn(GreetingController.class).greeting(name)).withSelfRel());
        new Thread(new GreetingRequestHandler(emitter, greeting)).start();
        log.info("returning emitter");
        return emitter;
    }
}
</code>```

The Greeting class is the following:

```<code>package hello;

import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.hateoas.ResourceSupport;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Greeting extends ResourceSupport {

    private final String content;
    private final static AtomicInteger idProvider = new AtomicInteger();
    private int greetingId;
    private Status status;

    enum Status {
        ENQUEUED,
        PROCESSING,
        COMPLETE;
    }

    @JsonCreator
    public Greeting(@JsonProperty("content") final String content) {
        this.greetingId = idProvider.addAndGet(1);
        this.status = Status.ENQUEUED;
        this.content = content;
    }

    public Status getStatus() {
        return this.status;
    }

    protected void setStatus(final Status status) {
        this.status = status;
    }

    public int getGreetingId() {
        return this.greetingId;
    }

    public String getContent() {
        return this.content;
    }

    @Override
    public String toString() {
        return "Greeting{id='" + this.greetingId + "', status='" + this.status + "' content='" + this.content + "', " + super.toString() + "}";
    }

    public void incrementStatus() {
        switch (this.status) {
            case ENQUEUED:
                this.status = Status.PROCESSING;
                break;
            case PROCESSING:
                this.status = Status.COMPLETE;
                break;
            default:
                break;
        }
    }
}
</code>```

This code works perfectly. If I try to reach the REST service using a web browser, I see events appearing with correct content and link.

The result looks like (each event appearing 5 seconds after the previous one):

```<code>data:{"content":"Hello, Kraal!","greetingId":8,"status":"ENQUEUED","_links":{"self":{"href":"http://localhost:8080/greeting?name=Kraal"}}}
data:{"content":"Hello, Kraal!","greetingId":8,"status":"PROCESSING","_links":{"self":{"href":"http://localhost:8080/greeting?name=Kraal"}}}
data:{"content":"Hello, Kraal!","greetingId":8,"status":"COMPLETE","_links":{"self":{"href":"http://localhost:8080/greeting?name=Kraal"}}}
</code>```

Now I need to call this REST service and read these events from another Spring application... But I have no clue how to write the client code using Spring. This does not work as RestTemplate is designed for synchronous client side HTTP access...

```<code>    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());

    // required for HATEOAS
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json"));
    converter.setObjectMapper(mapper);

    // required in order to be able to read serialized objects
    MappingJackson2HttpMessageConverter converter2 = new MappingJackson2HttpMessageConverter();
    converter2.setSupportedMediaTypes(MediaType.parseMediaTypes("application/octet-stream"));
    converter2.setObjectMapper(mapper);

    // required to understand SSE events
    MappingJackson2HttpMessageConverter converter3 = new MappingJackson2HttpMessageConverter();
    converter3.setSupportedMediaTypes(MediaType.parseMediaTypes("text/event-stream"));

    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    converters.add(converter);
    converters.add(converter2);
    converters.add(converter3);

    // probably wrong template
    RestTemplate restTemplate = new RestTemplate();
    restTemplate = new RestTemplate(converters);
    // this does not work as I receive events and no a single object
    Greeting greeting = restTemplate.getForObject("http://localhost:8080/greeting/?name=Kraal", Greeting.class);
    log.info(greeting.toString());
</code>```

The error message I get is:

```<code>Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'data': was expecting ('true', 'false' or 'null')
</code>```

Indeed each event is a SSE event and starts with "data:"...

So the questions are:

what ObjectMapper module should I register in order to be able to map SSE with Jackson ?

how can I subscribe to incoming SSE events (observer pattern) using Spring ?

Thanks in advance.

Side note: As I'm struggling doing it using Spring I tried to do it using Jersey SSE support as follows. Using Jersey I receive events as expected, but then I can't cast them to a Greeting class (for the same reason as above I guess which is that I don't have the right converter module .):

```<code>Client client = ClientBuilder.newBuilder().register(converter).register(SseFeature.class).build();
WebTarget target = client.target("http://localhost:8080/greeting/?name=Kraal");
EventInput eventInput = target.request().get(EventInput.class);
while (!eventInput.isClosed()) {
    final InboundEvent inboundEvent = eventInput.read();
    if (inboundEvent == null) {
        // connection has been closed
        break;
    }
    // this works fine and prints out events as they are incoming
    System.out.println(inboundEvent.readData(String.class));
    // but this doesn't as no proper way to deserialize the
    // class with HATEOAS links can be found
    // Greeting greeting = inboundEvent.readData(Greeting.class);
    // System.out.println(greeting.toString());
}
</code>```

答:
as per the documentation

you can use inboundEvent.readData(Class<T> type)

Body:
I wrote a Spring RestController that returns a SseEmitter (for server-sent-event), and adds HATEOAS links to each event. Here is a simplified but working example of this controller:

package hello;

import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import hello.Greeting.Status;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestController
public class GreetingController {

    private static final Logger log = LoggerFactory.getLogger(GreetingController.class);

    private static final String template = "Hello, %s!";

    class GreetingRequestHandler implements Runnable {

        private ResponseBodyEmitter emitter;
        private Greeting greeting;

        public GreetingRequestHandler(final ResponseBodyEmitter emitter, final Greeting greeting) {
            this.emitter = emitter;
            this.greeting = greeting;
        }

        @Override
        public void run() {
            try {
                log.info(this.greeting.toString());
                this.emitter.send(this.greeting);
                Thread.sleep(5000);
                if (Status.COMPLETE.equals(this.greeting.getStatus())) {
                    this.emitter.complete();
                } else {
                    this.greeting.incrementStatus();
                    new Thread(new GreetingRequestHandler(this.emitter, this.greeting)).start();
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping(path = "/greeting")
    public SseEmitter greeting(@RequestParam(value = "name", defaultValue = "World") final String name) {
        SseEmitter emitter = new SseEmitter();
        Greeting greeting = new Greeting(String.format(template, name));
        greeting.add(linkTo(methodOn(GreetingController.class).greeting(name)).withSelfRel());
        new Thread(new GreetingRequestHandler(emitter, greeting)).start();
        log.info("returning emitter");
        return emitter;
    }
}

The Greeting class is the following:

package hello;

import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.hateoas.ResourceSupport;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Greeting extends ResourceSupport {

    private final String content;
    private final static AtomicInteger idProvider = new AtomicInteger();
    private int greetingId;
    private Status status;

    enum Status {
        ENQUEUED,
        PROCESSING,
        COMPLETE;
    }

    @JsonCreator
    public Greeting(@JsonProperty("content") final String content) {
        this.greetingId = idProvider.addAndGet(1);
        this.status = Status.ENQUEUED;
        this.content = content;
    }

    public Status getStatus() {
        return this.status;
    }

    protected void setStatus(final Status status) {
        this.status = status;
    }

    public int getGreetingId() {
        return this.greetingId;
    }

    public String getContent() {
        return this.content;
    }

    @Override
    public String toString() {
        return "Greeting{id='" + this.greetingId + "', status='" + this.status + "' content='" + this.content + "', " + super.toString() + "}";
    }

    public void incrementStatus() {
        switch (this.status) {
            case ENQUEUED:
                this.status = Status.PROCESSING;
                break;
            case PROCESSING:
                this.status = Status.COMPLETE;
                break;
            default:
                break;
        }
    }
}

This code works perfectly. If I try to reach the REST service using a web browser, I see events appearing with correct content and link.

The result looks like (each event appearing 5 seconds after the previous one):

data:{"content":"Hello, Kraal!","greetingId":8,"status":"ENQUEUED","_links":{"self":{"href":"http://localhost:8080/greeting?name=Kraal"}}}
data:{"content":"Hello, Kraal!","greetingId":8,"status":"PROCESSING","_links":{"self":{"href":"http://localhost:8080/greeting?name=Kraal"}}}
data:{"content":"Hello, Kraal!","greetingId":8,"status":"COMPLETE","_links":{"self":{"href":"http://localhost:8080/greeting?name=Kraal"}}}

Now I need to call this REST service and read these events from another Spring application... But I have no clue how to write the client code using Spring. This does not work as RestTemplate is designed for synchronous client side HTTP access...

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());

    // required for HATEOAS
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json"));
    converter.setObjectMapper(mapper);

    // required in order to be able to read serialized objects
    MappingJackson2HttpMessageConverter converter2 = new MappingJackson2HttpMessageConverter();
    converter2.setSupportedMediaTypes(MediaType.parseMediaTypes("application/octet-stream"));
    converter2.setObjectMapper(mapper);

    // required to understand SSE events
    MappingJackson2HttpMessageConverter converter3 = new MappingJackson2HttpMessageConverter();
    converter3.setSupportedMediaTypes(MediaType.parseMediaTypes("text/event-stream"));

    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    converters.add(converter);
    converters.add(converter2);
    converters.add(converter3);

    // probably wrong template
    RestTemplate restTemplate = new RestTemplate();
    restTemplate = new RestTemplate(converters);
    // this does not work as I receive events and no a single object
    Greeting greeting = restTemplate.getForObject("http://localhost:8080/greeting/?name=Kraal", Greeting.class);
    log.info(greeting.toString());

The error message I get is:

Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'data': was expecting ('true', 'false' or 'null')

Indeed each event is a SSE event and starts with "data:"...

So the questions are:

what ObjectMapper module should I register in order to be able to map SSE with Jackson ?

how can I subscribe to incoming SSE events (observer pattern) using Spring ?

Thanks in advance.

Side note: As I'm struggling doing it using Spring I tried to do it using Jersey SSE support as follows. Using Jersey I receive events as expected, but then I can't cast them to a Greeting class (for the same reason as above I guess which is that I don't have the right converter module .):

Client client = ClientBuilder.newBuilder().register(converter).register(SseFeature.class).build();
WebTarget target = client.target("http://localhost:8080/greeting/?name=Kraal");
EventInput eventInput = target.request().get(EventInput.class);
while (!eventInput.isClosed()) {
    final InboundEvent inboundEvent = eventInput.read();
    if (inboundEvent == null) {
        // connection has been closed
        break;
    }
    // this works fine and prints out events as they are incoming
    System.out.println(inboundEvent.readData(String.class));
    // but this doesn't as no proper way to deserialize the
    // class with HATEOAS links can be found
    // Greeting greeting = inboundEvent.readData(Greeting.class);
    // System.out.println(greeting.toString());
}


问:
Predicting the future with pandas and statsmodels
What i need to do  is plot future temperature with these "requirments" : " assume that temperature is roughly a linear function of CO2 emission,
estimating the coefficients of the linear function from recent data points (using
the past 2 is fine, as is using the past 10 or so if you want to be more thorough).
Further, assume that the rate of increase of CO2 emissions is going to be the
same as it is today (i.e. if there were X tons more CO2 emissions in 2016 than
in 2015, there will be X tons more CO2 emissions in 2017 than in 2016)".

I have 2 data sets, one with temperature for each month per year, and one with Carbon level per year.

(posted the merged and shortened down one as its not that big, but if its more helpful to see them unmodified then i can post that as well, you can see how its done below where i post my code)

```<code>Year    Carbon    June

2000    6727  20.386
2001    6886  20.445
2002    6946  20.662
2003    7367  20.343
2004    7735  20.242
2005    8025  20.720
2006    8307  20.994
2007    8488  20.661
2008    8738  20.657
2009    8641  20.548
2010    9137  21.027
2011    9508  20.915
2012    9671  21.172
</code>```

What i have done so far is to merge the two datasets together and then try to predict temperature for one month for future years, i have limited it down to 2000-2012 just to make it simplerer and make sure that both tables have the same length as one table is longer than the other. I am pretty new to python and coding overall and i have no idea how to do this, below you can see what i have tried to far:

```<code>data1 = pd.read_csv("co2.csv", sep=',')
data2 = pd.read_csv("temperature.csv", sep=',')

data1 = data1.set_index('Year')
data2 = data2.set_index('Year')

data3 = data1.loc["2000":"2012"]

data4 = data2.loc["2000":"2012"]

data4 = data4.loc[:, "June":"June"]

data5 = pd.merge(data3,data4, how= 'left', left_index =True , right_index=True)

x = data5["Carbon"]

y = data5["June"]

model = sm.OLS(y,x).fit()

prediction = model.predict(x)

prediction.plot()

plt.show()
</code>```

答:
The method OLS.predict do not take x as arguments but the model parameters (and eventually exogenous data). Besides, you have to add a constant to X, otherwise it force the linear regression to pass through the origin. Here is an example:

```<code>import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
from StringIO import StringIO

data = StringIO("""
Year Carbon June
2000 6727 20.386
2001 6886 20.445
2002 6946 20.662
2003 7367 20.343
2004 7735 20.242
2005 8025 20.720
2006 8307 20.994
2007 8488 20.661
2008 8738 20.657
2009 8641 20.548
2010 9137 21.027
2011 9508 20.915
2012 9671 21.172
""")

# Model training
df = pd.read_table(data, index_col=0, sep='\s+')
Y_train = df['June']
X_train = df['Carbon']
X_train = sm.add_constant(X_train) # add this to your code
model = sm.OLS(Y_train, X_train)
results = model.fit()

# Prediction of future values
future_carbon = range(9700, 10000, 50)
X_pred = pd.DataFrame(data=future_carbon, columns=['Carbon'])
X_pred = sm.add_constant(X_pred)
prediction = model.predict(results.params, X_pred)

# Plot
plt.figure()
plt.plot(X_train['Carbon'], model.predict(results.params), '-r', label='Linear model')
plt.plot(X_pred['Carbon'], prediction, '--r', label='Linear prediction')
plt.scatter(df['Carbon'], df['June'], label='data')
plt.xlabel('Carbon')
plt.ylabel('June temperature')
plt.legend()
plt.show()
</code>```

Body:
What i need to do  is plot future temperature with these "requirments" : " assume that temperature is roughly a linear function of CO2 emission,
estimating the coefficients of the linear function from recent data points (using
the past 2 is fine, as is using the past 10 or so if you want to be more thorough).
Further, assume that the rate of increase of CO2 emissions is going to be the
same as it is today (i.e. if there were X tons more CO2 emissions in 2016 than
in 2015, there will be X tons more CO2 emissions in 2017 than in 2016)".

I have 2 data sets, one with temperature for each month per year, and one with Carbon level per year.

(posted the merged and shortened down one as its not that big, but if its more helpful to see them unmodified then i can post that as well, you can see how its done below where i post my code)

Year    Carbon    June

2000    6727  20.386
2001    6886  20.445
2002    6946  20.662
2003    7367  20.343
2004    7735  20.242
2005    8025  20.720
2006    8307  20.994
2007    8488  20.661
2008    8738  20.657
2009    8641  20.548
2010    9137  21.027
2011    9508  20.915
2012    9671  21.172

What i have done so far is to merge the two datasets together and then try to predict temperature for one month for future years, i have limited it down to 2000-2012 just to make it simplerer and make sure that both tables have the same length as one table is longer than the other. I am pretty new to python and coding overall and i have no idea how to do this, below you can see what i have tried to far:

data1 = pd.read_csv("co2.csv", sep=',')
data2 = pd.read_csv("temperature.csv", sep=',')

data1 = data1.set_index('Year')
data2 = data2.set_index('Year')

data3 = data1.loc["2000":"2012"]

data4 = data2.loc["2000":"2012"]

data4 = data4.loc[:, "June":"June"]

data5 = pd.merge(data3,data4, how= 'left', left_index =True , right_index=True)

x = data5["Carbon"]

y = data5["June"]

model = sm.OLS(y,x).fit()

prediction = model.predict(x)

prediction.plot()

plt.show()

Body:
The method OLS.predict do not take x as arguments but the model parameters (and eventually exogenous data). Besides, you have to add a constant to X, otherwise it force the linear regression to pass through the origin. Here is an example:

import pandas as pd
import statsmodels.api as sm
import matplotlib.pyplot as plt
from StringIO import StringIO

data = StringIO("""
Year Carbon June
2000 6727 20.386
2001 6886 20.445
2002 6946 20.662
2003 7367 20.343
2004 7735 20.242
2005 8025 20.720
2006 8307 20.994
2007 8488 20.661
2008 8738 20.657
2009 8641 20.548
2010 9137 21.027
2011 9508 20.915
2012 9671 21.172
""")

# Model training
df = pd.read_table(data, index_col=0, sep='\s+')
Y_train = df['June']
X_train = df['Carbon']
X_train = sm.add_constant(X_train) # add this to your code
model = sm.OLS(Y_train, X_train)
results = model.fit()

# Prediction of future values
future_carbon = range(9700, 10000, 50)
X_pred = pd.DataFrame(data=future_carbon, columns=['Carbon'])
X_pred = sm.add_constant(X_pred)
prediction = model.predict(results.params, X_pred)

# Plot
plt.figure()
plt.plot(X_train['Carbon'], model.predict(results.params), '-r', label='Linear model')
plt.plot(X_pred['Carbon'], prediction, '--r', label='Linear prediction')
plt.scatter(df['Carbon'], df['June'], label='data')
plt.xlabel('Carbon')
plt.ylabel('June temperature')
plt.legend()
plt.show()


问:
SharePoint 2013: Ho do I get the Total number of Documents in Multiple Document Libraries
I have a SharePoint 2013 with Team Site and four(4) Sub-sites. Each of the sub-sites have one(1) Document Library.

I will to create something like Dashboard on the Team Site Home page where the Total number of documents in each of the Document Libraries can be displayed.

I want this Dashboard to be updated automatically whenever documents are either added or removed.

Please guide me on how to go about this.

答:
Because of performance , the best way is to calculate count of items in client.
you can call counter function for every list like below code.</p>

```<code>ExecuteOrDelayUntilScriptLoaded(CountListItems, "sp.js");

var clientContext = null;
var web = null;

function CountListItems()
{

clientContext = new SP.ClientContext.get_current();

web = clientContext.get_web();

var list = web.get_lists().getByTitle("mydocumnets");

var camlQuery = new SP.CamlQuery();

var qry = "<View><Query><Where></Where></Query></View>";

camlQuery.set_viewXml(qry);

this.listItems = list.getItems(camlQuery);

clientContext.load(listItems, 'Include(Title)');

clientContext.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFailed));

}

function onSuccess(sender, args) {

alert(this.listItems.get_count());

}

function onFailed(sender, args) {
alert('request failed ');
}
</code>```

Body:
Because of performance , the best way is to calculate count of items in client.
you can call counter function for every list like below code.

ExecuteOrDelayUntilScriptLoaded(CountListItems, "sp.js");

var clientContext = null;
var web = null;

function CountListItems()
{

clientContext = new SP.ClientContext.get_current();

web = clientContext.get_web();

var list = web.get_lists().getByTitle("mydocumnets");

var camlQuery = new SP.CamlQuery();

var qry = "<View><Query><Where></Where></Query></View>";

camlQuery.set_viewXml(qry);

this.listItems = list.getItems(camlQuery);

clientContext.load(listItems, 'Include(Title)');

clientContext.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFailed));

}

function onSuccess(sender, args) {

alert(this.listItems.get_count());

}

function onFailed(sender, args) {
alert('request failed ');
}


问:
How to convert Array to CanvasPixelArray OR create a CanvasPixelArray object?
I got pixel data of an image in PHP that I would like to transfer to Javascript.

My only problem is that PHP returns a string that I convert in Javascript Array and the ImageData.data is not an Array, but a CanvasPixelArray.

```<code>var cvsPixelAr = [arStrFromPHP];
var imgData = ctx.createImageData(dim[0], dim[1]);
imgData.data = cvsPixelAr;
</code>```

I also tried "new CanvasPixelArray();", but still nothing.

Someone knows a work around?
If not I will use web workers to change every single value :-/.

Thanks

答:
I believe you will have to copy the items over piecewise into the final data array:</p>

```<code>var imgData = ctx.createImageData(dim[0], dim[1]);
var d = imgData.data;
for (var i=0,len=d.length;i<len;++i) d[i] = cvsPixelAr[i];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I got pixel data of an image in PHP that I would like to transfer to Javascript.

My only problem is that PHP returns a string that I convert in Javascript Array and the ImageData.data is not an Array, but a CanvasPixelArray.

var cvsPixelAr = [arStrFromPHP];
var imgData = ctx.createImageData(dim[0], dim[1]);
imgData.data = cvsPixelAr;

I also tried "new CanvasPixelArray();", but still nothing.

Someone knows a work around?
If not I will use web workers to change every single value :-/.

Thanks

Body:
I believe you will have to copy the items over piecewise into the final data array:

var imgData = ctx.createImageData(dim[0], dim[1]);
var d = imgData.data;
for (var i=0,len=d.length;i<len;++i) d[i] = cvsPixelAr[i];


问:
Passing arrays as parameters via log4j.xml & log4j.properties
Can some one let me know is it possible to pass array or list to a log4j appender property via log4j.xml or log4j.properties?

Something like below in appender I want to populate via log4j.xml or log4j.properties

```<code>private List<String> validPackages;

public List<String> getValidPackages() {
        return buildVersionFile;
}

public void setValidPackages(List<String> validPackages) {
        this.validPackages = validPackages
}
</code>```

答:
As discussed in log4j mailing list we can not just pass the properties in log4j . We have to implement a plugin

I haven't tested this out, but from the plugin documentation <
  http://logging.apache.org/log4j/2.x/manual/plugins.html>, if you make
  a  plugin that implements Collection, then you can automatically
  convert its  children into that collection. In that use case, though,
  you'd need another  plugin element for your validPackages list instead
  of a plain String.

There's no built-in TypeConverter for arrays (other than byte[] and
  char[]  which have special meaning anyways), so another alternative
  would be to add  a TypeConverter for Collection or similar,
  though reifying generics  at that point for more general Collection
  usage would become an exercise  in frustration IMO.

Body:
Can some one let me know is it possible to pass array or list to a log4j appender property via log4j.xml or log4j.properties?

Something like below in appender I want to populate via log4j.xml or log4j.properties

private List<String> validPackages;

public List<String> getValidPackages() {
        return buildVersionFile;
}

public void setValidPackages(List<String> validPackages) {
        this.validPackages = validPackages
}


问:
Dictionary unpacking into function when parameters are incompatible
I'm not sure that it's possible, I would like to unpack dictionary into function but I haven't similar parameters. Is it possible to easily restrict a dictionary to a subset?

```<code>def foo(a=0, b=0, c=0):
    print("a=%s, b=%s, c=%s"%(a,b,c))

my_dict = {'a':10, 'b':20, 'd':40}
foo(**my_dict)
</code>```

Output

```<code>TypeError                                 Traceback (most recent call last)
<ipython-input-1-d40731664736> in <module>()
      3
      4 my_dict = {'a':10, 'b':20, 'd':40}
----> 5 foo(**my_dict)

TypeError: foo() got an unexpected keyword argument 'd'
</code>```

And I want to obtain

```<code>a=10, b=20, c=0
</code>```

result where 'd' is automatically rejected.

It's just an example. In my case the function is not mine, I cannot redefined her parameters, foo is unmodifiable.

I have many functions in similar case as foo() and these functions are object's methods.

Any ideas?

答:
Here is a (hopefully) correct solution using inspect. Since the parameter list returned by inspect may contain star args and also positional only args, it is not enough to just compare the names.

```<code>import inspect

def filter_kwds(f, kwds):
    params = inspect.signature(f).parameters
    if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()):
        return kwds
    else:
        return {k:kwds[k] for k, v in params.items()
                if k in kwds and v.kind in (inspect.Parameter.KEYWORD_ONLY,
                                            inspect.Parameter.POSITIONAL_OR_KEYWORD)}

def f(a, *b, c=4):
    pass

def g(a, *b, c=4, **d):
    pass

print(filter_kwds(f, dict(a=1, b=2, d=4)))
print(filter_kwds(g, dict(a=1, b=2, d=4)))
</code>```

Output:

```<code>{'a': 1}
{'a': 1, 'b': 2, 'd': 4}
</code>```

Note that the function in the first example omits the name of the star arg, and in the second example detects the presence of a double star arg and therefore does no filtering

Body:
I'm not sure that it's possible, I would like to unpack dictionary into function but I haven't similar parameters. Is it possible to easily restrict a dictionary to a subset?

def foo(a=0, b=0, c=0):
    print("a=%s, b=%s, c=%s"%(a,b,c))

my_dict = {'a':10, 'b':20, 'd':40}
foo(**my_dict)

Output

TypeError                                 Traceback (most recent call last)
<ipython-input-1-d40731664736> in <module>()
      3
      4 my_dict = {'a':10, 'b':20, 'd':40}
----> 5 foo(**my_dict)

TypeError: foo() got an unexpected keyword argument 'd'

And I want to obtain

a=10, b=20, c=0

result where 'd' is automatically rejected.

It's just an example. In my case the function is not mine, I cannot redefined her parameters, foo is unmodifiable.

I have many functions in similar case as foo() and these functions are object's methods.

Any ideas?

Body:
Here is a (hopefully) correct solution using inspect. Since the parameter list returned by inspect may contain star args and also positional only args, it is not enough to just compare the names.

import inspect

def filter_kwds(f, kwds):
    params = inspect.signature(f).parameters
    if any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()):
        return kwds
    else:
        return {k:kwds[k] for k, v in params.items()
                if k in kwds and v.kind in (inspect.Parameter.KEYWORD_ONLY,
                                            inspect.Parameter.POSITIONAL_OR_KEYWORD)}

def f(a, *b, c=4):
    pass

def g(a, *b, c=4, **d):
    pass

print(filter_kwds(f, dict(a=1, b=2, d=4)))
print(filter_kwds(g, dict(a=1, b=2, d=4)))

Output:

{'a': 1}
{'a': 1, 'b': 2, 'd': 4}

Note that the function in the first example omits the name of the star arg, and in the second example detects the presence of a double star arg and therefore does no filtering


问:
SBT compilation for play framework 2.x disabled by default
I created a new Play Framework project using the activator, activator new my-project-name and  then I selected the play-java template and the project is created with no errors.

Then I import the project into my IDE, IntelliJ, as a SBT project. When the project is imported a popup is shown saying: SBT compilation for play framework 2.x disabled by default.

On IntelliJ project's panel it doesn't show all (mostly the files with the code) files. Just a handful of them.

The build.sbt file looks like full of compilation error (pretty much all the lines are red underlined).

Here's the build.sbt file

```<code>name := """my-project-name"""

version := "1.0-SNAPSHOT"

lazy val root = (project in file(".")).enablePlugins(PlayJava)

scalaVersion := "2.11.6"

libraryDependencies ++= Seq(
  javaJdbc,
  cache,
  javaWs
)

// Play provides two styles of routers, one expects its actions to be injected, the
// other, legacy style, accesses its actions statically.
routesGenerator := InjectedRoutesGenerator

fork in run := true
</code>```

I can compile and run the code with activator ui with no errors. So, why isn't IntelliJ fully importing the project and it shows me SBT compilation for play framework 2.x disabled by default message?

I googled around and couldn't find any hint related to this so I'm kinda lost here.

EDIT: -------------------------------------

I closed the project on IntelliJ and deleted the project folder. Closed IntelliJ and using activator I created again the same project. Using activator ui I compiled the project. Then I fired up IntelliJ and was prompted to either open a project, create a new one or import a project.

Selected import a project and did the normal "import a project steps" and IntelliJ imported the project with no hassle. But if I try to import the project while with an open project on IntelliJ I get the same problem that lead me to make this question. Maybe this is a bug on IntelliJ?

EDIT 2 ------------------------------------------

The solution to these two problems (the "SBT compilation for play framework 2.x disabled by default" and the files not showing on IntelliJ) can be fixed with user3384225 and DarkShadow answers.

答:
I Stumbled upon this problem myself when configuring play framework for IntelliJ IDEA IDE (version: 2017.3). I overcame this problem by following the steps below.

Navigate to:

```<code>File --> Settings --> Languages and Frameworks --> Play2 --> Compiler tab
</code>```

and inside the compiler tab:

put a tick to the Use Play2 compiler for this project

Hope this helped.

Body:
I created a new Play Framework project using the activator, activator new my-project-name and  then I selected the play-java template and the project is created with no errors.

Then I import the project into my IDE, IntelliJ, as a SBT project. When the project is imported a popup is shown saying: SBT compilation for play framework 2.x disabled by default.

On IntelliJ project's panel it doesn't show all (mostly the files with the code) files. Just a handful of them.

The build.sbt file looks like full of compilation error (pretty much all the lines are red underlined).

Here's the build.sbt file

name := """my-project-name"""

version := "1.0-SNAPSHOT"

lazy val root = (project in file(".")).enablePlugins(PlayJava)

scalaVersion := "2.11.6"

libraryDependencies ++= Seq(
  javaJdbc,
  cache,
  javaWs
)

// Play provides two styles of routers, one expects its actions to be injected, the
// other, legacy style, accesses its actions statically.
routesGenerator := InjectedRoutesGenerator

fork in run := true

I can compile and run the code with activator ui with no errors. So, why isn't IntelliJ fully importing the project and it shows me SBT compilation for play framework 2.x disabled by default message?

I googled around and couldn't find any hint related to this so I'm kinda lost here.

EDIT: -------------------------------------

I closed the project on IntelliJ and deleted the project folder. Closed IntelliJ and using activator I created again the same project. Using activator ui I compiled the project. Then I fired up IntelliJ and was prompted to either open a project, create a new one or import a project.

Selected import a project and did the normal "import a project steps" and IntelliJ imported the project with no hassle. But if I try to import the project while with an open project on IntelliJ I get the same problem that lead me to make this question. Maybe this is a bug on IntelliJ?

EDIT 2 ------------------------------------------

The solution to these two problems (the "SBT compilation for play framework 2.x disabled by default" and the files not showing on IntelliJ) can be fixed with user3384225 and DarkShadow answers.

Body:
I Stumbled upon this problem myself when configuring play framework for IntelliJ IDEA IDE (version: 2017.3). I overcame this problem by following the steps below.

Navigate to:

File --> Settings --> Languages and Frameworks --> Play2 --> Compiler tab

and inside the compiler tab:

put a tick to the Use Play2 compiler for this project

Hope this helped.


问:
Visual Studio 2017 not showing API request traces
Earlier I had a feature that was showing me the successful API requests over a specific controller, now this feature is gone, do you know which one it could be?

I'm not sure if it's a Resharper feature...

How I can enable it again?

EDIT: I'm using Visual Studio 2017 Enterprise

答:
After digging deeper, I finally found it, the name of the feature is CodeLens.

How to enable it: How to enable CodeLens for Visual Studio 2017 Community


问:
How to Render Two Components Conditionally?

How can I render these two components conditionally?

import React, { Component } from 'react';
import { Container, Header, Content, Card, CardItem, Text, Body } from 'native-base';
export default class CardHeaderFooterExample extends Component {
  render() {

    return (
      <Card>
        <CardItem header>
          <Text>NativeBase</Text>
        </CardItem>
        <CardItem>

            <Text>
              //Your text here
            </Text>

        </CardItem>
        <CardItem footer>
          <Text>GeekyAnts</Text>
        </CardItem>
      </Card>
```

<p>lets say:  </p>

<pre class="lang-js prettyprint-override"><code>if logedin={true}
  return
    <Card>
      <CardItem header>
        <Text>NativeBase</Text>
      </CardItem>
      <CardItem>
        <Body>
          <Text>
            //Your text here
          </Text>
        </Body>
      </CardItem>
      <CardItem footer>
        <Text>GeekyAnts</Text>
      </CardItem>
    </Card>

else return

  <Text> signup to access this content </Text>
</code>```

How can be this conditional rendering be done for this situation? Those components should be rendered based on boolean logedin.

答:
This is also possible:</p>

```<code>return (
    { logedin && <YourComponentWhenLogedinIsTrue/> }
    { ! logedin && <YourComponentWhenLogedinIsFalse/> }
);
</code>```

Body:
How can I render these two components conditionally?

import React, { Component } from 'react';
import { Container, Header, Content, Card, CardItem, Text, Body } from 'native-base';
export default class CardHeaderFooterExample extends Component {
  render() {

    return (
      <Card>
        <CardItem header>
          <Text>NativeBase</Text>
        </CardItem>
        <CardItem>

            <Text>
              //Your text here
            </Text>

        </CardItem>
        <CardItem footer>
          <Text>GeekyAnts</Text>
        </CardItem>
      </Card>

lets say:

if logedin={true}
  return
    <Card>
      <CardItem header>
        <Text>NativeBase</Text>
      </CardItem>
      <CardItem>

          <Text>
            //Your text here
          </Text>

      </CardItem>
      <CardItem footer>
        <Text>GeekyAnts</Text>
      </CardItem>
    </Card>

else return

  <Text> signup to access this content </Text>

How can be this conditional rendering be done for this situation? Those components should be rendered based on boolean logedin.

Body:
This is also possible:

return (
    { logedin && <YourComponentWhenLogedinIsTrue/> }
    { ! logedin && <YourComponentWhenLogedinIsFalse/> }
);


问:
<?php mail() won't work
```<code><?php
if (isset($_POST["submit"])){
$to = 'somebody@once.told.me';
$subject = 'the world was gonna roll me';
$user = $_POST['user'];
$comment = $_POST['comment'];
$tel = $_POST['tel'];
$email = $_POST['mail'];

$message = "From " . $user . "\r\n" .
"Im not the sharpest tool in the shed" . "\r\n" .
"Addidtional details " . "\r\n" .
$email . "\r\n" .
$tel;}

if ($_POST){
mail($to, $subject ,$message);
$feedback = 'she was looking kind of dumb'; }
?>
</code>```

Now it's a bit more readable, after switching the breaks and appling everything I needed, it just stopped sending to the email as before. It sends the feedback and nothing else.

  Do you know why?

答:
If you want to send it by an HTML mail, try this</p>

```<code>$message = "form:" . $user . "\r\n<br>" .
$comment . "\r\n<br>"
         . "additional contact:" . $email . $tel;
</code>```

Title: <?php mail() won't work

Body:
<?php
if (isset($_POST["submit"])){
$to = 'somebody@once.told.me';
$subject = 'the world was gonna roll me';
$user = $_POST['user'];
$comment = $_POST['comment'];
$tel = $_POST['tel'];
$email = $_POST['mail'];

$message = "From " . $user . "\r\n" .
"Im not the sharpest tool in the shed" . "\r\n" .
"Addidtional details " . "\r\n" .
$email . "\r\n" .
$tel;}

if ($_POST){
mail($to, $subject ,$message);
$feedback = 'she was looking kind of dumb'; }
?>

Now it's a bit more readable, after switching the breaks and appling everything I needed, it just stopped sending to the email as before. It sends the feedback and nothing else.

  Do you know why?

Body:
If you want to send it by an HTML mail, try this

$message = "form:" . $user . "\r\n<br>" .
$comment . "\r\n<br>"
         . "additional contact:" . $email . $tel;


问:
Disassemble x86 code in a program at a specific address
Is there any x86 disassembler framework that can be used to analyze code from a specific address in a program, as in:

```<code>info = disassemble(  startAddress , stopAddress)
</code>```

It should show every instruction and its operands and any other info that is good for analysis but it should have also fast mode where it isn't so important to obtain that much info for each instruction, but only for some of them that can be specified.

答: Google's protobuf uses libdisasm for that matter. Sad thing is that (judging from source code) it only supports ia32 and x86 and homepage states that "it is x86 specific and will not be expanded to include other CPU architectures". But since you didn't mention other archs, this library may be sufficient.

Body:
Is there any x86 disassembler framework that can be used to analyze code from a specific address in a program, as in:

info = disassemble(  startAddress , stopAddress)

It should show every instruction and its operands and any other info that is good for analysis but it should have also fast mode where it isn't so important to obtain that much info for each instruction, but only for some of them that can be specified.


问:
How to configure Python in a GPU cluster?
I have a GPU cluster with one storage-node and several computing nodes each has 8 GPU. I am configuring the cluster.

One of the task is to configure the python, what we need is several versions of Python and some python packages, and for some packages we may require several versions of it, such as different version of tensorflow.

So the question is how to configure the python and the packages so that it' convenient to use different version of the package I want to use.

I have installed both python2.7 and python3.6 in each computing node and in the storage node. But I think it is a good way if one has a huge amount of computing node to configure.  One of the solution is to install python in the share directory of the cluster instead of the default /usr/local path.
Anyone has a better way to do this?

What I use now is OpenPBS(Torque) and I am new to HPC.

Thanks a lot.

答:
You can install Modules software environment in a shared directory accessible on every node. Then it will be easy to load a specific version of python or TensorFlow:

```<code>module load lang/Python/3.6.0
module load lib/Tensorflow/1.1.0
</code>```

Then, if for some packages we may require several versions of it, you can have a look at Python virtualenv that permits to install several version of the same package. To share it on all the nodes, consider to create your virtualenv on a shared mount point.

Body:
You can install Modules software environment in a shared directory accessible on every node. Then it will be easy to load a specific version of python or TensorFlow:

module load lang/Python/3.6.0
module load lib/Tensorflow/1.1.0

Then, if for some packages we may require several versions of it, you can have a look at Python virtualenv that permits to install several version of the same package. To share it on all the nodes, consider to create your virtualenv on a shared mount point.


问:
Overwriting data in memory
I've written a password manager in Ocaml. In order to make it as secure as possible, I'd like to store a string (an encryption key) in memory in such a way that it can be overwritten. Since Ocaml is pass by value , and there's a garbage collector, this has proven difficult. I encrypt all buffers and variables I can, but I still need a "session key" stored to do this. To prevent this from being detected by automated key searching programs or put into swap, it's assembled from a bunch of random data in a buffer using a random increment. So really, all I need is a single variable that can be overwritten for the assembled key for a few seconds before it's passed into the Nocrypto library... Would a reference work for this?

According to this cornell "Refs and Arrays" page, refs are mutable and work similarly to pointers in C. That being said, I also found a stack overflow answer discussing Ocaml refs, in which the answer mentions "they act like pointers to new allocated memory". Does this mean every time, it just allocates a new thing in memory instead of actually mutating the stuff in memory? If so, you couldn't really "overwrite" a ref.

Other possible solutions I've come across are Bigarrays, and "custom blocks". I'm not entirely sure if "custom blocks" are actually allocated outside of the scope of garbage collection or not. They seem like they're used to access external C code. Are they copied around by the garbage collector? Could they be "overwritten?" There's also this idea of "opaque bytes" and opaque objects in memory. I'm having a pretty hard time wrapping my head around how this all fits together. A useful but confusing (to me) discussion of custom blocks in memory on stack overflow is here: Are custom blocks ever copied in memory? Answer says they can be moved around. Even so, could they be overwritten?

The last possible solution is to store it using a Cstruct like the Nocrypto library seems to do. They discuss it in this github issue: Secret material erasure The asker states:

"Granted, most key material is Cstruct.t, which is a Bigarray.Array1.t, which is allocated outside of the GC heap"

Is this even correct? If so, I can't seem to find a source file that actually does this. I'm pretty new to Ocaml and functional programming in general. If you're curious, my program is located on github here: ocaml-pass

答:
TL;DR;

You shall not store any secret information in OCaml heap. Thus you must never copy your secret into any OCaml heap-allocated value, consequently, neither Bytes, nor Strings or Arrays could be used, even temporary.

Introduction to the OCaml Memory Model

OCaml values are uniformly represented as tagged machine words. The least significant bit of a word is used as a tag, that distinguishes between pointers (tag=0) and immediate values (tag=1). Thus a value has always a fixed size, and is a pointer or an immediate.

Immediate values store their data in the most significant part of the word, that is 31-bits in 32 bit systems, and 63 bits in 64-bit systems. Pointers store their data in blocks, that are located in a so-called OCaml Heap. The OCaml Heap is a set of blocks managed by the Garbage Collector (GC). A block is a chunk of data prefixed with a header. The header specifies the size of data, and some other meta information, used by the GC. Block can contain OCaml values (pointers or immediate values) or opaque data.

To summarize. All OCaml values are represented as machine words, that either store data directly in the word or are pointers to heap-allocated blocks. Each pointer points to one and only one block. Several pointers may point to the same block. Such values are considered physically equal. Some blocks are not pointed by any pointers. Such blocks are called dead and are reclaimed by the GC.

Introduction to the OCaml Garbage Collector

The GC manages blocks, by allocating, moving, and deallocating them. The GC itself uses an arena, that is either obtained from the C memory allocator (malloc) or directly from a kernel via the memmap syscall (depends on a particular system and runtime).

The GC is generational, that means that values are first allocated in a special region of a heap called minor heap. The minor heap is a contiguous region of memory of fixed size, represented in the runtime with three pointers: the pointer beg to the beginning of the minor heap, a pointer end to the end of the minor heap, and the pointer cur to the beginning of the free area of the minor heap. When a block is allocated, cur is increased by the size of the block. Then the block is initialized with data. When there is no more free space in the minor heap (i.e., then end - cur is less than the required block size), then a minor GC cycle is triggered. The GC analyzes all blocks stored in the Minor Heap and copies all blocks that are referenced by at least one pointer to the Major Heap. After that, the cur pointer is set to beg.

In the Major Heap, a block may also be copied several times during a process called compaction. The compactor may try to rearrange blocks in its arena in order to achieve more compact representation of the heap.

Security Consequences

As the OCaml GC is a moving GC, it may copy the heap-allocated data arbitrarily. Although it is called moving, it is still in fact just copying. I.e., when a block is moved from the minor heap to the major heap, it is in fact just bit-copied, and thus is duplicated. The block phantom in the minor heap may live for an arbitrary amount of time until it is overwritten by some newly allocated value. When an object is moved during the compaction, it is also copied, and may or may not be overwritten during the process. And, of course, it goes without saying, that once a block becomes dead, it still may survive in a heap for an arbitrary amount of time until reused by the GC.

That all means, that if a secret ends up in the OCaml heap, it will go wild, as the GC can replicate it multiple times in an arbitrary and rather unpredictable ways. Thus, we can only store secrets either in immediate values or in regions that are not controlled by the GC. As it was said before, all OCaml values that are pointers, always point to a block in the OCaml heap. A block may contain data directly, or it could contain a pointer itself, that will point outside the memory heap. The so-called custom blocks, may or may not store their information in the OCaml heap, it depeds on a particular representation of each custom block. For example, the Bigarray library provides custom blocks that store their payload outside of the OCaml heap. Thus a Bigarray is a custom block, that has two fields: a pointer and size. It is an opaque block, i.e., the GC will never treat these two values as OCaml values, and will never follow neither the size nor the pointer. The data pointed by a pointer is located outside of the OCaml heap, and is either allocated by malloc or by memmap (in fact, it could be arbitrary integer, and even point to stack, or static data, it doesn't really matter, as long as we treat bigarrays just as a ptr,len pair).

This all makes Bigarrays ideal for storing secrets. We can be sure, that they are not moved by the GC, we can overwrite them to prevent the information leakage once they are freed.

Further considerations

We should be careful, and never allow a secret to be copied into the OCaml heap from our safe place. That means, that even if our main storage is a safe bigarray the information will still leak if we will copy its contents to an OCaml string. Consequently, if we first read the information into OCaml string, and then copy it into bigarray, the information will still leak. Thus, any interface that uses OCaml heap-allocated values is unsafe and shall not be used. For example, we can't use OCaml channels to read or write secrets (we should rely on memory mapping or unbuffered IO provided by the Unix module). And again, whenever you get a string data type from a Bigarray, you get your data copied, with all the ramifications.

Title: Overwriting data in memory


问:
Changing default action doesn't work for ASP.NET Core 2
On latest ASP.NET MVC CORE 2 default template, i am trying to change default action by modifying controller and action as below. I am expecting to see login page as default but i am having 404 http error. What I am doing wrong ?

You can verify this issue on default ASP.NET CORE 2 MVC project.

```<code>app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Account}/{action=Login}/{id?}");
    });
}
</code>```

答:
If you look at the AccountController class, you'll see it's decorated with a Route attribute, like so:

```<code>[Route("[controller]/[action]")]
public class AccountController : Controller
</code>```

However, if you look at the HomeController class, you'll see that it is not decorated with such an attribute:

```<code>public class HomeController : Controller
</code>```

Because the AccountController is using Attribute routing, it will not be picked up using the Conventional routing template. The docs explain this mutual exclusivity:

Actions that define attribute routes cannot be reached through the conventional routes and vice-versa.

Body:
On latest ASP.NET MVC CORE 2 default template, i am trying to change default action by modifying controller and action as below. I am expecting to see login page as default but i am having 404 http error. What I am doing wrong ?

You can verify this issue on default ASP.NET CORE 2 MVC project.

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Account}/{action=Login}/{id?}");
    });
}

Body:
If you look at the AccountController class, you'll see it's decorated with a Route attribute, like so:

[Route("[controller]/[action]")]
public class AccountController : Controller

However, if you look at the HomeController class, you'll see that it is not decorated with such an attribute:

public class HomeController : Controller

Because the AccountController is using Attribute routing, it will not be picked up using the Conventional routing template. The docs explain this mutual exclusivity:

Actions that define attribute routes cannot be reached through the conventional routes and vice-versa.

ContentLicense: CC BY-SA 4.0


问:
Create json file out of a multidimensional array
I have a multi dimensional array that consists of 3 arrays inside. See below my minimum runnable example:

```<code><?php

$array1 = array("Bitcoin", "Ethereum", "Bitcoin Cash");
$array2 = array("BTC", "ETH", "BTC");
$array3 = array("10000", "3000", "6666");

//Multi Dimensional Array
$multi = array($array1, $array2, $array3);
print_r($multi);

foreach($multi as $k =>$a){
  $multi[$k] = json_decode(json_encode($a));
}

print_r($multi);

// $json_data = json_encode($multi);
file_put_contents('data/myfile.json', $multi);
</code>```

However, I get the following output in my output file:

```<code>ArrayArrayArray
</code>```

Any suggestions how to get the data like the following:

```<code>{
"Bitcoin",
"BTC",
"10000"
},
{
"Ethereum",
"ETH",
"3000"
},
{
"Bitcoin Cash",
"BTC",
"6666"
},
</code>```

答:
First off, your expected result isn't valid json. It should be arrays [] instead of {}.

Below is how you can format the data like you want it.

However, it assumes that the three arrays always are of equal length:

```<code>$array1 = array("Bitcoin", "Ethereum", "Bitcoin Cash");
$array2 = array("BTC", "ETH", "BTC");
$array3 = array("10000", "3000", "6666");

$new = [];

// Restructure your array to get one item from each array
foreach ($array1 as $index => $value) {
    $new[] = [
        $value,
        $array2[$index],
        $array3[$index]
    ];
}

$multi = json_encode($new);
</code>```

This would produce the format you want, but in valid json format:

```<code>[
    [
        "Bitcoin",
        "BTC",
        "10000"
    ],
    [
        "Ethereum",
        "ETH",
        "3000"
    ],
    [
        "Bitcoin Cash",
        "BTC",
        "6666"
    ]
]
</code>```

Demo: https://3v4l.org/39kuA

Body:
I have a multi dimensional array that consists of 3 arrays inside. See below my minimum runnable example:

<?php

$array1 = array("Bitcoin", "Ethereum", "Bitcoin Cash");
$array2 = array("BTC", "ETH", "BTC");
$array3 = array("10000", "3000", "6666");

//Multi Dimensional Array
$multi = array($array1, $array2, $array3);
print_r($multi);

foreach($multi as $k =>$a){
  $multi[$k] = json_decode(json_encode($a));
}

print_r($multi);

// $json_data = json_encode($multi);
file_put_contents('data/myfile.json', $multi);

However, I get the following output in my output file:

ArrayArrayArray

Any suggestions how to get the data like the following:

{
"Bitcoin",
"BTC",
"10000"
},
{
"Ethereum",
"ETH",
"3000"
},
{
"Bitcoin Cash",
"BTC",
"6666"
},

Body:
First off, your expected result isn't valid json. It should be arrays [] instead of {}.

Below is how you can format the data like you want it.

However, it assumes that the three arrays always are of equal length:

$array1 = array("Bitcoin", "Ethereum", "Bitcoin Cash");
$array2 = array("BTC", "ETH", "BTC");
$array3 = array("10000", "3000", "6666");

$new = [];

// Restructure your array to get one item from each array
foreach ($array1 as $index => $value) {
    $new[] = [
        $value,
        $array2[$index],
        $array3[$index]
    ];
}

$multi = json_encode($new);

This would produce the format you want, but in valid json format:

[
    [
        "Bitcoin",
        "BTC",
        "10000"
    ],
    [
        "Ethereum",
        "ETH",
        "3000"
    ],
    [
        "Bitcoin Cash",
        "BTC",
        "6666"
    ]
]

Demo: https://3v4l.org/39kuA


问:
NO 'Access-control-allow-origin' header is present on the requested resource.Origin http://localhost:4200 is therefore not allowed access
I am trying to send request through angular.js 4 to java rest api.I am getting the following error : NO 'Access-control-allow-origin' header is present on the requested  resource.Origin http://localhost:4200 is therefore not allowed access
My code looks like :

```<code>    signupUser() {
    // if (this.signupForm.dirty && this.signupForm.valid) {
    // let headers = new Headers({ 'Content-Type': 'application/json' });
    let data = {
      "email": this.signupForm.value.email,
      "password": this.signupForm.value.password,
      'phone': this.signupForm.value.mobile,

      // 'first_name': 'dd1',
      // 'email': 'xyz@gmail.com',
      // 'password': 'manju',
      // 'phone': '123456',
      'signup_type': 'Custom',
      // social_media:
      // "email": this.loginForm.value.name,
      // "password": this.loginForm.value.password
    };
    console.log(data)

    let options = {
      type: "GET",
      url: "http://localhost:8085/dashboard/signUp",
      body: JSON.stringify(data)
    };

    this.http.post(options.url, options.body, {
      headers: this.headers
    }).subscribe((data) => {
      console.log(data);
      this.otpScreen = true;
    }, (err) => {
      console.log(err);
    });
    // alert(`Name: ${this.userForm.value.name} Email:         ${this.userForm.value.password}`);
    // }
}
</code>```

@CrossOrigin(origins="http://localhost:4200")
Adding this line in java code has to resolve this issue but still same error I'm getting can anyone let me know how to solve this issue? My Controller looks like:

```<code>@CrossOrigin
@RequestMapping("/signUp")
public void getOTP(HttpServletRequest request, HttpServletResponse response){
    System.out.println("In Signup");
}
</code>```

答:
Just add an extension Allow-Control-Allow-Origin: * 1.0.3 to your chrome browser.
Then a CORS button will appear besides address bar, just enable it and run your project on chrome it will work fine.
Link for Allow-Control-Allow-Origin extension</p>

Body:
I am trying to send request through angular.js 4 to java rest api.I am getting the following error : NO 'Access-control-allow-origin' header is present on the requested  resource.Origin http://localhost:4200 is therefore not allowed access
My code looks like :

    signupUser() {
    // if (this.signupForm.dirty && this.signupForm.valid) {
    // let headers = new Headers({ 'Content-Type': 'application/json' });
    let data = {
      "email": this.signupForm.value.email,
      "password": this.signupForm.value.password,
      'phone': this.signupForm.value.mobile,

      // 'first_name': 'dd1',
      // 'email': 'xyz@gmail.com',
      // 'password': 'manju',
      // 'phone': '123456',
      'signup_type': 'Custom',
      // social_media:
      // "email": this.loginForm.value.name,
      // "password": this.loginForm.value.password
    };
    console.log(data)

    let options = {
      type: "GET",
      url: "http://localhost:8085/dashboard/signUp",
      body: JSON.stringify(data)
    };

    this.http.post(options.url, options.body, {
      headers: this.headers
    }).subscribe((data) => {
      console.log(data);
      this.otpScreen = true;
    }, (err) => {
      console.log(err);
    });
    // alert(`Name: ${this.userForm.value.name} Email:         ${this.userForm.value.password}`);
    // }
}

@CrossOrigin(origins="http://localhost:4200")
Adding this line in java code has to resolve this issue but still same error I'm getting can anyone let me know how to solve this issue? My Controller looks like:

@CrossOrigin
@RequestMapping("/signUp")
public void getOTP(HttpServletRequest request, HttpServletResponse response){
    System.out.println("In Signup");
}


问:
Stripe - Add new card to existing customer
I have a need to add a card to a pre-existing customer. Here's what I did:

1. obtain token from user submission

```<code>card_token = request.POST('stripeToken')
</code>```

2. retrieve a customer

```<code>customer =  stripe.Customer.retrieve('cus_xxxxxxxxxx')
</code>```

3. add card to this customer

```<code>customer.Cards.create(card=card_token)
</code>```

It is # 3 that I'm having trouble because it looks like the customer doesn't have method Cards, but I've seen people done it elsewhere.

How should I achieve this?

答:
Example (customerId - cus_xxxxxxxxxx):</p>

```<code>    Stripe.apiKey = stripeApiKey;

    Customer customer = Customer.retrieve(customerId);

    Map<String, Object> cardParams = new HashMap<String, Object>();
    cardParams.put("number", "4242424242424242");
    cardParams.put("exp_month", "12");
    cardParams.put("exp_year", "2018");
    cardParams.put("cvc", "314");

    Map<String, Object> tokenParams = new HashMap<String, Object>();
    tokenParams.put("card", cardParams);
    Token cardToken = Token.create(tokenParams);

    Map<String, Object> sourceParams = new HashMap<String, Object>();
    sourceParams.put("source", cardToken.getId()); //?
    Card source = (Card) customer.getSources().create(sourceParams);
    logger.info("Card created: " + source.toString());
</code>```

Body:
I have a need to add a card to a pre-existing customer. Here's what I did:

1. obtain token from user submission

card_token = request.POST('stripeToken')

2. retrieve a customer

customer =  stripe.Customer.retrieve('cus_xxxxxxxxxx')

3. add card to this customer

customer.Cards.create(card=card_token)

It is # 3 that I'm having trouble because it looks like the customer doesn't have method Cards, but I've seen people done it elsewhere.

How should I achieve this?

Body:
Example (customerId - cus_xxxxxxxxxx):

    Stripe.apiKey = stripeApiKey;

    Customer customer = Customer.retrieve(customerId);

    Map<String, Object> cardParams = new HashMap<String, Object>();
    cardParams.put("number", "4242424242424242");
    cardParams.put("exp_month", "12");
    cardParams.put("exp_year", "2018");
    cardParams.put("cvc", "314");

    Map<String, Object> tokenParams = new HashMap<String, Object>();
    tokenParams.put("card", cardParams);
    Token cardToken = Token.create(tokenParams);

    Map<String, Object> sourceParams = new HashMap<String, Object>();
    sourceParams.put("source", cardToken.getId()); //?
    Card source = (Card) customer.getSources().create(sourceParams);
    logger.info("Card created: " + source.toString());


问:
VBA Loop with multiple ifs won't compile, not sure why
I'm trying to get two columns of data on one sheet rearranged into rows on another sheet, controlled by a column on the first sheet.

I'm going through the code, debugging it with the F8 command, and have run into an issue with the looping command at the end. I'm getting a "Loop without Do" compile error, with the "Loop Until" at the end highlighted by Excel.

This is what it's supposed to do:

The "JCX" (10, AttributeRowCounter) cell and "08-Attribute" (1, AttributeRowCounter) should match, and control which row in "JCX" the "08-Attribute" (11,AttributeRowCounter) value goes.

The "08-Attribute" (9,AttributeRowCounter) value controls which column in "JCX" to put the "08-Attribute" (11,AttributeRowCounter) value.

If there's a list of values in "08-Attribute" (1, AttributeRowCounter) called AHU-2, with corresponding list of values in "08-Attribute" (9, AttributeRowCounter) as "CFM, EAT, LAT, RPM, and SP", then the value in "08-Attribute" (11,AttributeRowCounter) with CFM in (9,AttributeRowCounter) goes in the "JCX" (14,TagNumberRow).

The value in "08-Attribute" (11,AttributeRowCounter) with RPM in (9,AttributeRowCounter) goes in "JCX" (16,TagNumberRow).

The value in "08-Attribute" (11,AttributeRowCounter) with SP in (9,AttributeRowCounter) goes in "JCX" (15,TagNumberRow).

If there is a value in "08-Attribute" (11,AttributeRowCounter) that has something other than "CFM, SP, RPM, and Motor HP" in (9,AttributeRowCounter), then the value in (11,AttributeRowCounter) goes in "JCX" (21,TagNumberRow), and the value in (9,AttributeRowCounter) goes in "JCX" (20,TagNumberRow).

The previous statement loops, to load any additional non-"CFM, SP, RPM, and Motor HP" values into the next columns to the right, skipping as needed (Name1, Value1, Name2, Value2, Name3, Value3, etc).

Anybody know what's going on?

```<code>'Tag Values
Do
    With Sheets("08-Attribute")
    Copy.Range("9,AttributeRowCounter").Value
    Application.WorksheetFunction.VLookup((Sheets("JCX").Cells(10, AttributeRowCounter)), (Sheets("08-Attribute").Cells(1, AttributeRowCounter)), True).Value
    With Sheets("08-Attribute")
If "9,AttributeRowCounter" = "CFM" Then
    .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("14,TagNumberRow").Value
    ElseIf "9" = "SP" Then
    .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("15,TagNumberRow").Value
    ElseIf "9" = "RPM" Then
    .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("16,TagNumberRow").Value
    ElseIf "9" = "Motor_HP" Then
    .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("17,TagNumberRow").Value
    Else
    .Range("9,AttributeRowCounter").Value = Sheets("JCX").Range("20,TagNumberRow").Value
    TagValueNameColumn = TagValueNameColumn + 2
    .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("21,TagNumberRow").Value
    TagValueNameColumn = TagValueNameColumn + 2
    Loop Until Cells(1, AttributeRowCounter) = False
</code>```

答:
If you indent, the problems become clearer.

```<code>Do
    With Sheets("08-Attribute")
        copy.Range("9,AttributeRowCounter").Value
        Application.WorksheetFunction.VLookup((Sheets("JCX").Cells(10, attributerowcounter)), (Sheets("08-Attribute").Cells(1, attributerowcounter)), True).Value

        With Sheets("08-Attribute")
            If "9,AttributeRowCounter" = "CFM" Then
                .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("14,TagNumberRow").Value
            ElseIf "9" = "SP" Then
                .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("15,TagNumberRow").Value
            ElseIf "9" = "RPM" Then
                .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("16,TagNumberRow").Value
            ElseIf "9" = "Motor_HP" Then
                .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("17,TagNumberRow").Value
            Else
                .Range("9,AttributeRowCounter").Value = Sheets("JCX").Range("20,TagNumberRow").Value
                TagValueNameColumn = TagValueNameColumn + 2
                .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("21,TagNumberRow").Value
                TagValueNameColumn = TagValueNameColumn + 2
            End If 'new
        End With 'new
    End With 'new
Loop Until Cells(1, attributerowcounter) = False
</code>```

The three lines near the bottom with 'new at the end are necessary to close the If block and the two With blocks.

Body:
I'm trying to get two columns of data on one sheet rearranged into rows on another sheet, controlled by a column on the first sheet.

I'm going through the code, debugging it with the F8 command, and have run into an issue with the looping command at the end. I'm getting a "Loop without Do" compile error, with the "Loop Until" at the end highlighted by Excel.

This is what it's supposed to do:

The "JCX" (10, AttributeRowCounter) cell and "08-Attribute" (1, AttributeRowCounter) should match, and control which row in "JCX" the "08-Attribute" (11,AttributeRowCounter) value goes.

The "08-Attribute" (9,AttributeRowCounter) value controls which column in "JCX" to put the "08-Attribute" (11,AttributeRowCounter) value.

If there's a list of values in "08-Attribute" (1, AttributeRowCounter) called AHU-2, with corresponding list of values in "08-Attribute" (9, AttributeRowCounter) as "CFM, EAT, LAT, RPM, and SP", then the value in "08-Attribute" (11,AttributeRowCounter) with CFM in (9,AttributeRowCounter) goes in the "JCX" (14,TagNumberRow).

The value in "08-Attribute" (11,AttributeRowCounter) with RPM in (9,AttributeRowCounter) goes in "JCX" (16,TagNumberRow).

The value in "08-Attribute" (11,AttributeRowCounter) with SP in (9,AttributeRowCounter) goes in "JCX" (15,TagNumberRow).

If there is a value in "08-Attribute" (11,AttributeRowCounter) that has something other than "CFM, SP, RPM, and Motor HP" in (9,AttributeRowCounter), then the value in (11,AttributeRowCounter) goes in "JCX" (21,TagNumberRow), and the value in (9,AttributeRowCounter) goes in "JCX" (20,TagNumberRow).

The previous statement loops, to load any additional non-"CFM, SP, RPM, and Motor HP" values into the next columns to the right, skipping as needed (Name1, Value1, Name2, Value2, Name3, Value3, etc).

Anybody know what's going on?

'Tag Values
Do
    With Sheets("08-Attribute")
    Copy.Range("9,AttributeRowCounter").Value
    Application.WorksheetFunction.VLookup((Sheets("JCX").Cells(10, AttributeRowCounter)), (Sheets("08-Attribute").Cells(1, AttributeRowCounter)), True).Value
    With Sheets("08-Attribute")
If "9,AttributeRowCounter" = "CFM" Then
    .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("14,TagNumberRow").Value
    ElseIf "9" = "SP" Then
    .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("15,TagNumberRow").Value
    ElseIf "9" = "RPM" Then
    .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("16,TagNumberRow").Value
    ElseIf "9" = "Motor_HP" Then
    .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("17,TagNumberRow").Value
    Else
    .Range("9,AttributeRowCounter").Value = Sheets("JCX").Range("20,TagNumberRow").Value
    TagValueNameColumn = TagValueNameColumn + 2
    .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("21,TagNumberRow").Value
    TagValueNameColumn = TagValueNameColumn + 2
    Loop Until Cells(1, AttributeRowCounter) = False

Body:
If you indent, the problems become clearer.

Do
    With Sheets("08-Attribute")
        copy.Range("9,AttributeRowCounter").Value
        Application.WorksheetFunction.VLookup((Sheets("JCX").Cells(10, attributerowcounter)), (Sheets("08-Attribute").Cells(1, attributerowcounter)), True).Value

        With Sheets("08-Attribute")
            If "9,AttributeRowCounter" = "CFM" Then
                .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("14,TagNumberRow").Value
            ElseIf "9" = "SP" Then
                .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("15,TagNumberRow").Value
            ElseIf "9" = "RPM" Then
                .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("16,TagNumberRow").Value
            ElseIf "9" = "Motor_HP" Then
                .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("17,TagNumberRow").Value
            Else
                .Range("9,AttributeRowCounter").Value = Sheets("JCX").Range("20,TagNumberRow").Value
                TagValueNameColumn = TagValueNameColumn + 2
                .Range("11,AttributeRowCounter").Value = Sheets("JCX").Range("21,TagNumberRow").Value
                TagValueNameColumn = TagValueNameColumn + 2
            End If 'new
        End With 'new
    End With 'new
Loop Until Cells(1, attributerowcounter) = False

The three lines near the bottom with 'new at the end are necessary to close the If block and the two With blocks.


问:
Vue iterating though object of arrays
Im trying to loop through some data with different categories with data, that would look something like this:

10m

-2017

--name: cup1

--file: file1.pdf

--name: cup2

--file: file2.pdf

-2016

--name: cup1

--file: file1.pdf

--name: cup2

--file: file2.pdf

(and then the same under 15m - however i can only make it show under 10m)

The problem with my loop is, that it only shows under the first category (atm. "10m")

I'm using VueJS to do this.

var vm = new Vue({
  el: '#results',

  data: {
    results: [
  {
    "kategori": "10m",
    "year": [
      {
        "2017": [
          {
              "name": "stævne",
              "file": "pdf.pdf"
            },
             {
              "name": "stævne",
              "file": "pdf.pdf"
            }
        ],
        "2016": [
          {
              "name": "stævne",
              "file": "pdf.pdf"
            },
             {
              "name": "stævne",
              "file": "pdf.pdf"
            }
        ]
      }
    ]
  },
  {
    "kategori": "15m",
    "year": [{
        "2017": [
          {
              "name": "stævne",
              "file": "pdf.pdf"
            },
             {
              "name": "stævne",
              "file": "pdf.pdf"
            }
        ],
        "2016": [
          {
              "name": "stævne",
              "file": "pdf.pdf"
            },
             {
              "name": "stævne",
              "file": "pdf.pdf"
            }
        ]
      }
    ]
  }
]
,
  },

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.category {
  font-weight: bold;
}

.year {
  margin-left: 5px;
  font-weight: normal;
}</code>```

      {{ allCategory.kategori }}

        {{ key }}

```

JSFiddle: https://jsfiddle.net/tj5413om/

Thanks in advance

答:
The problem is inside your iteration index goes from 0 to 1: it's kinda hard to explain but look at this fiddle: https://jsfiddle.net/tj5413om/2/ and you will see key 0 and 1 replace second loop from, but your data is the same:

```<code>[ { "2016": [ { "name": "stævne", "file": "pdf.pdf" }, { "name": "stævne", "file": "pdf.pdf" } ], "2017": [ { "name": "stævne", "file": "pdf.pdf" }, { "name": "stævne", "file": "pdf.pdf" } ] } ]
</code>```

This does not have key 1: It's only one array;

so replace your second loop from

```<code><div v-for="(allYear, key) in results[index].year[index]" class="year">
</code>```

to

```<code> <div v-for="(allYear, key) in results[index].year[0]" class="year">
</code>```

Title: Vue iterating though object of arrays

Body:
Im trying to loop through some data with different categories with data, that would look something like this:

10m

-2017

--name: cup1

--file: file1.pdf

--name: cup2

--file: file2.pdf

-2016

--name: cup1

--file: file1.pdf

--name: cup2

--file: file2.pdf

(and then the same under 15m - however i can only make it show under 10m)

The problem with my loop is, that it only shows under the first category (atm. "10m")

I'm using VueJS to do this.

var vm = new Vue({
  el: '#results',

  data: {
    results: [
  {
    "kategori": "10m",
    "year": [
      {
        "2017": [
          {
              "name": "stævne",
              "file": "pdf.pdf"
            },
             {
              "name": "stævne",
              "file": "pdf.pdf"
            }
        ],
        "2016": [
          {
              "name": "stævne",
              "file": "pdf.pdf"
            },
             {
              "name": "stævne",
              "file": "pdf.pdf"
            }
        ]
      }
    ]
  },
  {
    "kategori": "15m",
    "year": [{
        "2017": [
          {
              "name": "stævne",
              "file": "pdf.pdf"
            },
             {
              "name": "stævne",
              "file": "pdf.pdf"
            }
        ],
        "2016": [
          {
              "name": "stævne",
              "file": "pdf.pdf"
            },
             {
              "name": "stævne",
              "file": "pdf.pdf"
            }
        ]
      }
    ]
  }
]
,
  },

})

.category {
  font-weight: bold;
}

.year {
  margin-left: 5px;
  font-weight: normal;
}

      {{ allCategory.kategori }}

        {{ key }}

JSFiddle: https://jsfiddle.net/tj5413om/

Thanks in advance

Body:
The problem is inside your iteration index goes from 0 to 1: it's kinda hard to explain but look at this fiddle: https://jsfiddle.net/tj5413om/2/ and you will see key 0 and 1 replace second loop from, but your data is the same:

[ { "2016": [ { "name": "stævne", "file": "pdf.pdf" }, { "name": "stævne", "file": "pdf.pdf" } ], "2017": [ { "name": "stævne", "file": "pdf.pdf" }, { "name": "stævne", "file": "pdf.pdf" } ] } ]

This does not have key 1: It's only one array;

so replace your second loop from

<div v-for="(allYear, key) in results[index].year[index]" class="year">

to

 <div v-for="(allYear, key) in results[index].year[0]" class="year">


问:
Tomcat, Docker, Logging, and STDOUT?
I'm running tomcat in docker, but I can't see the logs. They are written to various log files under tomcat/logs, but I can't see them when tomcat is running in a docker container.

Here is my Dockerfile

```<code>FROM tomcat:7-jre8
COPY target/MYAPP.war /usr/local/tomcat/webapps/MYAPP.war
RUN ["/usr/local/tomcat/bin/catalina.sh", "start"]
</code>```

This is how I build image & start container from it:

```<code>docker build -t MYAPP .
docker run -it --rm -p 8080:8080 --name MYAPP MYAPP
</code>```

My app creates log file: /var/log/MYAPP.log after tomcat deploys MYAPP.war

How should I amend Dockerfile and which command should I use to run it ("docker run ...") so that right after starting the container MYAPP using the oneliner "docker run -it --rm -p 8080:8080 --name MYAPP MYAPP" the contents of /var/log/MYAPP.log would be printed to stdout?

I tried to add to Dockerfile the command below but it didn't help.

```<code>CMD tail -f /usr/local/MYAPP.log
</code>```

答:
You seem to be confused about the different between RUN and CMD.

The RUN directive is used to run commands during the build process.  It is never executed in a container.  When you write...

```<code>RUN ["/usr/local/tomcat/bin/catalina.sh", "start"]
</code>```

...this means that during the docker build process, Docker will start tomcat, but will immediately kill it and continue to build your image.

Only the CMD and ENTRYPOINT directives define commands that will be run when you boot an image with docker run.  So possibly you want something like:

```<code>CMD /usr/local/tomcat/bin/catalina.sh start && tail -f /usr/local/MYAPP.log
</code>```

Title: Tomcat, Docker, Logging, and STDOUT?

Body:
I'm running tomcat in docker, but I can't see the logs. They are written to various log files under tomcat/logs, but I can't see them when tomcat is running in a docker container.

Here is my Dockerfile

FROM tomcat:7-jre8
COPY target/MYAPP.war /usr/local/tomcat/webapps/MYAPP.war
RUN ["/usr/local/tomcat/bin/catalina.sh", "start"]

This is how I build image & start container from it:

docker build -t MYAPP .
docker run -it --rm -p 8080:8080 --name MYAPP MYAPP

My app creates log file: /var/log/MYAPP.log after tomcat deploys MYAPP.war

How should I amend Dockerfile and which command should I use to run it ("docker run ...") so that right after starting the container MYAPP using the oneliner "docker run -it --rm -p 8080:8080 --name MYAPP MYAPP" the contents of /var/log/MYAPP.log would be printed to stdout?

I tried to add to Dockerfile the command below but it didn't help.

CMD tail -f /usr/local/MYAPP.log

Body:
You seem to be confused about the different between RUN and CMD.

The RUN directive is used to run commands during the build process.  It is never executed in a container.  When you write...

RUN ["/usr/local/tomcat/bin/catalina.sh", "start"]

...this means that during the docker build process, Docker will start tomcat, but will immediately kill it and continue to build your image.

Only the CMD and ENTRYPOINT directives define commands that will be run when you boot an image with docker run.  So possibly you want something like:

CMD /usr/local/tomcat/bin/catalina.sh start && tail -f /usr/local/MYAPP.log