问:
keras (lstm) - necessary shape when using return_sequences=True
I am trying to fit an LSTM network to a sin function. Currently, as far as I understand Keras, my code does only predict the next value. According to this link: Many to one and many to many LSTM examples in Keras it is a many to one model. However, my goal is to implement a Many-to-many model. Basically, I want to be able to predict let's say 10 values, to a given time. When I am trying to use
return_sequences=True (see line model.add(..)), which is supposed to be the solution, the following error occurs:

```<code>ValueError: Error when checking target: expected lstm_8 to have 3 dimensions, but got array with shape (689, 1)
</code>```

Unfortunately, I have absolutely no clue why this happens. Is there a general rule how the input shape needs to be when using return_sequences=True ? Furthermore what exactly would I need to change? Thanks for any help.

```<code>import pandas
import numpy as np
import matplotlib.pylab as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import sklearn

from keras.models import Sequential
from keras.layers import Activation, LSTM
from keras import optimizers
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot

#generate sin function with noise
x = np.arange(0, 100, 0.1)
noise = np.random.uniform(-0.1, 0.1, size=(1000,))
Y = np.sin(x) + noise

# Perform feature scaling
scaler = MinMaxScaler()
Y = scaler.fit_transform(Y.reshape(-1, 1))

# split in train and test
train_size = int(len(Y) * 0.7)
test_size = len(Y) - train_size
train, test = Y[0:train_size,:], Y[train_size:len(Y),:]

def create_dataset(dataset, look_back=1):
    dataX, dataY = [], []
    for i in range(len(dataset)-look_back-1):
         a = dataset[i:(i+look_back), 0]
         dataX.append(a)
         dataY.append(dataset[i + look_back, 0])
    return np.array(dataX), np.array(dataY)

# reshape into X=t and Y=t+1
look_back = 10
X_train, y_train = create_dataset(train, look_back)
X_test, y_test = create_dataset(test, look_back)

# LSTM network expects the input data in form of [samples, time steps, features]
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
np.set_printoptions(threshold=np.inf)

# compile model
model = Sequential()
model.add(LSTM(1, input_shape=(look_back, 1)))#, return_sequences=True))  <== uncomment this
model.compile(loss='mean_squared_error', optimizer='adam')
SVG(model_to_dot(model).create(prog='dot', format='svg'))

model.fit(X_train, y_train, validation_data=(X_test, y_test),
batch_size=10, epochs=10, verbose=2)
prediction = model.predict(X_test, batch_size=1, verbose=0)
prediction.reshape(-1)
#Transform back to original representation
Y = scaler.inverse_transform(Y)
prediction = scaler.inverse_transform(prediction)
plt.plot(np.arange(0,Y.shape[0]), Y)
plt.plot(np.arange(Y.shape[0] - X_test.shape[0] , Y.shape[0]), prediction, 'red')
plt.show()
error = mean_squared_error(y_test, prediction)
print(error)
</code>```

答:
The problem is not the input, but the output.
The error says: "Error when checking target", target = y_train and y_test.

Because your lstm returns a sequence (return_sequences=True) the output dimention will be: (n_batch,lookback,1).

You can verify it by using model.summary()

```<code>_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
lstm_1 (LSTM)                (None, 10, 1)             12
=================================================================
Total params: 12
Trainable params: 12
Non-trainable params: 0
_________________________________________________________________
</code>```

You will need to change your create_dataset function so each ground truth will be shaped (lookback,1).

Something you might want to do:

for each seqeuence x in the train set,its y will be the next proceedings sequence.

For example, lets say we would like to learn something easier, the seqeuence will be the previous number plus 1 --> 1,2,3,4,5,6,7,8,9,10.
For loockback=4:

```<code>X_train[0] = 1,2,3,4
y_train[0] will be: 2,3,4,5
X_train[1] = 2,3,4,5
y_train[1] will be: 3,4,5,6
and so on...
</code>```

Body:
I am trying to fit an LSTM network to a sin function. Currently, as far as I understand Keras, my code does only predict the next value. According to this link: Many to one and many to many LSTM examples in Keras it is a many to one model. However, my goal is to implement a Many-to-many model. Basically, I want to be able to predict let's say 10 values, to a given time. When I am trying to use
return_sequences=True (see line model.add(..)), which is supposed to be the solution, the following error occurs:

ValueError: Error when checking target: expected lstm_8 to have 3 dimensions, but got array with shape (689, 1)

Unfortunately, I have absolutely no clue why this happens. Is there a general rule how the input shape needs to be when using return_sequences=True ? Furthermore what exactly would I need to change? Thanks for any help.

import pandas
import numpy as np
import matplotlib.pylab as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import sklearn

from keras.models import Sequential
from keras.layers import Activation, LSTM
from keras import optimizers
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot

#generate sin function with noise
x = np.arange(0, 100, 0.1)
noise = np.random.uniform(-0.1, 0.1, size=(1000,))
Y = np.sin(x) + noise

# Perform feature scaling
scaler = MinMaxScaler()
Y = scaler.fit_transform(Y.reshape(-1, 1))

# split in train and test
train_size = int(len(Y) * 0.7)
test_size = len(Y) - train_size
train, test = Y[0:train_size,:], Y[train_size:len(Y),:]

def create_dataset(dataset, look_back=1):
    dataX, dataY = [], []
    for i in range(len(dataset)-look_back-1):
         a = dataset[i:(i+look_back), 0]
         dataX.append(a)
         dataY.append(dataset[i + look_back, 0])
    return np.array(dataX), np.array(dataY)

# reshape into X=t and Y=t+1
look_back = 10
X_train, y_train = create_dataset(train, look_back)
X_test, y_test = create_dataset(test, look_back)

# LSTM network expects the input data in form of [samples, time steps, features]
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
np.set_printoptions(threshold=np.inf)

# compile model
model = Sequential()
model.add(LSTM(1, input_shape=(look_back, 1)))#, return_sequences=True))  <== uncomment this
model.compile(loss='mean_squared_error', optimizer='adam')
SVG(model_to_dot(model).create(prog='dot', format='svg'))

model.fit(X_train, y_train, validation_data=(X_test, y_test),
batch_size=10, epochs=10, verbose=2)
prediction = model.predict(X_test, batch_size=1, verbose=0)
prediction.reshape(-1)
#Transform back to original representation
Y = scaler.inverse_transform(Y)
prediction = scaler.inverse_transform(prediction)
plt.plot(np.arange(0,Y.shape[0]), Y)
plt.plot(np.arange(Y.shape[0] - X_test.shape[0] , Y.shape[0]), prediction, 'red')
plt.show()
error = mean_squared_error(y_test, prediction)
print(error)

Body:
The problem is not the input, but the output.
The error says: "Error when checking target", target = y_train and y_test.

Because your lstm returns a sequence (return_sequences=True) the output dimention will be: (n_batch,lookback,1).

You can verify it by using model.summary()

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
lstm_1 (LSTM)                (None, 10, 1)             12
=================================================================
Total params: 12
Trainable params: 12
Non-trainable params: 0
_________________________________________________________________

You will need to change your create_dataset function so each ground truth will be shaped (lookback,1).

Something you might want to do:

for each seqeuence x in the train set,its y will be the next proceedings sequence.

For example, lets say we would like to learn something easier, the seqeuence will be the previous number plus 1 --> 1,2,3,4,5,6,7,8,9,10.
For loockback=4:

X_train[0] = 1,2,3,4
y_train[0] will be: 2,3,4,5
X_train[1] = 2,3,4,5
y_train[1] will be: 3,4,5,6
and so on...


来源: stackexchange

问:
Remove Duplicate Arrays in PHP for laravel framework
I have more than 4 arrays in single variable as shown below

```<code>$myArray = Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UK [3] => NA [4] => Texas  )Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas ) Array ( [0] => NA [1] => NA [2] => UAE [3] => NA [4] => Texas )
</code>```

Now i need to compare each and every array of [2] index.

If second index ([2] => USA) is present in some other array then delete duplicate array.

Finally the arrays should look like this

```<code>Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UK [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UAE [3] => NA [4] => Texas ).
</code>```

I have tried this but not able to sort it out.

```<code>$myArray = array_map("unserialize", array_unique(array_map("serialize", $myArray)));
</code>```

Is there any way?

答:
You need to iterate through your array with two loops and check the second index value in each of the inner arrays and if there is a duplicated value you can just unset the second one.

Here is a piece of code that should do well:

```<code><?php

for($i=0; $i < count($myArray); $i++) {
    for($j=$i+1; $j < count($myArray); $j++) {
        if ($myArray[$i][2] == $myArray[$j][2]) {
            unset($myArray[$j][2]);
        }
    }
}
</code>```

P.S: The code is not tested and may need some modifications, but you could get the main idea.

ContentLicense: CC BY-SA 3.0

Body:
I have more than 4 arrays in single variable as shown below

$myArray = Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UK [3] => NA [4] => Texas  )Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas ) Array ( [0] => NA [1] => NA [2] => UAE [3] => NA [4] => Texas )

Now i need to compare each and every array of [2] index.

If second index ([2] => USA) is present in some other array then delete duplicate array.

Finally the arrays should look like this

Array ( [0] => NA [1] => NA [2] => USA [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UK [3] => NA [4] => Texas )Array ( [0] => NA [1] => NA [2] => UAE [3] => NA [4] => Texas ).

I have tried this but not able to sort it out.

$myArray = array_map("unserialize", array_unique(array_map("serialize", $myArray)));

Is there any way?

Body:
You need to iterate through your array with two loops and check the second index value in each of the inner arrays and if there is a duplicated value you can just unset the second one.

Here is a piece of code that should do well:

<?php

for($i=0; $i < count($myArray); $i++) {
    for($j=$i+1; $j < count($myArray); $j++) {
        if ($myArray[$i][2] == $myArray[$j][2]) {
            unset($myArray[$j][2]);
        }
    }
}

P.S: The code is not tested and may need some modifications, but you could get the main idea.


答:
You can use a foreach loop for this, like DEMO:

```<code>$match = [];
foreach($myArray as $key => $value)
{
    if(!in_array($value[2], $match))
    {
        $match[] = $value[2];
        continue;
    }
    unset($myArray[$key]);
}
</code>```

This will remove all of the arrays which have duplicate value for [2]

Title: Remove Duplicate Arrays in PHP for laravel framework

Body:
You can use a foreach loop for this, like DEMO:

$match = [];
foreach($myArray as $key => $value)
{
    if(!in_array($value[2], $match))
    {
        $match[] = $value[2];
        continue;
    }
    unset($myArray[$key]);
}

This will remove all of the arrays which have duplicate value for [2]


问:
rest controller not working in spring boot
I have checked most similar questions, and don't find the answer.So I can only post a new question.

I can successfully run my application without errors, but the rest api I write can't be access correctly.I have compared my launch log to the official tutorials, then I have found out I don't have the similar  log below:

```<code>2017-11-13 17:37:50.921  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2328c243: startup date [Mon Nov 13 17:37:49 CST 2017]; root of context hierarchy
2017-11-13 17:37:51.061  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2017-11-13 17:37:51.066  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-13 17:37:51.067  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-13 17:37:51.126  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.127  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.188  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
</code>```

Here are some my java files, Hope anyone can find some keypoint to solve my problem

the main application file:

```<code>package com.teachermate;

import com.alibaba.druid.pool.DruidDataSource;
import com.teachermate.entites.TeacherMateSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@SpringBootApplication
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication.run(JobScheduleApplication.class, args);
    }

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
}
</code>```

the controller file:

```<code>@RestController
@RequestMapping(path = "/test")
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
</code>```

the pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.teachermate</groupId>
    <artifactId>job-scheduler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jobSchedule</name>
    <description>job schedule for teachermate</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.2-jre</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.19</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

BTW, the rest api works fine before I add some code or library(like druid).But I don't know what cause it, can anyone help? Or can anyone show me a way to debug it? Thanks!

If you need any other information, just tell me in the comments.

update

I have modified the controller in official tutorials to

```<code>@RestController
@RequestMapping(path = "/test")
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
</code>```

it works fine!

答:
Good day !

```<code> The @RequestMapping annotation should be made in this way

@RestController
public class TestController {

  @RequestMapping(value = "/test", method = RequestMethod.GET)
     public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}
</code>```

but that way you get the same result

```<code>@RestController
public class TestController {

  @RequestMapping(value = "/test", method = RequestMethod.GET,
          produces = MediaType.APPLICATION_JSON_VALUE )
    public HashMap HelloWorld() {

         HashMap<String, String> res = new HashMap<String, String>();
            res.put("data", "hello world");
            res.put("errorCode", "0");
            return res;

    }
}
</code>```

url -> localhost:{port}/test

References:

http://spring.io/guides/tutorials/bookmarks/#_getting_started

https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-first-application-code

Body:
I have checked most similar questions, and don't find the answer.So I can only post a new question.

I can successfully run my application without errors, but the rest api I write can't be access correctly.I have compared my launch log to the official tutorials, then I have found out I don't have the similar  log below:

2017-11-13 17:37:50.921  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2328c243: startup date [Mon Nov 13 17:37:49 CST 2017]; root of context hierarchy
2017-11-13 17:37:51.061  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/greeting]}" onto public hello.Greeting hello.GreetingController.greeting(java.lang.String)
2017-11-13 17:37:51.066  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-11-13 17:37:51.067  INFO 6503 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-11-13 17:37:51.126  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.127  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-11-13 17:37:51.188  INFO 6503 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

Here are some my java files, Hope anyone can find some keypoint to solve my problem

the main application file:

package com.teachermate;

import com.alibaba.druid.pool.DruidDataSource;
import com.teachermate.entites.TeacherMateSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

@SpringBootApplication
@EnableConfigurationProperties({TeacherMateSettings.class})
public class JobScheduleApplication {

    @Autowired
    private Environment env;

    public static void main(String[] args) {
        SpringApplication.run(JobScheduleApplication.class, args);
    }

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));
        dataSource.setPassword(env.getProperty("spring.datasource.password"));
        dataSource.setInitialSize(2);
        dataSource.setMaxActive(20);
        dataSource.setMinIdle(0);
        dataSource.setMaxWait(60000);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setPoolPreparedStatements(false);
        return dataSource;
    }
}

the controller file:

@RestController
@RequestMapping(path = "/test")
public class TestController {
  @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

the pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.teachermate</groupId>
    <artifactId>job-scheduler</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>jobSchedule</name>
    <description>job schedule for teachermate</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.7.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.39</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
        </dependency>
        <dependency>
            <groupId>org.quartz-scheduler</groupId>
            <artifactId>quartz</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>23.2-jre</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.19</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <executable>true</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

BTW, the rest api works fine before I add some code or library(like druid).But I don't know what cause it, can anyone help? Or can anyone show me a way to debug it? Thanks!

If you need any other information, just tell me in the comments.

update

I have modified the controller in official tutorials to

@RestController
@RequestMapping(path = "/test")
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping(method = RequestMethod.GET)
    public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

it works fine!

Body:
Good day !

 The @RequestMapping annotation should be made in this way

@RestController
public class TestController {

  @RequestMapping(value = "/test", method = RequestMethod.GET)
     public JSONObject HelloWorld() {
        JSONObject res = new JSONObject();
        LOGGER.info("HelloWorld Test!");
        res.put("data", "hello world!");
        res.put("errCode", 0);
        return res;
    }
}

but that way you get the same result

@RestController
public class TestController {

  @RequestMapping(value = "/test", method = RequestMethod.GET,
          produces = MediaType.APPLICATION_JSON_VALUE )
    public HashMap HelloWorld() {

         HashMap<String, String> res = new HashMap<String, String>();
            res.put("data", "hello world");
            res.put("errorCode", "0");
            return res;

    }
}

url -> localhost:{port}/test

References:

http://spring.io/guides/tutorials/bookmarks/#_getting_started

https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-first-application-code


问:
How can I join lazy translation in Django?
I need to use lazy translation but also I need to make translation - how to deal with?

This code is doing what I need:

```<code>print ugettext_lazy('Hello world!')
</code>```

Now I want join two lazy translations together and translate it separately (I now that will not work and why but want to have two translation strings).

```<code>print ugettext_lazy('Hello world!') + ' ' + ugettext_lazy('Have a fun!')
</code>```

I can do such code but it generates more translation than is need.

```<code>print ugettext_lazy('Hello world! Have a fun!')
</code>```

Is it possible to have two translation strings and lazy translation?

答:
Since django 1.11 string-concat is deprecated, and format_lazy should be used instead

```<code>from django.utils.text import format_lazy
from django.utils.translation import ugettext_lazy

name = ugettext_lazy('John Lennon')
instrument = ugettext_lazy('guitar')
result = format_lazy('{} : {}', name, instrument)
</code>```

Body:
I need to use lazy translation but also I need to make translation - how to deal with?

This code is doing what I need:

print ugettext_lazy('Hello world!')

Now I want join two lazy translations together and translate it separately (I now that will not work and why but want to have two translation strings).

print ugettext_lazy('Hello world!') + ' ' + ugettext_lazy('Have a fun!')

I can do such code but it generates more translation than is need.

print ugettext_lazy('Hello world! Have a fun!')

Is it possible to have two translation strings and lazy translation?

Body:
Since django 1.11 string-concat is deprecated, and format_lazy should be used instead

from django.utils.text import format_lazy
from django.utils.translation import ugettext_lazy

name = ugettext_lazy('John Lennon')
instrument = ugettext_lazy('guitar')
result = format_lazy('{} : {}', name, instrument)

ContentLicense: CC BY-SA 4.0


问:
Rails 3 migration - what is the equivalent of this route in the new world
```<code>map.resource :account, :controller => "users"
</code>```

That is, how do I map the resource account to the users controller?

Thanks, Chris

答: Same as before, as stated there in the RailsGuides. You may want to make your resource plural though (assuming you have several accounts, it makes some sense, but after all it depends on the actual meaning you give it).</p>

ContentLicense: CC BY-SA 2.5

Body:
map.resource :account, :controller => "users"

That is, how do I map the resource account to the users controller?

Thanks, Chris


问:
Creating a nested array from a single array
I have a search function in my app which gets data from a fetchedResultsController. The problem is when I display the filtered data in the tableView everytime it gets to a new section, the array starts over and over (due to indexPath.row being 0 everytime indexPath.section increments). I've never been good at nested arrays and I thought this is the perfect time to learn them, since I can't get over my problem without this array.

So I have this array which is the filtered data out of the fetchedResultsController:

```<code>filteredItems = (fetchedResultsController.fetchedObjects?.filter({(budget : Budget) -> Bool in
 return (budget.dataDescription?.lowercased().contains(searchText.lowercased()))!
        }))!
</code>```

How can I make an array called filteredObjects which sorts my items for sections? For example

- Section 1 (  filteredObjects[0] ):

item 1 (  filteredObjects[0][1] )

item 2 (  filteredObjects[0][2] )

-

Section 2 ( filteredObjects[1] ):

item 1 ( filteredObjects[1][0] )
etc

答:
Use below method to define number of sections

```<code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return filteredObjects.count
}
</code>```

And, for number of rows

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return filteredObjects[section].count
    }
</code>```

And Finally, for CellForRowAtIndexpath

```<code>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TaskTableViewCell
    let currentItem = filteredObjects[indexPath.section][indexPath.row]

    ... Here, use currentItem as whatever it is (Object or dictionary)

            return cell
}
</code>```

Body:
I have a search function in my app which gets data from a fetchedResultsController. The problem is when I display the filtered data in the tableView everytime it gets to a new section, the array starts over and over (due to indexPath.row being 0 everytime indexPath.section increments). I've never been good at nested arrays and I thought this is the perfect time to learn them, since I can't get over my problem without this array.

So I have this array which is the filtered data out of the fetchedResultsController:

filteredItems = (fetchedResultsController.fetchedObjects?.filter({(budget : Budget) -> Bool in
 return (budget.dataDescription?.lowercased().contains(searchText.lowercased()))!
        }))!

How can I make an array called filteredObjects which sorts my items for sections? For example

- Section 1 (  filteredObjects[0] ):

item 1 (  filteredObjects[0][1] )

item 2 (  filteredObjects[0][2] )

-

Section 2 ( filteredObjects[1] ):

item 1 ( filteredObjects[1][0] )
etc

Body:
Use below method to define number of sections

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  return filteredObjects.count
}

And, for number of rows

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return filteredObjects[section].count
    }

And Finally, for CellForRowAtIndexpath

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TaskTableViewCell
    let currentItem = filteredObjects[indexPath.section][indexPath.row]

    ... Here, use currentItem as whatever it is (Object or dictionary)

            return cell
}


问:
Add images into string? Translate word into image
I want to create a program that let you input a sentence such as:
I am happy.
And outputs: I am  (happy emoji, in my case an image I've created myself).

So far I am able to replace happy by another word but I need to replace it with an image.
Can I add images to a string?
If so, how?

UPDATE: My code finally works, this is the html and javascript I've used:

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Parse emotional expressions with emoticions.</title>
     <style>
      .inline-img {
          height: 40px;
        }
    </style>
     </head>
      <body>
        <font size="+3" face="Helvetica">
       <p id="output"></p>
     </font>
         <script>
         document.addEventListener('DOMContentLoaded', function() {
         function word_replace(replacements, str) {
           var result = str;
            for (var [x, url] of replacements) {
             result = result.replace(x, '<img src="' + url + '" alt="emoji" class="inline-img" />');
                    }
          return result;
          }
            var input = prompt('Input your sentence');
            var output = word_replace([

            [/(happy)/ig, 'https://c1.staticflickr.com/5/4521/38517798662_418a72e9d9_b.jpg'],
            [/(sad|depressed)/ig, 'https://c1.staticflickr.com/5/4553/38517797352_6c8fba1a3d_o.png'],
            [/(confused)/ig, "https://c1.staticflickr.com/5/4519/37833334134_109952bda2_b.jpg"],
            [/(afraid)/ig, 'https://c1.staticflickr.com/5/4516/37833334324_c43f01a30d_b.jpg'],
            [/(angry)/ig, 'https://c1.staticflickr.com/5/4532/26773555349_63894fa4be_b.jpg'],
            [/(determined)/ig, 'https://c1.staticflickr.com/5/4537/37833333874_ff92cb8647_b.jpg'],
            [/(love)/ig, 'https://c1.staticflickr.com/5/4530/37833331724_8a90312ddb_b.jpg'],
            [/(indifferent)/ig, 'https://c1.staticflickr.com/5/4543/37833333744_59da46444d_b.jpg']

          ], input);

          var outputElement = document.getElementById("output");
          outputElement.innerHTML = output;
      });

    </script>
  </body>
</html>
</code>```

答: I think you can try to create ico font and use it to replace some words or etc..</p>

Body:
I want to create a program that let you input a sentence such as:
I am happy.
And outputs: I am  (happy emoji, in my case an image I've created myself).

So far I am able to replace happy by another word but I need to replace it with an image.
Can I add images to a string?
If so, how?

UPDATE: My code finally works, this is the html and javascript I've used:

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Parse emotional expressions with emoticions.</title>


问:
Retrieving multiple sub queries output with different rows into a single response in postgresql
I'd like to receive the output of a few sub queries(each of them return a single column with different number of rows) into a single response.

I'm trying the following but it doesn't work with error as [21000] ERROR: more than one row returned by a subquery used as an expression.

```<code>SELECT
  (SELECT DISTINCT org_name
   FROM table_1
   WHERE column1= 1)                        AS terminal_1,
  (SELECT org_name
   FROM table_5
   WHERE column5= 1)                          AS cfs_1,
  (SELECT DISTINCT org_name
   FROM table_4 where column7= 136 )     AS terminals_2,
  (SELECT org_name
   FROM table_6
   WHERE column1=7)                           AS cfs_2;
</code>```

I'd like to do in the way such that in future I can add a few more sub-queries, each of which will also return a single column with a different number of rows. Is there a good practice to achieve the same? Thank you.

EDIT 1: The output response could be in any logical form. i.e. tabular or JSON.

答:
I believe you simply need UNION ALL

```<code>SELECT DISTINCT  't1' tableNum, org_name
FROM table_1
WHERE column1= 1
UNION ALL
SELECT 't5' tableNum, org_name
FROM table_5
WHERE column5= 1
UNION ALL
SELECT DISTINCT 't4' tableNum, org_name
FROM table_4
where column7= 136
UNION ALL
SELECT 't6' tableNum, org_name
FROM table_6
WHERE column1=7
</code>```

Body:
I'd like to receive the output of a few sub queries(each of them return a single column with different number of rows) into a single response.

I'm trying the following but it doesn't work with error as [21000] ERROR: more than one row returned by a subquery used as an expression.

SELECT
  (SELECT DISTINCT org_name
   FROM table_1
   WHERE column1= 1)                        AS terminal_1,
  (SELECT org_name
   FROM table_5
   WHERE column5= 1)                          AS cfs_1,
  (SELECT DISTINCT org_name
   FROM table_4 where column7= 136 )     AS terminals_2,
  (SELECT org_name
   FROM table_6
   WHERE column1=7)                           AS cfs_2;

I'd like to do in the way such that in future I can add a few more sub-queries, each of which will also return a single column with a different number of rows. Is there a good practice to achieve the same? Thank you.

EDIT 1: The output response could be in any logical form. i.e. tabular or JSON.

Body:
I believe you simply need UNION ALL

SELECT DISTINCT  't1' tableNum, org_name
FROM table_1
WHERE column1= 1
UNION ALL
SELECT 't5' tableNum, org_name
FROM table_5
WHERE column5= 1
UNION ALL
SELECT DISTINCT 't4' tableNum, org_name
FROM table_4
where column7= 136
UNION ALL
SELECT 't6' tableNum, org_name
FROM table_6
WHERE column1=7


问:
LINQ query to check same date in the list?
I have a list of list complex object itemofsamestartDate means it has itemofsamestartDate[0],itemofsamestartDate[1],itemofsamestartDate[2].... and so on. itemofsamestartDate[i] has startDate property. I want to write a LINQ query to return True if all the list has same start date.

Below query, I tried -

```<code>var itemofsamestartDate = from aIndex in Enumerable.Range(0, itemOfSinglePrority.Count())
       from b in itemOfSinglePrority.Skip(aIndex + 1)
       let a = itemOfSinglePrority.ElementAt(aIndex)
       where a != b && a.StartDate == b.StartDate
       select new
       {
            object1 = a,
            object2 = b
       };
</code>```

Now  I am checking if itemofsamestartDate count is greater than 0, then it has the same startdate, but above is working fine if I have list count of 2 only i.e. itemofsamestartDate[0] & itemofsamestartDate[1].

What should be a LINQ query to check if the list has same startdata(DateTime datatype).

答:
A readable way of checking this can be :

```<code>bool allEqual=false;

if(itemofsamestartDate != null && itemofsamestartDate.Count()>0) {
    int countEqual = itemofsamestartDate
        .Count(x => x.StartDate == itemofsamestartDate[0].StartDate);
    int count = itemofsamestartDate.Count();

    allEqual = countEqual == count;
}
</code>```

A less readable way :

```<code>bool allEqual=false;
if(itemofsamestartDate != null && itemofsamestartDate.Count()>0)
    allEqual = itemofsamestartDate.Count(x => x.StartDate == itemofsamestartDate[0].StartDate) == itemofsamestartDate.Count();
</code>```

You could also group your list by StartDate and check if there is only one group.

Body:
I have a list of list complex object itemofsamestartDate means it has itemofsamestartDate[0],itemofsamestartDate[1],itemofsamestartDate[2].... and so on. itemofsamestartDate[i] has startDate property. I want to write a LINQ query to return True if all the list has same start date.

Below query, I tried -

var itemofsamestartDate = from aIndex in Enumerable.Range(0, itemOfSinglePrority.Count())
       from b in itemOfSinglePrority.Skip(aIndex + 1)
       let a = itemOfSinglePrority.ElementAt(aIndex)
       where a != b && a.StartDate == b.StartDate
       select new
       {
            object1 = a,
            object2 = b
       };

Now  I am checking if itemofsamestartDate count is greater than 0, then it has the same startdate, but above is working fine if I have list count of 2 only i.e. itemofsamestartDate[0] & itemofsamestartDate[1].

What should be a LINQ query to check if the list has same startdata(DateTime datatype).

Body:
A readable way of checking this can be :

bool allEqual=false;

if(itemofsamestartDate != null && itemofsamestartDate.Count()>0) {
    int countEqual = itemofsamestartDate
        .Count(x => x.StartDate == itemofsamestartDate[0].StartDate);
    int count = itemofsamestartDate.Count();

    allEqual = countEqual == count;
}

A less readable way :

bool allEqual=false;
if(itemofsamestartDate != null && itemofsamestartDate.Count()>0)
    allEqual = itemofsamestartDate.Count(x => x.StartDate == itemofsamestartDate[0].StartDate) == itemofsamestartDate.Count();

You could also group your list by StartDate and check if there is only one group.


问:
How to Resolve duplicate entry: com/google/gson/JsonParseException.class?
I am using android studio 3.0,no matter what i do i can't generate or build APK astonishingly it runs on emulator but build fails on real android device.

This is how the error appears when i try to build APK.

It actually works on other computers only on this system there is this issue.

答:
Try this:</p>

```<code>configurations {
    all*.exclude  module: 'gson'
}
</code>```

Body:
Try this:

configurations {
    all*.exclude  module: 'gson'
}


问:
What are the security concerns when using AD distribution groups to control access to program features?
I'm relatively new to using AD, and I'm using group memberships to control what features and functions are loaded/visible to a given user, both in web and desktop applications.

AD has security groups and distribution groups, and I'm using some of each to get fine-grained discrimination among roles.

What should be my concerns about using distribution groups in this way?

答:
You might consider looking at AzMan (Authorization Manager).

It can be tied to active directory accounts and completely stored within AD.  AzMan provides a lot more fine grained control over Roles and even Actions allowed.  In short you would code your apps to test if the user is authorized for particular Actions.  When creating Roles you would assign one or more actions to that role.

This would allow you to mix and match actions in various roles as necessary without having to change your code base.   I've used it extensively and it's pretty good.

The downside to just using regular AD groups is that you might end up with dozens or even hundreds (depending on the complexity of your apps) roles that pollute the AD space.

For example, let's say you want to have a security check before allowing an account to be deleted.  In AzMan you would create an AccountDelete action and assign that action to one or more roles like Administrator, Account Administrator, etc.

In AD you would have to create a new group altogether and assign it out.  This gets very complicated very quickly.


问:
Uncaught TypeError: Cannot read property 'style' of null - jquery solution?
I created a div in my html code. When the user clicks a button, I execute a simple JS script where I try to hide it:

```<code>  document.getElementById("samplques").style.display = "none";
</code>```

When executed, I get the error

cannot read property style

I understand that the cause may be that the div has not loaded when the JS is executed. I tried putting the JS script at the bottom of the page, but that did not solve it.

Elsewhere on stackoverflow, people have suggested using jQuery. I am not skilled at jQuery, though I am using it occasionally.

Is using jQuery the answer? And if so, how would I accomplish my goal? If not, how do I solve this?

==============================================

Code snippet is here:

```<code><div id="samplques" style="display:block">
samplques starts here - want to hide this when clicked below<p>

heading here<p>

<form>
<input type=radio onclick="posts('here')">click here</a><br>
</form><p>

samplques ends here<p>
</div>

<script type="text/javascript">
function posts(selected) {
    document.getElementById(samplques).style.display = 'none';
}
</script>
</code>```

=============================================

JS error onclick is:

```<code>Uncaught TypeError: Cannot read property 'style' of null
</code>```

答:
try this..Style display Property or try
document.getElementById("samplques").style.display = 'none';</p>

Body:
I created a div in my html code. When the user clicks a button, I execute a simple JS script where I try to hide it:

  document.getElementById("samplques").style.display = "none";

When executed, I get the error

cannot read property style

I understand that the cause may be that the div has not loaded when the JS is executed. I tried putting the JS script at the bottom of the page, but that did not solve it.

Elsewhere on stackoverflow, people have suggested using jQuery. I am not skilled at jQuery, though I am using it occasionally.

Is using jQuery the answer? And if so, how would I accomplish my goal? If not, how do I solve this?

==============================================

Code snippet is here:

samplques starts here - want to hide this when clicked below

heading here

<form>
<input type=radio onclick="posts('here')">click here

</form>

samplques ends here

=============================================

JS error onclick is:

Uncaught TypeError: Cannot read property 'style' of null


问:
Behaviour difference between HashSet and LinkedHashSet for Knights Path solution
I'm seeing a strange behaviour in a coding puzzle I was working on 'Knights Path'. I generate the set of possible moves and store these in a HashSet (the Move class simply has an x,y co-ordinates and a standard hashcode and equals). When I use a HashSet in the generateMoves() method the program doesn't find a solution whereas when I change to the LinkedHashSet it does.

```<code>public static Collection<Move> generateMoves(int startX, int startY){
    Set<Move> moves = new HashSet<Move>(); <-- doesn't work

public static Collection<Move> generateMoves(int startX, int startY){
    Set<Move> moves = new LinkedHashSet<Move>(); <-- works
</code>```

I know that HashSet doesn't provide any guarantees on the ordering of the iterator elements but the ordering of the moves should not matter in terms of the eventual finding of a solution using backtracking method (some ordering of moves would be more optimal than others but with this brute force approach eventually all paths should be considered).

Clearly there is something funky going on with the iterator of the Collection from HashSet but I have conducted multiple tests to compare the output of the generateMoves for every board position using a LinkedHashSet and a HashSet and they are the same.

Full code below, any pointers greatly appreciated as I'm very curious to understand what may be going on here!

```<code>import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class KnightTour {

    private static int countSteps = 0;

    public static void main(String[] args){
        int[][] board = new int[8][8];
        board[0][0] = 1;
        solveTour(board,0,0,1);
    }

    public static class Move{
        @Override
        public String toString() {
            return "["+ x + "," + y + "]";
        }
        int x;
        int y;
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + x;
            result = prime * result + y;
            return result;
        }
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Move other = (Move) obj;
            if (x != other.x)
                return false;
            if (y != other.y)
                return false;
            return true;
        }
    }

    private static void printBoard(int[][] board){
        System.out.println("---------");
        for(int i=0;i <8;i++){
            for(int j=0; j<8; j++){
                if(board[i][j] != 0){
                    System.out.print('x');
                }else{
                    System.out.print('0');
                }

            }
            System.out.println('\r');
        }
        System.out.println("---------");
    }

    public static boolean solveTour(int[][] sol, int x, int y, int movei){
        countSteps++;
        if(countSteps%100000 == 0){
            System.out.println("Count:"+countSteps);
        }

        Collection<Move> moves = generateMoves(x,y);

        if(movei == 64){
            printBoard(sol);
            return true;
        }

        for(Move tryMove : moves){
            int next_x = tryMove.x;
            int next_y = tryMove.y;

            if(isValidMove(sol, next_x,next_y)){
                sol[next_x][next_y] = movei;
                if(solveTour(sol, next_x, next_y, movei+1)){
                    return true;
                }else{
                    sol[next_x][next_y] = 0;
                }
            }
        }

        return false;
    }

    public static boolean isValidMove(int[][] board, int destX, int destY){
        if(destX < 0 || destX > 7 || destY < 0 || destY > 7){
            return false;//Off the board!
        }

        return board[destX][destY] == 0;
    }

    public static Collection<Move> generateMoves(int startX, int startY){
        Set<Move> moves = new HashSet<Move>();//Doesn't terminate
//      Set<Move> moves = new LinkedHashSet<Move>();//Works with Linked

        for(int i=-2; i<=2; i++){
            for(int j=-2; j<=2; j++){
                if(Math.abs(i) == Math.abs(j) || i == 0 || j==0 ){
                    //no op
                }else{
                    Move m = new Move();
                    m.x = startX + i;
                    m.y = startY + j;
                    moves.add(m);
                }
            }
        }

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

答:
It looks to me like what you might be seeing is a side effect of LinkedHashMap iteration, which guarantees to iterate in the order of insert. HashSet does not have this same guarantee and can return the results in any order.

I think that the ordering of moves is probably important to your algorithm and perhaps an accidental heuristic you are applying by traversing in that order. The random ordering of moves may increase the complexity and introduce many new and suboptimal routes to explore recursively.

The HashSet solution might complete, it might be interesting to try with a small board and see if you get a result from that.

Body:
I'm seeing a strange behaviour in a coding puzzle I was working on 'Knights Path'. I generate the set of possible moves and store these in a HashSet (the Move class simply has an x,y co-ordinates and a standard hashcode and equals). When I use a HashSet in the generateMoves() method the program doesn't find a solution whereas when I change to the LinkedHashSet it does.

public static Collection<Move> generateMoves(int startX, int startY){
    Set<Move> moves = new HashSet<Move>(); <-- doesn't work

public static Collection<Move> generateMoves(int startX, int startY){
    Set<Move> moves = new LinkedHashSet<Move>(); <-- works

I know that HashSet doesn't provide any guarantees on the ordering of the iterator elements but the ordering of the moves should not matter in terms of the eventual finding of a solution using backtracking method (some ordering of moves would be more optimal than others but with this brute force approach eventually all paths should be considered).

Clearly there is something funky going on with the iterator of the Collection from HashSet but I have conducted multiple tests to compare the output of the generateMoves for every board position using a LinkedHashSet and a HashSet and they are the same.

Full code below, any pointers greatly appreciated as I'm very curious to understand what may be going on here!

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;

public class KnightTour {

    private static int countSteps = 0;

    public static void main(String[] args){
        int[][] board = new int[8][8];
        board[0][0] = 1;
        solveTour(board,0,0,1);
    }

    public static class Move{
        @Override
        public String toString() {
            return "["+ x + "," + y + "]";
        }
        int x;
        int y;
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + x;
            result = prime * result + y;
            return result;
        }
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Move other = (Move) obj;
            if (x != other.x)
                return false;
            if (y != other.y)
                return false;
            return true;
        }
    }

    private static void printBoard(int[][] board){
        System.out.println("---------");
        for(int i=0;i <8;i++){
            for(int j=0; j<8; j++){
                if(board[i][j] != 0){
                    System.out.print('x');
                }else{
                    System.out.print('0');
                }

            }
            System.out.println('\r');
        }
        System.out.println("---------");
    }

    public static boolean solveTour(int[][] sol, int x, int y, int movei){
        countSteps++;
        if(countSteps%100000 == 0){
            System.out.println("Count:"+countSteps);
        }

        Collection<Move> moves = generateMoves(x,y);

        if(movei == 64){
            printBoard(sol);
            return true;
        }

        for(Move tryMove : moves){
            int next_x = tryMove.x;
            int next_y = tryMove.y;

            if(isValidMove(sol, next_x,next_y)){
                sol[next_x][next_y] = movei;
                if(solveTour(sol, next_x, next_y, movei+1)){
                    return true;
                }else{
                    sol[next_x][next_y] = 0;
                }
            }
        }

        return false;
    }

    public static boolean isValidMove(int[][] board, int destX, int destY){
        if(destX < 0 || destX > 7 || destY < 0 || destY > 7){
            return false;//Off the board!
        }

        return board[destX][destY] == 0;
    }

    public static Collection<Move> generateMoves(int startX, int startY){
        Set<Move> moves = new HashSet<Move>();//Doesn't terminate
//      Set<Move> moves = new LinkedHashSet<Move>();//Works with Linked

        for(int i=-2; i<=2; i++){
            for(int j=-2; j<=2; j++){
                if(Math.abs(i) == Math.abs(j) || i == 0 || j==0 ){
                    //no op
                }else{
                    Move m = new Move();
                    m.x = startX + i;
                    m.y = startY + j;
                    moves.add(m);
                }
            }
        }

        return moves;
    }
}


问:
Bundle not cleared
I have weird problem. How a Bundle can not be cleared after calling its method clear()
This is my code :

```<code>if(isFromPushNotif) {
                        Bundle pushNotifBundle = getIntent().getExtras() ;
                        Log.i("SplashScreen"," before clear "+pushNotifBundle);
                        intent.putExtras(pushNotifBundle) ;
                        getIntent().getExtras().clear();
                        Log.i("SplashScreen"," after clear "+getIntent().getExtras()); //Here bundle is not cleared , log displays all the initial elements

                    }

startActivity(intent);
overridePendingTransition(0, 0);
finish();
</code>```

答:
Try this

clear your bundle

```<code> getIntent().removeExtra("your_key_here_to_be_removed");
</code>```

Title: Bundle not cleared

Body:
I have weird problem. How a Bundle can not be cleared after calling its method clear()
This is my code :

if(isFromPushNotif) {
                        Bundle pushNotifBundle = getIntent().getExtras() ;
                        Log.i("SplashScreen"," before clear "+pushNotifBundle);
                        intent.putExtras(pushNotifBundle) ;
                        getIntent().getExtras().clear();
                        Log.i("SplashScreen"," after clear "+getIntent().getExtras()); //Here bundle is not cleared , log displays all the initial elements

                    }

startActivity(intent);
overridePendingTransition(0, 0);
finish();

Body:
Try this

clear your bundle

 getIntent().removeExtra("your_key_here_to_be_removed");


答:
Exactly as before but without map.:

```<code>resource :account, :controller => "users"
</code>```

Title: Rails 3 migration - what is the equivalent of this route in the new world

Body:
Exactly as before but without map.:

resource :account, :controller => "users"


问:
Create DB link to oracle cloud database which installed in private network
I have public IP, the Oracle cloud DB installed in private IP. through  the public IP we can establish ssh tunnel to private IP and forward localhost port to access Oracle cloud DB.

My task is to create DB link from my localhost oracle DB to cloud Oracle DB. So I can access Oracle cloud DB schema from my localhost oracle DB.

I using Putty to establish SSH & localhost port forward and I can access Oracle Cloud DB using SQL developer/Toad. So public/private IP and SSH details are correct.

In this case, how to create DB link?

答:
You already have forwarded connections coming to localhost port X to the target private IP in AWS (let it be RDS:1521). So your config is localhost:X -> RDS:1521. You also need schema name (myusername) and its password (mypassword).

```<code>CREATE DATABASE LINK mylink
    CONNECT TO myusername IDENTIFIED BY mypassword
    USING '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=X))
           (CONNECT_DATA=(SERVER=dedicated)
           (SERVICE_NAME=myrdsservicename)))';
</code>```

Oracle's 12c syntax for creating db links can be found here.

Instead of using RAW connection parameters (as above) you my prefer to create an entry in tnsnames.ora for the connection string above and use the symbolic name for the localhost forwarded connection.

Body:
You already have forwarded connections coming to localhost port X to the target private IP in AWS (let it be RDS:1521). So your config is localhost:X -> RDS:1521. You also need schema name (myusername) and its password (mypassword).

CREATE DATABASE LINK mylink
    CONNECT TO myusername IDENTIFIED BY mypassword
    USING '(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=X))
           (CONNECT_DATA=(SERVER=dedicated)
           (SERVICE_NAME=myrdsservicename)))';

Oracle's 12c syntax for creating db links can be found here.

Instead of using RAW connection parameters (as above) you my prefer to create an entry in tnsnames.ora for the connection string above and use the symbolic name for the localhost forwarded connection.


问:
Doctrine ORM HYDRATE_SCALAR vs HYDRATE_ARRAY
I'm trying to get all values of a column from a table through Doctrine ORM using following query:

```<code>SELECT item.templateId FROM MyBundle:Item item WHERE item.id IN (:ids)
</code>```

I know Doctrine has hydration mode Query::HYDRATE_SINGLE_SCALAR which returns single scalar value. When, however, having more than one record in result it throws NonUniqueResultException which is fine.

Naturally, I guessed that Query::HYDRATE_SCALAR would do the trick. However, it returns exactly the same result as when using Query::HYDRATE_ARRAY.

Code:

```<code>$ids   = [1, 2, 3];
$query = $this->entityManager->createQuery('
          SELECT item.templateId FROM MyBundle:Item item WHERE item.id IN (:ids)
    ')
    ->setParameter('ids', $ids)
;

// Regardles whether I use HYDRATE_SCALAR or HYDRATE_ARRAY
// $result is the same
$result = $query->getResult(Query::HYDRATE_SCALAR);
</code>```

Here is how $result looks in both cases:

```<code>Array
(
    [0] => Array
        (
            [templateId] => 52
        )

    [1] => Array
        (
            [templateId] => 90
        )

    [2] => Array
        (
            [templateId] => 89
        )
)
</code>```

How I wish it looked:

```<code>Array
(
    [0] => 52

    [1] => 90

    [2] => 89
)
</code>```

I know I can transform it into the form I want, but I wonder why HYDRATE_SCALAR isn't behaving as I expect it to.

答:
Try this:

```<code>$result = $query->getResult(Query::HYDRATE_SCALAR);

return array_map('reset', $result);
</code>```

There you go :)

Body:
I'm trying to get all values of a column from a table through Doctrine ORM using following query:

SELECT item.templateId FROM MyBundle:Item item WHERE item.id IN (:ids)

I know Doctrine has hydration mode Query::HYDRATE_SINGLE_SCALAR which returns single scalar value. When, however, having more than one record in result it throws NonUniqueResultException which is fine.

Naturally, I guessed that Query::HYDRATE_SCALAR would do the trick. However, it returns exactly the same result as when using Query::HYDRATE_ARRAY.

Code:

$ids   = [1, 2, 3];
$query = $this->entityManager->createQuery('
          SELECT item.templateId FROM MyBundle:Item item WHERE item.id IN (:ids)
    ')
    ->setParameter('ids', $ids)
;

// Regardles whether I use HYDRATE_SCALAR or HYDRATE_ARRAY
// $result is the same
$result = $query->getResult(Query::HYDRATE_SCALAR);

Here is how $result looks in both cases:

Array
(
    [0] => Array
        (
            [templateId] => 52
        )

    [1] => Array
        (
            [templateId] => 90
        )

    [2] => Array
        (
            [templateId] => 89
        )
)

How I wish it looked:

Array
(
    [0] => 52

    [1] => 90

    [2] => 89
)

I know I can transform it into the form I want, but I wonder why HYDRATE_SCALAR isn't behaving as I expect it to.

Body:
Try this:

$result = $query->getResult(Query::HYDRATE_SCALAR);

return array_map('reset', $result);

There you go :)


问:
How to exit Python script in Command Prompt?
On previous computers, when I would try to exit a Python script on the Windows command prompt, all you need to do is press ctrl+c.

But when I do that on my computer it tells me "KeyboardInterrupt":

```<code>C:\Windows\System32
>python
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> [I press ctrl+c]
KeyboardInterrupt
>>>
</code>```

So how do I fix this so I can exit the Python script?

Thanks.

Edit:

ctrl+z works, but I need to enter it as code. Was hoping for a quick and easy way to just exit the script, but oh well.

答:
You could simply type "quit()" and its done!

CTRL + C will interrupt a running script; but you only want to quit the interpreter. So quit() function will work for you.

Body:
On previous computers, when I would try to exit a Python script on the Windows command prompt, all you need to do is press ctrl+c.

But when I do that on my computer it tells me "KeyboardInterrupt":

C:\Windows\System32
>python
Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> [I press ctrl+c]
KeyboardInterrupt
>>>

So how do I fix this so I can exit the Python script?

Thanks.

Edit:

ctrl+z works, but I need to enter it as code. Was hoping for a quick and easy way to just exit the script, but oh well.


问:
The "ResolveLibraryProjectImports" task failed unexpectedly
I have a Xamarin project, which is based on MvvmCross. The project is for both iOS and Android. I opened this project in Visual Studio 15. I got some errors, which I solved in no time. There are some errors, which are stuck and I couldn't solve them even after searching on Google and on Stackoverflow. I have tried each and every method found on Stackoverflow, but still all remaining errors are there.
This project is using 3rd party libraries like RestSharp and BoxApi.V2 (few more)

I am posting my error log below.

```<code>Severity    Code    Description Project File    Line    Suppression State
Error       The "ResolveLibraryProjectImports" task failed unexpectedly.
System.IO.FileNotFoundException: Could not load assembly 'RestSharp(Android), Version=0.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'RestSharp(Android).dll'
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(String fullName, ReaderParameters parameters)
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(String fullName)
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.GetAssembly(String fileName)
   at Xamarin.Android.Tasks.ResolveLibraryProjectImports.Extract(DirectoryAssemblyResolver res, ICollection`1 jars, ICollection`1 resolvedResourceDirectories, ICollection`1 resolvedAssetDirectories, ICollection`1 resolvedEnvironments)
   at Xamarin.Android.Tasks.ResolveLibraryProjectImports.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() BoxApi.V2 (Android)
</code>```

This error is repeating for all projects included in this solution. So I am getting this error multiple times.

I also want to add that the project was previously built on MAC and I am using windows, does this make some compatibility or cross OS issue?
I have checked all assembly references and all are working fine.

答:
Here is the problem:
System.IO.PathTooLongException: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

Try to move you project to another location like "C:/" , or change the name of the project for something more brief

Body:
I have a Xamarin project, which is based on MvvmCross. The project is for both iOS and Android. I opened this project in Visual Studio 15. I got some errors, which I solved in no time. There are some errors, which are stuck and I couldn't solve them even after searching on Google and on Stackoverflow. I have tried each and every method found on Stackoverflow, but still all remaining errors are there.
This project is using 3rd party libraries like RestSharp and BoxApi.V2 (few more)

I am posting my error log below.

Severity    Code    Description Project File    Line    Suppression State
Error       The "ResolveLibraryProjectImports" task failed unexpectedly.
System.IO.FileNotFoundException: Could not load assembly 'RestSharp(Android), Version=0.0.0.0, Culture=neutral, PublicKeyToken='. Perhaps it doesn't exist in the Mono for Android profile?
File name: 'RestSharp(Android).dll'
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(AssemblyNameReference reference, ReaderParameters parameters)
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(String fullName, ReaderParameters parameters)
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.Resolve(String fullName)
   at Java.Interop.Tools.Cecil.DirectoryAssemblyResolver.GetAssembly(String fileName)
   at Xamarin.Android.Tasks.ResolveLibraryProjectImports.Extract(DirectoryAssemblyResolver res, ICollection`1 jars, ICollection`1 resolvedResourceDirectories, ICollection`1 resolvedAssetDirectories, ICollection`1 resolvedEnvironments)
   at Xamarin.Android.Tasks.ResolveLibraryProjectImports.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext() BoxApi.V2 (Android)

This error is repeating for all projects included in this solution. So I am getting this error multiple times.

I also want to add that the project was previously built on MAC and I am using windows, does this make some compatibility or cross OS issue?
I have checked all assembly references and all are working fine.


问:
Bootstrap Multiselect scroll bar drag doesn't work in Bootstrap Modal
I'm trying to use bootstrap multi-select in a bootstrap modal. I'm able to initialize it and render it perfectly no issues with that. I'm facing a really annoying issue wherein when I try to drag the scrollbar inside the modal the drop down closes. I tried and replicated the same code outside the bootstrap modal, it works perfectly. I've created the jsFiddle to demonstrate the issue.

Normal scrolling works fine but dragging the scrollbar in the modal closes the drop-down. Any way to fix this issue?

JSFiddle Link

```<code><!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<select id="example-multiple-selected1" multiple="multiple">
  <option value="1">Option 1</option>
  <option value="2" selected="selected">Option 2</option>
  <!-- Option 3 will be selected in advance ... -->
  <option value="3" selected="selected">Option 3</option>
  <option value="4">Option 4</option>
  <option value="5">Option 5</option>
  <option value="6">Option 6</option>
</select>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
      </div>
      <div class="modal-body">
        <select id="example-multiple-selected" multiple="multiple">
          <option value="1">Option 1</option>
          <option value="2" selected="selected">Option 2</option>
          <!-- Option 3 will be selected in advance ... -->
          <option value="3" selected="selected">Option 3</option>
          <option value="4">Option 4</option>
          <option value="5">Option 5</option>
          <option value="6">Option 6</option>
        </select>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
<script>
    $('#example-multiple-selected').multiselect({
          maxHeight: 100
    });
    $('#example-multiple-selected1').multiselect({
          maxHeight: 100
    });
</script>
</code>```

答:
Here is your solution:

```<code>$('.modal').on('mousedown mouseup click', '.multiselect-container', function(e) {
    e.preventDefault();
});
</code>```

Working Jsfiddle: https://jsfiddle.net/scooterlord/hdnf9x61/10/

Body:
I'm trying to use bootstrap multi-select in a bootstrap modal. I'm able to initialize it and render it perfectly no issues with that. I'm facing a really annoying issue wherein when I try to drag the scrollbar inside the modal the drop down closes. I tried and replicated the same code outside the bootstrap modal, it works perfectly. I've created the jsFiddle to demonstrate the issue.

Normal scrolling works fine but dragging the scrollbar in the modal closes the drop-down. Any way to fix this issue?

JSFiddle Link

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<select id="example-multiple-selected1" multiple="multiple">
  <option value="1">Option 1</option>
  <option value="2" selected="selected">Option 2</option>

  <option value="3" selected="selected">Option 3</option>
  <option value="4">Option 4</option>
  <option value="5">Option 5</option>
  <option value="6">Option 6</option>
</select>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <select id="example-multiple-selected" multiple="multiple">
          <option value="1">Option 1</option>
          <option value="2" selected="selected">Option 2</option>

          <option value="3" selected="selected">Option 3</option>
          <option value="4">Option 4</option>
          <option value="5">Option 5</option>
          <option value="6">Option 6</option>
        </select>

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

Body:
Here is your solution:

$('.modal').on('mousedown mouseup click', '.multiselect-container', function(e) {
    e.preventDefault();
});

Working Jsfiddle: https://jsfiddle.net/scooterlord/hdnf9x61/10/


问:
Java MultiChoice, 2 false answers?

Which one of the following is false about classes and inheritance in Java?

a) The sub class can have a method with the same name as the super class.

  b) A sub class can inherit from only one super class by using the keyword “implements”.

  c) In Java, classes can be derived from other classes, in order to create more complex relationships.

  d) A sub class cannot have more attributes than its super class.

My guess is d but b also seems false.
Can a super class be called an interface? I thought a sub class "extends" a super class and a class "implements" an interface. So why is "implements" used in the question?

I'm also having trouble with this question.

Which of the following is correct terminology about inheritance in Java?

A) We extend from a base class and implement a subclass

  B) We implement a base class and extend from an interface

  C) We extend from a subclass and implement a base class

  D) We implement from a subclass and extend an interface

My guess is C yet it's just an educated guess. An explanation would be great!

Thank you

答: Interfaces are not classes. A sub class can have more attributes, It is really natural. Imagine super class Person and sub class Student extends Person. Should Student has less attrituttes than Person?

Title: Java MultiChoice, 2 false answers?


问:
What does exactly mean by 'Line feeds' in HTML and PHP? How do they are added in HTML and PHP code?
I was reading PHP Manual and I come across following text paragraph :

Line feeds have little meaning in HTML, however it is still a good
  idea to make your HTML look nice and clean by putting line feeds in. A
  linefeed that follows immediately after a closing ?> will be removed
  by PHP. This can be extremely useful when you are putting in many
  blocks of PHP or include files containing PHP that aren't supposed to
  output anything. At the same time it can be a bit confusing. You can
  put a space after the closing ?> to force a space and a line feed to
  be output, or you can put an explicit line feed in the last echo/print
  from within your PHP block.

I've following questions related to the text from above paragraph :

What does exactly mean by 'Line feeds' in HTML?

How to add them to the HTML code as well as PHP code and make visible in a web browser? What HTML entities/tags/characters are used to achieve this?

Is the meaning of 'Line feed' same in case of HTML and PHP? If no, what's the difference in meaning in both the contexts?

Why the PHP manual is saying in first line of paragraph itself that? What does PHP Manual want to say by the below sentence?

"Line feeds have little meaning in HTML"

How can it be useful to remove a linefeed that follows immediately after a closing tag ?> when someone is putting in many blocks of PHP or include files containing PHP that aren't supposed to output anything?

Please someone clear my above mentioned doubts by giving answer in simple, lucid and easy to understand language. If someone could accompany the answer by suitable working code examples it would be of great help to me in understanding the concept more clearly.

Thank You.

答:
What does exactly mean by 'Line feeds' in HTML?

It is a general computing term.

The character (0x0a in ASCII) which advances the paper by one line in a teletype or printer, or moves the cursor to the next line on a display.

— source: Wiktionary

How to add them to the HTML code

Press the enter key on your keyboard. Note that (with a couple of exceptions like ```</code>) all whitespace characters are interchangeable in HTML. A new line will be treated as a space.</p>

<blockquote>
  <p>as well as PHP code</p>
</blockquote>

<p>Ditto … or you could use the escape sequence <code>\n</code> inside a string literal.</p>

<blockquote>
  <p>and make visible in a web browser?</p>
</blockquote>

<p>The material you quoted is talking about making source code look nice. You generally don't want line feed characters to be visible in a browser.</p>

<p>You could use a <code>``` element instead.

Outside of ``` elements (and the CSS setting they have by default) you can use a space instead of a new line for the same effect in HTML.

What HTML entities/tags/characters are used to achieve this?

… but the advice given in the last sentence of the material you quoted is probably a better approach.

Body:
What does exactly mean by 'Line feeds' in HTML?

It is a general computing term.

The character (0x0a in ASCII) which advances the paper by one line in a teletype or printer, or moves the cursor to the next line on a display.

— source: Wiktionary

How to add them to the HTML code

Press the enter key on your keyboard. Note that (with a couple of exceptions like <pre>) all whitespace characters are interchangeable in HTML. A new line will be treated as a space.

as well as PHP code

Ditto … or you could use the escape sequence \n inside a string literal.

and make visible in a web browser?

The material you quoted is talking about making source code look nice. You generally don't want line feed characters to be visible in a browser.

You could use a <pre> element instead.

Outside of <pre> elements (and the CSS setting they have by default) you can use a space instead of a new line for the same effect in HTML.

What HTML entities/tags/characters are used to achieve this?

&#10;

… but the advice given in the last sentence of the material you quoted is probably a better approach.


问:
How to get Create Account Link in Liferay 7 or DXP form themeDisplay
In Liferay 6 it was possible to get various types of links, for example you could get CreateAccount link from themeDiplay by using themeDisplay.getURLCreateAccount().toString(). Check this link

Recently I've migrated to Liferay 7. In my custom theme when I am working with .ftl files I'd like to have create account link but I can't find any suitable methods for it. Although you can find getURLSignIn() and getURLSignOut. Check this link

Is there any chance to find a create account url by themeDisplay? If not what should I do?

答:
For theme freemaker template, you can use following.</p>

```<code><#assign plid = layout.getPlid()>
<#assign createAccountURL = portletURLFactory.create(request,"com_liferay_login_web_portlet_LoginPortlet",plid,"RENDER_PHASE")>
${createAccountURL.setParameter("mvcRenderCommandName", "/login/create_account")}
${createAccountURL.setParameter("p_p_state", "maximized")}
${createAccountURL.setParameter("p_p_mode", "view")}

<a href="${createAccountURL}"> Create Account </a>
</code>```

Body:
For theme freemaker template, you can use following.

<#assign plid = layout.getPlid()>
<#assign createAccountURL = portletURLFactory.create(request,"com_liferay_login_web_portlet_LoginPortlet",plid,"RENDER_PHASE")>
${createAccountURL.setParameter("mvcRenderCommandName", "/login/create_account")}
${createAccountURL.setParameter("p_p_state", "maximized")}
${createAccountURL.setParameter("p_p_mode", "view")}

<a href="${createAccountURL}"> Create Account </a>


问:
Dynamically Sorting with LINQ
I have a collection of CLR objects. The class definition for the object has three properties: FirstName, LastName, BirthDate.

I have a string that reflects the name of the property the collection should be sorted by. In addition, I have a sorting direction. How do I dynamically apply this sorting information to my collection? Please note that sorting could be multi-layer, so for instance I could sort by LastName, and then by FirstName.

Currently, I'm trying the following without any luck:

```<code>var results = myCollection.OrderBy(sortProperty);
</code>```

However, I'm getting a message that says:

... does not contain a defintion for 'OrderBy'  and the best extension method overload ... has some invalid arguments.

答:
Okay, my argument with SLaks in his comments has compelled me to come up with an answer :)

I'm assuming that you only need to support LINQ to Objects. Here's some code which needs significant amounts of validation adding, but does work:

```<code>// We want the overload which doesn't take an EqualityComparer.
private static MethodInfo OrderByMethod = typeof(Enumerable)
    .GetMethods(BindingFlags.Public | BindingFlags.Static)
    .Where(method => method.Name == "OrderBy"
           && method.GetParameters().Length == 2)
    .Single();

public static IOrderedEnumerable<TSource> OrderByProperty<TSource>(
    this IEnumerable<TSource> source,
    string propertyName)
{
    // TODO: Lots of validation :)
    PropertyInfo property = typeof(TSource).GetProperty(propertyName);
    MethodInfo getter = property.GetGetMethod();
    Type propType = property.PropertyType;
    Type funcType = typeof(Func<,>).MakeGenericType(typeof(TSource), propType);
    Delegate func = Delegate.CreateDelegate(funcType, getter);
    MethodInfo constructedMethod = OrderByMethod.MakeGenericMethod(
        typeof(TSource), propType);
    return (IOrderedEnumerable<TSource>) constructedMethod.Invoke(null,
        new object[] { source, func });
}
</code>```

Test code:

```<code>string[] foo = new string[] { "Jon", "Holly", "Tom", "William", "Robin" };

foreach (string x in foo.OrderByProperty("Length"))
{
    Console.WriteLine(x);
}
</code>```

Output:

```<code>Jon
Tom
Holly
Robin
William
</code>```

It even returns an IOrderedEnumerable<TSource> so you can chain ThenBy clauses on as normal :)

Title: Dynamically Sorting with LINQ

Body:
I have a collection of CLR objects. The class definition for the object has three properties: FirstName, LastName, BirthDate.

I have a string that reflects the name of the property the collection should be sorted by. In addition, I have a sorting direction. How do I dynamically apply this sorting information to my collection? Please note that sorting could be multi-layer, so for instance I could sort by LastName, and then by FirstName.

Currently, I'm trying the following without any luck:

var results = myCollection.OrderBy(sortProperty);

However, I'm getting a message that says:

... does not contain a defintion for 'OrderBy'  and the best extension method overload ... has some invalid arguments.

Body:
Okay, my argument with SLaks in his comments has compelled me to come up with an answer :)

I'm assuming that you only need to support LINQ to Objects. Here's some code which needs significant amounts of validation adding, but does work:

// We want the overload which doesn't take an EqualityComparer.
private static MethodInfo OrderByMethod = typeof(Enumerable)
    .GetMethods(BindingFlags.Public | BindingFlags.Static)
    .Where(method => method.Name == "OrderBy"
           && method.GetParameters().Length == 2)
    .Single();

public static IOrderedEnumerable<TSource> OrderByProperty<TSource>(
    this IEnumerable<TSource> source,
    string propertyName)
{
    // TODO: Lots of validation :)
    PropertyInfo property = typeof(TSource).GetProperty(propertyName);
    MethodInfo getter = property.GetGetMethod();
    Type propType = property.PropertyType;
    Type funcType = typeof(Func<,>).MakeGenericType(typeof(TSource), propType);
    Delegate func = Delegate.CreateDelegate(funcType, getter);
    MethodInfo constructedMethod = OrderByMethod.MakeGenericMethod(
        typeof(TSource), propType);
    return (IOrderedEnumerable<TSource>) constructedMethod.Invoke(null,
        new object[] { source, func });
}

Test code:

string[] foo = new string[] { "Jon", "Holly", "Tom", "William", "Robin" };

foreach (string x in foo.OrderByProperty("Length"))
{
    Console.WriteLine(x);
}

Output:

Jon
Tom
Holly
Robin
William

It even returns an IOrderedEnumerable<TSource> so you can chain ThenBy clauses on as normal :)