问:
how do i redirect to home page(root )when user signed out?
I am trying to get devise working on my simple rails app where;

1.I'd like when user_signed out it will redirect to home page(root).!

2.when the user create his/her own products, when go to products.index it will show all the products that users have created, and when signed in as a specific user, the person will see their own created products on the user dashboard.(at the moment the added products will automatically added to the products index page)

many thanks!

```<code><header class="navbar">

  <nav class="menu">
    <ul>
      <li>
        <a href="#"> Products <i class="fa fa-sort-desc" aria-hidden="true"></i></a>
          <ul>
            <li>
              <%= link_to "Create a product",new_product_path %>
             </li>
            </li>
            </li>
            <li>
              <%= link_to "View all the products", products_path%></i>
            </li>
          </ul>
      </li>
      <li>
        <a href="#">Profile <i class="fa fa-sort-desc" aria-hidden="true"></i></a>
        <ul>
          <%= link_to "My dashboard", profile_path %>
          <%= link_to "Log out", destroy_user_session_path, method: :delete %>
        </ul>
      </li>
      <li><a href="#">Contact </a></li>
    </ul>
  </nav>

</header>
</code>```

```<code><h2>Log in</h2>

<%= simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
  <div class='signup_create_product'>
    <%= f.input :email,
                required: false,
                autofocus: true,
                input_html: { autocomplete: "email" } %>
    <%= f.input :password,
                required: false,
                input_html: { autocomplete: "current-password" } %>
    <%= f.input :remember_me, as: :boolean if devise_mapping.rememberable? %>
  </div>

  <div class="form-actions">
    <%= f.button :submit, "Log in" %>
  </div>
<% end %>

<%= render "devise/shared/links" %>

</code>```

```<code>class ProductsController < ApplicationController

  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
  end

  def new
    @product = Product.new
  end

  def create

     @product = Product.new(product_params)
     @product.user = current_user

    if @product.save
      redirect_to products_path
    else
      render :new
    end
  end

  def edit
    @product = Product.find(params[:id])
  end

  def destroy
    @product = Product.find(params[:id])
    @product.destroy
    redirect_to products_path
  end

  private

  def product_params
    params.require(:product).permit(:product_name, :description)
  end
end
</code>```

user show page

```<code> <h1><%= @user.name %></h1>
</code>```

答:
From the official devise guide to redirection after sign out:

https://github.com/plataformatec/devise/wiki/How-To:-Change-the-redirect-path-after-destroying-a-session-i.e.-signing-out

In short, add this to your application controller:

```<code>class ApplicationController < ActionController::Base
  ...
  ...
  private

  # Overwriting the sign_out redirect path method
  def after_sign_out_path_for(resource_or_scope)
    root_path
  end
end
</code>```

Body:
I am trying to get devise working on my simple rails app where;

1.I'd like when user_signed out it will redirect to home page(root).!

2.when the user create his/her own products, when go to products.index it will show all the products that users have created, and when signed in as a specific user, the person will see their own created products on the user dashboard.(at the moment the added products will automatically added to the products index page)

many thanks!

         Products

              <%= link_to "Create a product",new_product_path %>

              <%= link_to "View all the products", products_path%>

        Profile

          <%= link_to "My dashboard", profile_path %>
          <%= link_to "Log out", destroy_user_session_path, method: :delete %>

Contact

Log in

<%= simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

    <%= f.input :email,
                required: false,
                autofocus: true,
                input_html: { autocomplete: "email" } %>
    <%= f.input :password,
                required: false,
                input_html: { autocomplete: "current-password" } %>
    <%= f.input :remember_me, as: :boolean if devise_mapping.rememberable? %>

    <%= f.button :submit, "Log in" %>

<% end %>

<%= render "devise/shared/links" %>

class ProductsController < ApplicationController

  def index
    @products = Product.all
  end

  def show
    @product = Product.find(params[:id])
  end

  def new
    @product = Product.new
  end

  def create

     @product = Product.new(product_params)
     @product.user = current_user

    if @product.save
      redirect_to products_path
    else
      render :new
    end
  end

  def edit
    @product = Product.find(params[:id])
  end

  def destroy
    @product = Product.find(params[:id])
    @product.destroy
    redirect_to products_path
  end

  private

  def product_params
    params.require(:product).permit(:product_name, :description)
  end
end

user show page

<%= @user.name %>

Body:
From the official devise guide to redirection after sign out:

https://github.com/plataformatec/devise/wiki/How-To:-Change-the-redirect-path-after-destroying-a-session-i.e.-signing-out

In short, add this to your application controller:

class ApplicationController < ActionController::Base
  ...
  ...
  private

  # Overwriting the sign_out redirect path method
  def after_sign_out_path_for(resource_or_scope)
    root_path
  end
end


来源: stackexchange

问:
When do EntityManager gets new session?
It's generally obvious that EntityManager is holding current session, we can get it using this:

```<code>Session session = entityManager.unwrap(Session.class);
</code>```

But I am curious when EntityManager gets the new one.

@edit

```<code>@PersistenceContext(type = PersistenceContextType.TRANSACTION, unitName = "context")
private EntityManager              em;
</code>```

答:
According to your code I assume that you are either using Java EE or Spring.

```<code>@PersistenceContext(type = PersistenceContextType.TRANSACTION, unitName = "context")
private EntityManager em;
</code>```

In that case the EntityManager is bound to the transaction. That means you get a new EntityManager with every new transaction.

The Session and the EntityManager are the same and have the same lifecycle. It's just another name for the same. Session is Hibernate slang and EntityManager JPA.

ContentLicense: CC BY-SA 4.0

Title: When do EntityManager gets new session?

Body:
It's generally obvious that EntityManager is holding current session, we can get it using this:

Session session = entityManager.unwrap(Session.class);

But I am curious when EntityManager gets the new one.

@edit

@PersistenceContext(type = PersistenceContextType.TRANSACTION, unitName = "context")
private EntityManager              em;

Body:
According to your code I assume that you are either using Java EE or Spring.

@PersistenceContext(type = PersistenceContextType.TRANSACTION, unitName = "context")
private EntityManager em;

In that case the EntityManager is bound to the transaction. That means you get a new EntityManager with every new transaction.

The Session and the EntityManager are the same and have the same lifecycle. It's just another name for the same. Session is Hibernate slang and EntityManager JPA.


问:
How do I overwrite input items in session in Vue.js?
When the input screen is opened when the screen is displayed, input items on the screen are set from session information.
However, although jQuery performs display switching based on the value of the input item on the screen, switching is performed based on the initial value (on the program), not the session information.
Presumably, jQuery display switching is performed before session information is set (the initial data is set in the input item).

For example, in the following source, a session is set, but the screen is displayed with the content of category = 1.

And the point of concern is that the following warning is displayed.

[Vue warn]: Avoid adding reactive properties to a Vue instance or its root $ data at runtime-declare it upfront in the data option.

```<code>data: {
    url: "",
    category: 1,
    errors: {},
},
created: function() {
    let count_data = 0;
    for (let key in old_data) {
        if (old_data[key] != null && old_data[key] != "") {
            count_data += 1;
        }
    }
    if(count_data > 0) {
        for(let key in old_data){
            this.$set(this, key, old_data[key]);
        }
    }else{
        let that = this;
        axios.get('api/getSession')
            .then(res => {
                Object.entries(res.data).map(function(data){
                    that.$set(that, data[0], data[1]);
                });
            })
    }
},
</code>```

答:
That console message is generated whenever a new property is added to the object returned from data. You shouldn't be getting that message for properties like "category" or "url", but you will if something else is added.

Try generating console messages wherever $set is called to ensure that key or data[0] is not a new unknown property. If it is, try adding it to the data object as a null or empty string.

Body:
When the input screen is opened when the screen is displayed, input items on the screen are set from session information.
However, although jQuery performs display switching based on the value of the input item on the screen, switching is performed based on the initial value (on the program), not the session information.
Presumably, jQuery display switching is performed before session information is set (the initial data is set in the input item).

For example, in the following source, a session is set, but the screen is displayed with the content of category = 1.

And the point of concern is that the following warning is displayed.

[Vue warn]: Avoid adding reactive properties to a Vue instance or its root $ data at runtime-declare it upfront in the data option.

data: {
    url: "",
    category: 1,
    errors: {},
},
created: function() {
    let count_data = 0;
    for (let key in old_data) {
        if (old_data[key] != null && old_data[key] != "") {
            count_data += 1;
        }
    }
    if(count_data > 0) {
        for(let key in old_data){
            this.$set(this, key, old_data[key]);
        }
    }else{
        let that = this;
        axios.get('api/getSession')
            .then(res => {
                Object.entries(res.data).map(function(data){
                    that.$set(that, data[0], data[1]);
                });
            })
    }
},


问:
Converting a shell script to PowerShell
After switching an application from Linux to Windows, I need to convert a shell script to a Windows equivalent. My choices were basically batch and PowerShell and I decided to give a shot to PowerShell.

For anyone interested, it's a local check for Check_MK to get information about SoftEther installed version and the number of sessions with performance data.

The initial shell script was as follow:

```<code>#!/bin/sh
cmd=$(/usr/local/vpnserver/vpncmd localhost:port /server /password:password /in:/usr/lib/check_mk_agent/local/vpncmd.txt)
version=$(echo "$cmd" | head -4 | tail -1)
sessions=$(echo "$cmd" | grep Sessions | awk '$1=$1' | cut -c21-22)

if [ -z "$version" ]; then
 echo "3 VPN_Version - Can't get the information from vpncmd"
else
 echo "0 VPN_Version - SoftEther VPN Server $version"
fi

if [ -z "$sessions" ]; then
 echo "3 VPN_Sessions - Can't get the information from vpncmd"
else
 echo "P VPN_Sessions sessions=$sessions;2;2"
fi
</code>```

I basically got everything working except the 2 hardest lines of code:

cd "C:\Program Files\SoftEther VPN Server"
$cmd = vpncmd localhost:port /server /password:password /in:vpncmd.txt
$version=
$sessions=

if($version -eq $null) {
    echo "3 VPN_Version - Can't get the information from vpncmd"
} else {
    echo "0 VPN_Version - SoftEther VPN Server $version"
}

if($sessions -eq $null) {
    echo "3 VPN_Sessions - Can't get the information from vpncmd"
} else {
    echo "P VPN_Sessions sessions=$sessions;2;2"
}
```

I need help with going from the head, tail, grep, awk and cut one liners to whatever is equivalent in PowerShell. I read about Get-Content but I'm not sure if it's the most efficient way to do this and would like to prevent going from 1 line definition to 10 lines if that's possible to be as efficient in PowerShell.

Sample output of vpncmd's output: https://pastebin.com/J5FcHzHK

答:
with the data being an array of lines & the word Version appearing multiple times in the actual source, the code needs to change a tad. in this version, it uses the way that -match works on an array to give the whole line as a result. that requires working on the output line to parse the desired data.

```<code>$Version = ($Vpncmd_Output -match '^Version \d{1,}\.\d{1,}' -split 'Version ' )[-1].Trim()
$SessionCount = [int]($Vpncmd_Output -match 'Number of Sessions\s+\|').Split('|')[-1].Trim()

$Version
$SessionCount
</code>```

output ...

```<code>4.29 Build 9680   (English)
0
</code>```

<s>using the data in your PasteBin post, and presuming that is a multiline string, not an array of strings, this seems to work [grin] ...

```<code>$Vpncmd_Output -match '(?m)Number of Sessions\s+\|(?<Sessions>.*)'
$Matches.Sessions
# output = 0
$Vpncmd_Output -match '(?m)Version (?<Version>.+)'
$Matches.Version
# output = 4.29 Build 9680   (English)
</code>```

i tried to combine the regex into one, but failed. [blush] the way i have it requires two passes, but it does work.</s>

Title: Converting a shell script to PowerShell

Body:
After switching an application from Linux to Windows, I need to convert a shell script to a Windows equivalent. My choices were basically batch and PowerShell and I decided to give a shot to PowerShell.

For anyone interested, it's a local check for Check_MK to get information about SoftEther installed version and the number of sessions with performance data.

The initial shell script was as follow:

#!/bin/sh
cmd=$(/usr/local/vpnserver/vpncmd localhost:port /server /password:password /in:/usr/lib/check_mk_agent/local/vpncmd.txt)
version=$(echo "$cmd" | head -4 | tail -1)
sessions=$(echo "$cmd" | grep Sessions | awk '$1=$1' | cut -c21-22)

if [ -z "$version" ]; then
 echo "3 VPN_Version - Can't get the information from vpncmd"
else
 echo "0 VPN_Version - SoftEther VPN Server $version"
fi

if [ -z "$sessions" ]; then
 echo "3 VPN_Sessions - Can't get the information from vpncmd"
else
 echo "P VPN_Sessions sessions=$sessions;2;2"
fi

I basically got everything working except the 2 hardest lines of code:

cd "C:\Program Files\SoftEther VPN Server"
$cmd = vpncmd localhost:port /server /password:password /in:vpncmd.txt
$version=
$sessions=

if($version -eq $null) {
    echo "3 VPN_Version - Can't get the information from vpncmd"
} else {
    echo "0 VPN_Version - SoftEther VPN Server $version"
}

if($sessions -eq $null) {
    echo "3 VPN_Sessions - Can't get the information from vpncmd"
} else {
    echo "P VPN_Sessions sessions=$sessions;2;2"
}

I need help with going from the head, tail, grep, awk and cut one liners to whatever is equivalent in PowerShell. I read about Get-Content but I'm not sure if it's the most efficient way to do this and would like to prevent going from 1 line definition to 10 lines if that's possible to be as efficient in PowerShell.

Sample output of vpncmd's output: https://pastebin.com/J5FcHzHK

Body:
with the data being an array of lines & the word Version appearing multiple times in the actual source, the code needs to change a tad. in this version, it uses the way that -match works on an array to give the whole line as a result. that requires working on the output line to parse the desired data.

$Version = ($Vpncmd_Output -match '^Version \d{1,}\.\d{1,}' -split 'Version ' )[-1].Trim()
$SessionCount = [int]($Vpncmd_Output -match 'Number of Sessions\s+\|').Split('|')[-1].Trim()

$Version
$SessionCount

output ...

4.29 Build 9680   (English)
0

<s>using the data in your PasteBin post, and presuming that is a multiline string, not an array of strings, this seems to work [grin] ...

$Vpncmd_Output -match '(?m)Number of Sessions\s+\|(?<Sessions>.*)'
$Matches.Sessions
# output = 0
$Vpncmd_Output -match '(?m)Version (?<Version>.+)'
$Matches.Version
# output = 4.29 Build 9680   (English)

i tried to combine the regex into one, but failed. [blush] the way i have it requires two passes, but it does work.</s>


问:
How to make UIFont conform to decodable
I'm trying to make UIFont conform to Decodable, but I'm having a hard time.

I currently have solution where im wrapping the UIFont in a Font struct like this

```<code>public struct Font: Decodable{
    let font: UIFont

    private enum CodingKeys: String, CodingKey {
        case size
        case font
    }

    public init(from decoder: Decoder){
        do{
            let values = try decoder.container(keyedBy: CodingKeys.self)
            font = UIFont(name: try values.decode(String.self, forKey: .font), size: try values.decode(CGFloat.self, forKey: .size))!
        } catch{
            fatalError("Font configuration error:\(error)")
        }
    }
}
</code>```

This works but I seems clumsy, so I was trying like this instead:

```<code>final class Font: UIFont, Decodable{
    private enum CodingKeys: String, CodingKey {
        case size
        case font
    }

    convenience init(from decoder: Decoder)  {
        do{
            let values = try decoder.container(keyedBy: CodingKeys.self)
            super.init(name: try values.decode(String.self, forKey: .font), size: try values.decode(CGFloat.self, forKey: .size))
        } catch{
            fatalError("Font configuration error:\(error)")
        }
    }
}
</code>```

This however do not work because init(from decoder: Decoder) can not be a failable initialiser and UIFont.init(name: String, size: CGFloat) is a failable initialiser, and calling a failable init from a non failable one is not possible.

Any suggestions to how to make UIFont conform to Decodable without wrapping it is highly appreciated.

答:
I'm writing at cell phone so I can't try this snippet but I think this can work. Let me know if it helps.</p>

```<code>final class Font: Codable {
let size: CGFloat
let name: String

var font: UIFont = UIFont.init()

init(s: CGFloat, n: String) {
    size = s
    name = n

    font = UIFont(name: name, size: size) ?? UIFont.systemFont(ofSize: size)
}

enum CodingKeys: String, CodingKey {
    case size
    case name
}

required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)

    size = try container.decode(CGFloat.self, forKey: .size)
    name = try container.decode(String.self, forKey: .name)

    font = UIFont(name: name, size: size) ?? UIFont.systemFont(ofSize: size)
}

func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)

    try container.encode(size, forKey: .size)
    try container.encode(name, forKey: .name)
}
}
</code>```

Title: How to make UIFont conform to decodable

Body:
I'm trying to make UIFont conform to Decodable, but I'm having a hard time.

I currently have solution where im wrapping the UIFont in a Font struct like this

public struct Font: Decodable{
    let font: UIFont

    private enum CodingKeys: String, CodingKey {
        case size
        case font
    }

    public init(from decoder: Decoder){
        do{
            let values = try decoder.container(keyedBy: CodingKeys.self)
            font = UIFont(name: try values.decode(String.self, forKey: .font), size: try values.decode(CGFloat.self, forKey: .size))!
        } catch{
            fatalError("Font configuration error:\(error)")
        }
    }
}

This works but I seems clumsy, so I was trying like this instead:

final class Font: UIFont, Decodable{
    private enum CodingKeys: String, CodingKey {
        case size
        case font
    }

    convenience init(from decoder: Decoder)  {
        do{
            let values = try decoder.container(keyedBy: CodingKeys.self)
            super.init(name: try values.decode(String.self, forKey: .font), size: try values.decode(CGFloat.self, forKey: .size))
        } catch{
            fatalError("Font configuration error:\(error)")
        }
    }
}

This however do not work because init(from decoder: Decoder) can not be a failable initialiser and UIFont.init(name: String, size: CGFloat) is a failable initialiser, and calling a failable init from a non failable one is not possible.

Any suggestions to how to make UIFont conform to Decodable without wrapping it is highly appreciated.

Body:
I'm writing at cell phone so I can't try this snippet but I think this can work. Let me know if it helps.

final class Font: Codable {
let size: CGFloat
let name: String

var font: UIFont = UIFont.init()

init(s: CGFloat, n: String) {
    size = s
    name = n

    font = UIFont(name: name, size: size) ?? UIFont.systemFont(ofSize: size)
}

enum CodingKeys: String, CodingKey {
    case size
    case name
}

required init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)

    size = try container.decode(CGFloat.self, forKey: .size)
    name = try container.decode(String.self, forKey: .name)

    font = UIFont(name: name, size: size) ?? UIFont.systemFont(ofSize: size)
}

func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)

    try container.encode(size, forKey: .size)
    try container.encode(name, forKey: .name)
}
}


问:
Java For each loop every instance from class
I start with OOP
And i have following problem:
I made a new class
Then I made ainstance from this class
Now, for every instance I want to do something
I tried it with a for each loop but it doesn't work...
There are some syntax problems

This is the class:

package main;

public class command
{
    String call;
    String execute;
}
```

<p>And this from the Main class:</p>

<pre class="lang-java prettyprint-override"><code> private static void load() {
        command greeting = new command();

        greeting.call = "hello";
        greeting.execute = "Hello Sir";

        for (command c: command) {
            System.out.println("Another command...");
        }

    }
</code>```

I don't know how to make the loop or is there another way to do it?

答:
The syntax you are using in your for loop must use a instance of a class that implements the Iterable interface. For example you can use implementations of the List interface.

For example, you can try:

private static void load() {
    command greeting = new command();

    greeting.call = "hello";
    greeting.execute = "Hello Sir";

    List<command> listOfCommands = new ArrayList<>();
    listOfCommands.add(greeting);

    for (command c: listOfCommands) {
        System.out.println("Another command...");
    }

}
```

Body:
I start with OOP
And i have following problem:
I made a new class
Then I made ainstance from this class
Now, for every instance I want to do something
I tried it with a for each loop but it doesn't work...
There are some syntax problems

This is the class:

package main;

public class command
{
    String call;
    String execute;
}

And this from the Main class:

 private static void load() {
        command greeting = new command();

        greeting.call = "hello";
        greeting.execute = "Hello Sir";

        for (command c: command) {
            System.out.println("Another command...");
        }

    }

I don't know how to make the loop or is there another way to do it?


问:
Paste table from Email body to an Excel sheet
I want the sender and the body of my mail pasted in my Excel file.

I have reached as far as pasting the sender but when the body, which is a table is pasted, it destroys the format since it pastes in one cell.

How to paste the table inside my email next to the sender?

I think the code for pasting a table should start at the comment: 'Paste the table inside the email body here.

```<code>Private Sub CommandButton1_Click()

    Dim OutlookApp As Outlook.Application
    Dim OutlookNamespace As Namespace
    Dim Folder As MAPIFolder
    Dim OutlookMail As Variant
    Dim i As Integer

    Set OutlookApp = New Outlook.Application
    Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
    Set Folder = OutlookNamespace.GetDefaultFolder(olFolderInbox).Folders("ABV")

    i = 2

    With ThisWorkbook.Sheets("Sheet2")
        For Each OutlookMail In Folder.Items
            If OutlookMail.ReceivedTime >= .Range("C1") Then
                With .Cells(i, 1)
                    .Value = OutlookMail.SenderName
                    .Columns.AutoFit
                    .VerticalAlignment = xlTop
                End With
                With .Cells(i, 2)
                    'Paste the table inside the email body here
                End With
                i = i + 1
            End If
        Next OutlookMail
    End With

    Set Folder = Nothing
    Set OutlookNamespace = Nothing
    Set OutlookApp = Nothing

End Sub
</code>```

All the emails in this folder will contain a table, so I would like to loop as every sender and its table gets pasted.

答:
You can address and copy the table within the email's body by this:

```<code>OutlookMail.GetInspector.WordEditor.Range.Tables(1).Range.Copy
</code>```

and then you paste it e. g. as values into your Excel.Range:

```<code>With ThisWorkbook.Sheets("Sheet2")
    .Range("A1").PasteSpecial xlPasteValues
</code>```

If you want to paste in a different clipboard-supported format, try to get the ideal format with Excel's macro recorder. It results in something like this:

```<code>With ThisWorkbook.Sheets("Sheet2")
    .Range("A1").Select
    .PasteSpecial Format:="Text"   ' or "HTML" or ...
</code>```

Body:
I want the sender and the body of my mail pasted in my Excel file.

I have reached as far as pasting the sender but when the body, which is a table is pasted, it destroys the format since it pastes in one cell.

How to paste the table inside my email next to the sender?

I think the code for pasting a table should start at the comment: 'Paste the table inside the email body here.

Private Sub CommandButton1_Click()

    Dim OutlookApp As Outlook.Application
    Dim OutlookNamespace As Namespace
    Dim Folder As MAPIFolder
    Dim OutlookMail As Variant
    Dim i As Integer

    Set OutlookApp = New Outlook.Application
    Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
    Set Folder = OutlookNamespace.GetDefaultFolder(olFolderInbox).Folders("ABV")

    i = 2

    With ThisWorkbook.Sheets("Sheet2")
        For Each OutlookMail In Folder.Items
            If OutlookMail.ReceivedTime >= .Range("C1") Then
                With .Cells(i, 1)
                    .Value = OutlookMail.SenderName
                    .Columns.AutoFit
                    .VerticalAlignment = xlTop
                End With
                With .Cells(i, 2)
                    'Paste the table inside the email body here
                End With
                i = i + 1
            End If
        Next OutlookMail
    End With

    Set Folder = Nothing
    Set OutlookNamespace = Nothing
    Set OutlookApp = Nothing

End Sub

All the emails in this folder will contain a table, so I would like to loop as every sender and its table gets pasted.

Body:
You can address and copy the table within the email's body by this:

OutlookMail.GetInspector.WordEditor.Range.Tables(1).Range.Copy

and then you paste it e. g. as values into your Excel.Range:

With ThisWorkbook.Sheets("Sheet2")
    .Range("A1").PasteSpecial xlPasteValues

If you want to paste in a different clipboard-supported format, try to get the ideal format with Excel's macro recorder. It results in something like this:

With ThisWorkbook.Sheets("Sheet2")
    .Range("A1").Select
    .PasteSpecial Format:="Text"   ' or "HTML" or ...


问:
Laravel scope not responding
I am using laravel for my backend api.
My question is about an scopefilter, the problem is that it is not responding when I call to it.

I have a lot of examples for using scopefilters.
So I looked at each of them to see if I did something wrong.
But I can't seem to find the problem.

When I call to this model in laravel, I use a parameter to define too the scopefilter to use a specific function.
The point only is that it never gets to this function, I don't get a response when I have put a log in this function.

I assume it is a syntax problem but maybe someone else can find the problem for this.

```<code>    public static $scopeFilters = [
        "supplierArticleClientId" => "bySupplierArticleClientId"
    ];

    public function scopeBySupplierArticleClientId($query, $clientId) {
        \Log::info([$clientId]);
    }

</code>```

In this case I expect that I see an clientId in my log.

答:
You have to create a Custom validation function Implementing Rule Class
please go through this link for reference

Title: Laravel scope not responding

Body:
I am using laravel for my backend api.
My question is about an scopefilter, the problem is that it is not responding when I call to it.

I have a lot of examples for using scopefilters.
So I looked at each of them to see if I did something wrong.
But I can't seem to find the problem.

When I call to this model in laravel, I use a parameter to define too the scopefilter to use a specific function.
The point only is that it never gets to this function, I don't get a response when I have put a log in this function.

I assume it is a syntax problem but maybe someone else can find the problem for this.

    public static $scopeFilters = [
        "supplierArticleClientId" => "bySupplierArticleClientId"
    ];

    public function scopeBySupplierArticleClientId($query, $clientId) {
        \Log::info([$clientId]);
    }

In this case I expect that I see an clientId in my log.


问:
Does HTML Encoding a mailto tag stop spammers
I think its fairly common practice these days not to include a mailto: tag in your webpage.  I also realize that a better solution is to have a contact us form.

Recently I've seen some mailto tags that include and HTML encoded email address.  Is this an effective way to stop spammers from attacking an email address?

Example:

```<code><a href="mailto:newbi...">email me</a>
</code>```

Also, are there any other techniques that I've left out?  Which is the best method?

答:
I typically use the Hivelogic Enkoder.  It is helpful for encoding an entire link element, not just the mailto.

One lesson learned the annoying way, however, is to comment your code with what the original element looked like before encoding. I've accidentally left off classes on the  tag a few times.

OwnerDisplayName: bendewey

ContentLicense: CC BY-SA 3.0

Body:
I think its fairly common practice these days not to include a mailto: tag in your webpage.  I also realize that a better solution is to have a contact us form.

Recently I've seen some mailto tags that include and HTML encoded email address.  Is this an effective way to stop spammers from attacking an email address?

Example:

email me

Also, are there any other techniques that I've left out?  Which is the best method?

LastEditorDisplayName: bendewey

Body:
I typically use the Hivelogic Enkoder.  It is helpful for encoding an entire link element, not just the mailto.

One lesson learned the annoying way, however, is to comment your code with what the original element looked like before encoding. I've accidentally left off classes on the <a> tag a few times.

OwnerDisplayName: Mark Hurd

ContentLicense: CC BY-SA 2.5


问:
replace conditional to polymorphism when using typescript model class
I have built a game of life simulation and now I am trying to clean the code and make it more Object Orientated. Despite several days of search, I am having a hard time replacing conditionals with polymorphism.

So I have a component.ts a game model and a cell model. The cell model contains property status: boolean amongst other things. which can be dead or alive. Then I have given the user the ability to toggle a cell status on start. So I have tried for the status to create an abstract class and then two subclasses with dead or alive but I am not sure if that is the right way to go.

this is the cell.model

```<code>import { Coordinates } from './coordinates.model';

export class Cell {
  private coordinates: Coordinates;
  public status: string;

  constructor(coordinates) {
    this.coordinates = coordinates;
    this.status = new Alive().status;
  }

  getCoordinates(): Coordinates {
    return this.coordinates;
  }

  toggleCell(): void {
    console.log(this.status)
  }

}

export abstract class Status {
  status: string;
  abstract setStatus(): string;
}

export class Alive extends Status {
  status = 'alive';
  setStatus(): string {
    return this.status = 'dead';
  }
}

export class Dead extends Status {
  status = 'dead';
  setStatus(): string {
    return this.status = 'alive';
  }
}
</code>```

In the game model as u can see below, I used conditionals to change the status

```<code>toggleCell(cellIndex: number) {
  const cell: Cell = this.cells[cellIndex];
  // if (this.cells[cellIndex].status === 'dead') {
  //     this.cells[cellIndex].status = 'alive';
  //     this.addToLivingCells(cellIndex);

  // } else {
  //     this.cells[cellIndex].status = 'dead';
  //     this.removeFromLivingCells(cellIndex);
  // }

  cell.toggleCell()
}
</code>```

so what I want to do is remove the conditionals and use polymorphism to toggle the status from the dead to alive and back depending on the current status.

Let me know if the rest of the code is needed.

Thanks in advance

答:
I think your approuch is too much complicated for such a simple case. For this case this code is enough: </p>

```<code>export class Cell {
    private coordinates: Coordinates;
    public status: 'alive' | 'dead';

    constructor(coordinates) {
        this.coordinates = coordinates;
        this.status = 'alive';
    }

    getCoordinates(): Coordinates {
        return this.coordinates;
    }

    toggleCell(): void {
        this.status = this.status === 'alive' ? 'dead' : 'alive';
        console.log(this.status);
    }
}
</code>```

Body:
I have built a game of life simulation and now I am trying to clean the code and make it more Object Orientated. Despite several days of search, I am having a hard time replacing conditionals with polymorphism.

So I have a component.ts a game model and a cell model. The cell model contains property status: boolean amongst other things. which can be dead or alive. Then I have given the user the ability to toggle a cell status on start. So I have tried for the status to create an abstract class and then two subclasses with dead or alive but I am not sure if that is the right way to go.

this is the cell.model

import { Coordinates } from './coordinates.model';

export class Cell {
  private coordinates: Coordinates;
  public status: string;

  constructor(coordinates) {
    this.coordinates = coordinates;
    this.status = new Alive().status;
  }

  getCoordinates(): Coordinates {
    return this.coordinates;
  }

  toggleCell(): void {
    console.log(this.status)
  }

}

export abstract class Status {
  status: string;
  abstract setStatus(): string;
}

export class Alive extends Status {
  status = 'alive';
  setStatus(): string {
    return this.status = 'dead';
  }
}

export class Dead extends Status {
  status = 'dead';
  setStatus(): string {
    return this.status = 'alive';
  }
}

In the game model as u can see below, I used conditionals to change the status

toggleCell(cellIndex: number) {
  const cell: Cell = this.cells[cellIndex];
  // if (this.cells[cellIndex].status === 'dead') {
  //     this.cells[cellIndex].status = 'alive';
  //     this.addToLivingCells(cellIndex);

  // } else {
  //     this.cells[cellIndex].status = 'dead';
  //     this.removeFromLivingCells(cellIndex);
  // }

  cell.toggleCell()
}

so what I want to do is remove the conditionals and use polymorphism to toggle the status from the dead to alive and back depending on the current status.

Let me know if the rest of the code is needed.

Thanks in advance

Body:
I think your approuch is too much complicated for such a simple case. For this case this code is enough:

export class Cell {
    private coordinates: Coordinates;
    public status: 'alive' | 'dead';

    constructor(coordinates) {
        this.coordinates = coordinates;
        this.status = 'alive';
    }

    getCoordinates(): Coordinates {
        return this.coordinates;
    }

    toggleCell(): void {
        this.status = this.status === 'alive' ? 'dead' : 'alive';
        console.log(this.status);
    }
}


问:
How to extract columns which contains lots of 0 value with R?
I have a matrix with lots of columns (more than 817.000) and 40 rows . I would like to extract the columns which contain lots of 0 (for example > 30 or 35 , no matter the number) .

That should extract several columns, and I will choose one randomnly which I will use as a reference for the rest of the matrix.

Any idea?

Edit :

```<code>              OTU0001 OTU0004 OTU0014 OTU0016 OTU0017 OTU0027 OTU0029 OTU0030
Sample_10.rare       0       0      85       0       0       0       0       0
Sample_11.rare       0      42     169       0      42     127       0      85
Sample_12.rare       0       0       0       0       0       0       0      42
Sample_13.rare     762     550    2159     127     550       0     677    1397
Sample_14.rare     847     508    2751     169    1397     169     593    1990
Sample_15.rare    1143     593    3725     677    2116     466     212    2286
Sample_16.rare    5630    5291    5291    1270    3852    1185     296    2836
</code>```

It should extract 4 columns, OTU0001 OTU0016  OTU0027 OTU0029 because they got 3 zero each. And if it is possible, I would like to extract the position of the extracted columns.

答:
You could do something like this (Where 7 is the number of relevant zeros):</p>

```<code>library(dplyr)
df <- tibble(Col1 = c(rep(0, 10), rep(1, 10)),
                     Col2 = c(rep(0,5), rep(1, 15)),
                     Col3 = c(rep(0,15), rep(1, 5)))

y <- df %>%
      select_if(function(col) length(which(col==0)) > 7)
</code>```

Body:
I have a matrix with lots of columns (more than 817.000) and 40 rows . I would like to extract the columns which contain lots of 0 (for example > 30 or 35 , no matter the number) .

That should extract several columns, and I will choose one randomnly which I will use as a reference for the rest of the matrix.

Any idea?

Edit :

              OTU0001 OTU0004 OTU0014 OTU0016 OTU0017 OTU0027 OTU0029 OTU0030
Sample_10.rare       0       0      85       0       0       0       0       0
Sample_11.rare       0      42     169       0      42     127       0      85
Sample_12.rare       0       0       0       0       0       0       0      42
Sample_13.rare     762     550    2159     127     550       0     677    1397
Sample_14.rare     847     508    2751     169    1397     169     593    1990
Sample_15.rare    1143     593    3725     677    2116     466     212    2286
Sample_16.rare    5630    5291    5291    1270    3852    1185     296    2836

It should extract 4 columns, OTU0001 OTU0016  OTU0027 OTU0029 because they got 3 zero each. And if it is possible, I would like to extract the position of the extracted columns.

Body:
You could do something like this (Where 7 is the number of relevant zeros):

library(dplyr)
df <- tibble(Col1 = c(rep(0, 10), rep(1, 10)),
                     Col2 = c(rep(0,5), rep(1, 15)),
                     Col3 = c(rep(0,15), rep(1, 5)))

y <- df %>%
      select_if(function(col) length(which(col==0)) > 7)


问:
How do I find the name of soccer players with same first name but different surnames?
I need to find the names of players from soccer team A that have the same first name but different surname as players from soccer team B. I need to produce the full names of all players from Team A, not just 'John'. I am able to use an additional column with Player IDs unique across all teams.

Basically table looks like this:

```<code>FirstName  LastName     Team
John       Snow         A
Batman     Dies         B
John       Dies         B
</code>```

I can produce a list of Team A names with the same first name as Team B players.

```<code>SELECT firstname, lastname FROM table
</code>```

Even though surname can't be used for one entry, it should be considered for other entries.

答:
Try the following:</p>

```<code>select distinct t1.FirstName
from
(
SELECT firstname, lastname FROM @t where Team = 'A'
) as t1
inner join
(
SELECT firstname, lastname FROM @t where Team = 'B'
) as t2
on (t1.FirstName = t2.FirstName)
where t1.LastName <> t2.LastName
</code>```

Body:
I need to find the names of players from soccer team A that have the same first name but different surname as players from soccer team B. I need to produce the full names of all players from Team A, not just 'John'. I am able to use an additional column with Player IDs unique across all teams.

Basically table looks like this:

FirstName  LastName     Team
John       Snow         A
Batman     Dies         B
John       Dies         B

I can produce a list of Team A names with the same first name as Team B players.

SELECT firstname, lastname FROM table

Even though surname can't be used for one entry, it should be considered for other entries.

Body:
Try the following:

select distinct t1.FirstName
from
(
SELECT firstname, lastname FROM @t where Team = 'A'
) as t1
inner join
(
SELECT firstname, lastname FROM @t where Team = 'B'
) as t2
on (t1.FirstName = t2.FirstName)
where t1.LastName <> t2.LastName


问:
How to set "-aspectpath" for the FreeFair AspectJ Gradle Plugin?
I am trying to use an AspectJ Annotation that is in a Library, that I am pulling into my project. My project uses Gradle, so I am attempting to use FreeFair AspectJ Gradle Plugin.

I need to be able to set the AspectJ -aspectpath argument, to the Library Dependency that Gradle is pulling in.

FreeFair, does not seem to have much Documentation, mainly just Sample Code.

In their sample code, I see that I can use this to set the -aspectpath to a local "project":

```<code>aspect project(":aspectj:aspect")
</code>```

Does anyone know how to set the -aspectpath to an external library dependency?

I created an example Project and put it on GitHub: freefair-aspectpath-external-library.

Note: I am using io.freefair.gradle:aspectj-plugin version 2.9.5 because my project is stuck using Gradle version 4.10.3.

Update: I have created a bug for this: https://github.com/freefair/gradle-plugins/issues/46

答:
Thanks to @larsgrefer, who provided the answer in the GitHub Issue (46).

For the io.freefair.aspectj.compile-time-weaving plugin 2.9.5 the configuration is named "aspects" instead of "aspect".

The following fixed the issue:

```<code>aspects project(":aspectj:aspect")
</code>```

The full build file resembles:

```<code>buildscript {
    repositories {
        maven { url "https://plugins.gradle.org/m2/" }
    }
    dependencies {
        // 2.9.5 for use with Gradle 4.10.3.
        classpath "io.freefair.gradle:aspectj-plugin:2.9.5"
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'

apply plugin: "io.freefair.aspectj.compile-time-weaving"
aspectj.version = '1.9.3'

group 'xyz.swatt'
version '1.0.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {

    ///// SWATT ///// https://mvnrepository.com/artifact/xyz.swatt/swatt
    compile group: 'xyz.swatt', name: 'swatt', version: '1.12.0'
    aspect "xyz.swatt:swatt:1.12.0"
}
</code>```

Body:
I am trying to use an AspectJ Annotation that is in a Library, that I am pulling into my project. My project uses Gradle, so I am attempting to use FreeFair AspectJ Gradle Plugin.

I need to be able to set the AspectJ -aspectpath argument, to the Library Dependency that Gradle is pulling in.

FreeFair, does not seem to have much Documentation, mainly just Sample Code.

In their sample code, I see that I can use this to set the -aspectpath to a local "project":

aspect project(":aspectj:aspect")

Does anyone know how to set the -aspectpath to an external library dependency?

I created an example Project and put it on GitHub: freefair-aspectpath-external-library.

Note: I am using io.freefair.gradle:aspectj-plugin version 2.9.5 because my project is stuck using Gradle version 4.10.3.

Update: I have created a bug for this: https://github.com/freefair/gradle-plugins/issues/46

Body:
Thanks to @larsgrefer, who provided the answer in the GitHub Issue (46).

For the io.freefair.aspectj.compile-time-weaving plugin 2.9.5 the configuration is named "aspects" instead of "aspect".

The following fixed the issue:

aspects project(":aspectj:aspect")

The full build file resembles:

buildscript {
    repositories {
        maven { url "https://plugins.gradle.org/m2/" }
    }
    dependencies {
        // 2.9.5 for use with Gradle 4.10.3.
        classpath "io.freefair.gradle:aspectj-plugin:2.9.5"
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'

apply plugin: "io.freefair.aspectj.compile-time-weaving"
aspectj.version = '1.9.3'

group 'xyz.swatt'
version '1.0.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {

    ///// SWATT ///// https://mvnrepository.com/artifact/xyz.swatt/swatt
    compile group: 'xyz.swatt', name: 'swatt', version: '1.12.0'
    aspect "xyz.swatt:swatt:1.12.0"
}


问:
Is a synchronous void method with Func<Task> or Func<Task<T>> arguments practically useful?
I am teaching async-await keyword to my friends and up to now I gave them some examples as follows.

```<code>static async Task Do(Func<Task> job)
{
    // some algorithm depends on job parameter.
    await job();
}
</code>```

I think this example is practically useful in many scenarios.

Question

Is there any usefulness of having void methods with arguments of type Func<Task> or Func<Task<T>>? As far as I think, it does make sense for this kind of method to exist because blocking asynchronous methods are not recommended. Any comments are always welcome!

答:
Is there any usefulness of having void methods with arguments of type Func<Task> or Func<Task<T>>?

Yes. It would be a method that synchronously does something with that delegate. It would not execute the delegate directly.

One example that comes to mind is a kind of Add method for a queue of asynchronous work to do. The delegate would be executed elsewhere, in the "queue runner" code. Adding a delegate to the queue would be a synchronous operation, even though the delegate itself is asynchronous. Here's an example.

Body:
I am teaching async-await keyword to my friends and up to now I gave them some examples as follows.

static async Task Do(Func<Task> job)
{
    // some algorithm depends on job parameter.
    await job();
}

I think this example is practically useful in many scenarios.

Question

Is there any usefulness of having void methods with arguments of type Func<Task> or Func<Task<T>>? As far as I think, it does make sense for this kind of method to exist because blocking asynchronous methods are not recommended. Any comments are always welcome!


问:
How to configure two or multiple routes in an Apache reverse proxy setup
I inherited an reverse proxy setup that is part of an Apache SSL termination EC2 instance stack (with ALBs and DNS). The Apache server and its configurations are baked from rpm spec files that are built into RPMs that are deployed on the server during its creation or update.
I currently have a mapping that routes requests to a domain name or hostname to a private (not on public internet) backend API. I have static assets in S3 that consume this API and my requirement is to also configure routing from a user friendly domain name to this S3 bucket, then, hopefully, make this backend S3 url private.

Swapping the API's backend url with the S3's url, I have been able to route from the public domain to the S3 bucket. However, I am not sure how I can have both routes in place with the same origin or domain name as I have to consume the API from the S3 bucket with certificate verification of the users accessing these resources.

This system is like a black box and I do not currently have access to the logs. In the code below, I have added the S3_URL and /visualizer/ mappings to the original API mapping. The API mapping is working but the S3_URL is not working when combined together.

```<code>#!/bin/bash

set -eu -o pipefail

API_URL=$(cat $1 | jq -r '.configuration.API_URL')
echo $API_URL

S3_URL=$(cat $1 | jq -r '.configuration.S3_URL')
echo $S3_URL

cat > /etc/httpd/conf.d/coy-httpd-includes/https_vhost/proxypass.inc <<EOF
ProxyRequests Off
SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyMachineCertificateFile /etc/pki/tls/private/client_crt_rsa.pem

<Proxy *>
    Require all granted
</Proxy>

ProxyPass / ${API_URL} retry=\${CLOUD_HTTPS_PROXY_RETRY} keepalive=\${CLOUD_HTTPS_PROXY_KEEPALIVE} nocanon
ProxyPassReverse / ${API_URL}

ProxyPass /visualizer/ ${S3_URL} retry=\${CLOUD_HTTPS_PROXY_RETRY} keepalive=\${CLOUD_HTTPS_PROXY_KEEPALIVE} nocanon
ProxyPassReverse /visualizer/ ${S3_URL}
EOF

cat > /etc/httpd/conf.d/coy-httpd-includes/http_vhost/elb_health_check_proxypass.inc <<'CONFIG'
RewriteEngine on
RewriteRule / /var/www/cgi-bin/status
<Directory /var/www/cgi-bin>
  Options +ExecCGI
  SetHandler cgi-script
</Directory>
CONFIG
</code>```

答:
After hours of searching the internet for a solution and learning a bit more about Apache and similar servers like Nginx, I was able to find a solution.

I added a Location directive that mapped a path on the public reverse proxy's hostname that triggered the proxying of the traffic to the static resources in the S3 buckets URL in the backend such that I can access https://app.test.api.coy.co.uk/visualizer/visualize-graph.html. It still raised another question of how to block directory browsing except for this particular html page.

This is what my apache config looks like after applying the solution:

```<code>#!/bin/bash

set -eu -o pipefail

API_URL=$(cat $1 | jq -r '.configuration.API_URL')
echo $API_URL

S3_URL=$(cat $1 | jq -r '.configuration.S3_URL')
echo $S3_URL

cat > /etc/httpd/conf.d/coy-httpd-includes/https_vhost/proxypass.inc <<EOF
ProxyRequests Off
SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyMachineCertificateFile /etc/pki/tls/private/client_crt_rsa.pem

<Proxy *>
    Require all granted
</Proxy>

ProxyPass / ${API_URL} retry=\${CLOUD_HTTPS_PROXY_RETRY} keepalive=\${CLOUD_HTTPS_PROXY_KEEPALIVE} nocanon
ProxyPassReverse / ${API_URL}

<Location /visualizer/ >
  ProxyPreserveHost Off
  ProxyPass ${S3_URL} retry=\${CLOUD_HTTPS_PROXY_RETRY} keepalive=\${CLOUD_HTTPS_PROXY_KEEPALIVE} nocanon
  ProxyPassReverse ${S3_URL}
</Location>
EOF

cat > /etc/httpd/conf.d/coy-httpd-includes/http_vhost/elb_health_check_proxypass.inc <<'CONFIG'
RewriteEngine on
RewriteRule / /var/www/cgi-bin/status
<Directory /var/www/cgi-bin>
  Options +ExecCGI
  SetHandler cgi-script
</Directory>
CONFIG
</code>```

These resources helped me in reaching my solution:
Getting 404 for S3 static website JS behind Apache proxy,
https://www.jamescoyle.net/how-to/116-simple-apache-reverse-proxy-example, and
https://serverfault.com/questions/120488/redirect-url-within-apache-virtualhost

Body:
I inherited an reverse proxy setup that is part of an Apache SSL termination EC2 instance stack (with ALBs and DNS). The Apache server and its configurations are baked from rpm spec files that are built into RPMs that are deployed on the server during its creation or update.
I currently have a mapping that routes requests to a domain name or hostname to a private (not on public internet) backend API. I have static assets in S3 that consume this API and my requirement is to also configure routing from a user friendly domain name to this S3 bucket, then, hopefully, make this backend S3 url private.

Swapping the API's backend url with the S3's url, I have been able to route from the public domain to the S3 bucket. However, I am not sure how I can have both routes in place with the same origin or domain name as I have to consume the API from the S3 bucket with certificate verification of the users accessing these resources.

This system is like a black box and I do not currently have access to the logs. In the code below, I have added the S3_URL and /visualizer/ mappings to the original API mapping. The API mapping is working but the S3_URL is not working when combined together.

#!/bin/bash

set -eu -o pipefail

API_URL=$(cat $1 | jq -r '.configuration.API_URL')
echo $API_URL

S3_URL=$(cat $1 | jq -r '.configuration.S3_URL')
echo $S3_URL

cat > /etc/httpd/conf.d/coy-httpd-includes/https_vhost/proxypass.inc <<EOF
ProxyRequests Off
SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyMachineCertificateFile /etc/pki/tls/private/client_crt_rsa.pem

<Proxy *>
    Require all granted
</Proxy>

ProxyPass / ${API_URL} retry=\${CLOUD_HTTPS_PROXY_RETRY} keepalive=\${CLOUD_HTTPS_PROXY_KEEPALIVE} nocanon
ProxyPassReverse / ${API_URL}

ProxyPass /visualizer/ ${S3_URL} retry=\${CLOUD_HTTPS_PROXY_RETRY} keepalive=\${CLOUD_HTTPS_PROXY_KEEPALIVE} nocanon
ProxyPassReverse /visualizer/ ${S3_URL}
EOF

cat > /etc/httpd/conf.d/coy-httpd-includes/http_vhost/elb_health_check_proxypass.inc <<'CONFIG'
RewriteEngine on
RewriteRule / /var/www/cgi-bin/status
<Directory /var/www/cgi-bin>
  Options +ExecCGI
  SetHandler cgi-script
</Directory>
CONFIG

Body:
After hours of searching the internet for a solution and learning a bit more about Apache and similar servers like Nginx, I was able to find a solution.

I added a Location directive that mapped a path on the public reverse proxy's hostname that triggered the proxying of the traffic to the static resources in the S3 buckets URL in the backend such that I can access https://app.test.api.coy.co.uk/visualizer/visualize-graph.html. It still raised another question of how to block directory browsing except for this particular html page.

This is what my apache config looks like after applying the solution:

#!/bin/bash

set -eu -o pipefail

API_URL=$(cat $1 | jq -r '.configuration.API_URL')
echo $API_URL

S3_URL=$(cat $1 | jq -r '.configuration.S3_URL')
echo $S3_URL

cat > /etc/httpd/conf.d/coy-httpd-includes/https_vhost/proxypass.inc <<EOF
ProxyRequests Off
SSLProxyEngine on
SSLProxyVerify none
SSLProxyCheckPeerCN off
SSLProxyCheckPeerName off
SSLProxyMachineCertificateFile /etc/pki/tls/private/client_crt_rsa.pem

<Proxy *>
    Require all granted
</Proxy>

ProxyPass / ${API_URL} retry=\${CLOUD_HTTPS_PROXY_RETRY} keepalive=\${CLOUD_HTTPS_PROXY_KEEPALIVE} nocanon
ProxyPassReverse / ${API_URL}

<Location /visualizer/ >
  ProxyPreserveHost Off
  ProxyPass ${S3_URL} retry=\${CLOUD_HTTPS_PROXY_RETRY} keepalive=\${CLOUD_HTTPS_PROXY_KEEPALIVE} nocanon
  ProxyPassReverse ${S3_URL}
</Location>
EOF

cat > /etc/httpd/conf.d/coy-httpd-includes/http_vhost/elb_health_check_proxypass.inc <<'CONFIG'
RewriteEngine on
RewriteRule / /var/www/cgi-bin/status
<Directory /var/www/cgi-bin>
  Options +ExecCGI
  SetHandler cgi-script
</Directory>
CONFIG

These resources helped me in reaching my solution:
Getting 404 for S3 static website JS behind Apache proxy,
https://www.jamescoyle.net/how-to/116-simple-apache-reverse-proxy-example, and
https://serverfault.com/questions/120488/redirect-url-within-apache-virtualhost


问:
Module not found: Can't resolve 'react '
I am following a tutorial and all of a sudden I am getting this error. I have tried all the solution I could find but no success

./src/Components/Views/Dashboard/Notification.js
Module not found: Can't resolve 'react ' in 'C:\Users....\Dashboard'

I have tried these solutions :
How to fix "Module not found: Can't resolve 'react'"?

https://github.com/facebook/create-react-app/issues/2534

Dashboard.js

```<code>  import React, { Component} from 'react'
  import Notifications from './Notification'
  import ProjectList from '../Projects/ProjectList'

   class Dashboard extends Component {
     render() {
        return(
               <div className="dasboard container">
                    <div className="row">
                          <div className="col s12 m6">
                                <ProjectList />
                          </div>
                          <div className="col s12 m5 offset-m1">
                                <Notifications />

                          </div>
                    </div>
              </div>
             )
       }
   }
</code>```

Notification.js

```<code>  import React from 'react '

  const Notifications = () => {
    return(
          <div className="container">
                <p>Nostifications</p>
          </div>
      )
   }

   export default Notifications
</code>```

答:
this might not help but you have a few typos. I'm not sure if its just from posting it on SO but try this

Dashboard.js

```<code>  import React, { Component} from 'react'
  import Notifications from './Notification' // Notification that you're importing isnt the same as the import name - Notifications from Notifications not Notification
  import ProjectList from '../Projects/ProjectList'

   class Dashboard extends Component {
     render() {
        return(
               <div className="dasboard container">
                    <div className="row">
                          <div className="col s12 m6">
                                <ProjectList />
                          </div>
                          <div className="col s12 m5 offset-m1">
                                <Notifications />

                          </div>
                    </div>
              </div>
             )
       }
   }
</code>```

Notification.js

```<code>import React from 'react ' // <- there is a space here after the react import try taking it out

  const Notifications = () => {
    return(
          <div className="container">
                <p>Nostifications</p>
          </div>
      )
   }

   export default Notifications
</code>```

Body:
I am following a tutorial and all of a sudden I am getting this error. I have tried all the solution I could find but no success

./src/Components/Views/Dashboard/Notification.js
Module not found: Can't resolve 'react ' in 'C:\Users....\Dashboard'

I have tried these solutions :
How to fix "Module not found: Can't resolve 'react'"?

https://github.com/facebook/create-react-app/issues/2534

Dashboard.js

  import React, { Component} from 'react'
  import Notifications from './Notification'
  import ProjectList from '../Projects/ProjectList'

   class Dashboard extends Component {
     render() {
        return(

                                <ProjectList />

                                <Notifications />

             )
       }
   }

Notification.js

  import React from 'react '

  const Notifications = () => {
    return(

Nostifications

      )
   }

   export default Notifications

Body:
this might not help but you have a few typos. I'm not sure if its just from posting it on SO but try this

Dashboard.js

  import React, { Component} from 'react'
  import Notifications from './Notification' // Notification that you're importing isnt the same as the import name - Notifications from Notifications not Notification
  import ProjectList from '../Projects/ProjectList'

   class Dashboard extends Component {
     render() {
        return(
               <div className="dasboard container">
                    <div className="row">
                          <div className="col s12 m6">
                                <ProjectList />
                          </div>
                          <div className="col s12 m5 offset-m1">
                                <Notifications />

                          </div>
                    </div>
              </div>
             )
       }
   }

Notification.js

import React from 'react ' // <- there is a space here after the react import try taking it out

  const Notifications = () => {
    return(
          <div className="container">
                <p>Nostifications</p>
          </div>
      )
   }

   export default Notifications


问:
How to flag items with repeated names and with condition its value less than 20?
Problem

How to return "True" for the repeated items and with both values less than 20?

```<code>=COUNTIF(A:A, A1)>1
</code>```

I am able to detect repeated items, but not sure how to combine another condition.

Expected Results

答:
Use AND() if you want to check multiple true/false statements.

=AND( COUNTIF(A:A, A2)>1,  B2<20)

Body:
Problem

How to return "True" for the repeated items and with both values less than 20?

=COUNTIF(A:A, A1)>1

I am able to detect repeated items, but not sure how to combine another condition.

Expected Results


问:
Python Tkinter DnD2 root = TkinterDnD.Tk() Unable to load tkdnd library
I installed TkDnD as instructed here: How to Install and Use TkDnD with Python 2.7 Tkinter on OSX?

Mainly i followed this advice:

On Windows:

1) Copy the tkdnd2.8 directory to C:\Python27\tcl

2) Copy the TkinterDnD2 directory to C:\Python27\Lib\site-packages

I am using anaconda so I copied it into my environments directories (C:\ProgramData\Anaconda3\envs\gui)

And yet when i try to run this code:

```<code>import sys
if sys.version_info[0] == 2:
    from Tkinter import *
else:
    from tkinter import *
from TkinterDnD2 import *

def drop(event):
    entry_sv.set(event.data)

root = TkinterDnD.Tk()
entry_sv = StringVar()
entry_sv.set('Drop Here...')
entry = Entry(root, textvar=entry_sv, width=80)
entry.pack(fill=X, padx=10, pady=10)
entry.drop_target_register(DND_FILES)
entry.dnd_bind('<<Drop>>', drop)
root.mainloop()
</code>```

I get this error

```<code>Exception has occurred: RuntimeError
Unable to load tkdnd library.
  File "drag_and_drop_GUI.py", line 10, in <module>
    root = TkinterDnD.Tk()
</code>```

Thinking it's a problem with anaconda I installed TkDnD in my system Python too (no virtual environments) but the issue still persists.
Any ideas ?

答: Try installing the tkdnd binary matching your python installation (64 bit or 32 bit).</p>

Body:
I installed TkDnD as instructed here: How to Install and Use TkDnD with Python 2.7 Tkinter on OSX?

Mainly i followed this advice:

On Windows:

1) Copy the tkdnd2.8 directory to C:\Python27\tcl

2) Copy the TkinterDnD2 directory to C:\Python27\Lib\site-packages

I am using anaconda so I copied it into my environments directories (C:\ProgramData\Anaconda3\envs\gui)

And yet when i try to run this code:

import sys
if sys.version_info[0] == 2:
    from Tkinter import *
else:
    from tkinter import *
from TkinterDnD2 import *

def drop(event):
    entry_sv.set(event.data)

root = TkinterDnD.Tk()
entry_sv = StringVar()
entry_sv.set('Drop Here...')
entry = Entry(root, textvar=entry_sv, width=80)
entry.pack(fill=X, padx=10, pady=10)
entry.drop_target_register(DND_FILES)
entry.dnd_bind('<<Drop>>', drop)
root.mainloop()

I get this error

Exception has occurred: RuntimeError
Unable to load tkdnd library.
  File "drag_and_drop_GUI.py", line 10, in <module>
    root = TkinterDnD.Tk()

Thinking it's a problem with anaconda I installed TkDnD in my system Python too (no virtual environments) but the issue still persists.
Any ideas ?


问:
SELECT only row where all other activity are completed
I have a table with column called , ID,Activity,Activity_type,Activity Status.

Here activity status 11 = Completed, 12 = Incomplete.

Each ID is associated with activity type call1,call2,email1,email2 and text1. I only want to query all the ID with activity Text1 with "Activity Status"=12  when all other "Activity Status" related to that ID = 11.

In the example I would like to get output of Text1 with ID 10 as ID 11 still has email 2 with activity status 12. Any help on this is much appreciated.

答:
You can use group by and having:

```<code>select id
from t
group by id
having sum(case when activity = 'Text1' and activity_status = 12 then 1 else 0 end) > 0 and
       sum(case when activity <> 'Text1' and activity_status <> 11 then 1 else 0 end) = 0;
</code>```

Body:
You can use group by and having:

select id
from t
group by id
having sum(case when activity = 'Text1' and activity_status = 12 then 1 else 0 end) > 0 and
       sum(case when activity <> 'Text1' and activity_status <> 11 then 1 else 0 end) = 0;


问:
how to create a button that links to textfile/excel sheet/url (EXTJS)?
I need to create a button that links to textfile/excel sheet/url.How to do the same in EXTJS ? Can anyone help me with the code ?</p>

答:
I use the Ext.LinkButton (an extension you have to add your self) made by Animal and it works very well.

It uses an HTML  element so it acts as a normal link. I have had some troubles with wombleton's solution, because the browser might ask the user if it is okay to open this popup - due to the use of JavaScript methods.

You can also see the reference from a previous question here on href="http://www.stackoverflow.com">stackoverflow.

Body:
I use the Ext.LinkButton (an extension you have to add your self) made by Animal and it works very well.

It uses an HTML <a href...> element so it acts as a normal link. I have had some troubles with wombleton's solution, because the browser might ask the user if it is okay to open this popup - due to the use of JavaScript methods.

You can also see the reference from a previous question here on stackoverflow.


问:
Are these examples correct or the tutorial has an error?
I am reading this tutorial and I am not sure that I understand correctly the text (or that it is correct at whole). There is an example:

The following predicates are valid because they encode modus ponens:
  if you know that a implies b and you know that a is true, then it must
  be the case that b is also true:

```<code>{-@ ex6 :: Bool -> Bool -> TRUE @-}
ex6 a b = (a && (a ==> b)) ==> b

{-@ ex7 :: Bool -> Bool -> TRUE @-}
ex7 a b = a ==> (a ==> b) ==> b
</code>```

and ex6 is fine, but ex7 is not, it fails for a = false and b = false. And LH repot it as:

```<code>Error: Liquid Type Mismatch

 88 | ex7 a b = a ==> (a ==> b) ==> b
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

   Inferred type
     VV : {v : GHC.Types.Bool | v <=> ((a => (a => b)) => b)}

   not a subtype of Required type
     VV : {VV : GHC.Types.Bool | VV}

   In Context
     a : GHC.Types.Bool

     b : GHC.Types.Bool
</code>```

Also I don't understand their definition of the implication: "You should read p ==> q as if p is true then q must also be true". It does not sound correctly, because it asserts only one case: T -> T = T. What do I miss here? May be tutorial has error in "ex7"?

答:
I suspect in the example, they have made (==>) right associative, while in your tests you left it at the default, which is left associative. Compare:

```<code>> infixl 9 ==>; False ==> x = True; True ==> x = x
> False ==> (False ==> False) ==> False
False
> infixr 9 ==>; False ==> x = True; True ==> x = x
> False ==> (False ==> False) ==> False
True
</code>```

The Report has further details.

Body:
I am reading this tutorial and I am not sure that I understand correctly the text (or that it is correct at whole). There is an example:

The following predicates are valid because they encode modus ponens:
  if you know that a implies b and you know that a is true, then it must
  be the case that b is also true:

{-@ ex6 :: Bool -> Bool -> TRUE @-}
ex6 a b = (a && (a ==> b)) ==> b

{-@ ex7 :: Bool -> Bool -> TRUE @-}
ex7 a b = a ==> (a ==> b) ==> b

and ex6 is fine, but ex7 is not, it fails for a = false and b = false. And LH repot it as:

Error: Liquid Type Mismatch

 88 | ex7 a b = a ==> (a ==> b) ==> b
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

   Inferred type
     VV : {v : GHC.Types.Bool | v <=> ((a => (a => b)) => b)}

   not a subtype of Required type
     VV : {VV : GHC.Types.Bool | VV}

   In Context
     a : GHC.Types.Bool

     b : GHC.Types.Bool

Also I don't understand their definition of the implication: "You should read p ==> q as if p is true then q must also be true". It does not sound correctly, because it asserts only one case: T -> T = T. What do I miss here? May be tutorial has error in "ex7"?

Body:
I suspect in the example, they have made (==>) right associative, while in your tests you left it at the default, which is left associative. Compare:

> infixl 9 ==>; False ==> x = True; True ==> x = x
> False ==> (False ==> False) ==> False
False
> infixr 9 ==>; False ==> x = True; True ==> x = x
> False ==> (False ==> False) ==> False
True

The Report has further details.


问:
Concatenate string in typescript/javascript
EDIT: This string is a part of json and i am writing it onto a file. In that json file i see the escape charaters. With console.log, I don't see any escape character.

I am trying to concatenate a string such that I get the following output:

```<code>"OR("1admin", "2admin")"
</code>```

But the output I keep on getting is

```<code>"OR(\"1admin\", \"2admin\")"
</code>```

Sample code

var str = "OR("
for (let i = 1; i < 3; i++) {
  str += '"' + i + 'admin' + '", ';
}
str = str.trim().substring(0, str.length - 2).concat(')')
console.log(str)```
</div>
</div>
</p>

<p>I have tried using regex and string split.
eg.</p>

<p><code>.replace(/'/g, '"')</code> This when i tried something like this <code>"'" + i + "admin" + "', "</code> and tried to replace <code>'</code> with <code>"</code></p>

```.split('\\').join('').trim() This also didn' work.
```

What am I doing wrong?

答:
This seems to do the job:

```<code>const NUM_ADMINS = 2;
const CONCAT_STRING =
 `OR(${
   Array(NUM_ADMINS)
   .fill()
   .map((_, idx) => `"${idx + 1}admin"`)
   .join(", ")})`;

</code>```

It creates a new array with the needed number of admins, then maps it to strings in th form "admin", joins with a comma and a space. And then it it is all wrapped in a "OR()" string.

Body:
EDIT: This string is a part of json and i am writing it onto a file. In that json file i see the escape charaters. With console.log, I don't see any escape character.

I am trying to concatenate a string such that I get the following output:

"OR("1admin", "2admin")"

But the output I keep on getting is

"OR(\"1admin\", \"2admin\")"

Sample code

var str = "OR("
for (let i = 1; i < 3; i++) {
  str += '"' + i + 'admin' + '", ';
}
str = str.trim().substring(0, str.length - 2).concat(')')
console.log(str)

I have tried using regex and string split.
eg.

.replace(/'/g, '"') This when i tried something like this "'" + i + "admin" + "', " and tried to replace ' with "

.split('\\').join('').trim() This also didn' work.

What am I doing wrong?

Body:
This seems to do the job:

const NUM_ADMINS = 2;
const CONCAT_STRING =
 `OR(${
   Array(NUM_ADMINS)
   .fill()
   .map((_, idx) => `"${idx + 1}admin"`)
   .join(", ")})`;

It creates a new array with the needed number of admins, then maps it to strings in th form "admin", joins with a comma and a space. And then it it is all wrapped in a "OR()" string.


问:
How to get the index of the checkbox list
I need to loop through the checkbox list. I searched the web and found some code. However I still have a problem - the alert only shows the first time and the index is 0. I referenced this question.

```<code><tr>
  <td>Language:</td>
  <td>
    <asp:checkboxlist runat="server" ID="chk" cssClass="chkClass"></asp:checkboxlist>
    <asp:HiddenField ID="hd" runat="server" />
  </td>
</tr>
</code>```

function setcheckbox() {
  $('.chkClass').each(function (i, obj) {
    alert(i);
    if (i == 2) {
      this.prop('checked', true);
    }
  });
}
```

答:
<asp:CheckBoxList cssClass="myClass"> renders as
. Therefore, you're not looping through the items, you're looping through the (single)
.

Try adding input[type=checkbox] to your selector, specifying that you're looking for the checkboxes within the
.

```<code>function setcheckbox() {
  $('.chkClass input[type=checkbox]').each(function (i, obj) {
    alert(i);
    if (i == 2) {
      this.prop('checked', true);
    }
  });
}
</code>```

Body:
I need to loop through the checkbox list. I searched the web and found some code. However I still have a problem - the alert only shows the first time and the index is 0. I referenced this question.

  Language:

    <asp:checkboxlist runat="server" ID="chk" cssClass="chkClass"></asp:checkboxlist>
    <asp:HiddenField ID="hd" runat="server" />

function setcheckbox() {
  $('.chkClass').each(function (i, obj) {
    alert(i);
    if (i == 2) {
      this.prop('checked', true);
    }
  });
}

Body:
<asp:CheckBoxList cssClass="myClass"> renders as <ul class="myClass">. Therefore, you're not looping through the items, you're looping through the (single) <ul>.

Try adding input[type=checkbox] to your selector, specifying that you're looking for the checkboxes within the <ul>.

function setcheckbox() {
  $('.chkClass input[type=checkbox]').each(function (i, obj) {
    alert(i);
    if (i == 2) {
      this.prop('checked', true);
    }
  });
}


问:
How to encapsulate a request manager in Angular7 using httpClient?
I'm new to Angular, and I am using the httpClient like this:

 public getFocusAreaDataWithHttpClient() {

    this.http.get(Api.focusAreaApi).subscribe({
      next(response) {
        console.log("httpClient handle data");
        console.dir(response);
      },
      error(err) {
        console.error("Error: " + err);
      },
      complete() {
        console.log("Completed");
      }
    });
  }
```

<p>I want to encapsulate a service (apiManager.service)to provide a public method then other service can use it to fetch data(need to pass apiurl), what I expect is like this:</p>

```export class ApiManager {
  constructor(private http: HttpClient) {}
// define request header , content-Type , auth token ,and some common config here
// and there should be 2 method - get and post

}
```

<p>and other service can use it like:</p>

```
apiManager.get(apiurl,parameters).subscript...
apiManager.post(apiurl,parameters).subscript...

```

but I have no idea for how to encapsulate it , I'm appreciate if anyone can give me some demo to show how to encapsulate a manager class to provide data fetch function.

答:
In Angular this type of activity is done through services.

If you use the Angular CLI (which you should definitely use), just type ng generate service api-manager in the terminal and it will create all the boilerplate for you.

Body:
I'm new to Angular, and I am using the httpClient like this:

 public getFocusAreaDataWithHttpClient() {

    this.http.get(Api.focusAreaApi).subscribe({
      next(response) {
        console.log("httpClient handle data");
        console.dir(response);
      },
      error(err) {
        console.error("Error: " + err);
      },
      complete() {
        console.log("Completed");
      }
    });
  }

I want to encapsulate a service (apiManager.service)to provide a public method then other service can use it to fetch data(need to pass apiurl), what I expect is like this:

export class ApiManager {
  constructor(private http: HttpClient) {}
// define request header , content-Type , auth token ,and some common config here
// and there should be 2 method - get and post

}

and other service can use it like:

apiManager.get(apiurl,parameters).subscript...
apiManager.post(apiurl,parameters).subscript...

but I have no idea for how to encapsulate it , I'm appreciate if anyone can give me some demo to show how to encapsulate a manager class to provide data fetch function.


问:
ListBox showing one property in different rows
I am using the following code for binding ListBox to a list i.e. List and set the binding Path=Name. But the list box shows just the one name with letter divided in rows. Like if a Name is JOHN, the list box row 1 shows "J", row 2 shows "O", row 3 shows "H", row 4 shows "N". Here's the code.

Xaml

```<code><ListBox Height="Auto" ItemsSource="{Binding Path=Name}" HorizontalAlignment="Stretch" Margin="0,80,0,0" Name="ledgerListView" VerticalAlignment="Stretch" Width="200" KeyDown="ledgerListView_KeyDown" MouseDoubleClick="ledgerListView_MouseDoubleClick" IsSynchronizedWithCurrentItem="True" />
</code>```

Code-Behind

```<code>List<Ledgers> ledgers = new List<Ledgers>();
        ledgers = DAL_Ledgers.LoadLedgers();
        this.DataContext = ledgers;
</code>```

答: Also, you might want to use an ObservableList, otherwise changes in ledgers won't be taken into account.</p>

Body:
I am using the following code for binding ListBox to a list i.e. List and set the binding Path=Name. But the list box shows just the one name with letter divided in rows. Like if a Name is JOHN, the list box row 1 shows "J", row 2 shows "O", row 3 shows "H", row 4 shows "N". Here's the code.

Xaml

<ListBox Height="Auto" ItemsSource="{Binding Path=Name}" HorizontalAlignment="Stretch" Margin="0,80,0,0" Name="ledgerListView" VerticalAlignment="Stretch" Width="200" KeyDown="ledgerListView_KeyDown" MouseDoubleClick="ledgerListView_MouseDoubleClick" IsSynchronizedWithCurrentItem="True" />

Code-Behind

List<Ledgers> ledgers = new List<Ledgers>();
        ledgers = DAL_Ledgers.LoadLedgers();
        this.DataContext = ledgers;


问:
Lazy initialization / memoization without volatile
It appears the Java Memory Model does not define "refreshing" and "flushing" of the local cache, instead people only call it that way for simplicity, but actually the "happens-before" relationship implies refreshing and flushing somehow (would be great if you can explain that, but not directly part of the question).

This is getting me really confused combined with the fact that the section about the Java Memory Model in the JLS is not written in a way which makes it easy to understand.

Therefore could you please tell me if the assumptions I made in the following code are correct and if it is therefore guaranteed to run correctly?

It is partially based on the code provided in the Wikipedia article on Double-checked locking, however there the author used a wrapper class (FinalWrapper), but the reason for this is not entirely obvious to me. Maybe to support null values?

```<code>public class Memoized<T> {
    private T value;
    private volatile boolean _volatile;
    private final Supplier<T> supplier;

    public Memoized(Supplier<T> supplier) {
        this.supplier = supplier;
    }

    public T get() {
        /* Apparently have to use local variable here, otherwise return might use older value
         * see https://jeremymanson.blogspot.com/2008/12/benign-data-races-in-java.html
         */
        T tempValue = value;

        if (tempValue == null) {
            // Refresh
            if (_volatile);
            tempValue = value;

            if (tempValue == null) {
                // Entering refreshes, or have to use `if (_volatile)` again?
                synchronized (this) {
                    tempValue = value;

                    if (tempValue == null) {
                        value = tempValue = supplier.get();
                    }

                    /*
                     * Exit should flush changes
                     * "Flushing" does not actually exists, maybe have to use
                     * `_volatile = true` instead to establish happens-before?
                     */
                }
            }
        }

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

Also I have read that the constructor call can be inlined and reordered resulting in a reference to an uninitialized object (see this comment on a blog). Is it then safe to directly assign the result of the supplier or does this have to be done in two steps?

```<code>value = tempValue = supplier.get();
</code>```

Two steps:

```<code>tempValue = supplier.get();
// Reorder barrier, maybe not needed?
if (_volatile);
value = tempValue;
</code>```

Edit: The title of this question is a little bit misleading, the goal was to have reduced usage of a volatile field. If the initialized value is already in the cache of a thread, then value is directly accessed without the need to look in the main memory again.

答:
Your code is not thread safe, which can easily be shown by stripping off all irrelevant parts:

```<code>public class Memoized<T> {
    private T value;
    // irrelevant parts omitted

    public T get() {
        T tempValue = value;

        if (tempValue == null) {
            // irrelevant parts omitted
        }

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

So value has no volatile modifier and you’re reading it within the get() method without synchronization and when non-null, proceed using it without any synchronization.

This code path alone is already making the code broken, regardless of what you are doing when assigning value, as all thread safe constructs require both ends, reading and writing sides, to use a compatible synchronization mechanism.

The fact that you are using esoteric constructs like if (_volatile); becomes irrelevant then, as the code is already broken.

The reason why the Wikipedia example uses a wrapper with a final field is that immutable objects using only final fields are immune to data races and hence, the only construct that is safe when reading its reference without a synchronization action.

Note that since lambda expressions fall into the same category, you can use them to simplify the example for your use case:

```<code>public class Memoized<T> {
    private boolean initialized;
    private Supplier<T> supplier;

    public Memoized(Supplier<T> supplier) {
        this.supplier = () -> {
            synchronized(this) {
                if(!initialized) {
                    T value = supplier.get();
                    this.supplier = () -> value;
                    initialized = true;
                }
            }
            return this.supplier.get();
        };
    }

    public T get() {
        return supplier.get();
    }
}
</code>```

Here, supplier.get() within Memoized.get() may read an updated value of supplier without synchronization action, in which case it will read the correct value, because it is implicitly final. If the method reads an outdated value for the supplier reference, it will end up at the synchronized(this) block which uses the initialized flag to determine whether the evaluation of the original supplier is necessary.

Since the initialized field will only be accessed within the synchronized(this) block, it will always evaluate to the correct value. This block will be executed at most once for every thread, whereas only the first one will evaluate get() on the original supplier. Afterwards, each thread will use the () -> value supplier, returning the value without needing any synchronization actions.

Body:
It appears the Java Memory Model does not define "refreshing" and "flushing" of the local cache, instead people only call it that way for simplicity, but actually the "happens-before" relationship implies refreshing and flushing somehow (would be great if you can explain that, but not directly part of the question).

This is getting me really confused combined with the fact that the section about the Java Memory Model in the JLS is not written in a way which makes it easy to understand.

Therefore could you please tell me if the assumptions I made in the following code are correct and if it is therefore guaranteed to run correctly?

It is partially based on the code provided in the Wikipedia article on Double-checked locking, however there the author used a wrapper class (FinalWrapper), but the reason for this is not entirely obvious to me. Maybe to support null values?

public class Memoized<T> {
    private T value;
    private volatile boolean _volatile;
    private final Supplier<T> supplier;

    public Memoized(Supplier<T> supplier) {
        this.supplier = supplier;
    }

    public T get() {
        /* Apparently have to use local variable here, otherwise return might use older value
         * see https://jeremymanson.blogspot.com/2008/12/benign-data-races-in-java.html
         */
        T tempValue = value;

        if (tempValue == null) {
            // Refresh
            if (_volatile);
            tempValue = value;

            if (tempValue == null) {
                // Entering refreshes, or have to use `if (_volatile)` again?
                synchronized (this) {
                    tempValue = value;

                    if (tempValue == null) {
                        value = tempValue = supplier.get();
                    }

                    /*
                     * Exit should flush changes
                     * "Flushing" does not actually exists, maybe have to use
                     * `_volatile = true` instead to establish happens-before?
                     */
                }
            }
        }

        return tempValue;
    }
}

Also I have read that the constructor call can be inlined and reordered resulting in a reference to an uninitialized object (see this comment on a blog). Is it then safe to directly assign the result of the supplier or does this have to be done in two steps?

value = tempValue = supplier.get();

Two steps:

tempValue = supplier.get();
// Reorder barrier, maybe not needed?
if (_volatile);
value = tempValue;

Edit: The title of this question is a little bit misleading, the goal was to have reduced usage of a volatile field. If the initialized value is already in the cache of a thread, then value is directly accessed without the need to look in the main memory again.

Body:
Your code is not thread safe, which can easily be shown by stripping off all irrelevant parts:

public class Memoized<T> {
    private T value;
    // irrelevant parts omitted

    public T get() {
        T tempValue = value;

        if (tempValue == null) {
            // irrelevant parts omitted
        }

        return tempValue;
    }
}

So value has no volatile modifier and you’re reading it within the get() method without synchronization and when non-null, proceed using it without any synchronization.

This code path alone is already making the code broken, regardless of what you are doing when assigning value, as all thread safe constructs require both ends, reading and writing sides, to use a compatible synchronization mechanism.

The fact that you are using esoteric constructs like if (_volatile); becomes irrelevant then, as the code is already broken.

The reason why the Wikipedia example uses a wrapper with a final field is that immutable objects using only final fields are immune to data races and hence, the only construct that is safe when reading its reference without a synchronization action.

Note that since lambda expressions fall into the same category, you can use them to simplify the example for your use case:

public class Memoized<T> {
    private boolean initialized;
    private Supplier<T> supplier;

    public Memoized(Supplier<T> supplier) {
        this.supplier = () -> {
            synchronized(this) {
                if(!initialized) {
                    T value = supplier.get();
                    this.supplier = () -> value;
                    initialized = true;
                }
            }
            return this.supplier.get();
        };
    }

    public T get() {
        return supplier.get();
    }
}

Here, supplier.get() within Memoized.get() may read an updated value of supplier without synchronization action, in which case it will read the correct value, because it is implicitly final. If the method reads an outdated value for the supplier reference, it will end up at the synchronized(this) block which uses the initialized flag to determine whether the evaluation of the original supplier is necessary.

Since the initialized field will only be accessed within the synchronized(this) block, it will always evaluate to the correct value. This block will be executed at most once for every thread, whereas only the first one will evaluate get() on the original supplier. Afterwards, each thread will use the () -> value supplier, returning the value without needing any synchronization actions.


问:
Can I somehow use nested functions in ANSI C?
I have background with high level languages, such as Java/Kotlin/Scala. Now I need to create a C library, but it's pretty hard for me to work without closures.

There is the nice extension in GCC, called "nested functions", that (if I correctly understood) is exactly what I need. Also the Apple "blocks" extension looks interesting. But I need a code, that will work with any compiler.

Does any existing solution present? I've seen some projects, that allow generating C code: https://github.com/dbohdan/compilers-targeting-c. But I really don't need another language, just one feature - closures. (I think that it hard to maintain completely different language and result C code will be not optimized).

UPD
Some explanation, why do I need closures.

Let say we have some function, connect(void (*on_failed_callback)());. It manages a connection in some way, and when the connection is lost, it calls the callback. And it takes 0 arguments, but I want to create some function that will bring some data with callback. If I've correctly understood, the most common used solution is to pass the callback with some arg connect(void (*on_failed_callback)(void *callback_arg), void* arg);. But it leads to a boilerplate code, that can be fixed by nested functions.

So next code:

```<code>void connect(void (*on_failed_callback)(void* arg), void* arg) {
    ...
    on_failed_callback(arg);
}

void print_error(char* error) {
    printf(error);
}

void main() {
    char *msg = "Failed connection";
    ...
    connect(print_error, msg);
}
</code>```

Can be simplified to next:

```<code>void connect(void (*on_failed_callback)()) {
    ...
    on_failed_callback();
}

void print_error(char* error) {
    printf(error);
}

void main() {
    char* msg = "Failed connection";
    ...
    void callback() {
       print_error(msg);
    }
    connect(callback);
}
</code>```

I mean, I want some tool/app, that analyzes my code with closures/nested functions and generates pure ANSI C code.

答:
For the specific example you have asked about there is an approach with C that achieves something similar to a closure in that it packages a function pointer with the data needed to be used with the function.

```<code>typedef struct {
    char sBuff[128];              // data for the function to use
    void (* func) (char* error);  // pointer to function to execute
} ErrorMsg;

void connect(ErrorMsg myMsg) {
    ...
    myMsg.func(myMsg.sBuff);  // call the function with the packaged data
}

// the function that we will be encapsulating with the data to be
// used.
void print_error(char* error) {
    printf(error);
}

void main() {
    ErrorMsg msg = {"Failed connection", print_error} ;
    …
    connect(msg);  // invoke our function package and its data.
}
</code>```

And if at the time that the function package is used, you would like to add additional data, you could do so along the lines of the following.

```<code>typedef struct {
    char sBuff[128];              // packaged data for the function to use
    void (* func) (char* error, int iExtra);  // pointer to function to execute
} ErrorMsg;

void connect(ErrorMsg myMsg) {
    ...
    myMsg.func(myMsg.sBuff, errno);  // call the function with the packaged data and extra info
}

// the function that we will be encapsulating with the data to be
// used.
void print_error(char* error, int iExtra) {
    printf(error, iExtra);
}

void main() {
    ErrorMsg msg = {"Failed connection: errno %d", print_error} ;
    …
    connect(msg);  // invoke our function package and its data.
}
</code>```

Body:
I have background with high level languages, such as Java/Kotlin/Scala. Now I need to create a C library, but it's pretty hard for me to work without closures.

There is the nice extension in GCC, called "nested functions", that (if I correctly understood) is exactly what I need. Also the Apple "blocks" extension looks interesting. But I need a code, that will work with any compiler.

Does any existing solution present? I've seen some projects, that allow generating C code: https://github.com/dbohdan/compilers-targeting-c. But I really don't need another language, just one feature - closures. (I think that it hard to maintain completely different language and result C code will be not optimized).

UPD
Some explanation, why do I need closures.

Let say we have some function, connect(void (*on_failed_callback)());. It manages a connection in some way, and when the connection is lost, it calls the callback. And it takes 0 arguments, but I want to create some function that will bring some data with callback. If I've correctly understood, the most common used solution is to pass the callback with some arg connect(void (*on_failed_callback)(void *callback_arg), void* arg);. But it leads to a boilerplate code, that can be fixed by nested functions.

So next code:

void connect(void (*on_failed_callback)(void* arg), void* arg) {
    ...
    on_failed_callback(arg);
}

void print_error(char* error) {
    printf(error);
}

void main() {
    char *msg = "Failed connection";
    ...
    connect(print_error, msg);
}

Can be simplified to next:

void connect(void (*on_failed_callback)()) {
    ...
    on_failed_callback();
}

void print_error(char* error) {
    printf(error);
}

void main() {
    char* msg = "Failed connection";
    ...
    void callback() {
       print_error(msg);
    }
    connect(callback);
}

I mean, I want some tool/app, that analyzes my code with closures/nested functions and generates pure ANSI C code.

Body:
For the specific example you have asked about there is an approach with C that achieves something similar to a closure in that it packages a function pointer with the data needed to be used with the function.

typedef struct {
    char sBuff[128];              // data for the function to use
    void (* func) (char* error);  // pointer to function to execute
} ErrorMsg;

void connect(ErrorMsg myMsg) {
    ...
    myMsg.func(myMsg.sBuff);  // call the function with the packaged data
}

// the function that we will be encapsulating with the data to be
// used.
void print_error(char* error) {
    printf(error);
}

void main() {
    ErrorMsg msg = {"Failed connection", print_error} ;
    …
    connect(msg);  // invoke our function package and its data.
}

And if at the time that the function package is used, you would like to add additional data, you could do so along the lines of the following.

typedef struct {
    char sBuff[128];              // packaged data for the function to use
    void (* func) (char* error, int iExtra);  // pointer to function to execute
} ErrorMsg;

void connect(ErrorMsg myMsg) {
    ...
    myMsg.func(myMsg.sBuff, errno);  // call the function with the packaged data and extra info
}

// the function that we will be encapsulating with the data to be
// used.
void print_error(char* error, int iExtra) {
    printf(error, iExtra);
}

void main() {
    ErrorMsg msg = {"Failed connection: errno %d", print_error} ;
    …
    connect(msg);  // invoke our function package and its data.
}


问:
Wordpress plugin for course registration
I'm building a WordPress Page for course registration. All I want the plugin to do is send the filled in form details to my email ID and send an email to the user that he/she has successfully registered for the course. I don't need users to signup with username and password.

I've tried my luck with WP Forms but it only seems to have the option to forward the email to me and not the user.

Any suggestion on which plugin I should use?

答:
As @Hughes mentioned, you cant use wpcf7, and just hook on it to insert custom post on every query.</p>

```<code>// Hook on wpcf7
add_filter( 'wpcf7_mail_components', 'do_on_cf7_submit', 50, 2 );
function do_on_cf7_submit($mail_params, $form = null) {
    // Empty post content
    $content = '';

    // set post content if field not empty
    if ($_POST['field-name'] != '') {
        $content .= 'Field Name Label: '.$_POST['field-name'] ;
    }

    // insert post if content not epmty
    if ($content != '')  {
        insertQueryPost($_POST['email'], $content);
    }

    // allow cf7 to do his stuff
    return $mail_params;
}

// insert custom post type "query", don't forget to setup your custom post type first
function insertQueryPost($title, $content) {
    // insted of proper post slug, just make a hashed slug, when setting custom post type, set it to not public and not search-able
    $t = time();
    $thash = md5($t);

    $my_query = array(
        'post_title'    => wp_strip_all_tags( $title ),
        'post_content'  => $content,
        'post_type' => 'query',
        'post_name' => $thash,
        'post_status'   => 'publish',
        'post_author'   => 1
    );
    $data = wp_insert_post( $my_query );
}
</code>```

Body:
As @Hughes mentioned, you cant use wpcf7, and just hook on it to insert custom post on every query.

// Hook on wpcf7
add_filter( 'wpcf7_mail_components', 'do_on_cf7_submit', 50, 2 );
function do_on_cf7_submit($mail_params, $form = null) {
    // Empty post content
    $content = '';

    // set post content if field not empty
    if ($_POST['field-name'] != '') {
        $content .= 'Field Name Label: '.$_POST['field-name'] ;
    }

    // insert post if content not epmty
    if ($content != '')  {
        insertQueryPost($_POST['email'], $content);
    }

    // allow cf7 to do his stuff
    return $mail_params;
}

// insert custom post type "query", don't forget to setup your custom post type first
function insertQueryPost($title, $content) {
    // insted of proper post slug, just make a hashed slug, when setting custom post type, set it to not public and not search-able
    $t = time();
    $thash = md5($t);

    $my_query = array(
        'post_title'    => wp_strip_all_tags( $title ),
        'post_content'  => $content,
        'post_type' => 'query',
        'post_name' => $thash,
        'post_status'   => 'publish',
        'post_author'   => 1
    );
    $data = wp_insert_post( $my_query );
}