问:
Renaming Variable and data frame iteratively using R
I want to summarize data and create dynamic columns columns and store in different data frame:

data is something like:

```<code>col1  col2  col3
A     1      200
B     1      300
A     2      400

k=c("A","B","C")
for(i in k)
  {
    group_data <- group_by(data[data$col1==i,], col2)
    summary_i<- summarize(group_data ,paste("var",k[i],sep="_") = n())
   }
</code>```

Expected output:

Three data frame with name summary_A, summary_B, summary_C containing variable var_A, var_B and var_C respectively.

答:
As correctly pointed out by @MrFlick, there are better ways to manage your problem.

Anyway, here is a working version of your code:

```<code>data <- structure(list(col1 = structure(c(1L, 2L, 1L), .Label = c("A",
"B"), class = "factor"), col2 = c(1L, 1L, 2L), col3 = c(200L,
300L, 400L)), .Names = c("col1", "col2", "col3"), class = "data.frame", row.names = c(NA,
-3L))

k=c("A","B","C")
for (i in seq_along(k)) {
  group_data <- group_by(data[data$col1==k[i],], col2)
  vark <- paste('var',i,sep='_')
  eval(parse(text=paste("summary_",i," <- summarize(group_data,", vark, " = n())",sep="")))
}

print(summary_1)
# A tibble: 2 x 2
#    col2 var_1
#   <int> <int>
# 1     1     1
# 2     2     1

print(summary_2)
# A tibble: 1 x 2
#    col2 var_2
#   <int> <int>
# 1     1     1

print(summary_3)
# A tibble: 0 x 2
# ... with 2 variables: col2 <int>, var_3 <int>
</code>```

Body:
I want to summarize data and create dynamic columns columns and store in different data frame:

data is something like:

col1  col2  col3
A     1      200
B     1      300
A     2      400

k=c("A","B","C")
for(i in k)
  {
    group_data <- group_by(data[data$col1==i,], col2)
    summary_i<- summarize(group_data ,paste("var",k[i],sep="_") = n())
   }

Expected output:

Three data frame with name summary_A, summary_B, summary_C containing variable var_A, var_B and var_C respectively.

Body:
As correctly pointed out by @MrFlick, there are better ways to manage your problem.

Anyway, here is a working version of your code:

data <- structure(list(col1 = structure(c(1L, 2L, 1L), .Label = c("A",
"B"), class = "factor"), col2 = c(1L, 1L, 2L), col3 = c(200L,
300L, 400L)), .Names = c("col1", "col2", "col3"), class = "data.frame", row.names = c(NA,
-3L))

k=c("A","B","C")
for (i in seq_along(k)) {
  group_data <- group_by(data[data$col1==k[i],], col2)
  vark <- paste('var',i,sep='_')
  eval(parse(text=paste("summary_",i," <- summarize(group_data,", vark, " = n())",sep="")))
}

print(summary_1)
# A tibble: 2 x 2
#    col2 var_1
#   <int> <int>
# 1     1     1
# 2     2     1

print(summary_2)
# A tibble: 1 x 2
#    col2 var_2
#   <int> <int>
# 1     1     1

print(summary_3)
# A tibble: 0 x 2
# ... with 2 variables: col2 <int>, var_3 <int>


来源: stackexchange

问:
How to make file_get_contents return an unique result
I am new to php and would like to ask you for some help returning an unique result from file_get_contents(). The reason is I want to give each photo an unique name, so that later it will be possible to delete just one of them and not all.

```<code>$file =addslashes(file_get_contents($_FILES['image']['tmp_name'][$key]));
</code>```

Unfortunately time() and microtime() doesn't help in this situation.

答:
Maybe this will help you: http://php.net/manual/en/function.uniqid.php

uniqid();

$imageName = $imageName . '_' . uniqid();

ContentLicense: CC BY-SA 3.0

Body:
I am new to php and would like to ask you for some help returning an unique result from file_get_contents(). The reason is I want to give each photo an unique name, so that later it will be possible to delete just one of them and not all.

$file =addslashes(file_get_contents($_FILES['image']['tmp_name'][$key]));

Unfortunately time() and microtime() doesn't help in this situation.


问:
Using cassandra in a data grid to sort and filter data
We are converting from SQL Server to Cassandra for various reasons. The back end system is converted and working and now we are focusing on the front end systems.

In the current system we have a number of Telerik data grids where the app loads all the data and search/sort/filter is done in the grid itself. We want to avoid this and are going to push the search/sort/filter to the DB. In SQL Server this is not a problem because of ad-hoc queries. However in Cassandra it becomes very confusing.

If any operation was allowed then of course a Cassandra table would have to model the data that way. However I was wondering how this is performed in real world scenarios for large amounts of data and large amounts of columns.

For instance, if I had a grid with columns 1, 2, 3, 4 what is the best course of action?

Highly control what the user can do

Create a lot of tables to model the data and pick the one to select from

Don't allow the user to do any data operations

答:
As any NoSQL system, Cassandra performs the queries on Primary Keys best. You can of course use secondary indices, but it will be a lot slower.

So the recommended way is to create Materialized Views for all possible queries.

Another way is to use something like Apache Ignite on top of Cassandra to do analytics, but you don't want to use grids for some reason as i get it.


问:
subprocess "TypeError: a bytes-like object is required, not 'str'"
I'm using this code from a previously asked question a few years ago, however, I believe this is outdated. Trying to run the code, I receive the error above. I'm still a novice in Python, so I could not get much clarification from similar questions. Does anyone know why this is happening?

```<code>import subprocess

def getLength(filename):
  result = subprocess.Popen(["ffprobe", filename],
    stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
  return [x for x in result.stdout.readlines() if "Duration" in x]

print(getLength('bell.mp4'))
</code>```

Traceback

```<code>Traceback (most recent call last):
  File "B:\Program Files\ffmpeg\bin\test3.py", line 7, in <module>
    print(getLength('bell.mp4'))
  File "B:\Program Files\ffmpeg\bin\test3.py", line 6, in getLength
    return [x for x in result.stdout.readlines() if "Duration" in x]
  File "B:\Program Files\ffmpeg\bin\test3.py", line 6, in <listcomp>
    return [x for x in result.stdout.readlines() if "Duration" in x]
TypeError: a bytes-like object is required, not 'str'
</code>```

答:
subprocess returns bytes objects for stdout or stderr streams by default. That means you also need to use bytes objects in operations against these objects. "Duration" in x uses str object. Use a bytes literal (note the b prefix):

```<code>return [x for x in result.stdout.readlines() if b"Duration" in x]
</code>```

or decode your data first, if you know the encoding used (usually, the locale default, but you could set LC_ALL or more specific locale environment variables for the subprocess):

```<code>return [x for x in result.stdout.read().decode(encoding).splitlines(True)
        if "Duration" in x]
</code>```

The alternative is to tell subprocess.Popen() to decode the data to Unicode strings by setting the encoding argument to a suitable codec:

```<code>result = subprocess.Popen(
    ["ffprobe", filename],
    stdout=subprocess.PIPE, stderr = subprocess.STDOUT,
    encoding='utf8'
)
</code>```

If you set text=True (Python 3.7 and up, in previous versions this version is called universal_newlines) you also enable decoding, using your system default codec, the same one that is used for open() calls. In this mode, the pipes are line buffered by default.

ContentLicense: CC BY-SA 4.0

Body:
I'm using this code from a previously asked question a few years ago, however, I believe this is outdated. Trying to run the code, I receive the error above. I'm still a novice in Python, so I could not get much clarification from similar questions. Does anyone know why this is happening?

import subprocess

def getLength(filename):
  result = subprocess.Popen(["ffprobe", filename],
    stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
  return [x for x in result.stdout.readlines() if "Duration" in x]

print(getLength('bell.mp4'))

Traceback

Traceback (most recent call last):
  File "B:\Program Files\ffmpeg\bin\test3.py", line 7, in <module>
    print(getLength('bell.mp4'))
  File "B:\Program Files\ffmpeg\bin\test3.py", line 6, in getLength
    return [x for x in result.stdout.readlines() if "Duration" in x]
  File "B:\Program Files\ffmpeg\bin\test3.py", line 6, in <listcomp>
    return [x for x in result.stdout.readlines() if "Duration" in x]
TypeError: a bytes-like object is required, not 'str'

Body:
subprocess returns bytes objects for stdout or stderr streams by default. That means you also need to use bytes objects in operations against these objects. "Duration" in x uses str object. Use a bytes literal (note the b prefix):

return [x for x in result.stdout.readlines() if b"Duration" in x]

or decode your data first, if you know the encoding used (usually, the locale default, but you could set LC_ALL or more specific locale environment variables for the subprocess):

return [x for x in result.stdout.read().decode(encoding).splitlines(True)
        if "Duration" in x]

The alternative is to tell subprocess.Popen() to decode the data to Unicode strings by setting the encoding argument to a suitable codec:

result = subprocess.Popen(
    ["ffprobe", filename],
    stdout=subprocess.PIPE, stderr = subprocess.STDOUT,
    encoding='utf8'
)

If you set text=True (Python 3.7 and up, in previous versions this version is called universal_newlines) you also enable decoding, using your system default codec, the same one that is used for open() calls. In this mode, the pipes are line buffered by default.


问:
Choose weights that minimize portfolio variance
I am looking for a method that chooses the weights that minimize the portfolio variance.

For example:

I have 3 assets; their returns are given in an array below:

```<code>import numpy as np
x = np.array([[0.2,-0.1,0.5,-0.2],[0, -0.9, 0.8, 0.2],[0.4,0.5,-0.3,-.01]])
</code>```

I can weight them how I want to as long as sum of their weights adds to 1. I am looking for such weights that minimize variance of the portfolio.

Here are two examples of randomly chosen weights:

```<code>weight_1 = [0.3,0.3,0.4]

weighted_x_1 = [ele_x*ele_w for ele_x,ele_w in zip (x,weight_1)]

var_1 = np.var(sum(weighted_x_1))

weight_2 = [-0.2,0.4,0.8]

weighted_x_2 = [ele_x*ele_w for ele_x,ele_w in zip (x,weight_2)]

var_2 = np.var(sum(weighted_x_2))
</code>```

Output:

```<code>>>> var_1
0.02351675000000001
>>> var_2
0.012071999999999999
</code>```

The second way is better.

Is there a Python (or a Python library) method that could do this for me? If not any suggestions on what method I should use to do the above are welcome.

Thank You in Advance

答:
My full solution can be viewed in PDF.

The trick is to put the vectors x_i as columns of a matrix X.

Then writing the problem becomes a Convex Problem with constrain of the solution to be on the Unit Simplex.

I solved it using Projected Sub Gradient Method.

I calculated the Gradient of the objective function and created a projection to the Unit Simplex.

Now all needed is to iterate them.

I validated my solution using CVX.

```<code>% StackOverflow 44984132
% How to calculate weight to minimize variance?
% Remarks:
%   1.  sa
% TODO:
%   1.  ds
% Release Notes
% - 1.0.000     08/07/2017
%   *   First release.

%% General Parameters

run('InitScript.m');

figureIdx           = 0; %<! Continue from Question 1
figureCounterSpec   = '%04d';

generateFigures = OFF;

%% Simulation Parameters

dimOrder    = 3;
numSamples = 4;

mX = randi([1, 10], [dimOrder, numSamples]);
vE = ones([dimOrder, 1]);

%% Solve Using CVX

cvx_begin('quiet')
    cvx_precision('best');
    variable vW(numSamples)
    minimize( (0.5 * sum_square_abs( mX * vW - (1 / numSamples) * (vE.' * mX * vW) * vE )) )
    subject to
        sum(vW) == 1;
        vW >= 0;
cvx_end

disp([' ']);
disp(['CVX Solution -                       [ ', num2str(vW.'), ' ]']);

%% Solve Using Projected Sub Gradient

numIterations   = 20000;
stepSize        = 0.001;
simplexRadius   = 1; %<! Unit Simplex Radius
stopThr         = 1e-6;

hKernelFun  = @(vW) ((mX * vW) - ((1 / numSamples) * ((vE.' * mX * vW) * vE)));
hObjFun     = @(vW) 0.5 * sum(hKernelFun(vW) .^ 2);
hGradFun    = @(vW) (mX.' * hKernelFun(vW)) - ((1 / numSamples) * vE.' * (hKernelFun(vW)) * mX.' * vE);

vW = rand([numSamples, 1]);
vW = vW(:) / sum(vW);

for ii = 1:numIterations
    vGradW = hGradFun(vW);
    vW = vW - (stepSize * vGradW);

    % Projecting onto the Unit Simplex
    % sum(vW) == 1, vW >= 0.
    vW = ProjectSimplex(vW, simplexRadius, stopThr);
end

disp([' ']);
disp(['Projected Sub Gradient Solution -    [ ', num2str(vW.'), ' ]']);

%% Restore Defaults

% set(0, 'DefaultFigureWindowStyle', 'normal');
% set(0, 'DefaultAxesLooseInset', defaultLoosInset);
</code>```

You can see the full code in StackOverflow Q44984132 Repository (PDF is available as well).

The solution was taken from StackOverflow Q44984132.

Body:
I am looking for a method that chooses the weights that minimize the portfolio variance.

For example:

I have 3 assets; their returns are given in an array below:

import numpy as np
x = np.array([[0.2,-0.1,0.5,-0.2],[0, -0.9, 0.8, 0.2],[0.4,0.5,-0.3,-.01]])

I can weight them how I want to as long as sum of their weights adds to 1. I am looking for such weights that minimize variance of the portfolio.

Here are two examples of randomly chosen weights:

weight_1 = [0.3,0.3,0.4]

weighted_x_1 = [ele_x*ele_w for ele_x,ele_w in zip (x,weight_1)]

var_1 = np.var(sum(weighted_x_1))

weight_2 = [-0.2,0.4,0.8]

weighted_x_2 = [ele_x*ele_w for ele_x,ele_w in zip (x,weight_2)]

var_2 = np.var(sum(weighted_x_2))

Output:

>>> var_1
0.02351675000000001
>>> var_2
0.012071999999999999

The second way is better.

Is there a Python (or a Python library) method that could do this for me? If not any suggestions on what method I should use to do the above are welcome.

Thank You in Advance

Body:
My full solution can be viewed in PDF.

The trick is to put the vectors x_i as columns of a matrix X.

Then writing the problem becomes a Convex Problem with constrain of the solution to be on the Unit Simplex.

I solved it using Projected Sub Gradient Method.

I calculated the Gradient of the objective function and created a projection to the Unit Simplex.

Now all needed is to iterate them.

I validated my solution using CVX.

% StackOverflow 44984132
% How to calculate weight to minimize variance?
% Remarks:
%   1.  sa
% TODO:
%   1.  ds
% Release Notes
% - 1.0.000     08/07/2017
%   *   First release.

%% General Parameters

run('InitScript.m');

figureIdx           = 0; %<! Continue from Question 1
figureCounterSpec   = '%04d';

generateFigures = OFF;

%% Simulation Parameters

dimOrder    = 3;
numSamples = 4;

mX = randi([1, 10], [dimOrder, numSamples]);
vE = ones([dimOrder, 1]);

%% Solve Using CVX

cvx_begin('quiet')
    cvx_precision('best');
    variable vW(numSamples)
    minimize( (0.5 * sum_square_abs( mX * vW - (1 / numSamples) * (vE.' * mX * vW) * vE )) )
    subject to
        sum(vW) == 1;
        vW >= 0;
cvx_end

disp([' ']);
disp(['CVX Solution -                       [ ', num2str(vW.'), ' ]']);

%% Solve Using Projected Sub Gradient

numIterations   = 20000;
stepSize        = 0.001;
simplexRadius   = 1; %<! Unit Simplex Radius
stopThr         = 1e-6;

hKernelFun  = @(vW) ((mX * vW) - ((1 / numSamples) * ((vE.' * mX * vW) * vE)));
hObjFun     = @(vW) 0.5 * sum(hKernelFun(vW) .^ 2);
hGradFun    = @(vW) (mX.' * hKernelFun(vW)) - ((1 / numSamples) * vE.' * (hKernelFun(vW)) * mX.' * vE);

vW = rand([numSamples, 1]);
vW = vW(:) / sum(vW);

for ii = 1:numIterations
    vGradW = hGradFun(vW);
    vW = vW - (stepSize * vGradW);

    % Projecting onto the Unit Simplex
    % sum(vW) == 1, vW >= 0.
    vW = ProjectSimplex(vW, simplexRadius, stopThr);
end

disp([' ']);
disp(['Projected Sub Gradient Solution -    [ ', num2str(vW.'), ' ]']);

%% Restore Defaults

% set(0, 'DefaultFigureWindowStyle', 'normal');
% set(0, 'DefaultAxesLooseInset', defaultLoosInset);

You can see the full code in StackOverflow Q44984132 Repository (PDF is available as well).

The solution was taken from StackOverflow Q44984132.


问:
Capture value from infinite thread c++
I have created a thread that is running parrallel with main thread. Both threads are doing something infinitely (both have while(true) statement). Main thread while(true) is creating game logic in frames, and second thread is receiveing messages from socket.

Is it possible to get string value of message received from second thread into main thread each frame without returning from second thread?
In c#, I would do it with method invoker but I didn't find anything helpful for c++. Is it possible to perform in c++?

Function which creates thread:

```<code>void ReceiveMessage() {
    //std::promise<int> p;
    //auto f = p.get_future();
    char buf[1024];
    string usernput;
    int bytesReceived = 0;
    std::thread receiveMessage(&FactoredThread::ThreadFunction, *this);
    receiveMessage.detach();
    //pokusajporuke = f.get();
}
</code>```

ThreadFunction:

```<code>void ThreadFunction() {
    bytesReceived = 0;
    while (true) {
        bytesReceived = recv(sock, buf, 1024, 0);
        if (bytesReceived > 0) {
            string primljeniString = "";
            for (int i = 0; i < sizeof(buf); i++) {
                if (buf[i] != 0)
                {
                    primljeniString += buf[i];
                }
            }
            ZeroMemory(buf, 1024);
            pokusajporuke = primljeniString;

        }
    }
}
</code>```

So how to get "pokusajporuke" string for main thread?

答:
Yes, sure. There are many ways of solving this problem.
One way is to use signals and slots, like in Qt. For pure C++ you could use Boost.Signals2, which is thread safe.
Or you can realize pattern producer-consumer. One thread(producer) puts values into buffer(it should be thread-safe buffer), second takes them from there.
I think, for your problem second way is better. </p>

Title: Capture value from infinite thread c++

Body:
I have created a thread that is running parrallel with main thread. Both threads are doing something infinitely (both have while(true) statement). Main thread while(true) is creating game logic in frames, and second thread is receiveing messages from socket.

Is it possible to get string value of message received from second thread into main thread each frame without returning from second thread?
In c#, I would do it with method invoker but I didn't find anything helpful for c++. Is it possible to perform in c++?

Function which creates thread:

void ReceiveMessage() {
    //std::promise<int> p;
    //auto f = p.get_future();
    char buf[1024];
    string usernput;
    int bytesReceived = 0;
    std::thread receiveMessage(&FactoredThread::ThreadFunction, *this);
    receiveMessage.detach();
    //pokusajporuke = f.get();
}

ThreadFunction:

void ThreadFunction() {
    bytesReceived = 0;
    while (true) {
        bytesReceived = recv(sock, buf, 1024, 0);
        if (bytesReceived > 0) {
            string primljeniString = "";
            for (int i = 0; i < sizeof(buf); i++) {
                if (buf[i] != 0)
                {
                    primljeniString += buf[i];
                }
            }
            ZeroMemory(buf, 1024);
            pokusajporuke = primljeniString;

        }
    }
}

So how to get "pokusajporuke" string for main thread?


问:
Kafka - Idempotent producer in "exactly once delivery" semantic
From last version of Kafka (0.11.0.0) released the 28th of June 2017, the kafka team provided new features in order to support exactly once delivery.
After I downloaded the latest version I tried configuring the Producer (executed through kafka-console-producer.sh script) as described in Producer configs: I set enable.idempotence=true and transactional.id=0A0A.

The problem is that when I start the producer I get a ConfigException saying that acks must be set to all or -1 (even if I set it in the producer.properties file which I pass as argument to the console script).

Could be the root cause that idempotence cannot be set using the console script? Moreover, is there a way to do an atomic transaction producing messages through the provided console script?

Details:

Implementation details and motivations

Exactly once semantics

In sythesis, the adopted solution is based upon two main concepts:

idempotent Producer able to write a specific message only once, thanks to the introduction of transactional ids in producers config
that guarantee atomicity property also in case of multiple
partitions for a single topic);

on the Consumer side, through the isolation.level=read_committed property, we are now able to read messages only after the transaction is committed.

答: Console producer sets its own defaults. Try adding --request-required-acks "all" or --request-required-acks -1 to set acks to all in place of the default of 1.


问:
Property for react component is not defined
After running this code - I got the exception that "title" is not defined. I checked that api returns correct data. And on the debug mode I noticed that render() from Idea component is running earlier than getting the data from API. Can you explain why is it working in this way? And what options I have for resolving this issue?
Thanks</p>

```<code>'use strict';

const React = require('react');
const ReactDOM = require('react-dom');
const client = require('./client');

class App extends React.Component {

constructor(props) {
    super(props);
    this.state = {map: {}};
}

componentDidMount() {
    client({method: 'GET', path: '/api/maps/1'}).done(response => {
        this.setState({map: response.entity._embedded.map});
    });
}

render() {
    return (
        <Map map={this.state.map}/>
    )
}
}

class Map extends React.Component {
    render() {
        return (
            <div id="map_header">
                <AddIdeaButton></AddIdeaButton>
                <Idea idea={this.props.map.root}></Idea>
            </div>
        );
    }
}

class AddIdeaButton extends React.Component {
    render() {
        return (
            <a id="btn_add">
            </a>
        );
    }
}

class Idea extends React.Component {
    render() {
        <div id="root">{this.props.idea.title}</div>
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('react')
);
</code>```

答:
Asynchronous request for data takes some time during which React still renders Map and Idea components. You can simply render Idea conditionally when data is available:

    <AddIdeaButton></AddIdeaButton>
    {this.props.map.root && (
      <Idea idea={this.props.map.root}></Idea>
    )}

```

Body:
After running this code - I got the exception that "title" is not defined. I checked that api returns correct data. And on the debug mode I noticed that render() from Idea component is running earlier than getting the data from API. Can you explain why is it working in this way? And what options I have for resolving this issue?
Thanks

'use strict';

const React = require('react');
const ReactDOM = require('react-dom');
const client = require('./client');

class App extends React.Component {

constructor(props) {
    super(props);
    this.state = {map: {}};
}

componentDidMount() {
    client({method: 'GET', path: '/api/maps/1'}).done(response => {
        this.setState({map: response.entity._embedded.map});
    });
}

render() {
    return (
        <Map map={this.state.map}/>
    )
}
}

class Map extends React.Component {
    render() {
        return (

                <AddIdeaButton></AddIdeaButton>
                <Idea idea={this.props.map.root}></Idea>

        );
    }
}

class AddIdeaButton extends React.Component {
    render() {
        return (

        );
    }
}

class Idea extends React.Component {
    render() {

{this.props.idea.title}

    }
}

ReactDOM.render(
    <App />,
    document.getElementById('react')
);

Body:
Asynchronous request for data takes some time during which React still renders Map and Idea components. You can simply render Idea conditionally when data is available:

<div id="map_header">
    <AddIdeaButton></AddIdeaButton>
    {this.props.map.root && (
      <Idea idea={this.props.map.root}></Idea>
    )}
</div>


问:
Parsing String by pattern of substrings
I need to parse a formula and get all the variables that were used. The list of variables is available. For example, the formula looks like this:

```<code>String f = "(Min(trees, round(Apples1+Pears1,1)==1&&universe==big)*number";
</code>```

I know that possible variables are:

```<code>String[] vars = {"trees","rivers","Apples1","Pears1","Apricots2","universe","galaxy","big","number"};
</code>```

I need to get the following array:

```<code>String[] varsInF = {"trees", "Apples1","Pears1", "universe", "big","number"};
</code>```

I believe that split method is good here but can’t figure the regexp required for this.

答:
No need for any regex pattern - just check which item of the supported vars is contained in the given string:

```<code>List<String> varsInf = new ArrayList<>();
for(String var : vars)
    if(f.contains(var))
        varsInf.add(var);
</code>```

Using Stream<> you can:

```<code>String[] varsInf = Arrays.stream(vars).filter(f::contains).toArray(String[]::new);
</code>```

Title: Parsing String by pattern of substrings

Body:
I need to parse a formula and get all the variables that were used. The list of variables is available. For example, the formula looks like this:

String f = "(Min(trees, round(Apples1+Pears1,1)==1&&universe==big)*number";

I know that possible variables are:

String[] vars = {"trees","rivers","Apples1","Pears1","Apricots2","universe","galaxy","big","number"};

I need to get the following array:

String[] varsInF = {"trees", "Apples1","Pears1", "universe", "big","number"};

I believe that split method is good here but can’t figure the regexp required for this.

Body:
No need for any regex pattern - just check which item of the supported vars is contained in the given string:

List<String> varsInf = new ArrayList<>();
for(String var : vars)
    if(f.contains(var))
        varsInf.add(var);

Using Stream<> you can:

String[] varsInf = Arrays.stream(vars).filter(f::contains).toArray(String[]::new);


问:
Show Windows File Copy Progress Bar in Access-VBA (2016)
Copying many files from several sources to several destination over our network using MS Access 2016. Can use SysCmd to show Progress Bar on status Bar. Can also show file copy counter as a msg on status bar via Application.Echo True, "msg". But neither is as informative or visually appealing as that used by Windows file copy progress bar. Have looked at several customized progress bars on forms. If I could develop each to show the same information and progress bar as the one used by Windows, it'd be fine. But I wonder if there's a way to call the one used in Windows from MS Access VBA. Thank you in advance. </p>

答:
As far as I know, the only way to achieve this is to create a custom COM library. Because the explanation is rather long, I will refer you to some resources (you will need some version of Visual Studio to create the library, and some experience with either C# or VB.Net).

You will want to call FileSystem.CopyFile in your library, with ShowUI set to AllDialogs (https://msdn.microsoft.com/en-us/library/ms127965(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb).

See http://www.geeksengine.com/article/create-dll.html for instructions how to create the library, and register it in Access.


问:
Unable to embed a gif on imgur to a README.md on github
I want to show a large gif on README.md. Firstly, I uploaded it to imgur. And then, I added the url to README.md # .  But it cannot be loaded, it was compiled to:

```<code><a href="https://camo.githubusercontent.com/b4f1167e599ce7936bb83aad5d007ca8f04345ac/687474703a2f2f692e696d6775722e636f6d2f644e5973776d492e676966" target="_blank">
    <img alt="YAP" src="https://camo.githubusercontent.com/b4f1167e599ce7936bb83aad5d007ca8f04345ac/687474703a2f2f692e696d6775722e636f6d2f644e5973776d492e676966" data-canonical-src="http://i.imgur.com/dNYswmI.gif" style="max-width:100%;"></a>
</code>```

This is my README.

```<code>###Description
  A open source player.

###Screenshot
# <img alt="YAP" src="http://i.imgur.com/dNYswmI.gif">
</code>```

答:
GitHub does support Imgur embeds. Make sure to provide the image extension, which isn't on Imgurs default share hyperlink.

BAD

```<code>![Imgur Image](http://i.imgur.com/zTONrOD)
</code>```

GOOD

```<code>![Imgur Image](http://i.imgur.com/zTONrOD.jpg)
</code>```

Imgur also provides this preformatted link under the MarkDown links menu, see image below.

See also an example readme.md with Imgur image.

Body:
I want to show a large gif on README.md. Firstly, I uploaded it to imgur. And then, I added the url to README.md # .  But it cannot be loaded, it was compiled to:

This is my README.

###Description
  A open source player.

###Screenshot
#

Body:
GitHub does support Imgur embeds. Make sure to provide the image extension, which isn't on Imgurs default share hyperlink.

BAD

![Imgur Image](http://i.imgur.com/zTONrOD)

GOOD

![Imgur Image](http://i.imgur.com/zTONrOD.jpg)

Imgur also provides this preformatted link under the MarkDown links menu, see image below.

See also an example readme.md with Imgur image.


问:
make absolute div that appears above relative anchor tag (img inside) both clickable
I'm trying to get a hidden div, that appears above a anchor tag (while hovering), both clickable. The link contains an image and clicking it opens a modal box, and the div has social network links/images.

The parent is
 and the children are, in order, the  link with the  inside (both relative), the hidden div (absolute) and a
 (relative) that is the one above the hidden div and must remain like that until it hover and the div appears from the top.

I wonder why the z-index value of +0 doesn't work with absolute. It must be -1 or less to be behind the
 container. Some other tiny detail that bothers me: the top a/img outline border while focused is not visible with my code (see the fiddle at the end). What makes it so? Both have display: block and position: relative.

I'm using html5 tags, so:

```<code><figure class="team-grid twenny">
    <a href="#" data-toggle="modal" data-target="#t1_desc">
        <img src="http://via.placeholder.com/205x264" />
    </a>
    <div class="p-mask">
        <ul class="social-icons">
            <li><a href="#" class="icon-button twitter"><i class="icon-twitter"></i><span></span></a></li>
            <li><a href="#" class="icon-button google"><i class="icon-google"></i><span></span></a></li>
            <li><a href="#" class="icon-button v"><i class="icon-v"></i><span></span></a></li>
            <li><a href="#" class="icon-button pinterest"><i class="pinterest"></i><span></span></a></li>
        </ul>
    </div>
    <figcaption>
        <h4>Natasha César</h4>
        <p><?= $lang->getW('t1_title') ?></p>
    </figcaption>
</figure>
</code>```

The social network links should have 30px (for both width and height). The design is from a w3layout template (fiddle with the original code: https://jsfiddle.net/bfb1L7g1/ <-- this is what I want to achieve with simple html5 markup)

This is the css code:

```<code>.team-grid { position: relative }
.team figure {
    position: relative;
    overflow: hidden;
    display: inline-block
}
.team figure a {
    position: relative;
    display: block;
}
.team figure img {
    position: relative;
    display: block;
    max-width: 100%;
    height: auto;
}
.team figcaption {
    background-color: white;
    padding: 1em;
    border: 4px double #D0D0D0;
    text-align: center;
    z-index: 2;
}
.team .p-mask {
    position: absolute;
    opacity: 0;
    visibility: hidden;
    text-align: center;
    background: rgba(0, 0, 0, 0.72);
    bottom: 30%;
    padding: 1em 0 .6em;
    width: 87%;
    overflow: hidden;
    z-index: 1;
    -webkit-transform: translate3d( 0px, 100%, 0px );
       -moz-transform: translate3d( 0px, 100%, 0px );
        -ms-transform: translate3d( 0px, 100%, 0px );
         -o-transform: translate3d( 0px, 100%, 0px );
            transform: translate3d( 0px, 100%, 0px );
    -webkit-transition: all .5s ease 0s;
       -moz-transition: all .5s ease 0s;
            transition: all .5s ease 0s;
}
.team figure:hover .p-mask {
    opacity: 1;
    visibility: visible;
    -webkit-transform: translate3d( 0px, 0px, 0px );
       -moz-transform: translate3d( 0px, 0px, 0px );
        -ms-transform: translate3d( 0px, 0px, 0px );
         -o-transform: translate3d( 0px, 0px, 0px );
            transform: translate3d( 0px, 0px, 0px );
}
</code>```

Why is the absolute div above the figcaption element if this has z-index: 2 (1 more than the div)?

I have made a jsfiddle with the rest of the code: https://jsfiddle.net/cm3k6rot/1/

So the div.p-mask is exactly the same in both jsfiddles (html and css), why is behaving different? Does anyone see where's the difference?

答:
The different values of position in CSS affects it's vertical alignment.

The z-index property in CSS controls the vertical stacking order of
  elements that overlap. As in, which one appears as if it is physically
  closer to you. z-index only effects elements that have a position
  value other than static (the default).

Elements can overlap for a variety of reasons, for instance relative
  positioning has nudged it over something else. Negative margin has
  pulled the element over another. Absolutely positioned elements
  overlap each other. All sorts of reasons.

If you have two divs, and one is absolutely positioned and one isn't, no amount of z-index on the position: static; div is going to change anything.

div {
  width: 200px;
  height: 100px;
  border: 1px solid black;
}

.div1 {
  background-color: red;
  margin-top: 10px;
  margin-left: 10px;
}
.div2 {
  background-color: blue;
  z-index: 2147483647;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="div1" style="position: absolute;"></div>
<div class="div2"></div></code>```

But if both the divs are abosolutely positioned, then even a very small z-index value will do place it above the other div:

div {
  width: 200px;
  height: 100px;
  border: 1px solid black;
}

.div1 {
  background-color: red;
  position: absolute;
  margin-top: 10px;
  margin-left: 10px;
}
.div2 {
  background-color: blue;
  position: absolute;
  z-index: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="div1"></div>
<div class="div2"></div></code>```

You can read more about z-index here

Body:
I'm trying to get a hidden div, that appears above a anchor tag (while hovering), both clickable. The link contains an image and clicking it opens a modal box, and the div has social network links/images.

The parent is
 and the children are, in order, the  link with the  inside (both relative), the hidden div (absolute) and a
 (relative) that is the one above the hidden div and must remain like that until it hover and the div appears from the top.

I wonder why the z-index value of +0 doesn't work with absolute. It must be -1 or less to be behind the
 container. Some other tiny detail that bothers me: the top a/img outline border while focused is not visible with my code (see the fiddle at the end). What makes it so? Both have display: block and position: relative.

I'm using html5 tags, so:

Natasha César

<?= $lang->getW('t1_title') ?>

The social network links should have 30px (for both width and height). The design is from a w3layout template (fiddle with the original code: https://jsfiddle.net/bfb1L7g1/ <-- this is what I want to achieve with simple html5 markup)

This is the css code:

.team-grid { position: relative }
.team figure {
    position: relative;
    overflow: hidden;
    display: inline-block
}
.team figure a {
    position: relative;
    display: block;
}
.team figure img {
    position: relative;
    display: block;
    max-width: 100%;
    height: auto;
}
.team figcaption {
    background-color: white;
    padding: 1em;
    border: 4px double #D0D0D0;
    text-align: center;
    z-index: 2;
}
.team .p-mask {
    position: absolute;
    opacity: 0;
    visibility: hidden;
    text-align: center;
    background: rgba(0, 0, 0, 0.72);
    bottom: 30%;
    padding: 1em 0 .6em;
    width: 87%;
    overflow: hidden;
    z-index: 1;
    -webkit-transform: translate3d( 0px, 100%, 0px );
       -moz-transform: translate3d( 0px, 100%, 0px );
        -ms-transform: translate3d( 0px, 100%, 0px );
         -o-transform: translate3d( 0px, 100%, 0px );
            transform: translate3d( 0px, 100%, 0px );
    -webkit-transition: all .5s ease 0s;
       -moz-transition: all .5s ease 0s;
            transition: all .5s ease 0s;
}
.team figure:hover .p-mask {
    opacity: 1;
    visibility: visible;
    -webkit-transform: translate3d( 0px, 0px, 0px );
       -moz-transform: translate3d( 0px, 0px, 0px );
        -ms-transform: translate3d( 0px, 0px, 0px );
         -o-transform: translate3d( 0px, 0px, 0px );
            transform: translate3d( 0px, 0px, 0px );
}

Why is the absolute div above the figcaption element if this has z-index: 2 (1 more than the div)?

I have made a jsfiddle with the rest of the code: https://jsfiddle.net/cm3k6rot/1/

So the div.p-mask is exactly the same in both jsfiddles (html and css), why is behaving different? Does anyone see where's the difference?

Body:
The different values of position in CSS affects it's vertical alignment.

The z-index property in CSS controls the vertical stacking order of
  elements that overlap. As in, which one appears as if it is physically
  closer to you. z-index only effects elements that have a position
  value other than static (the default).

Elements can overlap for a variety of reasons, for instance relative
  positioning has nudged it over something else. Negative margin has
  pulled the element over another. Absolutely positioned elements
  overlap each other. All sorts of reasons.

If you have two divs, and one is absolutely positioned and one isn't, no amount of z-index on the position: static; div is going to change anything.

div {
  width: 200px;
  height: 100px;
  border: 1px solid black;
}

.div1 {
  background-color: red;
  margin-top: 10px;
  margin-left: 10px;
}
.div2 {
  background-color: blue;
  z-index: 2147483647;
}

<div class="div1" style="position: absolute;"></div>
<div class="div2"></div>

But if both the divs are abosolutely positioned, then even a very small z-index value will do place it above the other div:

div {
  width: 200px;
  height: 100px;
  border: 1px solid black;
}

.div1 {
  background-color: red;
  position: absolute;
  margin-top: 10px;
  margin-left: 10px;
}
.div2 {
  background-color: blue;
  position: absolute;
  z-index: 2;
}

<div class="div1"></div>
<div class="div2"></div>

You can read more about z-index here


问:
Using Bootstrap with Webpack
I have an app that uses Webpack. I'm new to Webpack and trying to learn how to use it effectively. Specifically, I'm trying to import Bootstrap with Font Awesome into my project. I found this SO post, however, I am still unable to use Bootstrap. I'm not sure if it's out-of-date, or if I'm misunderstanding something.

I tried loading Bootstrap and Font Awesome via the url-loader. I was referencing the following URLs:

```<code>https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/css/bootstrap.min.css
https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css
</code>```

I also tried using loading Bootstrap and Font Awesome via NPM and then referencing it in my entry file like this:

```<code>require('bootstrap');
require('font-awesome');
</code>```

It seems like this should be part of a commonly used template. However, I'm not finding one. How do I use Bootstrap and Font Awesome with Webpack?

However, I've come up short with that approach as well.

答:
I have created a simple example on GitHub. Webpack 2 and Bootstrap 3 are used.

Install dependency npm install jquery bootstrap

index.js

```<code>require('bootstrap');
require('bootstrap/dist/css/bootstrap.css');
require('font-awesome/css/font-awesome.css'); //Optional. The question author uses this package.
</code>```

webpack

```<code>const webpack = require('webpack');
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: path.resolve(__dirname, "index.js"),
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: "bundle.js"
    },
    module: {
        rules: [
            {
                test: /\.woff2?$|\.ttf$|\.eot$|\.svg$/,
                use: [{
                    loader: "file-loader"
                }]
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: 'css-loader'
                })
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin('bundle.styles.css'),
        new webpack.ProvidePlugin({
            // inject ES5 modules as global vars
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        })
    ]
};
</code>```

index.html

```<code><link rel="stylesheet" type="text/css" href="/dist/bundle.styles.css">
<script type="text/javascript" src="/dist/bundle.js"></script>
</code>```

You can use HtmlWebpackPlugin if don't want to insert bundle.styles.css and bundle.js manually.

Title: Using Bootstrap with Webpack

Body:
I have an app that uses Webpack. I'm new to Webpack and trying to learn how to use it effectively. Specifically, I'm trying to import Bootstrap with Font Awesome into my project. I found this SO post, however, I am still unable to use Bootstrap. I'm not sure if it's out-of-date, or if I'm misunderstanding something.

I tried loading Bootstrap and Font Awesome via the url-loader. I was referencing the following URLs:

https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.4/css/bootstrap.min.css
https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css

I also tried using loading Bootstrap and Font Awesome via NPM and then referencing it in my entry file like this:

require('bootstrap');
require('font-awesome');

It seems like this should be part of a commonly used template. However, I'm not finding one. How do I use Bootstrap and Font Awesome with Webpack?

However, I've come up short with that approach as well.

Body:
I have created a simple example on GitHub. Webpack 2 and Bootstrap 3 are used.

Install dependency npm install jquery bootstrap

index.js

require('bootstrap');
require('bootstrap/dist/css/bootstrap.css');
require('font-awesome/css/font-awesome.css'); //Optional. The question author uses this package.

webpack

const webpack = require('webpack');
const path = require("path");
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
    entry: path.resolve(__dirname, "index.js"),
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: "bundle.js"
    },
    module: {
        rules: [
            {
                test: /\.woff2?$|\.ttf$|\.eot$|\.svg$/,
                use: [{
                    loader: "file-loader"
                }]
            },
            {
                test: /\.css$/,
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: 'css-loader'
                })
            }
        ]
    },
    plugins: [
        new ExtractTextPlugin('bundle.styles.css'),
        new webpack.ProvidePlugin({
            // inject ES5 modules as global vars
            $: 'jquery',
            jQuery: 'jquery',
            'window.jQuery': 'jquery'
        })
    ]
};

index.html

<link rel="stylesheet" type="text/css" href="/dist/bundle.styles.css">
<script type="text/javascript" src="/dist/bundle.js"></script>

You can use HtmlWebpackPlugin if don't want to insert bundle.styles.css and bundle.js manually.


问:
Problem with Authentication in sharepoint using active directory
I am currently using windows server 2008 machine. I have active directory and sharepoint setup on the machine. I have a user 'A' in the active directory and i have given the user read permissions to my site.

The problem i now face is that, if i log in as user 'A' the site simply shows "error:access denied". This problem goes away if i put 'A' as a site collection administrator, however that is not what i want. I just want 'A' to be a visitor that can browse the site.
I also tried granting 'read' permission to my site for 'A' but that still gives me the access denied message.

Thank you for your time.

答: thats the cause of the problem your page library has got disintegrated from inherited permission from its parent site. you have to go to the page library settings and either add the user their as a viewer or start permission inheritance in the page library :)</p>

ContentLicense: CC BY-SA 2.5


问:
Combining click and touchstart events not working
I have a website that I'm trying to make functional on mobile as well.  However, when I combine click and touchstart events for PC and tablets respectively, neither works(Clicking on the element the events are attached to aren't firing).  Can anyone explain how I should go about fixing this?  Here's an example of one element not working, the pen has the entire project.

HTML

```<code><div id="menu">
    <h1>MENU</h1>
</div>
<div class="dropdown hidden">
    <ul>
        <li id="home_navlink">Home</li>
        <li id="about_navlink">About Me</li>
        <li id="work_navlink">My Work</li>
        <li id="contact_navlink">Contact Me</li>
    </ul>
</div>
</code>```

JS

```<code>let menu = document.getElementById("menu");
let dropdown = document.getElementsByClassName("dropdown")[0];
menu.addEventListener("click touchstart", function(){
    if(dropdown.classList.contains("showing")){
        dropdown.classList.remove("showing");
        dropdown.classList.add("hidden");
    }
    else{
        dropdown.classList.remove("hidden");
        dropdown.classList.add("showing");
    }
})
</code>```

Pen

答:
The event is firing if you just remove "touchstart" from the event listener, create a function containing the actual body of the event and create two event listener, one for click and one for touchstart. I don't think you can bind multiple events to one listener natively.

You set a lot of listener so you can use a function to bind one function for multiple events like this one : Binding multiple events to a listener.

Also, there is a typo when you start declaring the event listener :

```<code>inlineWorkLink.addEventListener("click touchstart", function(){});
</code>```

Body:
I have a website that I'm trying to make functional on mobile as well.  However, when I combine click and touchstart events for PC and tablets respectively, neither works(Clicking on the element the events are attached to aren't firing).  Can anyone explain how I should go about fixing this?  Here's an example of one element not working, the pen has the entire project.

HTML

MENU

Home

About Me

My Work

Contact Me

JS

let menu = document.getElementById("menu");
let dropdown = document.getElementsByClassName("dropdown")[0];
menu.addEventListener("click touchstart", function(){
    if(dropdown.classList.contains("showing")){
        dropdown.classList.remove("showing");
        dropdown.classList.add("hidden");
    }
    else{
        dropdown.classList.remove("hidden");
        dropdown.classList.add("showing");
    }
})

Pen

Body:
The event is firing if you just remove "touchstart" from the event listener, create a function containing the actual body of the event and create two event listener, one for click and one for touchstart. I don't think you can bind multiple events to one listener natively.

You set a lot of listener so you can use a function to bind one function for multiple events like this one : Binding multiple events to a listener.

Also, there is a typo when you start declaring the event listener :

inlineWorkLink.addEventListener("click touchstart", function(){});


问:
How to extract string after some character
I need to extract a known portion from a given string.

```<code>Ex:

test_str="http://localhost:8080/course-single.html"
</code>```

I need to extract "course-single" from above string. What is the most easiest way to do that?

答:
Chain a couple of str.split calls:

```<code>test = "http://localhost:8080/course-single.html"

test.rsplit('/', 1)[-1].split('.')[0]
# 'course-single'
</code>```

Details

First, get everything after the last /:

```<code>temp = test.rsplit('/', 1)[-1]
temp
# 'course-single.html'
</code>```

Next, get everything before the .html portion:

```<code>temp = temp.split('.')
temp
# ['course-single', 'html']

temp[0]
# 'course-single'
</code>```

Body:
I need to extract a known portion from a given string.

Ex:

test_str="http://localhost:8080/course-single.html"

I need to extract "course-single" from above string. What is the most easiest way to do that?

Body:
Chain a couple of str.split calls:

test = "http://localhost:8080/course-single.html"

test.rsplit('/', 1)[-1].split('.')[0]
# 'course-single'

Details

First, get everything after the last /:

temp = test.rsplit('/', 1)[-1]
temp
# 'course-single.html'

Next, get everything before the .html portion:

temp = temp.split('.')
temp
# ['course-single', 'html']

temp[0]
# 'course-single'


问:
fedex serviceavailabilityrequest is failing
I am trying to integrate the fedex serviceavailabilty to return estimated delivery times based on the service type used.

I am using xml via http post using curl, but it is giving me an error.

```<code><SOAP-ENV:Fault xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <faultcode>SOAP-ENV:Server</faultcode>
    <faultstring xml:lang="en">Fault</faultstring>
    <detail>
       <cause>Transient</cause>
       <code>unknownCode</code>
       <desc>java.lang.NullPointerException</desc>
</detail>
</SOAP-ENV:Fault
</code>```

My code is as follows:

```<code>$request = "<?xml version=\"1.0\"?>
    <ns:ServiceAvailabilityRequest xmlns:ns=\"http://fedex.com/ws/vacs/v4\">
        <ns:WebAuthenticationDetail>
            <ns:UserCredential>
                <ns:Key>{$this->apikey}</ns:Key>
                <ns:Password>{$this->password}</ns:Password>
            </ns:UserCredential>
        </ns:WebAuthenticationDetail>
        <ns:ClientDetail>
            <ns:AccountNumber>{$this->account}</ns:AccountNumber>
            <ns:MeterNumber>{$this->meter}</ns:MeterNumber>
        </ns:ClientDetail>
        <ns:TransactionDetail>
            <ns:CustomerTransactionId>ServiceAvailabilityRequest</ns:CustomerTransactionId>
        </ns:TransactionDetail>
        <ns:Version>
            <ns:ServiceId>trck</ns:ServiceId>
            <ns:Major>4</ns:Major>
            <ns:Intermediate>0</ns:Intermediate>
            <ns:Minor>0</ns:Minor>
        </ns:Version>
        <ns:Origin>
            <ns:PostalCode>07075</ns:PostalCode>
            <ns:CountryCode>US</ns:CountryCode>
        </ns:Origin>
        <ns:Destination>
            <ns:PostalCode>11216</ns:PostalCode>
            <ns:CountryCode>US</ns:CountryCode>
        </ns:Destination>
        <ns:ShipDate>2017-07-08</ns:ShipDate>
        <ns:CarrierCode>FDXE</ns:CarrierCode>

    </ns:ServiceAvailabilityRequest>";

$ch = curl_init('http://gateway.fedex.com:443/xml');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
</code>```

Any help is appreciated.

Thank you

Rick

答:
It looks like the error you are receiving is transient which means it may be an issue on the FedEx side and will probably resolve itself.

Your request XML looks OK to me.  The only difference I could see was the packaging tag.

Here is a working XML request I just took via RocketShipIt (I am the author):

```<code><ServiceAvailabilityRequest>
  <WebAuthenticationDetail>
    <UserCredential>
      <Key>...</Key>
      <Password>...</Password>
    </UserCredential>
  </WebAuthenticationDetail>
  <ClientDetail>
    <AccountNumber>...</AccountNumber>
    <MeterNumber>...</MeterNumber>
  </ClientDetail>
  <Version>
    <ServiceId>vacs</ServiceId>
    <Major>4</Major>
    <Intermediate>0</Intermediate>
    <Minor>0</Minor>
  </Version>
  <Origin>
    <PostalCode>94608</PostalCode>
    <CountryCode>US</CountryCode>
  </Origin>
  <Destination>
    <PostalCode>90210</PostalCode>
    <CountryCode>US</CountryCode>
  </Destination>
  <ShipDate>2017-07-08</ShipDate>
  <CarrierCode>FDXE</CarrierCode>
  <Packaging>YOUR_PACKAGING</Packaging>
</ServiceAvailabilityRequest>
</code>```

Response:

```<code><ServiceAvailabilityReply>
  <HighestSeverity>SUCCESS</HighestSeverity>
  <Notifications>
    <Severity>SUCCESS</Severity>
    <Source>vacs</Source>
    <Code>000</Code>
    <Message>SUCCESS</Message>
    <LocalizedMessage>SUCCESS</LocalizedMessage>
  </Notifications>
  <Version>
    <ServiceId>vacs</ServiceId>
    <Major>4</Major>
    <Intermediate>0</Intermediate>
    <Minor>0</Minor>
  </Version>
  <Options>
    <Service>FIRST_OVERNIGHT</Service>
    <DeliveryDate>2017-07-10</DeliveryDate>
    <DeliveryDay>MON</DeliveryDay>
    <DestinationStationId>SMOA </DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>PRIORITY_OVERNIGHT</Service>
    <DeliveryDate>2017-07-10</DeliveryDate>
    <DeliveryDay>MON</DeliveryDay>
    <DestinationStationId>SMOA </DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>STANDARD_OVERNIGHT</Service>
    <DeliveryDate>2017-07-10</DeliveryDate>
    <DeliveryDay>MON</DeliveryDay>
    <DestinationStationId>SMOA </DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>FEDEX_2_DAY_AM</Service>
    <DeliveryDate>2017-07-11</DeliveryDate>
    <DeliveryDay>TUE</DeliveryDay>
    <DestinationStationId>SMOA </DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>FEDEX_2_DAY</Service>
    <DeliveryDate>2017-07-11</DeliveryDate>
    <DeliveryDay>TUE</DeliveryDay>
    <DestinationStationId>SMOA </DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>FEDEX_EXPRESS_SAVER</Service>
    <DeliveryDate>2017-07-12</DeliveryDate>
    <DeliveryDay>WED</DeliveryDay>
    <DestinationStationId>SMOA </DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>FEDEX_FIRST_FREIGHT</Service>
    <DeliveryDate>2017-07-10</DeliveryDate>
    <DeliveryDay>MON</DeliveryDay>
    <DestinationStationId>LAXRT</DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>FEDEX_1_DAY_FREIGHT</Service>
    <DeliveryDate>2017-07-10</DeliveryDate>
    <DeliveryDay>MON</DeliveryDay>
    <DestinationStationId>LAXRT</DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>FEDEX_2_DAY_FREIGHT</Service>
    <DeliveryDate>2017-07-11</DeliveryDate>
    <DeliveryDay>TUE</DeliveryDay>
    <DestinationStationId>LAXRT</DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>FEDEX_3_DAY_FREIGHT</Service>
    <DeliveryDate>2017-07-12</DeliveryDate>
    <DeliveryDay>WED</DeliveryDay>
    <DestinationStationId>LAXRT</DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
</ServiceAvailabilityReply>
</code>```

Edit: Your ServiceId tag might be related to this error.

Body:
I am trying to integrate the fedex serviceavailabilty to return estimated delivery times based on the service type used.

I am using xml via http post using curl, but it is giving me an error.

<SOAP-ENV:Fault xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <faultcode>SOAP-ENV:Server</faultcode>
    <faultstring xml:lang="en">Fault</faultstring>
    <detail>
       <cause>Transient</cause>
       unknownCode
       <desc>java.lang.NullPointerException</desc>
</detail>
</SOAP-ENV:Fault

My code is as follows:

$request = "<?xml version=\"1.0\"?>
    <ns:ServiceAvailabilityRequest xmlns:ns=\"http://fedex.com/ws/vacs/v4\">
        <ns:WebAuthenticationDetail>
            <ns:UserCredential>
                <ns:Key>{$this->apikey}</ns:Key>
                <ns:Password>{$this->password}</ns:Password>
            </ns:UserCredential>
        </ns:WebAuthenticationDetail>
        <ns:ClientDetail>
            <ns:AccountNumber>{$this->account}</ns:AccountNumber>
            <ns:MeterNumber>{$this->meter}</ns:MeterNumber>
        </ns:ClientDetail>
        <ns:TransactionDetail>
            <ns:CustomerTransactionId>ServiceAvailabilityRequest</ns:CustomerTransactionId>
        </ns:TransactionDetail>
        <ns:Version>
            <ns:ServiceId>trck</ns:ServiceId>
            <ns:Major>4</ns:Major>
            <ns:Intermediate>0</ns:Intermediate>
            <ns:Minor>0</ns:Minor>
        </ns:Version>
        <ns:Origin>
            <ns:PostalCode>07075</ns:PostalCode>
            <ns:CountryCode>US</ns:CountryCode>
        </ns:Origin>
        <ns:Destination>
            <ns:PostalCode>11216</ns:PostalCode>
            <ns:CountryCode>US</ns:CountryCode>
        </ns:Destination>
        <ns:ShipDate>2017-07-08</ns:ShipDate>
        <ns:CarrierCode>FDXE</ns:CarrierCode>

    </ns:ServiceAvailabilityRequest>";

$ch = curl_init('http://gateway.fedex.com:443/xml');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);

Any help is appreciated.

Thank you

Rick

Body:
It looks like the error you are receiving is transient which means it may be an issue on the FedEx side and will probably resolve itself.

Your request XML looks OK to me.  The only difference I could see was the packaging tag.

Here is a working XML request I just took via RocketShipIt (I am the author):

<ServiceAvailabilityRequest>
  <WebAuthenticationDetail>
    <UserCredential>
      <Key>...</Key>
      <Password>...</Password>
    </UserCredential>
  </WebAuthenticationDetail>
  <ClientDetail>
    <AccountNumber>...</AccountNumber>
    <MeterNumber>...</MeterNumber>
  </ClientDetail>
  <Version>
    <ServiceId>vacs</ServiceId>
    <Major>4</Major>
    <Intermediate>0</Intermediate>
    <Minor>0</Minor>
  </Version>
  <Origin>
    <PostalCode>94608</PostalCode>
    <CountryCode>US</CountryCode>
  </Origin>
  <Destination>
    <PostalCode>90210</PostalCode>
    <CountryCode>US</CountryCode>
  </Destination>
  <ShipDate>2017-07-08</ShipDate>
  <CarrierCode>FDXE</CarrierCode>
  <Packaging>YOUR_PACKAGING</Packaging>
</ServiceAvailabilityRequest>

Response:

<ServiceAvailabilityReply>
  <HighestSeverity>SUCCESS</HighestSeverity>
  <Notifications>
    <Severity>SUCCESS</Severity>
    <Source>vacs</Source>
    <Code>000</Code>
    <Message>SUCCESS</Message>
    <LocalizedMessage>SUCCESS</LocalizedMessage>
  </Notifications>
  <Version>
    <ServiceId>vacs</ServiceId>
    <Major>4</Major>
    <Intermediate>0</Intermediate>
    <Minor>0</Minor>
  </Version>
  <Options>
    <Service>FIRST_OVERNIGHT</Service>
    <DeliveryDate>2017-07-10</DeliveryDate>
    <DeliveryDay>MON</DeliveryDay>
    <DestinationStationId>SMOA </DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>PRIORITY_OVERNIGHT</Service>
    <DeliveryDate>2017-07-10</DeliveryDate>
    <DeliveryDay>MON</DeliveryDay>
    <DestinationStationId>SMOA </DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>STANDARD_OVERNIGHT</Service>
    <DeliveryDate>2017-07-10</DeliveryDate>
    <DeliveryDay>MON</DeliveryDay>
    <DestinationStationId>SMOA </DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>FEDEX_2_DAY_AM</Service>
    <DeliveryDate>2017-07-11</DeliveryDate>
    <DeliveryDay>TUE</DeliveryDay>
    <DestinationStationId>SMOA </DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>FEDEX_2_DAY</Service>
    <DeliveryDate>2017-07-11</DeliveryDate>
    <DeliveryDay>TUE</DeliveryDay>
    <DestinationStationId>SMOA </DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>FEDEX_EXPRESS_SAVER</Service>
    <DeliveryDate>2017-07-12</DeliveryDate>
    <DeliveryDay>WED</DeliveryDay>
    <DestinationStationId>SMOA </DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>FEDEX_FIRST_FREIGHT</Service>
    <DeliveryDate>2017-07-10</DeliveryDate>
    <DeliveryDay>MON</DeliveryDay>
    <DestinationStationId>LAXRT</DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>FEDEX_1_DAY_FREIGHT</Service>
    <DeliveryDate>2017-07-10</DeliveryDate>
    <DeliveryDay>MON</DeliveryDay>
    <DestinationStationId>LAXRT</DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>FEDEX_2_DAY_FREIGHT</Service>
    <DeliveryDate>2017-07-11</DeliveryDate>
    <DeliveryDay>TUE</DeliveryDay>
    <DestinationStationId>LAXRT</DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
  <Options>
    <Service>FEDEX_3_DAY_FREIGHT</Service>
    <DeliveryDate>2017-07-12</DeliveryDate>
    <DeliveryDay>WED</DeliveryDay>
    <DestinationStationId>LAXRT</DestinationStationId>
    <DestinationAirportId>LAX</DestinationAirportId>
  </Options>
</ServiceAvailabilityReply>

Edit: Your ServiceId tag might be related to this error.


问:
C# express a type variable as a type
Let's say I'm working with generic function :

```<code>public interface IFoo
{
  Type Type;
  TValue Read<TValue>();
}

public class Foo : IFoo {}

var f = new Foo();
</code>```

I'd like to write :

```<code>var value = f.Read<f.Type>();
</code>```

but this gives error :

f is a variable but is used like a type

I could write conditionals :

```<code>object value;
if (f.Type == typeof(bool))
{
    value = f.Read<bool>();
}
if (f.Type == typeof(byte))
{
    value = f.Read<byte>();
}
...
</code>```

but this doesn't really work because it's verbose , may be incomplete if I don't know in advance all possible types , and value is an object instead of the type.

Is there a solution ?

答:
If the type is known at the time you create the instance of Foo (and doesn't change afterwards), then a generic interface would be the best solution:

```<code>public interface IFoo<T>
{
    T Read();
}

public class Foo<T> : IFoo<T>
{
    public T Read()
    {
        Type type = typeof(T);

        byte[] buffer = ...get byte array from wherever...;
        object boxedResult;

        using (MemoryStream ms = new MemoryStream(buffer))
        {
            using (BinaryReader br = new BinaryReader(ms))
            {
                if (type == typeof(int))
                    boxedResult = br.ReadInt32();
                else if (type == typeof(long))
                    boxedResult = br.ReadInt64();
                else if (type == typeof(bool))
                    boxedResult = br.ReadBoolean();
                else if (type == typeof(byte))
                    boxedResult = br.ReadByte();

                // ...
                // other types you want to process
                // ...

                else boxedResult = null;
            }
        }
        if (boxedResult != null)
            return (T)boxedResult;
        else
            throw new Exception(string.Format("{0} not supported", type.Name));
    }
}
</code>```

You use the class like this:

```<code>var intFoo = new Foo<int>();
var boolFoo = new Foo<bool>();

int intVal = intFoo.Read();
bool boolVal = boolFoo.Read();
</code>```

Title: C# express a type variable as a type

Body:
Let's say I'm working with generic function :

public interface IFoo
{
  Type Type;
  TValue Read<TValue>();
}

public class Foo : IFoo {}

var f = new Foo();

I'd like to write :

var value = f.Read<f.Type>();

but this gives error :

f is a variable but is used like a type

I could write conditionals :

object value;
if (f.Type == typeof(bool))
{
    value = f.Read<bool>();
}
if (f.Type == typeof(byte))
{
    value = f.Read<byte>();
}
...

but this doesn't really work because it's verbose , may be incomplete if I don't know in advance all possible types , and value is an object instead of the type.

Is there a solution ?

Body:
If the type is known at the time you create the instance of Foo (and doesn't change afterwards), then a generic interface would be the best solution:

public interface IFoo<T>
{
    T Read();
}

public class Foo<T> : IFoo<T>
{
    public T Read()
    {
        Type type = typeof(T);

        byte[] buffer = ...get byte array from wherever...;
        object boxedResult;

        using (MemoryStream ms = new MemoryStream(buffer))
        {
            using (BinaryReader br = new BinaryReader(ms))
            {
                if (type == typeof(int))
                    boxedResult = br.ReadInt32();
                else if (type == typeof(long))
                    boxedResult = br.ReadInt64();
                else if (type == typeof(bool))
                    boxedResult = br.ReadBoolean();
                else if (type == typeof(byte))
                    boxedResult = br.ReadByte();

                // ...
                // other types you want to process
                // ...

                else boxedResult = null;
            }
        }
        if (boxedResult != null)
            return (T)boxedResult;
        else
            throw new Exception(string.Format("{0} not supported", type.Name));
    }
}

You use the class like this:

var intFoo = new Foo<int>();
var boolFoo = new Foo<bool>();

int intVal = intFoo.Read();
bool boolVal = boolFoo.Read();


答:
You can use this:

```<code>test="http://localhost:8080/course-single.html"
str = test[test.find('8080/') + 5: test.find('.html')]
print str
</code>```

Details:

test.find('8080/') - find place where 8080/ string is located ( + 5 because we only have interested in string comes next in line ).

test.find('.html') - find where .html located.

test[test.find('8080/') + 5: test.find('.html')] - get string between this 2 located strings.

Title: How to extract string after some character

Body:
You can use this:

test="http://localhost:8080/course-single.html"
str = test[test.find('8080/') + 5: test.find('.html')]
print str

Details:

test.find('8080/') - find place where 8080/ string is located ( + 5 because we only have interested in string comes next in line ).

test.find('.html') - find where .html located.

test[test.find('8080/') + 5: test.find('.html')] - get string between this 2 located strings.


问:
Strange behaviour of the push
Here is the simple script i cannot understand:

```<code>function test() {
  var o = {"groupName":"A"};
  var a = [];
  var b = [{"name":"1"}, {"name":"2"}];
  for (var i in b) {
    var name = b[i].name;
    o.itemName = name;
    a.push(o);
  }
  Logger.log (a);
}
</code>```

I expect result to be

```<code>[
  {
    "groupName": "A",
    "itemName": {
      "name": "1"
    }
  },
  {
    "groupName": "A",
    "itemName": {
      "name": "2"
    }
  }
]
</code>```

but it is not. It is

```<code>[
  {
    "groupName": "A",
    "itemName": {
      "name": "2"
    }
  },
  {
    "groupName": "A",
    "itemName": {
      "name": "2"
    }
  }
]
</code>```

I want result include the same groupName for both iterations, but have different itemName

See the script here:

https://script.google.com/d/1VexsBJWZ1SBnb_4vnN1JA7a9KJkYzJ-hOcXwXvD2wa_GTXvdgt9xVOZb/edit?usp=sharing

答:
In JavaScript, cloning objects is not as easy as it sounds. Object is a reference type not value type. Value types like numbers or strings will get copied, objects will be passed by reference, which means that your variable is just a pointer to the area in memory where the object is stored.

Assigning this variable to another variable will create a pointer to a pointer, and so on.

If you compare object variables  using '===' operator, it will return 'true' if both variables are pointing to the same object and 'false' if they represent different instances. Note that the result will be 'false' even if the objects have completely identical set of properties. What's being compared is reference.

In your example, push(o) won't copy the object - it will add pointer variables. The following code will return 'true', because you are storing two pointers to the object instead of two its copies.

```<code>Logger.log(a[0] === a[1]); //returns true
</code>```

The code below copies the object.

```<code>  var array=[];

  for(var j in b) {

  var name = b[j].name;
  var newObj = {};
  newObj.itemName = name;

  for(var prop in o){

  newObj[prop] = o[prop];

  }

  array.push(newObj);

  }

  Logger.log(array);
  Logger.log(array[0] === array[1]); //will return false
</code>```

Title: Strange behaviour of the push

Body:
Here is the simple script i cannot understand:

function test() {
  var o = {"groupName":"A"};
  var a = [];
  var b = [{"name":"1"}, {"name":"2"}];
  for (var i in b) {
    var name = b[i].name;
    o.itemName = name;
    a.push(o);
  }
  Logger.log (a);
}

I expect result to be

[
  {
    "groupName": "A",
    "itemName": {
      "name": "1"
    }
  },
  {
    "groupName": "A",
    "itemName": {
      "name": "2"
    }
  }
]

but it is not. It is

[
  {
    "groupName": "A",
    "itemName": {
      "name": "2"
    }
  },
  {
    "groupName": "A",
    "itemName": {
      "name": "2"
    }
  }
]

I want result include the same groupName for both iterations, but have different itemName

See the script here:

https://script.google.com/d/1VexsBJWZ1SBnb_4vnN1JA7a9KJkYzJ-hOcXwXvD2wa_GTXvdgt9xVOZb/edit?usp=sharing

Body:
In JavaScript, cloning objects is not as easy as it sounds. Object is a reference type not value type. Value types like numbers or strings will get copied, objects will be passed by reference, which means that your variable is just a pointer to the area in memory where the object is stored.

Assigning this variable to another variable will create a pointer to a pointer, and so on.

If you compare object variables  using '===' operator, it will return 'true' if both variables are pointing to the same object and 'false' if they represent different instances. Note that the result will be 'false' even if the objects have completely identical set of properties. What's being compared is reference.

In your example, push(o) won't copy the object - it will add pointer variables. The following code will return 'true', because you are storing two pointers to the object instead of two its copies.

Logger.log(a[0] === a[1]); //returns true

The code below copies the object.

  var array=[];

  for(var j in b) {

  var name = b[j].name;
  var newObj = {};
  newObj.itemName = name;

  for(var prop in o){

  newObj[prop] = o[prop];

  }

  array.push(newObj);

  }

  Logger.log(array);
  Logger.log(array[0] === array[1]); //will return false


问:
unable to display spring mvc validation errors
I am learning spring mvc and got stuck in displaying validation error messages under textfields in spring mvc.

Here is the controller. In updateUser() method i want to code validation errors.

```<code>@Controller
public class ReportsController {

@Autowired
private ReportsDAO reportsDAO;

@Autowired
MyValidationUtils myValidationUtils;

public void setReportsDAO(ReportsDAO reportsDAO) {
    this.reportsDAO = reportsDAO;
}

@RequestMapping(value="/reports",method=RequestMethod.GET)
public ModelAndView report(){
    List<User> userList=reportsDAO.showAll();
    ModelAndView modelAndView=new ModelAndView();
    modelAndView.setViewName("Reports");
    modelAndView.addObject("userList", userList);
    modelAndView.addObject("User", new User());
    return modelAndView;
}

@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
public ModelAndView reportUpdate(@PathVariable("id") String id){
    User user=reportsDAO.showByUCode(id);
    List<User> userList=reportsDAO.showAll();
    ModelAndView modelAndView=new ModelAndView();
    modelAndView.setViewName("Reports");
    modelAndView.addObject("userList", userList);
    modelAndView.addObject("User", user);
    if(user!=null){
        modelAndView.addObject("editUser", user);
    }
    return modelAndView;
}
@RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
public ModelAndView reportDelete(@PathVariable("id") String id){
    int result=reportsDAO.deleteByID(id);
    ModelAndView modelAndView=new ModelAndView();
    modelAndView.setViewName("redirect:/reports");
    return modelAndView;
}

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(myValidationUtils);
}

@RequestMapping(value="/reportUpdate",method=RequestMethod.POST)
public ModelAndView updateUser(@ModelAttribute @Validated User user,BindingResult results,RedirectAttributes redirectAttributes){

    ModelAndView modelAndView=new ModelAndView();
    if(results.hasErrors()){
        modelAndView.setViewName("Reports");
        modelAndView.addObject("User", user);
        results.rejectValue("name", "Name cannot be empty.");
        return modelAndView;
    }
    if(user!=null){
        int result=reportsDAO.updateByCode(user);
        if(result!=-1){
            modelAndView.setViewName("redirect:/reports");
        }else{
            modelAndView.setViewName("Reports");
            modelAndView.addObject("message", "Unable to edit, Please try again.");
        }
    }else{
        modelAndView.setViewName("Reports");
        modelAndView.addObject("message", "Unable to edit, Please try again.");
    }

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

here is the jsp form.

```<code><form:form action="/ORMWebApp/reportUpdate" modelAttribute="User"
            method="post" class="form-style-9">
            <ul>
                <li><%-- <form:label path="ucode">UCODE</form:label> --%> <form:input type="hidden" path="ucode"
                         class="field-style field-full align-none"
                        placeholder="UCode" value="${editUser.ucode}" /> <form:errors
                        path="ucode" class="field-style field-full align-none"></form:errors></li>

                <li>
                <spring:bind path="name">
                <form:label path="name">NAME</form:label> <form:input type="text" path="name"
                         class="field-style field-full align-none"
                        placeholder="Name" value="${editUser.name}" /> <form:errors
                        path="name" class="field-style field-full align-none"></form:errors></spring:bind></li>
                <li>
                <spring:bind path="email">
                <form:label path="email">EMAIL</form:label> <form:input type="email" path="email"
                         class="field-style field-full align-none"
                        placeholder="Email" value="${editUser.email}" /> <form:errors
                        path="email" class="field-style field-full align-none"></form:errors></spring:bind></li>
                <li>
                <spring:bind path="address">
                <form:label path="address">ADDRESS</form:label> <form:input type="text"
                        path="address"
                        class="field-style field-full align-none" placeholder="Address"
                        value="${editUser.address}" /> <form:errors path="address"
                        class="field-style field-full align-none"></form:errors></spring:bind></li>
                <li>
                <spring:bind path="password">
                <form:label path="password">PASSWORD</form:label> <form:input type="password"
                        path="password"
                        class="field-style field-full align-none" placeholder="Password"
                        value="${editUser.password}" /> <form:errors path="password"
                        class="field-style field-full align-none"></form:errors></spring:bind></li>
                <li>
                <spring:bind path="about">
                <form:label path="about">ABOUT</form:label> <form:textarea path="about"
                         class="field-style" placeholder="About" ></form:textarea>
                        <form:errors path="about"
                        class="field-style field-full align-none"></form:errors></spring:bind></li>
                <li><input type="submit" value="UPDATE" /></li>
            </ul>
        </form:form>
</code>```

Here is validation utils class.

```<code>public class MyValidationUtils implements Validator{

@Override
public boolean supports(Class<?> arg0) {

    return User.class.equals(arg0);
}

@Override
public void validate(Object target, Errors errors) {

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "NotNull.user.name", "Name cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "NotNull.user.address", "Address cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "NotNull.user.email", "email cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotNull.user.password", "password cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "about", "NotNull.user.about", "About cannot be blank.");

}
}
</code>```

is something i am missing in this to return validation errors in form. Thanks in advance.

答:
the problem was that i was not binding model attribute properly and not returning result either. This works for me.

```<code>@RequestMapping(value="/reportUpdate",method=RequestMethod.POST)
public ModelAndView updateUser(@ModelAttribute("User") @Validated User user,BindingResult results,RedirectAttributes redirectAttributes){

    ModelAndView modelAndView=new ModelAndView();
    //myValidationUtils.validate(user, results);
    if(results.hasErrors()){
        return new ModelAndView("Reports", "User", user);
    }
    if(user!=null){
        int result=reportsDAO.updateByCode(user);
        if(result!=-1){
            modelAndView.setViewName("redirect:/reports");
        }else{
            modelAndView.setViewName("Reports");
            modelAndView.addObject("message", "Unable to edit, Please try again.");
        }
    }else{
        modelAndView.setViewName("Reports");
        modelAndView.addObject("message", "Unable to edit, Please try again.");
    }

    return modelAndView;
}
</code>```

and have to write this in MyValidationUtils.

```<code>@Override
public void validate(Object target, Errors errors) {
    User user=(User)target;
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "NotNull.user.name", "Name cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "NotNull.user.address", "Address cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "NotNull.user.email", "email cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotNull.user.password", "password cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "about", "NotNull.user.about", "About cannot be blank.");

}
</code>```

and put a messages.properties in resource folder.

```<code>NotNull.user.name=Please fill name.
NotNull.user.address=Please fill address.
NotNull.user.email=Please fill email.
NotNull.user.password=Please fill password.
NotNull.user.about=Please fill about.
</code>```

and make a bean in dispatcher-servlet.

```<code><bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename">
        <value>messages</value>
    </property>
</bean>
<bean id="myValidationUtils" class="org.apedusoft.validator.MyValidationUtils"></bean>
</code>```

And it returns values in the messages.properties file. But due to some jsp form bug by my side. the validation error message is returning twice for name only but working fine for email and etc.

Body:
I am learning spring mvc and got stuck in displaying validation error messages under textfields in spring mvc.

Here is the controller. In updateUser() method i want to code validation errors.

@Controller
public class ReportsController {

@Autowired
private ReportsDAO reportsDAO;

@Autowired
MyValidationUtils myValidationUtils;

public void setReportsDAO(ReportsDAO reportsDAO) {
    this.reportsDAO = reportsDAO;
}

@RequestMapping(value="/reports",method=RequestMethod.GET)
public ModelAndView report(){
    List<User> userList=reportsDAO.showAll();
    ModelAndView modelAndView=new ModelAndView();
    modelAndView.setViewName("Reports");
    modelAndView.addObject("userList", userList);
    modelAndView.addObject("User", new User());
    return modelAndView;
}

@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
public ModelAndView reportUpdate(@PathVariable("id") String id){
    User user=reportsDAO.showByUCode(id);
    List<User> userList=reportsDAO.showAll();
    ModelAndView modelAndView=new ModelAndView();
    modelAndView.setViewName("Reports");
    modelAndView.addObject("userList", userList);
    modelAndView.addObject("User", user);
    if(user!=null){
        modelAndView.addObject("editUser", user);
    }
    return modelAndView;
}
@RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
public ModelAndView reportDelete(@PathVariable("id") String id){
    int result=reportsDAO.deleteByID(id);
    ModelAndView modelAndView=new ModelAndView();
    modelAndView.setViewName("redirect:/reports");
    return modelAndView;
}

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(myValidationUtils);
}

@RequestMapping(value="/reportUpdate",method=RequestMethod.POST)
public ModelAndView updateUser(@ModelAttribute @Validated User user,BindingResult results,RedirectAttributes redirectAttributes){

    ModelAndView modelAndView=new ModelAndView();
    if(results.hasErrors()){
        modelAndView.setViewName("Reports");
        modelAndView.addObject("User", user);
        results.rejectValue("name", "Name cannot be empty.");
        return modelAndView;
    }
    if(user!=null){
        int result=reportsDAO.updateByCode(user);
        if(result!=-1){
            modelAndView.setViewName("redirect:/reports");
        }else{
            modelAndView.setViewName("Reports");
            modelAndView.addObject("message", "Unable to edit, Please try again.");
        }
    }else{
        modelAndView.setViewName("Reports");
        modelAndView.addObject("message", "Unable to edit, Please try again.");
    }

    return modelAndView;
}
}

here is the jsp form.

<form:form action="/ORMWebApp/reportUpdate" modelAttribute="User"
            method="post" class="form-style-9">

<%-- <form:label path="ucode">UCODE</form:label> --%> <form:input type="hidden" path="ucode"
                         class="field-style field-full align-none"
                        placeholder="UCode" value="${editUser.ucode}" /> <form:errors
                        path="ucode" class="field-style field-full align-none"></form:errors>

                <spring:bind path="name">
                <form:label path="name">NAME</form:label> <form:input type="text" path="name"
                         class="field-style field-full align-none"
                        placeholder="Name" value="${editUser.name}" /> <form:errors
                        path="name" class="field-style field-full align-none"></form:errors></spring:bind>

                <spring:bind path="email">
                <form:label path="email">EMAIL</form:label> <form:input type="email" path="email"
                         class="field-style field-full align-none"
                        placeholder="Email" value="${editUser.email}" /> <form:errors
                        path="email" class="field-style field-full align-none"></form:errors></spring:bind>

                <spring:bind path="address">
                <form:label path="address">ADDRESS</form:label> <form:input type="text"
                        path="address"
                        class="field-style field-full align-none" placeholder="Address"
                        value="${editUser.address}" /> <form:errors path="address"
                        class="field-style field-full align-none"></form:errors></spring:bind>

                <spring:bind path="password">
                <form:label path="password">PASSWORD</form:label> <form:input type="password"
                        path="password"
                        class="field-style field-full align-none" placeholder="Password"
                        value="${editUser.password}" /> <form:errors path="password"
                        class="field-style field-full align-none"></form:errors></spring:bind>

                <spring:bind path="about">
                <form:label path="about">ABOUT</form:label> <form:textarea path="about"
                         class="field-style" placeholder="About" ></form:textarea>
                        <form:errors path="about"
                        class="field-style field-full align-none"></form:errors></spring:bind>

<input type="submit" value="UPDATE" />

        </form:form>

Here is validation utils class.

public class MyValidationUtils implements Validator{

@Override
public boolean supports(Class<?> arg0) {

    return User.class.equals(arg0);
}

@Override
public void validate(Object target, Errors errors) {

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "NotNull.user.name", "Name cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "NotNull.user.address", "Address cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "NotNull.user.email", "email cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotNull.user.password", "password cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "about", "NotNull.user.about", "About cannot be blank.");

}
}

is something i am missing in this to return validation errors in form. Thanks in advance.

Body:
the problem was that i was not binding model attribute properly and not returning result either. This works for me.

@RequestMapping(value="/reportUpdate",method=RequestMethod.POST)
public ModelAndView updateUser(@ModelAttribute("User") @Validated User user,BindingResult results,RedirectAttributes redirectAttributes){

    ModelAndView modelAndView=new ModelAndView();
    //myValidationUtils.validate(user, results);
    if(results.hasErrors()){
        return new ModelAndView("Reports", "User", user);
    }
    if(user!=null){
        int result=reportsDAO.updateByCode(user);
        if(result!=-1){
            modelAndView.setViewName("redirect:/reports");
        }else{
            modelAndView.setViewName("Reports");
            modelAndView.addObject("message", "Unable to edit, Please try again.");
        }
    }else{
        modelAndView.setViewName("Reports");
        modelAndView.addObject("message", "Unable to edit, Please try again.");
    }

    return modelAndView;
}

and have to write this in MyValidationUtils.

@Override
public void validate(Object target, Errors errors) {
    User user=(User)target;
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "NotNull.user.name", "Name cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "NotNull.user.address", "Address cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "NotNull.user.email", "email cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotNull.user.password", "password cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "about", "NotNull.user.about", "About cannot be blank.");

}

and put a messages.properties in resource folder.

NotNull.user.name=Please fill name.
NotNull.user.address=Please fill address.
NotNull.user.email=Please fill email.
NotNull.user.password=Please fill password.
NotNull.user.about=Please fill about.

and make a bean in dispatcher-servlet.

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename">
        <value>messages</value>
    </property>
</bean>
<bean id="myValidationUtils" class="org.apedusoft.validator.MyValidationUtils"></bean>

And it returns values in the messages.properties file. But due to some jsp form bug by my side. the validation error message is returning twice for name only but working fine for email and etc.


问:
No connection could be made because the target machine actively refused it 127.0.0.1:10000
So I've been getting this error when I run my program, an F# web app, on my laptop, but not when I run it on my desktop. I know it has something to do with the firewall ports, and I've opened the port my web app uses, but for some reason I still get this error.

The web app is a simple Owin api with SPA front end, and it's meant to get data from my SQL Express database.

When it runs, my web app, is hosted on iis express and I've set it too port :1337. I've done a netstat -a to see all the ports, 1337 is set as listening, while :10000 isn't listed.

Any ideas?

答:
The IP address 127.0.0.1 is always a loopback port and is the same as "localhost". So you can't access that IP across a switch, a router, etc.

Find out the actual IP address of your desktop (where I presume your application is) and try to access it that way. For windows, you can do run "ipconfig" at the command prompt. For Linux you can run "ifconfig"


问:
How to order a list of paragraphs
A have a list:

§ 21 Item

§ 1 Item

§ 13 Item

§ 3 Item

§ 2 Item

I need to order it like this:

§ 1 Item

§ 2 Item

§ 3 Item

§ 13 Item

§ 21 Item

But after

```<code>newList = (from a in list orderby a.Name ascending select a).ToList();
</code>```

I get this:

§ 1 Item

§ 13 Item

§ 2 Item

§ 21 Item

§ 3 Item

How to fix it?

答: What you are looking for is a natural sort rather than the default lexical sort. A C# comparer that implements natural sort can be found at http://www.davekoelle.com/alphanum.html</p>

Title: How to order a list of paragraphs

Body:
A have a list:

§ 21 Item

§ 1 Item

§ 13 Item

§ 3 Item

§ 2 Item

I need to order it like this:

§ 1 Item

§ 2 Item

§ 3 Item

§ 13 Item

§ 21 Item

But after

newList = (from a in list orderby a.Name ascending select a).ToList();

I get this:

§ 1 Item

§ 13 Item

§ 2 Item

§ 21 Item

§ 3 Item

How to fix it?


问:
More than 2 simultaneous connections to Win Server 2016
Currently, on google compute engines, we can only have 2 simulatenous logins to a WinServer 2016 image. Is there any way we can have more? We'd be happy to buy more licences (through Google or Microsoft or some third party.)</p>

答:
The 2 simultaneous connections to the Windows Server is not a Google Cloud restriction, but a Windows Server restriction.

To use more than 2, you will need to install RD Session host role service. This includes purchasing a RD license.


问:
How to extract a list of URLs from specific domain?
I'm using Firefox 53, and have Scrapbook X and want to save a lot of pages using the Save Multiple URLs feature, but before I do that, I want to extract a specific list of URLs without having to do so manually.

The site I'm looking at extracting data from is www.address-data.co.uk - namely this page.

What I want to do is extract only the URLs and subpages within that page but not the privacy policy or contact us page and all the sub-pages with the EH postcodes.

Is there a way to do this online, or any tool for Mac OS X that can find all related URLs before I copy them into Scrapbook's Save Multiple URLs (where I save them in a subfolder of Scrapbook)?

答:
I assume that EH45 is typical of those you want to extract from the page you mentioned. Like its siblings it's of the form https://address-data.co.uk/postcode-district-EH<postcode number>.

This means that you can make a complete list of the urls if you have a list of the numbers, or of the postcodes.

My main difficulty in answering is that I don't know what tools (especially programming tools) you might have at your disposal. I will assume only that you have, or can obtain, access to an editor that can do macros or that can edit columns. On Windows I would use Emerald (ow known as Crimson).

Then copy the contents of the table in the EH page (not the table headings) and remove everything except the first column. Finally, prepend every item in the column with 'https://address-data.co.uk/postcode-district-'.

PS: This might also be a good question to put on SuperUser.