问:
Need help fixing javascript for creating individual click events on form page with multiple file upload inputs
I have a page with a Gravity Form containing multiple file upload fields.

When a user clicks the button (modified label) the div container holding the file input has the file name appended to it.

My problem is that based on the tutorial I used to restyle the fields and set up, the javascript only targets the first file input and the others won't work when they are clicked.

How do I fix my code so that the javascript is listening to all file inputs, not just the first?

(I was trying to attach the filename to an existing div in the container. If you know a better way I'm open)

Some screenshots

four file upload fields

When I click first field button, filename appears successfully. When I click remaining field buttons, no filename appears

The issue seems to be around using .querySelector() which only targets the first file input on the page.

I've tried that, also using getElementsByClassName, iterating through a loop using querySelectorAll. But can't quite figure it out

Using .querySelector()

HTML

```<code><li id="field_3_9" class="gfield gfield_upload w-100 field_sublabel_below field_description_below gfield_visibility_visible">
  <label class="gfield_label" for="input_3_9">upload file</label>
  <div class="ginput_container ginput_container_fileupload">
    <input type="hidden" name="MAX_FILE_SIZE" value="52428800">
    <input name="input_9" id="input_3_9" type="file" class="medium" aria-describedby="validation_message_3_9 live_validation_message_3_9 extensions_message_3_9" onchange="javascript:gformValidateFileSize( this, 52428800 );" tabindex="55">
    <span id="extensions_message_3_9" class="screen-reader-text"></span>
    <div class="validation_message" id="live_validation_message_3_9">pdf test.pdf</div>
  </div>
</li>
</code>```

Javascript

```<code>var inputLabel = document.querySelector('.gfield_label');
var inputWrapper = document.querySelector('.gfield_upload');
var input =  document.querySelector("input[type='file']");
var inputSuccess = document.querySelector('.validation_message');

input.addEventListener('change', () => {
  const name = input.value.split(/\\|\//).pop();
  const truncated = name.length > 20
    ? name.substr(name.length - 20)
    : name;

    inputSuccess.innerHTML = truncated;
});

</code>```

Tried with .querySelectorAll()

```<code>  var inputWrapper = document.querySelectorAll('.gfield_upload');

  Array.from(inputWrapper).forEach(input => {
    input.addEventListener('click', function(event) {
        var realInput =  document.querySelector("input[type='file']");
        var inputSuccess = document.querySelector('.validation_message');

        realInput.addEventListener('change', () => {
            const name = realInput.value.split(/\\|\//).pop();
            const truncated = name.length > 20
              ? name.substr(name.length - 20)
              : name;

            inputSuccess.innerHTML = truncated;
        });
    });
});
</code>```

My expectations are when I click the upload button for any of the file input fields, the file name will be appended to the input container and visible on the screen.

答: Your querySelectorAll solution is almost working, you are just querying from the wrong root element.

Body:
I have a page with a Gravity Form containing multiple file upload fields.

When a user clicks the button (modified label) the div container holding the file input has the file name appended to it.

My problem is that based on the tutorial I used to restyle the fields and set up, the javascript only targets the first file input and the others won't work when they are clicked.

How do I fix my code so that the javascript is listening to all file inputs, not just the first?

(I was trying to attach the filename to an existing div in the container. If you know a better way I'm open)

Some screenshots

four file upload fields

When I click first field button, filename appears successfully. When I click remaining field buttons, no filename appears

The issue seems to be around using .querySelector() which only targets the first file input on the page.

I've tried that, also using getElementsByClassName, iterating through a loop using querySelectorAll. But can't quite figure it out

Using .querySelector()

HTML

  upload file

    <input type="hidden" name="MAX_FILE_SIZE" value="52428800">
    <input name="input_9" id="input_3_9" type="file" class="medium" aria-describedby="validation_message_3_9 live_validation_message_3_9 extensions_message_3_9" onchange="javascript:gformValidateFileSize( this, 52428800 );" tabindex="55">

pdf test.pdf

Javascript

var inputLabel = document.querySelector('.gfield_label');
var inputWrapper = document.querySelector('.gfield_upload');
var input =  document.querySelector("input[type='file']");
var inputSuccess = document.querySelector('.validation_message');

input.addEventListener('change', () => {
  const name = input.value.split(/\\|\//).pop();
  const truncated = name.length > 20
    ? name.substr(name.length - 20)
    : name;

    inputSuccess.innerHTML = truncated;
});

Tried with .querySelectorAll()

  var inputWrapper = document.querySelectorAll('.gfield_upload');

  Array.from(inputWrapper).forEach(input => {
    input.addEventListener('click', function(event) {
        var realInput =  document.querySelector("input[type='file']");
        var inputSuccess = document.querySelector('.validation_message');

        realInput.addEventListener('change', () => {
            const name = realInput.value.split(/\\|\//).pop();
            const truncated = name.length > 20
              ? name.substr(name.length - 20)
              : name;

            inputSuccess.innerHTML = truncated;
        });
    });
});

My expectations are when I click the upload button for any of the file input fields, the file name will be appended to the input container and visible on the screen.


来源: stackexchange

问:
Single column (with spaces) name gets split into two
I am using codeigniter insert_batch($table, $data);
I have a column name as "Comment posted by the customer".

When I try to batch insert data into it. The insert query changes as:

```<code>INSERT INTO `table` (`id`, `Name`, `Status`,`Comment posted by the` `customer`, `isActive`) VALUES (),(),()...;
</code>```

As seen the column splits up into 2 parts -
1.Comment posted by the
2.customer

And this throws an error. How do I overcome this? I need to insert it considering it as a single column.

答:
Try to format the query like this

```<code>INSERT INTO table (id, Name, Status, `Comment posted by the customer`, isActive) VALUES (),(),()
</code>```

UPDATE

You can omit the column names and specify the values for all columns

```<code>INSERT INTO table VALUES (), (), ()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using codeigniter insert_batch($table, $data);
I have a column name as "Comment posted by the customer".

When I try to batch insert data into it. The insert query changes as:

INSERT INTO `table` (`id`, `Name`, `Status`,`Comment posted by the` `customer`, `isActive`) VALUES (),(),()...;

As seen the column splits up into 2 parts -
1.Comment posted by the
2.customer

And this throws an error. How do I overcome this? I need to insert it considering it as a single column.

Body:
Try to format the query like this

INSERT INTO table (id, Name, Status, `Comment posted by the customer`, isActive) VALUES (),(),()

UPDATE

You can omit the column names and specify the values for all columns

INSERT INTO table VALUES (), (), ()


问:
Update UI element from thread by arguments
I'm trying to use this code for updating a label from a separate thread but it's not working. Can someone help me with how to modify this function so that I can call it from within a separate thread?

```<code>Public Class Threader
  Private Sub message_UI_Update(email As String, message1 As String)
    If Me.InvokeRequired Then
      Me.Invoke(New MethodInvoker(AddressOf message_UI_Update), email, message1)
    Else
      Label5.Text = email
      Label6.Text = message1
    End If
  End Sub
End Class
</code>```

--Update--

After some research I was able to achieve this with this code. I hope I am using the correct approach.

```<code>Public Class Threader
  Public Delegate Sub mydelegate(str As String, message1 As String)

  Private Sub message_UI_Update(email As String, message1 As String)
    If Me.InvokeRequired Then
      Me.Invoke(New mydelegate(AddressOf message_UI_Update), email, message1)
    Else
      Label5.Text = email
      Label6.Text = message1
    End If
  End Sub
End Class
</code>```

答:
You can use Invoke (if you need it instantly) or BeginInvoke (on next paint event) like this.

```<code>Me.BeginInvoke(Sub()
                 Label5.Text = email
                 Label6.Text = message1
               End Sub)
</code>```

And you can put it in the thread/Sub where you do your work with labels, you don't need an additional sub for it.

Body:
I'm trying to use this code for updating a label from a separate thread but it's not working. Can someone help me with how to modify this function so that I can call it from within a separate thread?

Public Class Threader
  Private Sub message_UI_Update(email As String, message1 As String)
    If Me.InvokeRequired Then
      Me.Invoke(New MethodInvoker(AddressOf message_UI_Update), email, message1)
    Else
      Label5.Text = email
      Label6.Text = message1
    End If
  End Sub
End Class

--Update--

After some research I was able to achieve this with this code. I hope I am using the correct approach.

Public Class Threader
  Public Delegate Sub mydelegate(str As String, message1 As String)

  Private Sub message_UI_Update(email As String, message1 As String)
    If Me.InvokeRequired Then
      Me.Invoke(New mydelegate(AddressOf message_UI_Update), email, message1)
    Else
      Label5.Text = email
      Label6.Text = message1
    End If
  End Sub
End Class

Body:
You can use Invoke (if you need it instantly) or BeginInvoke (on next paint event) like this.

Me.BeginInvoke(Sub()
                 Label5.Text = email
                 Label6.Text = message1
               End Sub)

And you can put it in the thread/Sub where you do your work with labels, you don't need an additional sub for it.


问:
On-demand resources not downloading from testflight
I have enabled OnDemandResources and checked the flow in the simulator. It's working fine. When made a test flight release, I'm able to see the ODR field enabled and 1 asset file is available. But when installed, the resources are not getting downloaded.

I'm using Xcode 10.1 and changed build setting to legacy mode but it didn't work.

答:
I found the solution for the problem I was facing.

"An asset pack is eligible for purging when all of the associated tags are no longer retained by any request. The resources associated with a tag may remain on the device for some time before it is purged, including across app launches."

Ultimately, the cache will get automatically purged if there is a memory issue, so it is only a cosmetic issue where users will potentially see your app as being larger than they expected, and then at some point down the line, it will be magically smaller.

So I copied my resources into another directory locally.

Another idea is I zipped my images and added zip file as on-demand resources. So after ODR got installed I extracted and copied my zip files contents locally. (I did this because finding the path for images in asset file was difficult in my case)


问:
Can't apply background image in css (flask template)
I want to apply background image in internal css. I'm using flask template. this is my directory

```<code>src - templates - image - img.jpg
src- templates - upload.html
</code>```

I want to apply the background image at upload.html. but I got 404 error. can someone help me please?

my code:

```<code>background-image: url("/image/img.jpg");
</code>```

error message:

get /image/img.jpg HTTP/1.1 404

答:
I think you are giving wrong path and that's why you are getting 404 error.You can use following code.</p>

```<code>background-image: url{"image/img.jpg"};
</code>```

Body:
I want to apply background image in internal css. I'm using flask template. this is my directory

src - templates - image - img.jpg
src- templates - upload.html

I want to apply the background image at upload.html. but I got 404 error. can someone help me please?

my code:

background-image: url("/image/img.jpg");

error message:

get /image/img.jpg HTTP/1.1 404

Body:
I think you are giving wrong path and that's why you are getting 404 error.You can use following code.

background-image: url{"image/img.jpg"};


问:
Python : Joining separated numeric characters in text but leave alphabetic texts
I've some sample strings like :

```<code>sample_lt1 = 'CANCEL Bitcoin kev 1 96 35 2 0 5 7 5 6'
sample_lt2 = 'CANCEL Bitcoln key 1 6 3 5 20 5 7 56 Cash 2 9 00'
sample_lt3 = 'CANCEL Bitcein key 0 1 5 0 0 4 4 1 6 Cash '
</code>```

I'm trying to join the numbers separated by spaces in the string but leave the chunk of alphabetic characters. The desired output for those sample inputs would be :

```<code>sample_out1 = 'CANCEL Bitcoin kev 19635205756'
sample_out2 = 'CANCEL Bitcoln key 1635205756 Cash 2900'
sample_out3 = 'CANCEL Bitcein key 015004416 Cash ' # Removal of last space is ok.
</code>```

Till now, I have done this :

```<code>def ReForm(lt):
    lts = lt.split()
    c = 0
    new = []
    temp = []
    while c<len(lts):
        if lts[c].isnumeric():
            temp.append(lts[c])
        else:
            if temp:
                s = ''.join(temp)
                new.append(s)
            new.append(lts[c])
        c += 1
    ret = ' '.join(new)
    return ret
</code>```

The output given by my code is :

```<code>CANCEL Bitcoin kev
CANCEL Bitcoln key 1635205756 Cash
CANCEL Bitcein key 015004416 Cash
</code>```

It fails to join the space separated numbers in the first and second case. What am I doing wrong?

答:
```<code>def ReForm(lt):
    lts = lt.split()
    c = 0
    new = []
    temp = []
    while c<len(lts):
        if lts[c].isnumeric():
            temp.append(lts[c])
        else:
            if temp:
                s = ''.join(temp)
                new.append(s)
                temp = []
            new.append(lts[c])
        c += 1
    if temp:
        s = ''.join(temp)
        new.append(s)
    ret = ' '.join(new)
    return ret
</code>```

Body:
I've some sample strings like :

sample_lt1 = 'CANCEL Bitcoin kev 1 96 35 2 0 5 7 5 6'
sample_lt2 = 'CANCEL Bitcoln key 1 6 3 5 20 5 7 56 Cash 2 9 00'
sample_lt3 = 'CANCEL Bitcein key 0 1 5 0 0 4 4 1 6 Cash '

I'm trying to join the numbers separated by spaces in the string but leave the chunk of alphabetic characters. The desired output for those sample inputs would be :

sample_out1 = 'CANCEL Bitcoin kev 19635205756'
sample_out2 = 'CANCEL Bitcoln key 1635205756 Cash 2900'
sample_out3 = 'CANCEL Bitcein key 015004416 Cash ' # Removal of last space is ok.

Till now, I have done this :

def ReForm(lt):
    lts = lt.split()
    c = 0
    new = []
    temp = []
    while c<len(lts):
        if lts[c].isnumeric():
            temp.append(lts[c])
        else:
            if temp:
                s = ''.join(temp)
                new.append(s)
            new.append(lts[c])
        c += 1
    ret = ' '.join(new)
    return ret

The output given by my code is :

CANCEL Bitcoin kev
CANCEL Bitcoln key 1635205756 Cash
CANCEL Bitcein key 015004416 Cash

It fails to join the space separated numbers in the first and second case. What am I doing wrong?


问:
auto_complete_for: prevent the first item from being auto-selected
The auto_complete_for dealio from script.aculo.us is great an all, but is there a way for me to selectively disable the fact that it always auto-selects the first item in the list?

The problem is that, if I want to type my own entry that is new, and novel, I don't want the first item in the list to be auto-selected. The reason is because when I TAB out of the field, it selects, and fills the text box with that first item.

I got around that, somewhat, by making the first item in the list the same as what I'm typing, but that's not perfect either, because the auto_complete list doesn't always update with every keystroke, depending on how fast I type. I've tried setting the list refresh rate to the lowest value (1 millisecond) but no go.

What I really want is an option in "auto_complete_for" that doesn't select that first item at all - the same way that Google Instant doesn't automatically select the first suggested search phrase - you have to arrow-down to select one.

Maybe I can do this via an HTML option that I'm missing?

答:
I'll add another alternative that works great with Rails 3:
http://github.com/crowdint/rails3-jquery-autocomplete</p>

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How to set TLS version on apache HttpClient
How can I change the supported TLS versions on my HttpClient?

I'm doing:

```<code>SSLContext sslContext = SSLContext.getInstance("TLSv1.1");
sslContext.init(
    keymanagers.toArray(new KeyManager[keymanagers.size()]),
    null,
    null);

SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, new String[]{"TLSv1.1"}, null, null);
Scheme scheme = new Scheme("https", 443, socketFactory);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(scheme);
BasicClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);
httpClient = new DefaultHttpClient(cm);
</code>```

But when I check the created socket, it still says the supported protocols are TLSv1.0, TLSv1.1 and TLSv1.2.

In reality I just want it to stop using TLSv1.2, for this specific HttpClient.

答:
Since this only came up hidden in comments, difficult to find as a solution:

You can use java -Dhttps.protocols=TLSv1,TLSv1.1, but you need to use also useSystemProperties()

```<code>client = HttpClientBuilder.create().useSystemProperties();
</code>```

We use this setup in our system now as this enables us to set this only for some usage of the code.
In our case we still have some Java 7 running and one API end point disallowed TLSv1,
so we use java -Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2 to enable current TLS versions.
Thanks @jebeaudet for pointing in this direction.

Body:
How can I change the supported TLS versions on my HttpClient?

I'm doing:

SSLContext sslContext = SSLContext.getInstance("TLSv1.1");
sslContext.init(
    keymanagers.toArray(new KeyManager[keymanagers.size()]),
    null,
    null);

SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, new String[]{"TLSv1.1"}, null, null);
Scheme scheme = new Scheme("https", 443, socketFactory);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(scheme);
BasicClientConnectionManager cm = new BasicClientConnectionManager(schemeRegistry);
httpClient = new DefaultHttpClient(cm);

But when I check the created socket, it still says the supported protocols are TLSv1.0, TLSv1.1 and TLSv1.2.

In reality I just want it to stop using TLSv1.2, for this specific HttpClient.

Body:
Since this only came up hidden in comments, difficult to find as a solution:

You can use java -Dhttps.protocols=TLSv1,TLSv1.1, but you need to use also useSystemProperties()

client = HttpClientBuilder.create().useSystemProperties();

We use this setup in our system now as this enables us to set this only for some usage of the code.
In our case we still have some Java 7 running and one API end point disallowed TLSv1,
so we use java -Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2 to enable current TLS versions.
Thanks @jebeaudet for pointing in this direction.


问:
Call Activity method from Custom view
How to call an activity method from custom view?

```<code>public class CustomView extends LinearLayout {

    private Context mContext;

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attributes) {
        findViewById(R.id.textView).setOnClickListener(v -> ((MyActivity) mContext).onClick(v));
    }
}
</code>```

This works fine as I know that View is generated from MyActivity.

Is there any way to know which activity has created this CustomView? Something like getActivity().onClick(v)

答:
Do what all existing widgets do: accept a callback. So:

Step #1: Define some sort of callback or listener interface.

Step #2: Add set...() on the widget to accept an instance of that interface, holding onto it in a field

Step #3: Have the activity, fragment, or whatever call that set...() method

Step #4: Have the view call the callback (if one was supplied) when the event occurs

You can see this pattern implemented for things like setOnClickListener().

Title: Call Activity method from Custom view

Body:
How to call an activity method from custom view?

public class CustomView extends LinearLayout {

    private Context mContext;

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attributes) {
        findViewById(R.id.textView).setOnClickListener(v -> ((MyActivity) mContext).onClick(v));
    }
}

This works fine as I know that View is generated from MyActivity.

Is there any way to know which activity has created this CustomView? Something like getActivity().onClick(v)


问:
Is there a way to generate a type within a template class out of a template argument and a string
i want to improve my code by getting rid of some template arguments. I have an idea but struggling with the correct code. Its also possible that c++ does not have such an feature, which would be also fine.

The current code looks like this:

class ModelProperties{
public:
    string name;
};

class Model{
public:
    ModelProperties properties;
};

template <class TModel, class TModelProperties>
class ModelWrapper{
private:
    TModel m_model;
public:
ModelWrapper(TModel model){
    m_model = model;
}

TModelProperties getProperties(){
    return m_model.properties;
}
};
```

<p>I would like to have something like this:</p>

<pre class="lang-cpp prettyprint-override"><code>
template <class TModel>
class ModelWrapper{

private:
    TModel m_model;

public:
ModelWrapper(TModel model){
    m_model = model;
}

TModel + "Properties" getProperties(){
    return m_model.properties;
}

};
</code>```

答:
You might simply use auto/decltype(auto) or decltype:

```<code>template <class TModel>
class ModelWrapper{
private:
    TModel m_model;
public:
    ModelWrapper(TModel model) : m_model{model} {}

    auto getProperties() const { return m_model.properties; } // Return by copy (unless properties **is** a reference)
};
</code>```

or

```<code>decltype(auto) getProperties() const { return (m_model.properties); } // Extra parenthesis for reference.
</code>```

or

```<code>auto getProperties() const
-> decltype(m_model.properties)& // By reference
{ return m_model.properties; }
</code>```

Body:
i want to improve my code by getting rid of some template arguments. I have an idea but struggling with the correct code. Its also possible that c++ does not have such an feature, which would be also fine.

The current code looks like this:

class ModelProperties{
public:
    string name;
};

class Model{
public:
    ModelProperties properties;
};

template <class TModel, class TModelProperties>
class ModelWrapper{
private:
    TModel m_model;
public:
ModelWrapper(TModel model){
    m_model = model;
}

TModelProperties getProperties(){
    return m_model.properties;
}
};

I would like to have something like this:

template <class TModel>
class ModelWrapper{

private:
    TModel m_model;

public:
ModelWrapper(TModel model){
    m_model = model;
}

TModel + "Properties" getProperties(){
    return m_model.properties;
}

};

Body:
You might simply use auto/decltype(auto) or decltype:

template <class TModel>
class ModelWrapper{
private:
    TModel m_model;
public:
    ModelWrapper(TModel model) : m_model{model} {}

    auto getProperties() const { return m_model.properties; } // Return by copy (unless properties **is** a reference)
};

or

decltype(auto) getProperties() const { return (m_model.properties); } // Extra parenthesis for reference.

or

auto getProperties() const
-> decltype(m_model.properties)& // By reference
{ return m_model.properties; }


问:
Avoid clickjacking for Java web application when opened in same session
I am trying to handle clickjacking for a java web application.
I got a solution from Clickjacking Defense Cheat Sheet

I have added a filter in web.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee                                        http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>OWASP ClickjackFilter</display-name>
    <filter>
        <filter-name>ClickjackFilterDeny</filter-name>
        <filter-class>org.owasp.filters.ClickjackFilter</filter-class>
        <init-param>
            <param-name>mode</param-name>
            <param-value>DENY</param-value>
        </init-param>
    </filter>

    <filter>
        <filter-name>ClickjackFilterSameOrigin</filter-name>
        <filter-class>org.owasp.filters.ClickjackFilter</filter-class>
        <init-param>
            <param-name>mode</param-name>
            <param-value>SAMEORIGIN</param-value>
        </init-param>
    </filter>

    <!--  use the Deny version to prevent anyone, including yourself, from framing the page -->
    <filter-mapping>
        <filter-name>ClickjackFilterDeny</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>
</code>```

My filter class look like

```<code>package org.owasp.filters;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class ClickjackFilter implements Filter
{

    private String mode = "DENY";

    /**
     * Add X-FRAME-OPTIONS response header to tell IE8 (and any other browsers who
     * decide to implement) not to display this content in a frame. For details, please
     * refer to http://blogs.msdn.com/sdl/archive/2009/02/05/clickjacking-defense-in-ie8.aspx.
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse)response;
        res.addHeader("X-FRAME-OPTIONS", mode );
        chain.doFilter(request, response);
    }

    public void destroy() {
    }

    public void init(FilterConfig filterConfig) {
        String configMode = filterConfig.getInitParameter("mode");
        if ( configMode != null ) {
            mode = configMode;
        }
    }

}
</code>```

Now the problem I'm facing is that this solution only works if I open the web page in a new session every time.

The solution fails if I try to frame the application in the same session.

答:
There are three settings for X-Frame-Options:

SAMEORIGIN This setting will allow a page to be displayed in a frame on the same origin as the page itself

DENY This setting will prevent a page displaying in a frame or iframe

ALLOW-FROM uri This setting will allow a page to be displayed only on the specified origin

Have you tried with SAMEORIGIN instead of DENY for mod?

Read more X-Frame-Options Header Types

Body:
I am trying to handle clickjacking for a java web application.
I got a solution from Clickjacking Defense Cheat Sheet

I have added a filter in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee                                        http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>OWASP ClickjackFilter</display-name>
    <filter>
        <filter-name>ClickjackFilterDeny</filter-name>
        <filter-class>org.owasp.filters.ClickjackFilter</filter-class>
        <init-param>
            <param-name>mode</param-name>
            <param-value>DENY</param-value>
        </init-param>
    </filter>

    <filter>
        <filter-name>ClickjackFilterSameOrigin</filter-name>
        <filter-class>org.owasp.filters.ClickjackFilter</filter-class>
        <init-param>
            <param-name>mode</param-name>
            <param-value>SAMEORIGIN</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>ClickjackFilterDeny</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

My filter class look like

package org.owasp.filters;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class ClickjackFilter implements Filter
{

    private String mode = "DENY";

    /**
     * Add X-FRAME-OPTIONS response header to tell IE8 (and any other browsers who
     * decide to implement) not to display this content in a frame. For details, please
     * refer to http://blogs.msdn.com/sdl/archive/2009/02/05/clickjacking-defense-in-ie8.aspx.
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse)response;
        res.addHeader("X-FRAME-OPTIONS", mode );
        chain.doFilter(request, response);
    }

    public void destroy() {
    }

    public void init(FilterConfig filterConfig) {
        String configMode = filterConfig.getInitParameter("mode");
        if ( configMode != null ) {
            mode = configMode;
        }
    }

}

Now the problem I'm facing is that this solution only works if I open the web page in a new session every time.

The solution fails if I try to frame the application in the same session.


问:
F# reading custom configuration and representing it as ConfigurationSection with ConfigurationElements
I am rather new to F# but I have a question about creating and reading custom configuration file. I know how it would look in c# so for example I have a simple config file

```<code><?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <configSections>
    <section name="customSection" type="Tool.Lib.Config, Tool.Lib" />
  </configSections>

  <communicationSection>
    <responseTimeoutInMs value="900000" />
  </communicationSection>

</configuration>
</code>```

Basing on that in c# it is simple. I am creating model named Config with properties marked as ConfigurationProperty (witch relates to xml node name, in this case responseTimeoutInMs) something like:

```<code>[ConfigurationProperty("responseTimeoutInMs")]
public ResponseTimeoutConfigElement ResponseTimeoutInMs
{
   get => (ResponseTimeoutConfigElement)base["responseTimeoutInMs"];
   set => base["responseTimeoutInMs"] = value;
}
</code>```

And of course value is set as ConfigurationElement so:

```<code>public class ResponseTimeoutConfigElement : ConfigurationElement
{
    [ConfigurationProperty("value", IsRequired = true, IsKey = true, DefaultValue = 0)]
    public int Value => (int)base["value"];
}
</code>```

It is a nice mechanism, I can pin converters into it and create types I need while reading configuration.

I know i can read default config using ConfigurationManager and exe configuration map, but this is basic config reading using key and value.

So my question is, is there something similar in F# to this in C#?

答:
You can do pretty much the same thing in F# as in C#:</p>

```<code>type ResponseTimeoutConfigElement() =
    inherit ConfigurationElement()

    [<ConfigurationProperty("value", IsRequired = true, IsKey = true, DefaultValue = 0)>]
    member this.Value = base.["value"] :?> int

type Config() =
    inherit ConfigurationSection()

    [<ConfigurationProperty("responseTimeoutInMs")>]
    member this.ResponseTimeInMs
        with get() = base.["responseTimeoutInMs"] :?> ResponseTimeoutConfigElement
        and set (value: ResponseTimeoutConfigElement) = base.["responseTimeoutInMs"] <- value
</code>```

Body:
I am rather new to F# but I have a question about creating and reading custom configuration file. I know how it would look in c# so for example I have a simple config file

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <configSections>

  </configSections>

  <communicationSection>
    <responseTimeoutInMs value="900000" />
  </communicationSection>

</configuration>

Basing on that in c# it is simple. I am creating model named Config with properties marked as ConfigurationProperty (witch relates to xml node name, in this case responseTimeoutInMs) something like:

[ConfigurationProperty("responseTimeoutInMs")]
public ResponseTimeoutConfigElement ResponseTimeoutInMs
{
   get => (ResponseTimeoutConfigElement)base["responseTimeoutInMs"];
   set => base["responseTimeoutInMs"] = value;
}

And of course value is set as ConfigurationElement so:

public class ResponseTimeoutConfigElement : ConfigurationElement
{
    [ConfigurationProperty("value", IsRequired = true, IsKey = true, DefaultValue = 0)]
    public int Value => (int)base["value"];
}

It is a nice mechanism, I can pin converters into it and create types I need while reading configuration.

I know i can read default config using ConfigurationManager and exe configuration map, but this is basic config reading using key and value.

So my question is, is there something similar in F# to this in C#?

Body:
You can do pretty much the same thing in F# as in C#:

type ResponseTimeoutConfigElement() =
    inherit ConfigurationElement()

    [<ConfigurationProperty("value", IsRequired = true, IsKey = true, DefaultValue = 0)>]
    member this.Value = base.["value"] :?> int

type Config() =
    inherit ConfigurationSection()

    [<ConfigurationProperty("responseTimeoutInMs")>]
    member this.ResponseTimeInMs
        with get() = base.["responseTimeoutInMs"] :?> ResponseTimeoutConfigElement
        and set (value: ResponseTimeoutConfigElement) = base.["responseTimeoutInMs"] <- value


问:
What URLs does the GKE extensible service proxy need to access
I'm running Istio in Google Kubenetes Engine. My application uses gRPC and has an Extensible Service Proxy container to link to the Google Enpoints Service.

Istio on GKE by default blocks all egress requests, bu that breaks the ESP container since it needs to request some data from outside the Istio mesh.

The logs from the ESP informed me it was trying to access IP 169.254.169.254 to get some metadata, so I opened up an egress channel from Istio to let that happen, and that's fine.

But the next thing the ESP attempts is to "fetch the service config ID from the rollouts service". Again this is blocked but this time the log error doesn't tell me the URL that it's trying to access, only the path. So I don't know what url to open up for egress.

This is the log entry:

WARNING:Retrying (Retry(total=2, connect=None, read=None, redirect=None,
  status=None)) after connection broken by 'ProtocolError('Connection
  aborted.', error(104, 'Connection reset by peer'))':
  /v1/services/rev79.endpoints.rev79-232812.cloud.goog/rollouts?filter=status=SUCCESS

so can anyone tell me what URLs the ESP needs to access to be able to work?

答:
I eventually stumbled across what I was looking for by googling parts of the path with some key words.
This looks like what the ESP is trying to access:
https://servicemanagement.googleapis.com/v1/services/{serviceName}/rollouts/{rolloutId}

Indeed opening up a route to that host gets the ESP up and running.


问:
How to validate that reCaptcha is checked
I'am creating a contact form that should send the mail if the Google reCaptcha v2 is checked.
Now it echoes my text even if the reCaptcha is checked.

Ive tried moving around the reCaptcha snippet and tried to do a if(isset but seems not to work.

```<code>  $email = $_POST['email'];
  $subject = $_POST['subject'];
  $message = $_POST['message'];

  $errorEmpty = false;
  $errorEmail = false;
  $errorCaptcha = false;

  if(empty($name) || empty($email) || empty($subject) || empty($message)){
    echo "<span style='color: red;font-weight: bold;'>Fyll i alla fält!</span>";
    $errorEmpty = true;
  }
  if(empty($_POST['g-recaptcha-response'])){
    echo "<span style='color: red;font-weight:bold;'>reCaptchan är inte ifylld!</span>";
    $errorCaptcha = true;
  }
   elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
     echo "<span style='color: red;font-weight: bold;'>Du måste skriva in en giltig e-mail adress!</span>";
     $errorEmail = true;
   }
    else{
      echo "<span style='color: green;font-weight: bold;'>Ditt meddelande skickades, vi återkommer inom max 3 arbetsdagar!</span>";
    }

    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
      $secret = '';
      $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
      $responseData = json_decode($verifyResponse);
      if($responseData->success){
  $to = $email;
  $subject = $subject;
  $text = "Name: $name\n From: $name\n Message: $message";
  $headers = "From: $email";
  if($errorEmpty == false && $errorEmail == false && $errorCaptcha == false){
  mail($to,$subject,$text,$headers);
  }
 }
} // ReCaptcha 2
</code>```

I want the mail() function to activate if the reCaptcha is checked, otherwise I want to echo a text to the user.

答:
i took a look at your code and found some errors. i am pasting the corrected code below, try it and let me know if it solves your problem.</p>

```<code><?php
$error = false;
$output = '';

$name    = $_POST["name"];
$email   = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

if (empty($name) || empty($email) || empty($subject) || empty($message)) {
  $output = "<span style='color: red;font-weight: bold;'>Fyll i alla fält!</span>";
  $error = true;
}
if (empty($_POST['g-recaptcha-response'])) {
  $output = "<span style='color: red;font-weight:bold;'>reCaptchan är inte ifylld!</span>";
  $error = true;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $output =  "<span style='color: red;font-weight: bold;'>Du måste skriva in en giltig e-mail adress!</span>";
  $error = true;
}
if ($error) {
  echo $output;
} else {
  $secretKey = "YOUR-SECRET-KEY";
  $captcha=$_POST['g-recaptcha-response'];
  $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' .
    urlencode($secretKey) .  '&response=' . urlencode($captcha);
  $response = file_get_contents($url);
  $responseKeys = json_decode($response, true);
  if ($responseKeys["success"]) {

    // mail then
    $to = $email;
    $email_subject = $subject;
    $email_body = "Name: $name\n From: $name\n Message: $message";
    //Send the email!
    $mail_check = mail($to, $email_subject, $email_body);
    if ($mail_check) {
      echo "Mail Sent!";
    } else {
      echo 'Mail Failed';
    }
  } else {
    echo 'Response not Success';
  }
}
?>
</code>```

Body:
I'am creating a contact form that should send the mail if the Google reCaptcha v2 is checked.
Now it echoes my text even if the reCaptcha is checked.

Ive tried moving around the reCaptcha snippet and tried to do a if(isset but seems not to work.

  $email = $_POST['email'];
  $subject = $_POST['subject'];
  $message = $_POST['message'];

  $errorEmpty = false;
  $errorEmail = false;
  $errorCaptcha = false;

  if(empty($name) || empty($email) || empty($subject) || empty($message)){
    echo "Fyll i alla fält!";
    $errorEmpty = true;
  }
  if(empty($_POST['g-recaptcha-response'])){
    echo "reCaptchan är inte ifylld!";
    $errorCaptcha = true;
  }
   elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
     echo "Du måste skriva in en giltig e-mail adress!";
     $errorEmail = true;
   }
    else{
      echo "Ditt meddelande skickades, vi återkommer inom max 3 arbetsdagar!";
    }

    if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
      $secret = '';
      $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
      $responseData = json_decode($verifyResponse);
      if($responseData->success){
  $to = $email;
  $subject = $subject;
  $text = "Name: $name\n From: $name\n Message: $message";
  $headers = "From: $email";
  if($errorEmpty == false && $errorEmail == false && $errorCaptcha == false){
  mail($to,$subject,$text,$headers);
  }
 }
} // ReCaptcha 2

I want the mail() function to activate if the reCaptcha is checked, otherwise I want to echo a text to the user.

Body:
i took a look at your code and found some errors. i am pasting the corrected code below, try it and let me know if it solves your problem.

<?php
$error = false;
$output = '';

$name    = $_POST["name"];
$email   = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];

if (empty($name) || empty($email) || empty($subject) || empty($message)) {
  $output = "<span style='color: red;font-weight: bold;'>Fyll i alla fält!</span>";
  $error = true;
}
if (empty($_POST['g-recaptcha-response'])) {
  $output = "<span style='color: red;font-weight:bold;'>reCaptchan är inte ifylld!</span>";
  $error = true;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $output =  "<span style='color: red;font-weight: bold;'>Du måste skriva in en giltig e-mail adress!</span>";
  $error = true;
}
if ($error) {
  echo $output;
} else {
  $secretKey = "YOUR-SECRET-KEY";
  $captcha=$_POST['g-recaptcha-response'];
  $url = 'https://www.google.com/recaptcha/api/siteverify?secret=' .
    urlencode($secretKey) .  '&response=' . urlencode($captcha);
  $response = file_get_contents($url);
  $responseKeys = json_decode($response, true);
  if ($responseKeys["success"]) {

    // mail then
    $to = $email;
    $email_subject = $subject;
    $email_body = "Name: $name\n From: $name\n Message: $message";
    //Send the email!
    $mail_check = mail($to, $email_subject, $email_body);
    if ($mail_check) {
      echo "Mail Sent!";
    } else {
      echo 'Mail Failed';
    }
  } else {
    echo 'Response not Success';
  }
}
?>


问:
update with decode is not working, why does null data input?
```<code>update x1 a set (a.cd)=
 (select distinct(decode(b.cd1,null,a.cd,b.cd1))
     from x2 b where b.nm(+)=a.nm
                and d.nm2(+)=a.nm2
</code>```

if b.cd1 data is null, a.cd input a.cd, but I operate this sql, null data enter in a.cd but when I operate only subquery, it work well so i don't know why this problem happen

can you help me?

答:
How about phrasing this like this?

```<code>update x1 a
    set a.cd = (select b.cd1
                from x2 b
                where b.nm = a.nm and b.nm2 = a.nm2
--------------------------------------^ assume you intend b here
               )
    where (select b.cd1
           from x2 b
           where b.nm = a.nm and b.nm2 = a.nm2
          ) is not null;
</code>```

That is, only update the rows where the value is not NULL.

Body:
update x1 a set (a.cd)=
 (select distinct(decode(b.cd1,null,a.cd,b.cd1))
     from x2 b where b.nm(+)=a.nm
                and d.nm2(+)=a.nm2

if b.cd1 data is null, a.cd input a.cd, but I operate this sql, null data enter in a.cd but when I operate only subquery, it work well so i don't know why this problem happen

can you help me?

Body:
How about phrasing this like this?

update x1 a
    set a.cd = (select b.cd1
                from x2 b
                where b.nm = a.nm and b.nm2 = a.nm2
--------------------------------------^ assume you intend b here
               )
    where (select b.cd1
           from x2 b
           where b.nm = a.nm and b.nm2 = a.nm2
          ) is not null;

That is, only update the rows where the value is not NULL.


问:
How to connect specific LatLng coordinates with polyline without it automatically connects to other points?
I'm creating a page that shows a world map with markers placed at LatLng coordinates and I'm trying to link them with Polylines. However, I don't want each of them to be linked together. For example, given a set {A,B,C,D,E,F},
 the links are A->B, B->C and C->D, also A->E.

When I try to do D->F, D->E magically appears even when I didn't specify it.

Initially I tried with the default path array, but it didn't work so I used another array called coordinates. The first few polylines were drawn from one specific point and it didn't have problems, but when I try to draw from another point to another, it works but polylines that I didn't specify also appeared.

```<code>$(document).ready(function() {
        // If the browser supports the Geolocation API
        if (typeof navigator.geolocation == "undefined") {
          $("#error").text("Your browser doesn't support the Geolocation API");
      return;
    }
    // Save the positions' history
    var path = [];

    navigator.geolocation.watchPosition(function(position) {
      // Save the current position
      path.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));

      // Create the map
      var myOptions = {
        zoom : 3,
        center : path[0],
        mapTypeId : google.maps.MapTypeId.ROADMAP
      }
      var map = new google.maps.Map(document.getElementById("map"), myOptions);

        path.push(new google.maps.LatLng(2.745537, 101.707316)); //mas
        path.push(new google.maps.LatLng(37.460353, 126.440674)); //kor
        path.push(new google.maps.LatLng(34.789594, 135.438084)); //jpn
        path.push(new google.maps.LatLng(-37.665357, 144.840642)); //aus
        path.push(new google.maps.LatLng(55.410343, 37.902312)); //rus
        path.push(new google.maps.LatLng(40.085148, 116.552407)); //chi
        path.push(new google.maps.LatLng(-6.127211, 106.653684)); //ind
        path.push(new google.maps.LatLng(1.364860, 103.991594)); //sin
        path.push(new google.maps.LatLng(40.760284, -73.772304)); //usa
        path.push(new google.maps.LatLng(53.358796, -2.272773)); //uk
        path.push(new google.maps.LatLng(40.498275, -3.567727)); //spa

      // Create the array that will be used to fit the view to the points range and
      // place the markers to the polyline's points
      var latLngBounds = new google.maps.LatLngBounds();
      for(var i = 0; i < path.length; i++) {
        latLngBounds.extend(path[i]);
        // Place the marker
        new google.maps.Marker({
          map: map,
          position: path[i],
          title: "Point " + (i + 1)
        });
      }
      var coordinates = [
        //mas
        {lat:2.745537, lng:101.707316}, {lat:37.460353,lng:126.440674}, //to kor
        {lat:2.745537, lng:101.707316}, {lat:34.789594,lng:135.438084}, //to jpn
        {lat:2.745537, lng:101.707316}, {lat:-37.665357,lng:144.840642}, //to aus
        {lat:2.745537, lng:101.707316}, {lat:40.085148,lng:116.552407}, //to chi
        {lat:2.745537, lng:101.707316}, {lat:-6.127211,lng:106.653684}, //to ind
        {lat:2.745537, lng:101.707316}, {lat:1.364860,lng:103.991594}, //to sin
        {lat:2.745537, lng:101.707316}, {lat:40.498275,lng:-3.567727}, //to spa

        //kor
        {lat:36.460353, lng:126.440674}, {lat:34.789594,lng:135.438084}, //to jpn
        {lat:36.460353, lng:126.440674}, {lat:55.410343,lng:37.902312}, //to rus
        {lat:36.460353, lng:126.440674}, {lat:40.085148,lng:116.552407}, //to chi

      ];
      // Creates the polyline object
      var polyline = new google.maps.Polyline({
        map: map,
        path: coordinates,
        strokeColor: '#0000FF',
        strokeOpacity: 0.7,
        strokeWeight: 1,
        geodesic: true
      });
      // Fit the bounds of the generated points
      //map.fitBounds(latLngBounds);
      polyline.setMap(map);
    },
    function(positionError){
      $("#error").append("Error: " + positionError.message + "<br />");
    },
    {
      enableHighAccuracy: true,
      timeout: 10 * 1000 // 10 seconds
    });
  });
</code>```

https://imgur.com/KyoSUmu

I expect the point South Korea to only connects to Moscow, China, Japan and Malaysia, not Spain.

答:
You are only making one polyline.  It connects all the points in the coordinates array.  So it goes from spain to korea.

```<code>{lat:2.745537, lng:101.707316}, {lat:40.498275,lng:-3.567727}, //to spa

//kor
{lat:36.460353, lng:126.440674}, {lat:34.789594,lng:135.438084}, //to jpn
</code>```

Simplest solution, make multiple separate polylines.  Make your existing array an array of arrays, with each inner array holding the coordinates for each separate polyline.

```<code>var coordinates = [
  [
    //mas
    {lat:2.745537, lng:101.707316}, {lat:37.460353,lng:126.440674}, //to kor
    {lat:2.745537, lng:101.707316}, {lat:34.789594,lng:135.438084}, //to jpn
    {lat:2.745537, lng:101.707316}, {lat:-37.665357,lng:144.840642}, //to aus
    {lat:2.745537, lng:101.707316}, {lat:40.085148,lng:116.552407}, //to chi
    {lat:2.745537, lng:101.707316}, {lat:-6.127211,lng:106.653684}, //to ind
    {lat:2.745537, lng:101.707316}, {lat:1.364860,lng:103.991594}, //to sin
    {lat:2.745537, lng:101.707316}, {lat:40.498275,lng:-3.567727}, //to spa
  ],[
    //kor
    {lat:36.460353, lng:126.440674}, {lat:34.789594,lng:135.438084}, //to jpn
    {lat:36.460353, lng:126.440674}, {lat:55.410343,lng:37.902312}, //to rus
    {lat:36.460353, lng:126.440674}, {lat:40.085148,lng:116.552407}, //to chi
  ]
];
</code>```

Then process through the top level array making separate polylines:

```<code>for (var i=0; i<coordinates.length; i++) {
  // Creates the polyline object
  var polyline = new google.maps.Polyline({
    map: map,
    path: coordinates[i],
    strokeColor: '#0000FF',
    strokeOpacity: 0.7,
    strokeWeight: 1,
    geodesic: true
  });
  // Fit the bounds of the generated points
  polyline.setMap(map);
}
</code>```

proof of concept fiddle

$(document).ready(function() {
  // If the browser supports the Geolocation API
  if (typeof navigator.geolocation == "undefined") {
    $("#error").text("Your browser doesn't support the Geolocation API");
    return;
  }
  // Save the positions' history
  var path = [];

  // Create the map
  var myOptions = {
    zoom: 2,
    center: {
      lat: 48.019573,
      lng: 66.923684
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map"), myOptions);

  path.push(new google.maps.LatLng(2.745537, 101.707316)); //mas
  path.push(new google.maps.LatLng(37.460353, 126.440674)); //kor
  path.push(new google.maps.LatLng(34.789594, 135.438084)); //jpn
  path.push(new google.maps.LatLng(-37.665357, 144.840642)); //aus
  path.push(new google.maps.LatLng(55.410343, 37.902312)); //rus
  path.push(new google.maps.LatLng(40.085148, 116.552407)); //chi
  path.push(new google.maps.LatLng(-6.127211, 106.653684)); //ind
  path.push(new google.maps.LatLng(1.364860, 103.991594)); //sin
  path.push(new google.maps.LatLng(40.760284, -73.772304)); //usa
  path.push(new google.maps.LatLng(53.358796, -2.272773)); //uk
  path.push(new google.maps.LatLng(40.498275, -3.567727)); //spa

  // Create the array that will be used to fit the view to the points range and
  // place the markers to the polyline's points
  var latLngBounds = new google.maps.LatLngBounds();
  for (var i = 0; i < path.length; i++) {
    latLngBounds.extend(path[i]);
    // Place the marker
    new google.maps.Marker({
      map: map,
      position: path[i],
      title: "Point " + (i + 1)
    });
  }
  var coordinates = [
    [
      //mas
      {lat:2.745537, lng:101.707316}, {lat:37.460353,lng:126.440674}, //to kor
      {lat:2.745537, lng:101.707316}, {lat:34.789594,lng:135.438084}, //to jpn
      {lat:2.745537, lng:101.707316}, {lat:-37.665357,lng:144.840642}, //to aus
      {lat:2.745537, lng:101.707316}, {lat:40.085148,lng:116.552407}, //to chi
      {lat:2.745537, lng:101.707316}, {lat:-6.127211,lng:106.653684}, //to ind
      {lat:2.745537, lng:101.707316}, {lat:1.364860,lng:103.991594}, //to sin
      {lat:2.745537, lng:101.707316}, {lat:40.498275,lng:-3.567727}, //to spa
    ],[
      //kor
      {lat:36.460353, lng:126.440674}, {lat:34.789594,lng:135.438084}, //to jpn
      {lat:36.460353, lng:126.440674}, {lat:55.410343,lng:37.902312}, //to rus
      {lat:36.460353, lng:126.440674}, {lat:40.085148,lng:116.552407}, //to chi
    ]
  ];
  for (var i = 0; i < coordinates.length; i++) {
    // Creates the polyline object
    var polyline = new google.maps.Polyline({
      map: map,
      path: coordinates[i],
      strokeColor: '#0000FF',
      strokeOpacity: 0.7,
      strokeWeight: 1,
      geodesic: true
    });
    // Fit the bounds of the generated points
    polyline.setMap(map);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}</code>```

```

Body:
I'm creating a page that shows a world map with markers placed at LatLng coordinates and I'm trying to link them with Polylines. However, I don't want each of them to be linked together. For example, given a set {A,B,C,D,E,F},
 the links are A->B, B->C and C->D, also A->E.

When I try to do D->F, D->E magically appears even when I didn't specify it.

Initially I tried with the default path array, but it didn't work so I used another array called coordinates. The first few polylines were drawn from one specific point and it didn't have problems, but when I try to draw from another point to another, it works but polylines that I didn't specify also appeared.

$(document).ready(function() {
        // If the browser supports the Geolocation API
        if (typeof navigator.geolocation == "undefined") {
          $("#error").text("Your browser doesn't support the Geolocation API");
      return;
    }
    // Save the positions' history
    var path = [];

    navigator.geolocation.watchPosition(function(position) {
      // Save the current position
      path.push(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));

      // Create the map
      var myOptions = {
        zoom : 3,
        center : path[0],
        mapTypeId : google.maps.MapTypeId.ROADMAP
      }
      var map = new google.maps.Map(document.getElementById("map"), myOptions);

        path.push(new google.maps.LatLng(2.745537, 101.707316)); //mas
        path.push(new google.maps.LatLng(37.460353, 126.440674)); //kor
        path.push(new google.maps.LatLng(34.789594, 135.438084)); //jpn
        path.push(new google.maps.LatLng(-37.665357, 144.840642)); //aus
        path.push(new google.maps.LatLng(55.410343, 37.902312)); //rus
        path.push(new google.maps.LatLng(40.085148, 116.552407)); //chi
        path.push(new google.maps.LatLng(-6.127211, 106.653684)); //ind
        path.push(new google.maps.LatLng(1.364860, 103.991594)); //sin
        path.push(new google.maps.LatLng(40.760284, -73.772304)); //usa
        path.push(new google.maps.LatLng(53.358796, -2.272773)); //uk
        path.push(new google.maps.LatLng(40.498275, -3.567727)); //spa

      // Create the array that will be used to fit the view to the points range and
      // place the markers to the polyline's points
      var latLngBounds = new google.maps.LatLngBounds();
      for(var i = 0; i < path.length; i++) {
        latLngBounds.extend(path[i]);
        // Place the marker
        new google.maps.Marker({
          map: map,
          position: path[i],
          title: "Point " + (i + 1)
        });
      }
      var coordinates = [
        //mas
        {lat:2.745537, lng:101.707316}, {lat:37.460353,lng:126.440674}, //to kor
        {lat:2.745537, lng:101.707316}, {lat:34.789594,lng:135.438084}, //to jpn
        {lat:2.745537, lng:101.707316}, {lat:-37.665357,lng:144.840642}, //to aus
        {lat:2.745537, lng:101.707316}, {lat:40.085148,lng:116.552407}, //to chi
        {lat:2.745537, lng:101.707316}, {lat:-6.127211,lng:106.653684}, //to ind
        {lat:2.745537, lng:101.707316}, {lat:1.364860,lng:103.991594}, //to sin
        {lat:2.745537, lng:101.707316}, {lat:40.498275,lng:-3.567727}, //to spa

        //kor
        {lat:36.460353, lng:126.440674}, {lat:34.789594,lng:135.438084}, //to jpn
        {lat:36.460353, lng:126.440674}, {lat:55.410343,lng:37.902312}, //to rus
        {lat:36.460353, lng:126.440674}, {lat:40.085148,lng:116.552407}, //to chi

      ];
      // Creates the polyline object
      var polyline = new google.maps.Polyline({
        map: map,
        path: coordinates,
        strokeColor: '#0000FF',
        strokeOpacity: 0.7,
        strokeWeight: 1,
        geodesic: true
      });
      // Fit the bounds of the generated points
      //map.fitBounds(latLngBounds);
      polyline.setMap(map);
    },
    function(positionError){
      $("#error").append("Error: " + positionError.message + "
");
    },
    {
      enableHighAccuracy: true,
      timeout: 10 * 1000 // 10 seconds
    });
  });

https://imgur.com/KyoSUmu

I expect the point South Korea to only connects to Moscow, China, Japan and Malaysia, not Spain.

Body:
You are only making one polyline.  It connects all the points in the coordinates array.  So it goes from spain to korea.

{lat:2.745537, lng:101.707316}, {lat:40.498275,lng:-3.567727}, //to spa

//kor
{lat:36.460353, lng:126.440674}, {lat:34.789594,lng:135.438084}, //to jpn

Simplest solution, make multiple separate polylines.  Make your existing array an array of arrays, with each inner array holding the coordinates for each separate polyline.

var coordinates = [
  [
    //mas
    {lat:2.745537, lng:101.707316}, {lat:37.460353,lng:126.440674}, //to kor
    {lat:2.745537, lng:101.707316}, {lat:34.789594,lng:135.438084}, //to jpn
    {lat:2.745537, lng:101.707316}, {lat:-37.665357,lng:144.840642}, //to aus
    {lat:2.745537, lng:101.707316}, {lat:40.085148,lng:116.552407}, //to chi
    {lat:2.745537, lng:101.707316}, {lat:-6.127211,lng:106.653684}, //to ind
    {lat:2.745537, lng:101.707316}, {lat:1.364860,lng:103.991594}, //to sin
    {lat:2.745537, lng:101.707316}, {lat:40.498275,lng:-3.567727}, //to spa
  ],[
    //kor
    {lat:36.460353, lng:126.440674}, {lat:34.789594,lng:135.438084}, //to jpn
    {lat:36.460353, lng:126.440674}, {lat:55.410343,lng:37.902312}, //to rus
    {lat:36.460353, lng:126.440674}, {lat:40.085148,lng:116.552407}, //to chi
  ]
];

Then process through the top level array making separate polylines:

for (var i=0; i<coordinates.length; i++) {
  // Creates the polyline object
  var polyline = new google.maps.Polyline({
    map: map,
    path: coordinates[i],
    strokeColor: '#0000FF',
    strokeOpacity: 0.7,
    strokeWeight: 1,
    geodesic: true
  });
  // Fit the bounds of the generated points
  polyline.setMap(map);
}

proof of concept fiddle

$(document).ready(function() {
  // If the browser supports the Geolocation API
  if (typeof navigator.geolocation == "undefined") {
    $("#error").text("Your browser doesn't support the Geolocation API");
    return;
  }
  // Save the positions' history
  var path = [];

  // Create the map
  var myOptions = {
    zoom: 2,
    center: {
      lat: 48.019573,
      lng: 66.923684
    },
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map"), myOptions);

  path.push(new google.maps.LatLng(2.745537, 101.707316)); //mas
  path.push(new google.maps.LatLng(37.460353, 126.440674)); //kor
  path.push(new google.maps.LatLng(34.789594, 135.438084)); //jpn
  path.push(new google.maps.LatLng(-37.665357, 144.840642)); //aus
  path.push(new google.maps.LatLng(55.410343, 37.902312)); //rus
  path.push(new google.maps.LatLng(40.085148, 116.552407)); //chi
  path.push(new google.maps.LatLng(-6.127211, 106.653684)); //ind
  path.push(new google.maps.LatLng(1.364860, 103.991594)); //sin
  path.push(new google.maps.LatLng(40.760284, -73.772304)); //usa
  path.push(new google.maps.LatLng(53.358796, -2.272773)); //uk
  path.push(new google.maps.LatLng(40.498275, -3.567727)); //spa

  // Create the array that will be used to fit the view to the points range and
  // place the markers to the polyline's points
  var latLngBounds = new google.maps.LatLngBounds();
  for (var i = 0; i < path.length; i++) {
    latLngBounds.extend(path[i]);
    // Place the marker
    new google.maps.Marker({
      map: map,
      position: path[i],
      title: "Point " + (i + 1)
    });
  }
  var coordinates = [
    [
      //mas
      {lat:2.745537, lng:101.707316}, {lat:37.460353,lng:126.440674}, //to kor
      {lat:2.745537, lng:101.707316}, {lat:34.789594,lng:135.438084}, //to jpn
      {lat:2.745537, lng:101.707316}, {lat:-37.665357,lng:144.840642}, //to aus
      {lat:2.745537, lng:101.707316}, {lat:40.085148,lng:116.552407}, //to chi
      {lat:2.745537, lng:101.707316}, {lat:-6.127211,lng:106.653684}, //to ind
      {lat:2.745537, lng:101.707316}, {lat:1.364860,lng:103.991594}, //to sin
      {lat:2.745537, lng:101.707316}, {lat:40.498275,lng:-3.567727}, //to spa
    ],[
      //kor
      {lat:36.460353, lng:126.440674}, {lat:34.789594,lng:135.438084}, //to jpn
      {lat:36.460353, lng:126.440674}, {lat:55.410343,lng:37.902312}, //to rus
      {lat:36.460353, lng:126.440674}, {lat:40.085148,lng:116.552407}, //to chi
    ]
  ];
  for (var i = 0; i < coordinates.length; i++) {
    // Creates the polyline object
    var polyline = new google.maps.Polyline({
      map: map,
      path: coordinates[i],
      strokeColor: '#0000FF',
      strokeOpacity: 0.7,
      strokeWeight: 1,
      geodesic: true
    });
    // Fit the bounds of the generated points
    polyline.setMap(map);
  }
});

html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="map"></div>
<div id="error"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>


问:
"Fastest" hash function implemented in Java, comparing part of file
I need to compare two different files of the instance "File" in Java and want to do this with a fast hash function.

Idea:
- Hashing the 20 first lines in File 1
- Hashing the 20 first lines in File 2
- Compare the two hashes and return true if those are equal.

I want to use the "fastest" hash function ever been implemented in Java. Which one would you choose?

答:
If you're comparing two files at the same time on the same system there's no need to hash both of them. Just compare the bytes in both files are equal as you read both. If you're looking to compare them at different times or they're in different places then MD5 would be both fast and adequate. There's not much reason to need a faster one unless you're dealing with really large files. Even my laptop can hash hundreds of megabytes per second.

You also need to hash the whole file if you want to verify they're identical. Otherwise you might as well just check the size and last modified time if you want a really quick check. You could also check the beginning and end of the file if they're just really large and you trust that the middle won't be changing. If you're not dealing with hundreds of megabytes though, you may as well check every byte of each file.


问:
NSTextField set disabled text color
I have a NSTextField which is enabled or disabled. I can set the textColor but this only has an effect on the color of the text while the text field is enabled.

Any ideas how to set the text color for the disabled state?

I already tried to subclass NSTextField and override the enable methods as suggested in Disable NSTextField without changing color of multi-colored text ... but that doesn't work for me. I guess because of the latest SDK supporting dark mode.

答:
Simple approach is to override resignFirstResponder:

```<code>override func resignFirstResponder() -> Bool {
    //change text color here...

    return super.resignFirstResponder()
}
</code>```

You can simply add your colour change code for whichever controls you like here...

As stated by Apple:
The default implementation returns true, resigning first responder status. You can override this method in your custom responders to update your object's state or perform other actions, such as removing the highlight from a selection. You can also return false, refusing to relinquish first responder status. If you override this method, you must call super (the superclass implementation) at some point in your code.

Title: NSTextField set disabled text color

Body:
Simple approach is to override resignFirstResponder:

override func resignFirstResponder() -> Bool {
    //change text color here...

    return super.resignFirstResponder()
}

You can simply add your colour change code for whichever controls you like here...

As stated by Apple:
The default implementation returns true, resigning first responder status. You can override this method in your custom responders to update your object's state or perform other actions, such as removing the highlight from a selection. You can also return false, refusing to relinquish first responder status. If you override this method, you must call super (the superclass implementation) at some point in your code.


问:
Including multiple non defined variables
I'm trying to make a simple Discord bot that will take input from users and output it as a new nickname for another user. It works, but the new nickname needs 3 words in it. Is there a way to make it work with any number of input variables?

It first only worked with 1 word, but now I'm trying to add several words with spaces between them. And that now works too, unless the new nickname consists of more or less than 3 words. I dont really know what I'm doing, and I'm rather surprised I even got this far

```<code>function navnCommand(arguments, message) {
if (message.content.startsWith(".navn")){
    let args = message.content.split(" ");
    let userMention = message.mentions.users.first();
    let userNick = args[2]+' '+args[3]+' '+args[4]
    if (userMention == null){
        message.channel.send("Ey, bruk .navn @person nyttnavn din jævel")
    } else {
        let userID = userMention.id
        message.guild.members.get(userID).setNickname(userNick);
</code>```

If the nickname lacks a variable, I get an "undefined" in the new nickname, and any more than 3 is then not included.

答:
You could use the array-functions slice and join for that.

function navnCommand(arguments, message) {
  let args = message.content.split(" ");
  let words = args.slice(2, 5); // remove the second argument to allow any number of words
  if (!words.length) {
    // Handle no words found!
  }
  let userNick = words.join(" ");
  return userNick;
}

console.log(navnCommand(null, { content: ".navn UNKNOWN Adam" }));
console.log(navnCommand(null, { content: ".navn UNKNOWN Adam Bob" }));
console.log(navnCommand(null, { content: ".navn UNKNOWN Adam Bob Charly" }));
console.log(navnCommand(null, { content: ".navn UNKNOWN Adam Bob Charly Donald" }));```

Body:
I'm trying to make a simple Discord bot that will take input from users and output it as a new nickname for another user. It works, but the new nickname needs 3 words in it. Is there a way to make it work with any number of input variables?

It first only worked with 1 word, but now I'm trying to add several words with spaces between them. And that now works too, unless the new nickname consists of more or less than 3 words. I dont really know what I'm doing, and I'm rather surprised I even got this far

function navnCommand(arguments, message) {
if (message.content.startsWith(".navn")){
    let args = message.content.split(" ");
    let userMention = message.mentions.users.first();
    let userNick = args[2]+' '+args[3]+' '+args[4]
    if (userMention == null){
        message.channel.send("Ey, bruk .navn @person nyttnavn din jævel")
    } else {
        let userID = userMention.id
        message.guild.members.get(userID).setNickname(userNick);

If the nickname lacks a variable, I get an "undefined" in the new nickname, and any more than 3 is then not included.


问:
async onload not working in this case
I have some code to asynchronously load an Ad on my site which looks like this:

```<code><div id="ad-div"></div>
<script>function onAdReady() {
    debug_log('Method onAdReady called');
    new Ad(document.getElementById("ad-div"))
}
</script>
<script src="http://content.xxxxx.com/ads/ads.min.js" async onload="onAdReady()"></script>
</code>```

The problem is that the onAdReady function is never beeing called. The reason for this might be that the html code which contains this snippet is beeing loaded via javascript in the first place like this:

```<code>// Initiate out_window_view
$.ajax({
    url: loadPagePath("main.html"),
    success: function (result) {
        debug_log("Going in main.html view");
        $("#content").html(result);
    },
    error: function (result) {
        debug_log("Error, failed to load out_window_main view");
    }
});
</code>```

This code is beeing executed in the $(document).ready(function () {] in case that might matter.
Can anyone expalain to me why this is not working and provide me with a workaround or alternative way for solving this issue?

答:
If you are able to add the script programmatically, it will be async by default (reference here), and you can listen to the onload or onreadystatechange event (as you can read here, IE11 doesn't support onreadystatechange). Here is an example:

```<code>var setup = function(){
  console.log('the script has been parsed');
};

var script = document.createElement("script");
script.src = "http://content.xxxxx.com/ads/ads.min.js";

document.getElementsByTagName("head")[0].appendChild(script);

// standard browser
script.onreadystatechange = function (){
  if (this.readyState == 'complete'){
     setup();
  }
}
// IE
script.onload = setup;
</code>```

Title: async onload not working in this case

Body:
I have some code to asynchronously load an Ad on my site which looks like this:

The problem is that the onAdReady function is never beeing called. The reason for this might be that the html code which contains this snippet is beeing loaded via javascript in the first place like this:

// Initiate out_window_view
$.ajax({
    url: loadPagePath("main.html"),
    success: function (result) {
        debug_log("Going in main.html view");
        $("#content").html(result);
    },
    error: function (result) {
        debug_log("Error, failed to load out_window_main view");
    }
});

This code is beeing executed in the $(document).ready(function () {] in case that might matter.
Can anyone expalain to me why this is not working and provide me with a workaround or alternative way for solving this issue?

Body:
If you are able to add the script programmatically, it will be async by default (reference here), and you can listen to the onload or onreadystatechange event (as you can read here, IE11 doesn't support onreadystatechange). Here is an example:

var setup = function(){
  console.log('the script has been parsed');
};

var script = document.createElement("script");
script.src = "http://content.xxxxx.com/ads/ads.min.js";

document.getElementsByTagName("head")[0].appendChild(script);

// standard browser
script.onreadystatechange = function (){
  if (this.readyState == 'complete'){
     setup();
  }
}
// IE
script.onload = setup;


问:
how to assign value in List<T> type Xml class
I want to assign value in List. i am not able to understand how can i assign value in List under Stops node. Can you please tell me how can i do this.Below is the code with class file

Created class from XML

```<code>[XmlRoot(ElementName="Customer")]
    public class Customer {
        [XmlAttribute(AttributeName="CustomerID")]
        public string CustomerID { get; set; }
        [XmlAttribute(AttributeName="CustomerCode")]
        public string CustomerCode { get; set; }
        [XmlAttribute(AttributeName="Name")]
        public string Name { get; set; }
        [XmlAttribute(AttributeName="Address")]
        public string Address { get; set; }
    }

    [XmlRoot(ElementName="OrderStopPiece")]
    public class OrderStopPiece {
        [XmlAttribute(AttributeName="Sequence")]
        public string Sequence { get; set; }
        [XmlAttribute(AttributeName="PieceAction")]
        public string PieceAction { get; set; }
    }

    [XmlRoot(ElementName="OrderStopPieces")]
    public class OrderStopPieces {
        [XmlElement(ElementName="OrderStopPiece")]
        public OrderStopPiece OrderStopPiece { get; set; }
    }

    [XmlRoot(ElementName="Stop")]
    public class Stop {
        [XmlElement(ElementName="OrderStopPieces")]
        public OrderStopPieces OrderStopPieces { get; set; }
        [XmlAttribute(AttributeName="Sequence")]
        public string Sequence { get; set; }
        [XmlAttribute(AttributeName="StopType")]
        public string StopType { get; set; }
        [XmlAttribute(AttributeName="Note")]
        public string Note { get; set; }
        [XmlAttribute(AttributeName="Name")]
        public string Name { get; set; }
    }

    [XmlRoot(ElementName="Stops")]
    public class Stops {
        [XmlElement(ElementName="Stop")]
        public List<Stop> Stop { get; set; }
    }

    [XmlRoot(ElementName="Order")]
    public class Order {
        [XmlElement(ElementName="Customer")]
        public Customer Customer { get; set; }
        [XmlElement(ElementName="Stops")]
        public Stops Stops { get; set; }
        [XmlAttribute(AttributeName="UserID")]
        public string UserID { get; set; }
        [XmlAttribute(AttributeName="Notes")]
        public string Notes { get; set; }
        [XmlAttribute(AttributeName="CustomerID")]
        public string CustomerID { get; set; }
    }

    [XmlRoot(ElementName="SaveOrder", Namespace="http://www.uBB.com/schemas/")]
    public class SaveOrder {
        [XmlElement(ElementName="Order")]
        public Order Order { get; set; }
    }

    [XmlRoot(ElementName="Body", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
    public class Body {
        [XmlElement(ElementName="SaveOrder", Namespace="http://www.uBB.com/schemas/")]
        public SaveOrder SaveOrder { get; set; }
        [XmlAttribute(AttributeName="UserGUID")]
        public string UserGUID { get; set; }
    }

    [XmlRoot(ElementName="Envelope", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
    public class Envelope {
        [XmlElement(ElementName="Body", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
        public Body Body { get; set; }
        [XmlAttribute(AttributeName="m", Namespace="http://www.w3.org/2000/xmlns/")]
        public string M { get; set; }
        [XmlAttribute(AttributeName="SOAP", Namespace="http://www.w3.org/2000/xmlns/")]
        public string SOAP { get; set; }
    }
</code>```

Code where i am assiging other values

```<code>var SaveOrder = new ECSaveOrderRequest.Envelope
                {
                    Body = new ECSaveOrderRequest.Body
                    {
                        UserGUID = guid,
                        SaveOrder = new ECSaveOrderRequest.SaveOrder
                        {
                            Order = new ECSaveOrderRequest.Order
                            {
                                UserID = Uid,
                                Notes = "",
                                CustomerID = "",
                                Customer = new ECSaveOrderRequest.Customer
                                {
                                    CustomerID = "",
                                    CustomerCode = "",
                                    Name = "",
                                    Address = "",
                                    City = ""
                                },
                                Stops = new ECSaveOrderRequest.Stops()
                                {
                                    Stop = new List<ECSaveOrderRequest.Stop>()
                                    {
                                                /*  Here i want to Assign value in List<stop> */
                                    },

                                },
                                Jobs = new ECSaveOrderRequest.Jobs()
                                {
                                    Job = new ECSaveOrderRequest.Job()
                                    {
                                        Sequence=""
                                    }
                                }
                            },
                        }

                     }
                    };
</code>```

答:
```<code>[XmlRoot(ElementName="Stops")]
public class Stops {
    [XmlElement(ElementName="Stop")]
    public List<Stop> Stop { get; set; }
}
</code>```

You can define a list and populate it outside of the code where you assign values.
When the list has all the values you want it to have, then you can assign the list to the property.

```<code>Stops = new ECSaveOrderRequest.Stops()
 {
     Stop = listWithStopValuesYouAssignedOutsideOfThisCodeBlock
 }
</code>```

Or another way of doing is by adding a new stop to the list like

```<code>Stop = new List<ECSaveOrderRequest.Stop>()
    {
     new ECSaveOrderRequest.Stop() {},
     new ECSaveOrderRequest.Stop() {},
    },
</code>```

Body:
I want to assign value in List. i am not able to understand how can i assign value in List under Stops node. Can you please tell me how can i do this.Below is the code with class file

Created class from XML

[XmlRoot(ElementName="Customer")]
    public class Customer {
        [XmlAttribute(AttributeName="CustomerID")]
        public string CustomerID { get; set; }
        [XmlAttribute(AttributeName="CustomerCode")]
        public string CustomerCode { get; set; }
        [XmlAttribute(AttributeName="Name")]
        public string Name { get; set; }
        [XmlAttribute(AttributeName="Address")]
        public string Address { get; set; }
    }

    [XmlRoot(ElementName="OrderStopPiece")]
    public class OrderStopPiece {
        [XmlAttribute(AttributeName="Sequence")]
        public string Sequence { get; set; }
        [XmlAttribute(AttributeName="PieceAction")]
        public string PieceAction { get; set; }
    }

    [XmlRoot(ElementName="OrderStopPieces")]
    public class OrderStopPieces {
        [XmlElement(ElementName="OrderStopPiece")]
        public OrderStopPiece OrderStopPiece { get; set; }
    }

    [XmlRoot(ElementName="Stop")]
    public class Stop {
        [XmlElement(ElementName="OrderStopPieces")]
        public OrderStopPieces OrderStopPieces { get; set; }
        [XmlAttribute(AttributeName="Sequence")]
        public string Sequence { get; set; }
        [XmlAttribute(AttributeName="StopType")]
        public string StopType { get; set; }
        [XmlAttribute(AttributeName="Note")]
        public string Note { get; set; }
        [XmlAttribute(AttributeName="Name")]
        public string Name { get; set; }
    }

    [XmlRoot(ElementName="Stops")]
    public class Stops {
        [XmlElement(ElementName="Stop")]
        public List<Stop> Stop { get; set; }
    }

    [XmlRoot(ElementName="Order")]
    public class Order {
        [XmlElement(ElementName="Customer")]
        public Customer Customer { get; set; }
        [XmlElement(ElementName="Stops")]
        public Stops Stops { get; set; }
        [XmlAttribute(AttributeName="UserID")]
        public string UserID { get; set; }
        [XmlAttribute(AttributeName="Notes")]
        public string Notes { get; set; }
        [XmlAttribute(AttributeName="CustomerID")]
        public string CustomerID { get; set; }
    }

    [XmlRoot(ElementName="SaveOrder", Namespace="http://www.uBB.com/schemas/")]
    public class SaveOrder {
        [XmlElement(ElementName="Order")]
        public Order Order { get; set; }
    }

    [XmlRoot(ElementName="Body", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
    public class Body {
        [XmlElement(ElementName="SaveOrder", Namespace="http://www.uBB.com/schemas/")]
        public SaveOrder SaveOrder { get; set; }
        [XmlAttribute(AttributeName="UserGUID")]
        public string UserGUID { get; set; }
    }

    [XmlRoot(ElementName="Envelope", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
    public class Envelope {
        [XmlElement(ElementName="Body", Namespace="http://schemas.xmlsoap.org/soap/envelope/")]
        public Body Body { get; set; }
        [XmlAttribute(AttributeName="m", Namespace="http://www.w3.org/2000/xmlns/")]
        public string M { get; set; }
        [XmlAttribute(AttributeName="SOAP", Namespace="http://www.w3.org/2000/xmlns/")]
        public string SOAP { get; set; }
    }

Code where i am assiging other values

var SaveOrder = new ECSaveOrderRequest.Envelope
                {
                    Body = new ECSaveOrderRequest.Body
                    {
                        UserGUID = guid,
                        SaveOrder = new ECSaveOrderRequest.SaveOrder
                        {
                            Order = new ECSaveOrderRequest.Order
                            {
                                UserID = Uid,
                                Notes = "",
                                CustomerID = "",
                                Customer = new ECSaveOrderRequest.Customer
                                {
                                    CustomerID = "",
                                    CustomerCode = "",
                                    Name = "",
                                    Address = "",
                                    City = ""
                                },
                                Stops = new ECSaveOrderRequest.Stops()
                                {
                                    Stop = new List<ECSaveOrderRequest.Stop>()
                                    {
                                                /*  Here i want to Assign value in List<stop> */
                                    },

                                },
                                Jobs = new ECSaveOrderRequest.Jobs()
                                {
                                    Job = new ECSaveOrderRequest.Job()
                                    {
                                        Sequence=""
                                    }
                                }
                            },
                        }

                     }
                    };

Body:
[XmlRoot(ElementName="Stops")]
public class Stops {
    [XmlElement(ElementName="Stop")]
    public List<Stop> Stop { get; set; }
}

You can define a list and populate it outside of the code where you assign values.
When the list has all the values you want it to have, then you can assign the list to the property.

Stops = new ECSaveOrderRequest.Stops()
 {
     Stop = listWithStopValuesYouAssignedOutsideOfThisCodeBlock
 }

Or another way of doing is by adding a new stop to the list like

Stop = new List<ECSaveOrderRequest.Stop>()
    {
     new ECSaveOrderRequest.Stop() {},
     new ECSaveOrderRequest.Stop() {},
    },


问:
How to import a certificate (crt file) into keycloak?
I'm configuring keycloak as an SP which is connecting to a PingFederate IDP.

I'd like to import the IDP's certificate file into keycloack so that the trust will succeed.

How do I import a crt file into keycloak?

答:
This has been documented in the keycloak's site.
https://www.keycloak.org/docs/3.3/server_installation/topics/network/outgoing.html

```<code>keytool -import -alias HOSTDOMAIN -keystore truststore.jks -file host-certificate.cer
</code>```

The truststore is configured within the standalone.xml, standalone-ha.xml, or domain.xml file in your distribution. The location of this file depends on your operating mode.

```<code><spi name="truststore">
    <provider name="file" enabled="true">
        <properties>
            <property name="file" value="path to your .jks file containing public certificates"/>
            <property name="password" value="password"/>
            <property name="hostname-verification-policy" value="WILDCARD"/>
            <property name="disabled" value="false"/>
        </properties>
    </provider>
</spi>
</code>```

New link: https://www.keycloak.org/server/outgoinghttp#_outgoing_https_request_truststore

Body:
This has been documented in the keycloak's site.
https://www.keycloak.org/docs/3.3/server_installation/topics/network/outgoing.html

keytool -import -alias HOSTDOMAIN -keystore truststore.jks -file host-certificate.cer

The truststore is configured within the standalone.xml, standalone-ha.xml, or domain.xml file in your distribution. The location of this file depends on your operating mode.

<spi name="truststore">
    <provider name="file" enabled="true">
        <properties>
            <property name="file" value="path to your .jks file containing public certificates"/>
            <property name="password" value="password"/>
            <property name="hostname-verification-policy" value="WILDCARD"/>
            <property name="disabled" value="false"/>
        </properties>
    </provider>
</spi>

New link: https://www.keycloak.org/server/outgoinghttp#_outgoing_https_request_truststore


问:
Find all duplicate ids and add unique key
how to find all duplicate ids when the page is relaod:

Let's say we have html like this:

```<code><input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />
</code>```

The idea is to find duplicate ids and add +1 or something like that:

What I want to achieve is:

```<code><input type="radio" id="name1" />
<input type="radio" id="name2" />
<input type="radio" id="name3" />
<input type="radio" id="last1" />
<input type="radio" id="last2" />
</code>```

JS

```<code> $('[id]').each(function(){
  var ids = $('[id="'+this.id+'"]');
  if(ids.length>1 && ids[0]==this)
      $(this).attr('id', $(this).attr('id') + i);
 });
</code>```

Any ideas? Thank you all.

答:
try this</p>

```<code> var  i = 0;
 ('[id]').each(function(){
  var allIds = $('[id^="'+this.id+'"]').length
  var ids = $('[id="'+this.id+'"]');
  if(ids.length>1 && ids[0]==this)
   var i = allIds - ids.length + 1
      $(this).attr('id', $(this).attr('id') + i++);
 })
</code>```

Body:
how to find all duplicate ids when the page is relaod:

Let's say we have html like this:

<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="name" />
<input type="radio" id="last" />
<input type="radio" id="last" />

The idea is to find duplicate ids and add +1 or something like that:

What I want to achieve is:

<input type="radio" id="name1" />
<input type="radio" id="name2" />
<input type="radio" id="name3" />
<input type="radio" id="last1" />
<input type="radio" id="last2" />

JS

 $('[id]').each(function(){
  var ids = $('[id="'+this.id+'"]');
  if(ids.length>1 && ids[0]==this)
      $(this).attr('id', $(this).attr('id') + i);
 });

Any ideas? Thank you all.

Body:
try this

 var  i = 0;
 ('[id]').each(function(){
  var allIds = $('[id^="'+this.id+'"]').length
  var ids = $('[id="'+this.id+'"]');
  if(ids.length>1 && ids[0]==this)
   var i = allIds - ids.length + 1
      $(this).attr('id', $(this).attr('id') + i++);
 })


问:
Flyway migration blocked by null version_rank
I'm using PostgreSQL 9.5 and flyway 5.0.7

Everything worked fine for the previous 6 migrations but now it blocks for the latest

I have the following error :

```<code>22:27:45.230 [INFO ] o.f.c.i.u.l.slf4j.Slf4jLog - Flyway Community Edition 5.0.7 by Boxfuse
22:27:45.408 [INFO ] o.f.c.i.u.l.slf4j.Slf4jLog - Database: jdbc:postgresql://localhost:32767/my_db (PostgreSQL 9.5)
22:27:45.566 [INFO ] o.f.c.i.u.l.slf4j.Slf4jLog - Successfully validated 7 migrations (execution time 00:00.061s)
22:27:45.658 [INFO ] o.f.c.i.u.l.slf4j.Slf4jLog - Current version of schema "public": 6
22:27:45.733 [INFO ] o.f.c.i.u.l.slf4j.Slf4jLog - Migrating schema "public" to version 7 - update
Exception in thread "main" org.flywaydb.core.internal.exception.FlywaySqlException:
Unable to insert row for version '7' in Schema History table "public"."flyway_schema_history"
---------------------------------------------------------------------------------------------
SQL State  : 23502
Error Code : 0
Message    : ERROR: null value in column "version_rank" violates not-null constraint
  Détail : Failing row contains (null, 7, 7, update, SQL, V7__update.sql, -1303600795, postgres, 2018-02-25 22:28:00.536556, 158, t).

    at org.flywaydb.core.internal.schemahistory.JdbcTableSchemaHistory.doAddAppliedMigration(JdbcTableSchemaHistory.java:171)
    at org.flywaydb.core.internal.schemahistory.SchemaHistory.addAppliedMigration(SchemaHistory.java:146)
    at org.flywaydb.core.internal.command.DbMigrate.doMigrateGroup(DbMigrate.java:378)
    at org.flywaydb.core.internal.command.DbMigrate.access$400(DbMigrate.java:52)
    at org.flywaydb.core.internal.command.DbMigrate$5.call(DbMigrate.java:297)
    at org.flywaydb.core.internal.util.jdbc.TransactionTemplate.execute(TransactionTemplate.java:75)
    at org.flywaydb.core.internal.command.DbMigrate.applyMigrations(DbMigrate.java:294)
    at org.flywaydb.core.internal.command.DbMigrate.migrateGroup(DbMigrate.java:259)
    at org.flywaydb.core.internal.command.DbMigrate.access$300(DbMigrate.java:52)
    at org.flywaydb.core.internal.command.DbMigrate$4.call(DbMigrate.java:179)
    at org.flywaydb.core.internal.command.DbMigrate$4.call(DbMigrate.java:176)
    at org.flywaydb.core.internal.database.postgresql.PostgreSQLAdvisoryLockTemplate.execute(PostgreSQLAdvisoryLockTemplate.java:71)
    at org.flywaydb.core.internal.database.postgresql.PostgreSQLConnection.lock(PostgreSQLConnection.java:110)
    at org.flywaydb.core.internal.schemahistory.JdbcTableSchemaHistory.lock(JdbcTableSchemaHistory.java:148)
    at org.flywaydb.core.internal.command.DbMigrate.migrateAll(DbMigrate.java:176)
    at org.flywaydb.core.internal.command.DbMigrate.migrate(DbMigrate.java:145)
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1206)
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1168)
    at org.flywaydb.core.Flyway.execute(Flyway.java:1655)
    at org.flywaydb.core.Flyway.migrate(Flyway.java:1168)
    at com.test.MyApplication.main(MainApplication.java:47)
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "version_rank" violates not-null constraint
  Détail : Failing row contains (null, 7, 7, update, SQL, V7__update.sql, -1303600795, postgres, 2018-02-25 22:28:00.536556, 158, t).
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2422)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2167)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:306)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:155)
    at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:132)
    at org.flywaydb.core.internal.util.jdbc.JdbcTemplate.update(JdbcTemplate.java:334)
    at org.flywaydb.core.internal.schemahistory.JdbcTableSchemaHistory.doAddAppliedMigration(JdbcTableSchemaHistory.java:165)
    ... 20 more
</code>```

Any idea why this column "version_rank" is not generated or not initialized ?

Thanks in advance for your help

答:
it's worked for me for Postgres

```<code>CREATE TABLE flyway_schema_history (
  installed_rank INTEGER NOT NULL,
  version varchar(50) DEFAULT NULL,
  description varchar(200) NOT NULL,
  type varchar(20) NOT NULL,
  script varchar(1000) NOT NULL,
  checksum INTEGER DEFAULT NULL,
  installed_by varchar(100) NOT NULL,
  installed_on timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  execution_time INTEGER NOT NULL,
  success BOOLEAN NOT NULL,
  PRIMARY KEY (installed_rank)
);

INSERT INTO flyway_schema_history (installed_rank, version, description,     type, script, checksum, installed_by, installed_on, execution_time, success)
SELECT installed_rank, version, description, type, script, checksum,     installed_by, installed_on, execution_time, success
FROM schema_version;

ALTER TABLE schema_version RENAME TO bak_schema_version;
</code>```

Body:
I'm using PostgreSQL 9.5 and flyway 5.0.7

Everything worked fine for the previous 6 migrations but now it blocks for the latest

I have the following error :

22:27:45.230 [INFO ] o.f.c.i.u.l.slf4j.Slf4jLog - Flyway Community Edition 5.0.7 by Boxfuse
22:27:45.408 [INFO ] o.f.c.i.u.l.slf4j.Slf4jLog - Database: jdbc:postgresql://localhost:32767/my_db (PostgreSQL 9.5)
22:27:45.566 [INFO ] o.f.c.i.u.l.slf4j.Slf4jLog - Successfully validated 7 migrations (execution time 00:00.061s)
22:27:45.658 [INFO ] o.f.c.i.u.l.slf4j.Slf4jLog - Current version of schema "public": 6
22:27:45.733 [INFO ] o.f.c.i.u.l.slf4j.Slf4jLog - Migrating schema "public" to version 7 - update
Exception in thread "main" org.flywaydb.core.internal.exception.FlywaySqlException:
Unable to insert row for version '7' in Schema History table "public"."flyway_schema_history"
---------------------------------------------------------------------------------------------
SQL State  : 23502
Error Code : 0
Message    : ERROR: null value in column "version_rank" violates not-null constraint
  Détail : Failing row contains (null, 7, 7, update, SQL, V7__update.sql, -1303600795, postgres, 2018-02-25 22:28:00.536556, 158, t).

    at org.flywaydb.core.internal.schemahistory.JdbcTableSchemaHistory.doAddAppliedMigration(JdbcTableSchemaHistory.java:171)
    at org.flywaydb.core.internal.schemahistory.SchemaHistory.addAppliedMigration(SchemaHistory.java:146)
    at org.flywaydb.core.internal.command.DbMigrate.doMigrateGroup(DbMigrate.java:378)
    at org.flywaydb.core.internal.command.DbMigrate.access$400(DbMigrate.java:52)
    at org.flywaydb.core.internal.command.DbMigrate$5.call(DbMigrate.java:297)
    at org.flywaydb.core.internal.util.jdbc.TransactionTemplate.execute(TransactionTemplate.java:75)
    at org.flywaydb.core.internal.command.DbMigrate.applyMigrations(DbMigrate.java:294)
    at org.flywaydb.core.internal.command.DbMigrate.migrateGroup(DbMigrate.java:259)
    at org.flywaydb.core.internal.command.DbMigrate.access$300(DbMigrate.java:52)
    at org.flywaydb.core.internal.command.DbMigrate$4.call(DbMigrate.java:179)
    at org.flywaydb.core.internal.command.DbMigrate$4.call(DbMigrate.java:176)
    at org.flywaydb.core.internal.database.postgresql.PostgreSQLAdvisoryLockTemplate.execute(PostgreSQLAdvisoryLockTemplate.java:71)
    at org.flywaydb.core.internal.database.postgresql.PostgreSQLConnection.lock(PostgreSQLConnection.java:110)
    at org.flywaydb.core.internal.schemahistory.JdbcTableSchemaHistory.lock(JdbcTableSchemaHistory.java:148)
    at org.flywaydb.core.internal.command.DbMigrate.migrateAll(DbMigrate.java:176)
    at org.flywaydb.core.internal.command.DbMigrate.migrate(DbMigrate.java:145)
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1206)
    at org.flywaydb.core.Flyway$1.execute(Flyway.java:1168)
    at org.flywaydb.core.Flyway.execute(Flyway.java:1655)
    at org.flywaydb.core.Flyway.migrate(Flyway.java:1168)
    at com.test.MyApplication.main(MainApplication.java:47)
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "version_rank" violates not-null constraint
  Détail : Failing row contains (null, 7, 7, update, SQL, V7__update.sql, -1303600795, postgres, 2018-02-25 22:28:00.536556, 158, t).
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2422)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2167)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:306)
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:155)
    at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:132)
    at org.flywaydb.core.internal.util.jdbc.JdbcTemplate.update(JdbcTemplate.java:334)
    at org.flywaydb.core.internal.schemahistory.JdbcTableSchemaHistory.doAddAppliedMigration(JdbcTableSchemaHistory.java:165)
    ... 20 more

Any idea why this column "version_rank" is not generated or not initialized ?

Thanks in advance for your help

Body:
it's worked for me for Postgres

CREATE TABLE flyway_schema_history (
  installed_rank INTEGER NOT NULL,
  version varchar(50) DEFAULT NULL,
  description varchar(200) NOT NULL,
  type varchar(20) NOT NULL,
  script varchar(1000) NOT NULL,
  checksum INTEGER DEFAULT NULL,
  installed_by varchar(100) NOT NULL,
  installed_on timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  execution_time INTEGER NOT NULL,
  success BOOLEAN NOT NULL,
  PRIMARY KEY (installed_rank)
);

INSERT INTO flyway_schema_history (installed_rank, version, description,     type, script, checksum, installed_by, installed_on, execution_time, success)
SELECT installed_rank, version, description, type, script, checksum,     installed_by, installed_on, execution_time, success
FROM schema_version;

ALTER TABLE schema_version RENAME TO bak_schema_version;