问:
how to show a category of woocommerce products
How can I display the products of a category in my woocommerce theme ?

I'm going to design a woocommerce template and I want it in it display the products of a category .

For example : T-shirt category or ... .

答:
Code taken from Woo's github https://github.com/woocommerce/woocommerce/blob/master/templates/single-product/meta.php </p>

```<code>global $product
echo wc_get_product_category_list( $product->get_id(), ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', count( $product->get_category_ids() ), 'woocommerce' ) . ' ', '</span>' ); ?>
</code>```

Body:
Code taken from Woo's github https://github.com/woocommerce/woocommerce/blob/master/templates/single-product/meta.php

global $product
echo wc_get_product_category_list( $product->get_id(), ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', count( $product->get_category_ids() ), 'woocommerce' ) . ' ', '</span>' ); ?>


来源: stackexchange

问:
Is there an easy way to break a name column into Title, First, Middle, Last?
I am currently working on an excel file that has the person's entire name and title in one cell, obviously this is a bad idea as far as data validation goes. I am wondering if there is a a way in VBA or Excel to break the column into 4.

The name column follows the format: Last name, Title(if they have one) First Name Middle Name (or initial).

This makes it really tricky since I can't just separate by column. Any help is greatly appreciated!

答:
given some text in cell A1 then in cell B1 enter the formula

```<code>  LEFT(A1,FIND(" ",A1))
</code>```

and in C1 enter

```<code> RIGHT(A1,LEN(A1)-LEN(B1))
</code>```

Copy B1:C1 to D1:E1

Now copy B1:E1 down to the end of the names in column A

ContentLicense: CC BY-SA 3.0

Body:
given some text in cell A1 then in cell B1 enter the formula

  LEFT(A1,FIND(" ",A1))

and in C1 enter

 RIGHT(A1,LEN(A1)-LEN(B1))

Copy B1:C1 to D1:E1

Now copy B1:E1 down to the end of the names in column A


问:
How to use between operator with case statement in SQL Server 2005
How to use BETWEEN operator with CASE statement

```<code>@FromEmpAge
@ToempAge

select * from Emp
where EmpAge between
  case when ToempAge0 then @FromEmpAge and @ToempAge end
</code>```

How to do this?

答:
I'm not sure about what you mean with ToEmpAge0. Anyway, marc_s has answered your question on how to use CASE statement within a BETWEEN operator, that will work if you put a proper literal value after the WHEN.
You can also use the CASE statement for the second operand of the BETWEEN operator.

I will assume that ToEmpAge is a column of INT:

```<code>SELECT
    (list of columns)
FROM
    dbo.Emp
WHERE
    EmpAge BETWEEN
       CASE ToEmpAge
          WHEN 0 THEN @FromEmpAge
          WHEN 1 THEN @FromEmpAge+10 --or whatever
       END
    AND
       CASE ToEmpAge
          WHEN 0 THEN @ToEmpAge
          WHEN 1 THEN @ToEmpAge+5
       END
</code>```

ContentLicense: CC BY-SA 2.5

Body:
How to use BETWEEN operator with CASE statement

@FromEmpAge
@ToempAge

select * from Emp
where EmpAge between
  case when ToempAge0 then @FromEmpAge and @ToempAge end

How to do this?

Body:
I'm not sure about what you mean with ToEmpAge0. Anyway, marc_s has answered your question on how to use CASE statement within a BETWEEN operator, that will work if you put a proper literal value after the WHEN.
You can also use the CASE statement for the second operand of the BETWEEN operator.

I will assume that ToEmpAge is a column of INT:

SELECT
    (list of columns)
FROM
    dbo.Emp
WHERE
    EmpAge BETWEEN
       CASE ToEmpAge
          WHEN 0 THEN @FromEmpAge
          WHEN 1 THEN @FromEmpAge+10 --or whatever
       END
    AND
       CASE ToEmpAge
          WHEN 0 THEN @ToEmpAge
          WHEN 1 THEN @ToEmpAge+5
       END


问:
PIL remove colour mixing between colour regions
I have images with very few colours in them. (5 different colours max, and all are quite distinct.)

At the boundaries of the regions between colours, there is a (usually single pixel wide) line of a mix between these colours. How can I remove this?

I do manipulation with them as a numpy array afterwards anyways, so if this can be achieved with a numpy array, that works too.

For example, this image:

Which is made from this array:

```<code>image = np.append(
    np.append(np.ones((10, 10, 3)), np.ones((1, 10, 3)) / 5., axis=0),
    np.zeros((10, 10, 3)), axis=0
)

# Or a 10 * 10 white (0, 0, 0) region with a 1 * 10 line of (0.2, 0.2, 0.2) pixels
# underneath and a 10 * 10 black (1, 1, 1) region underneath that.

# Expected result:
expected = np.append(np.ones((10, 10, 3)), np.zeros((11, 10, 3)), axis=0)
</code>```

I would like a function that converts that 1 * 10 line of grey pixels into black, as it is closer to black.

答: You can use Image.quantize to force all colors to match your palette. This changes the mode of your image to P, convert it back to RGB when you're done.

Body:
I have images with very few colours in them. (5 different colours max, and all are quite distinct.)

At the boundaries of the regions between colours, there is a (usually single pixel wide) line of a mix between these colours. How can I remove this?

I do manipulation with them as a numpy array afterwards anyways, so if this can be achieved with a numpy array, that works too.

For example, this image:

Which is made from this array:

image = np.append(
    np.append(np.ones((10, 10, 3)), np.ones((1, 10, 3)) / 5., axis=0),
    np.zeros((10, 10, 3)), axis=0
)

# Or a 10 * 10 white (0, 0, 0) region with a 1 * 10 line of (0.2, 0.2, 0.2) pixels
# underneath and a 10 * 10 black (1, 1, 1) region underneath that.

# Expected result:
expected = np.append(np.ones((10, 10, 3)), np.zeros((11, 10, 3)), axis=0)

I would like a function that converts that 1 * 10 line of grey pixels into black, as it is closer to black.


问:
Using constexpr in a namespace with static_assert is giving error
I have declared the following in header file.

```<code>namespace G1
{
    inline namespace V1
    {
        constexpr float getV();
    }
}
</code>```

In CPP file, I have defined the getV function as

```<code>constexpr float G1::V1::getV()
{
    return 0.1f;
}
</code>```

In the main I am using static_assert to compare the version as shown.

```<code>int main()
{
    static_assert( G1::getV() == 1.0f, "Error"); // Please Ignore the way I am comparing the floats
    return 0;
}
</code>```

But when I compile the code, I am getting expression did not evaluate to a constant.

Am I doing anything wrong here? I am using VS2015.
Thanks in advance

答:
In practice, the C++ compilation model is 2 phase.  First you compile, then you link.

constexpr only works in the compile phase.  There is no requirement that compilers can fold constexpr function bodies into call sites when doing so would require link-time constexpr evaluation.

So when you fail to provide a body for your constexpr function, anyone that cannot see that body will not evaluate it at compile time, but rather wait until runtime.

constexpr doesn't mean "will be run at compile time", but rather "could be run at compile time in some situations".

Body:
I have declared the following in header file.

namespace G1
{
    inline namespace V1
    {
        constexpr float getV();
    }
}

In CPP file, I have defined the getV function as

constexpr float G1::V1::getV()
{
    return 0.1f;
}

In the main I am using static_assert to compare the version as shown.

int main()
{
    static_assert( G1::getV() == 1.0f, "Error"); // Please Ignore the way I am comparing the floats
    return 0;
}

But when I compile the code, I am getting expression did not evaluate to a constant.

Am I doing anything wrong here? I am using VS2015.
Thanks in advance


问:
Reading extensionattribute1 ro extensionattribute15 in AzureAd ClaimsPrincipal
How can I request more claims from the AzureAd server to populate my ASPNET Core Application..?

I'm trying to get claims coming through with AzureAd.
We have extensionattribute1 to extensionattribute15 defined in our onprem, and it's being synced. Yet I can't get them when I study the Claims collection in the ClaimsPrincipal object...

I've set the OpenIdConnectOptions with GetClaimsFromUserInfoEndpoint to true

I tried changing the manifest, but when trying to do so I can't save them (getting error like´Failed to update application AspNetCoreWebApplicationWithAzureAd. Error details: Request_BadRequest´). Additionally I also have no idea or haven't found documentation on what those values are (string / bool / array of strings)

```<code>"groupMembershipClaims": null,
"optionalClaims": null,
"acceptMappedClaims": null,
</code>```

答:
I've been trying to get this working using the steps in this link: https://learn.microsoft.com/en-us/azure/active-directory/active-directory-claims-mapping. The "Example claims mapping policies" section and the comments have some useful info.

So far I've got about half the claims I've mapped to come over during a login via AzureAD. I'm working with Microsoft support to figure out why its not fully working.

If I can get it going I'll post a fuller series of steps to save someone else the pain in the future! But hopefully this gets you going in the meantime.

PS: I had to set "acceptMappedClaims" to true in the application manifest which hasn't been mentioned in any of the articles I've read.

Body:
How can I request more claims from the AzureAd server to populate my ASPNET Core Application..?

I'm trying to get claims coming through with AzureAd.
We have extensionattribute1 to extensionattribute15 defined in our onprem, and it's being synced. Yet I can't get them when I study the Claims collection in the ClaimsPrincipal object...

I've set the OpenIdConnectOptions with GetClaimsFromUserInfoEndpoint to true

I tried changing the manifest, but when trying to do so I can't save them (getting error like´Failed to update application AspNetCoreWebApplicationWithAzureAd. Error details: Request_BadRequest´). Additionally I also have no idea or haven't found documentation on what those values are (string / bool / array of strings)

"groupMembershipClaims": null,
"optionalClaims": null,
"acceptMappedClaims": null,


问:
Print one more parameter with va_args
I have a function which implements a custom variant of printf.
Does anyone have a clue how I can print out one more parameter with va_list? My format is like "%d some text %s". I need a, to be printed as first parameter.

```<code>void func (int a, char *fmt, ...) {
    va_list ap;
    va_start (ap, fmt);
    // vprintf(stdout, fmt, a, ap) //Can't do like this :(
    vfprintf(fmt, a, ap);          //Or like this :(
    va_end(ap);
}
</code>```

答:
Based on previous answer to parse format, I've found a simple solution (if %d is always first):

```<code> void func (int a, char *fmt, ...) {
    char *new_format = malloc(10*sizeof(char));
    snprintf(new_format, 10, "%d", a);
    strcat(new_format, (fmt+2));
    va_list ap;
    va_start (ap, fmt);
    vprintf(stdout, new_format, ap);
    va_end(ap);
}
</code>```

Special Thanks to Jonathan Leffler

Title: Print one more parameter with va_args

Body:
I have a function which implements a custom variant of printf.
Does anyone have a clue how I can print out one more parameter with va_list? My format is like "%d some text %s". I need a, to be printed as first parameter.

void func (int a, char *fmt, ...) {
    va_list ap;
    va_start (ap, fmt);
    // vprintf(stdout, fmt, a, ap) //Can't do like this :(
    vfprintf(fmt, a, ap);          //Or like this :(
    va_end(ap);
}

Body:
Based on previous answer to parse format, I've found a simple solution (if %d is always first):

 void func (int a, char *fmt, ...) {
    char *new_format = malloc(10*sizeof(char));
    snprintf(new_format, 10, "%d", a);
    strcat(new_format, (fmt+2));
    va_list ap;
    va_start (ap, fmt);
    vprintf(stdout, new_format, ap);
    va_end(ap);
}

Special Thanks to Jonathan Leffler


问:
Azure VM, able to RDP even when not assigned to a NSG - ARM Model
I have added a new VM to a Subnet that has no NSG assigned to. I have a NSG where I have added rules to allow 3389 (RDP) port, but I did not associate this NSG to either the Subnet or the VM n/w interface. But still I am able to RDP into it and am also being able to reach the web server. Basically n/w traffic to port 80 and 3389 is going through.

How come this can happen, when there is no NSG assigned. Does n/w interface of the VM allow this traffic by default? If so where can I find the allowed rules and how can I restrich such a traffic?

答:
Yes, with no NSG around nothing is being blocked (imagine NSG is a firewall, what happens when there is NO firewall?).

Attach the NSG and it will work as you expect it.


问:
How to use threading to call a repetitive process in .NET?
In my website, I need to do a repetitive task which should not affect the main activity and performance of the website.

So I think I need to use threading. I am new into threading in .Net. How to use threading is .NET?

Any tutorials or reference to any article would be a great help.

答:
Here is a great tutorial on how to do multi-threaded applications in .NET a simple way to get work done on another thread is to use a BackgroundWorker.

When working with heavy tasks on other threads over the web, you might want to initiate the request using Ajax and then "poll" for answers.

There's an article over at MSDN: Use Threads and Build Asynchronous Handlers in Your Server-Side Web Code, it's a bit old but I think you can get a basic understanding by reading it.

ContentLicense: CC BY-SA 4.0


问:
woocommerce shop single product image not shown
I have tried the solution from a couple of posts, but none of them are working:

here is the link to the woocommerce single product page
https://happyukgo.com/product/aptamilfirstmilk/

It used to work until I upgrade woocommerce, theme, and wordpress (I don't know which one causes this).

any hints will be appreciated. thanks

答:
Finally, i found out it is the following function that removes the feature image display:

```<code>function my_post_image_html( $html, $post_id, $post_image_id ) {
  if(is_single()) {
    return '';
  }
  return $html;
}

add_filter( 'post_thumbnail_html', 'my_post_image_html', 10, 3 );
</code>```

Removing that from the functions.php brings back the image.

Body:
Finally, i found out it is the following function that removes the feature image display:

function my_post_image_html( $html, $post_id, $post_image_id ) {
  if(is_single()) {
    return '';
  }
  return $html;
}

add_filter( 'post_thumbnail_html', 'my_post_image_html', 10, 3 );

Removing that from the functions.php brings back the image.


问:
Django ImageField save to locations
I'm able to upload photos to the media folder just fine. My problem is I can't save them to a specific folder on upload. I want the image to be saved in a unique folder based on an id being passed into the django view. Below is the code that throws the following error:

views.py", line 90, in orderdetails
      settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image)
  TypeError: coercing to Unicode: need string or buffer, InMemoryUploadedFile found

```<code>if request.method == 'POST':
    # Loop through our files in the files list uploaded
    if not os.path.exists(settings.MEDIA_ROOT + '/orders/' + str(orderid)):
        os.makedirs(settings.MEDIA_ROOT + '/orders/' + str(orderid))
    for image in request.FILES.getlist('files[]'):
        # Create a new entry in our database
        new_image = UploadedImages(client_order=client, image=image.name)
        # Save the image using the model's ImageField settings
        filename, ext = os.path.splitext(image.name)
        new_image.image.save("%s-%s%s" % (filename, datetime.datetime.now(), ext),
                             settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image)
        new_image.save()
</code>```

If i just use image it saves just find in the media folder. Which is the code below. I know I set a folder inside my model with upload_to. Even with that I'm unsure how to set it to a folder based off of the ordierid.

```<code>if request.method == 'POST':
    # Loop through our files in the files list uploaded
    if not os.path.exists(settings.MEDIA_ROOT + '/orders/' + str(orderid)):
        os.makedirs(settings.MEDIA_ROOT + '/orders/' + str(orderid))
    for image in request.FILES.getlist('files[]'):
        # Create a new entry in our database
        new_image = UploadedImages(client_order=client, image=image.name)
        # Save the image using the model's ImageField settings
        filename, ext = os.path.splitext(image.name)
        new_image.image.save("%s-%s%s" % (filename, datetime.datetime.now(), ext), image)
        new_image.save()
</code>```

答:
After a night of searching I was able to find a fix. I had to define the Upload path with a dynamic function then set the upload_to to that function.

```<code>def image_upload_path(instance, filename):
    return settings.MEDIA_ROOT + '/orders/{0}/{1}'.format(instance.client_order.invoice, filename)

class UploadedImages(models.Model):
    ...
    image = models.ImageField(upload_to=image_upload_path)
</code>```

This fixed my image location being saved to the correct location.

Title: Django ImageField save to locations

Body:
I'm able to upload photos to the media folder just fine. My problem is I can't save them to a specific folder on upload. I want the image to be saved in a unique folder based on an id being passed into the django view. Below is the code that throws the following error:

views.py", line 90, in orderdetails
      settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image)
  TypeError: coercing to Unicode: need string or buffer, InMemoryUploadedFile found

if request.method == 'POST':
    # Loop through our files in the files list uploaded
    if not os.path.exists(settings.MEDIA_ROOT + '/orders/' + str(orderid)):
        os.makedirs(settings.MEDIA_ROOT + '/orders/' + str(orderid))
    for image in request.FILES.getlist('files[]'):
        # Create a new entry in our database
        new_image = UploadedImages(client_order=client, image=image.name)
        # Save the image using the model's ImageField settings
        filename, ext = os.path.splitext(image.name)
        new_image.image.save("%s-%s%s" % (filename, datetime.datetime.now(), ext),
                             settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image)
        new_image.save()

If i just use image it saves just find in the media folder. Which is the code below. I know I set a folder inside my model with upload_to. Even with that I'm unsure how to set it to a folder based off of the ordierid.

if request.method == 'POST':
    # Loop through our files in the files list uploaded
    if not os.path.exists(settings.MEDIA_ROOT + '/orders/' + str(orderid)):
        os.makedirs(settings.MEDIA_ROOT + '/orders/' + str(orderid))
    for image in request.FILES.getlist('files[]'):
        # Create a new entry in our database
        new_image = UploadedImages(client_order=client, image=image.name)
        # Save the image using the model's ImageField settings
        filename, ext = os.path.splitext(image.name)
        new_image.image.save("%s-%s%s" % (filename, datetime.datetime.now(), ext), image)
        new_image.save()

Body:
After a night of searching I was able to find a fix. I had to define the Upload path with a dynamic function then set the upload_to to that function.

def image_upload_path(instance, filename):
    return settings.MEDIA_ROOT + '/orders/{0}/{1}'.format(instance.client_order.invoice, filename)

class UploadedImages(models.Model):
    ...
    image = models.ImageField(upload_to=image_upload_path)

This fixed my image location being saved to the correct location.


问:
Calling RestAPI from java : No AuthenticationProvider found UsernamePasswordAuthenticationToken
I am just trying to call a rest api using the code below

```<code>SSLConnectionSocketFactory sslsf;
CredentialsProvider credentialsProvider;
HttpClient httpClient;

final static Logger LOGGER = Logger.getLogger(Constructor.class);

public Constructor() {
    try{
    sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault(), NoopHostnameVerifier.INSTANCE);

    credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
            ConfigData.getInstance().getSAEUsername(), ConfigData.getInstance().getSAEPassword()));
    httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(credentialsProvider)
            .build();
    }
    catch (Exception e) {
    }
}

public String callAPI() {
    String jsonResponse = "";
    try {
        String s = "111.11.11.11";
        //String s1 = "username"; // this works fine
        String s1 = "domain\username"; //AuthenticationProvider found Error
        String s2 =  "password";
        String endpoint = "https://" + s + ":3600/Xxxxxxx/Yyyyyy/Ccccccc";
        HttpGet request = new HttpGet(endpoint);
        request.addHeader("content-type", "application/json");
        request.addHeader("accept", "application/json");//

        byte[] credentials = Base64.encodeBase64(
                (s1 + ":" + s2)
                        .getBytes(StandardCharsets.UTF_8));
        String s3 = new String(credentials, StandardCharsets.UTF_8);
        request.addHeader("Authorization", "Basic " + s3);
        HttpResponse response = httpClient.execute(request);
        jsonResponse = EntityUtils.toString(response.getEntity());
        LOGGER.info("Response: " + jsonResponse);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return jsonResponse;
}
</code>```

Here if the username is just "username" (Eg: admin) the i get proper response but if the username is part of a domain like "domain\username"(Eg: DAAK\admin) then i get below error in response:

```<code><head>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/>
<title>Error 401 </title>
</head>
<body>
<h2>HTTP ERROR: 401</h2>
<p>Problem accessing /Xxxxxxx/Yyyyyy/Ccccccc. Reason:
```    No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken```</p>
<hr /><i><small>Powered by Jetty://</small></i>
</body>
</html>
</code>```

I do not know Srings framework. Is there a simple fox for this?

答:
Basic authentification consist only of username:password, you can't use the domaine here.

Why do you need to provide the domain ?

Body:
I am just trying to call a rest api using the code below

SSLConnectionSocketFactory sslsf;
CredentialsProvider credentialsProvider;
HttpClient httpClient;

final static Logger LOGGER = Logger.getLogger(Constructor.class);

public Constructor() {
    try{
    sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault(), NoopHostnameVerifier.INSTANCE);

    credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
            ConfigData.getInstance().getSAEUsername(), ConfigData.getInstance().getSAEPassword()));
    httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(credentialsProvider)
            .build();
    }
    catch (Exception e) {
    }
}

public String callAPI() {
    String jsonResponse = "";
    try {
        String s = "111.11.11.11";
        //String s1 = "username"; // this works fine
        String s1 = "domain\username"; //AuthenticationProvider found Error
        String s2 =  "password";
        String endpoint = "https://" + s + ":3600/Xxxxxxx/Yyyyyy/Ccccccc";
        HttpGet request = new HttpGet(endpoint);
        request.addHeader("content-type", "application/json");
        request.addHeader("accept", "application/json");//

        byte[] credentials = Base64.encodeBase64(
                (s1 + ":" + s2)
                        .getBytes(StandardCharsets.UTF_8));
        String s3 = new String(credentials, StandardCharsets.UTF_8);
        request.addHeader("Authorization", "Basic " + s3);
        HttpResponse response = httpClient.execute(request);
        jsonResponse = EntityUtils.toString(response.getEntity());
        LOGGER.info("Response: " + jsonResponse);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return jsonResponse;
}

Here if the username is just "username" (Eg: admin) the i get proper response but if the username is part of a domain like "domain\username"(Eg: DAAK\admin) then i get below error in response:

<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1"/>
<title>Error 401 </title>

HTTP ERROR: 401

Problem accessing /Xxxxxxx/Yyyyyy/Ccccccc. Reason:

    No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken

Powered by Jetty://

I do not know Srings framework. Is there a simple fox for this?


问:
React + Redux: undefined initial state and reducer not called as expected
I think this is pretty primitive. I'm having trouble with two things:

1.this.props.appState is undefined in the constructor. This is unexpected because in the reducer I have the initial state set to { appState: { name: "World!" } } and I was expecting this lead to initialization of the appState. So I added the if statement which I know is just a temporary fix before I find the actual issue.

2.When I click on the button and call the sendAction handler, the execution flow never reaches the reducer function!

```<code>class App extends React.Component {
  constructor(props) {
    super(props);
    if (this.props.appState) {
      this.state = { name: this.props.appState.name };
    }
    else {
      this.state = { name: "Unknown" };
    }
    this.nameChanged = this.nameChanged.bind(this);
    this.sendAction = this.sendAction.bind(this);
  }

  nameChanged(event) {
    this.setState({ name: event.target.value });
  }

  sendAction(event) {
    this.props.saveName(this.state.name);
  }

  render() {
    return (
      ```

Hello, {this.state.name}!

        <input type="text" value={this.state.name} onChange={this.nameChanged} />
        <input type="button" value="Click me!" onClick={this.sendAction} />
      ```
    );
  }
}

const appReducer = (state = { appState: { name: "World!" } }, action) => {
  debugger;
  switch (action.type) {
    case "SAVE_NAME":
      return Object.assign({}, state, { name: action.name });

    default:
      return state;
  }
};

const AppContainer = ReactRedux.connect(
  state => ({ appState: state.appState }),
  dispatch => ({
    saveName: (name) => Redux.bindActionCreators({ type: "SAVE_NAME", name }, dispatch)
  })
)(App);

const combinedReducers = Redux.combineReducers({
  appReducer
});

const store = Redux.createStore(combinedReducers);

ReactDOM.render(
  <ReactRedux.Provider store={store}>
    <AppContainer />
  </ReactRedux.Provider>,
  document.getElementsByTagName('main')[0]
);
</code>```

答:
Since your reducer is called : appReducer, you will need to access the appState property on appReducer.appState in mapStateToProps like so

```<code>const AppContainer = ReactRedux.connect(
  state => ({ appState: state.appReducer.appState }),
  dispatch => ({
    saveName: (name) => Redux.bindActionCreators({ type: "SAVE_NAME", name }, dispatch)
  })
)(App);
</code>```

For you second problem you can either do

```<code>const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    saveName: (name) => {
      dispatch({ type: "SAVE_NAME", name })
    }
  }
}
</code>```

Or have this defined like so.

```<code>const actionCreators = {
    saveName: (name) => {
       return { type: "SAVE_NAME", name }
     },
}
const mapDispatchToProps = (dispatch, ownProps) => {
  return bindActionCreators(actionCreators, dispatch);
}
</code>```

And then in connect

```<code>const AppContainer = ReactRedux.connect(
              state => ({ appState: state.appReducer.appState }),
              mapDispatchToProps,
              })
            )(App);
</code>```

Body:
I think this is pretty primitive. I'm having trouble with two things:

1.this.props.appState is undefined in the constructor. This is unexpected because in the reducer I have the initial state set to { appState: { name: "World!" } } and I was expecting this lead to initialization of the appState. So I added the if statement which I know is just a temporary fix before I find the actual issue.

2.When I click on the button and call the sendAction handler, the execution flow never reaches the reducer function!

class App extends React.Component {
  constructor(props) {
    super(props);
    if (this.props.appState) {
      this.state = { name: this.props.appState.name };
    }
    else {
      this.state = { name: "Unknown" };
    }
    this.nameChanged = this.nameChanged.bind(this);
    this.sendAction = this.sendAction.bind(this);
  }

  nameChanged(event) {
    this.setState({ name: event.target.value });
  }

  sendAction(event) {
    this.props.saveName(this.state.name);
  }

  render() {
    return (

Hello, {this.state.name}!

        <input type="text" value={this.state.name} onChange={this.nameChanged} />
        <input type="button" value="Click me!" onClick={this.sendAction} />

    );
  }
}

const appReducer = (state = { appState: { name: "World!" } }, action) => {
  debugger;
  switch (action.type) {
    case "SAVE_NAME":
      return Object.assign({}, state, { name: action.name });

    default:
      return state;
  }
};

const AppContainer = ReactRedux.connect(
  state => ({ appState: state.appState }),
  dispatch => ({
    saveName: (name) => Redux.bindActionCreators({ type: "SAVE_NAME", name }, dispatch)
  })
)(App);

const combinedReducers = Redux.combineReducers({
  appReducer
});

const store = Redux.createStore(combinedReducers);

ReactDOM.render(
  <ReactRedux.Provider store={store}>
    <AppContainer />
  </ReactRedux.Provider>,
  document.getElementsByTagName('main')[0]
);

Body:
Since your reducer is called : appReducer, you will need to access the appState property on appReducer.appState in mapStateToProps like so

const AppContainer = ReactRedux.connect(
  state => ({ appState: state.appReducer.appState }),
  dispatch => ({
    saveName: (name) => Redux.bindActionCreators({ type: "SAVE_NAME", name }, dispatch)
  })
)(App);

For you second problem you can either do

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    saveName: (name) => {
      dispatch({ type: "SAVE_NAME", name })
    }
  }
}

Or have this defined like so.

const actionCreators = {
    saveName: (name) => {
       return { type: "SAVE_NAME", name }
     },
}
const mapDispatchToProps = (dispatch, ownProps) => {
  return bindActionCreators(actionCreators, dispatch);
}

And then in connect

const AppContainer = ReactRedux.connect(
              state => ({ appState: state.appReducer.appState }),
              mapDispatchToProps,
              })
            )(App);


问:
R - Extract words with a pattern and replace them with the words in inverse order
I have the following string vector of phrases.

```<code>x <- c("I ate apples 100 already. No apples 50 uhmm" , "He has apples 20 yeah")
</code>```

And I expect the result to be:

```<code>"I ate 100 apples already. No 50 apples uhmm" , "He has 20 apples yeah"
</code>```

I want to replace de following pattern "apples \\d{1,4}" by the reverse order of the found words, in each element of the vector.

Any suggestions?

答:
We can do this with gsub to capture words as a group (\\w+) followed by space and then capture the numbers as another group, replace it with the backreference in reverse order

```<code>gsub("(\\w+)\\s+(\\d+)", "\\2 \\1", x)
#[1] "I ate 100 apples already. No 50 apples uhmm" "He has 20 apples yeah"
</code>```

Body:
I have the following string vector of phrases.

x <- c("I ate apples 100 already. No apples 50 uhmm" , "He has apples 20 yeah")

And I expect the result to be:

"I ate 100 apples already. No 50 apples uhmm" , "He has 20 apples yeah"

I want to replace de following pattern "apples \\d{1,4}" by the reverse order of the found words, in each element of the vector.

Any suggestions?

Body:
We can do this with gsub to capture words as a group (\\w+) followed by space and then capture the numbers as another group, replace it with the backreference in reverse order

gsub("(\\w+)\\s+(\\d+)", "\\2 \\1", x)
#[1] "I ate 100 apples already. No 50 apples uhmm" "He has 20 apples yeah"


问:
Swift: Simulate a pan-gesture programmatically
I have an animation which is animated with a pan-gesture. When the gesture recognizer state changes the animation proceeds (it's a rotation of a image).

Now I want to show the user in a tutorial that he has to pan/swipe up or down to animate.

Is there a way to "simulate" the translation and velocity of the pan-gesture in order to perform the animation once? The logic of the animation is based on the pan-gesture translation.

答:
There is nothing built into Cocoa Touch that does this for you, but you can build your own system.

One way to do this is to define your own UIPanGestureRecognizer subclass, RecordingPanGestureRecognizer, and build that so that it behaves like a normal gesture recognizer but also saves the timestamped history of all calls it makes on its action target. This can be done just by using the normal target-action mechanism to target two objects. You can save the call history to a file.

Then, also build a Player type that can read that recording and replay a similar set of target action events.

With this system, you can manually record a gesture and replay it later. This is approach used in the app where I work, and it works well.


问:
Doctype with goquery
Is there any possibility to retrieve document doctype with goquery?

I've tried several things, but any worked. I suppose that it is possible, because NodeName func has switch with "html.DoctypeNode" case.

That code didn't find doctype:

```<code>doc.Find("~").Each(func(_ int, item *goquery.Selection) {
    fmt.Println(goquery.NodeName(item))
})
</code>```

答: It doesn't seem like there is a reliable way to retrieve the doctype using either jQuery itself (in the web browser) or goquery on the backend.</p>

Title: Doctype with goquery

Body:
Is there any possibility to retrieve document doctype with goquery?

I've tried several things, but any worked. I suppose that it is possible, because NodeName func has switch with "html.DoctypeNode" case.

That code didn't find doctype:

doc.Find("~").Each(func(_ int, item *goquery.Selection) {
    fmt.Println(goquery.NodeName(item))
})


问:
C99 boolean data type?
What's the C99 boolean data type and how to use it?</p>

答:
Include <stdbool.h> header

```<code>#include <stdbool.h>

int main(void){
  bool b = false;
}
</code>```

Macros true and false expand to 1 and 0 respectively.

Section 7.16 Boolean type and values < stdbool.h >

1      The header <stdbool.h> deﬁnes four macros.

2      The macro

bool
  expands to _Bool.

3      The remaining three macros are suitable for use in #if preprocessing directives.  They
  are

true : which expands to the integer constant 1,

false: which expands to the integer constant 0, and

__bool_true_false_are_defined
  which expands to the integer constant 1.

4      Notwithstanding  the  provisions  of  7.1.3,  a  program  may  undeﬁne  and  perhaps  then
  redeﬁne the macros bool, true, and false.

Title: C99 boolean data type?

Body:
Include <stdbool.h> header

#include <stdbool.h>

int main(void){
  bool b = false;
}

Macros true and false expand to 1 and 0 respectively.

Section 7.16 Boolean type and values < stdbool.h >

1      The header <stdbool.h> deﬁnes four macros.

2      The macro

bool
  expands to _Bool.

3      The remaining three macros are suitable for use in #if preprocessing directives.  They
  are

true : which expands to the integer constant 1,

false: which expands to the integer constant 0, and

__bool_true_false_are_defined
  which expands to the integer constant 1.

4      Notwithstanding  the  provisions  of  7.1.3,  a  program  may  undeﬁne  and  perhaps  then
  redeﬁne the macros bool, true, and false.


问:
Mysql 5.7 Innodb Delete query very slow randomly
I have table with 5 simple fields. Total rows in table is cca 250.

When I use PHPmyAdmin with one DELETE query it is processed in 0.05 sec. (always).

Problem is that my PHP application (PDO connection) processing same query between other queries and this query is extremely slow (cca 10 sec.). And another SELECT query on table with 5 rows too (cca 1 sec.). It happened only sometimes!
Other queries (cca 100) are always OK with normal time response.

What problem should be or how to find what is the problem?

Table:

```<code>CREATE TABLE `list_ip` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`type` CHAR(20) NOT NULL DEFAULT '',
`address` CHAR(50) NOT NULL DEFAULT '',
`description` VARCHAR(50) NOT NULL DEFAULT '',
`datetime` DATETIME NOT NULL DEFAULT '1000-01-01 00:00:00',
PRIMARY KEY (`id`),
INDEX `address` (`address`),
INDEX `type` (`type`),
INDEX `datetime` (`datetime`) ) COLLATE='utf8_general_ci' ENGINE=InnoDB;
</code>```

Query:

```<code>DELETE FROM list_ip WHERE address='1.2.3.4' AND type='INT' AND datetime<='2017-12-06 08:04:30';
</code>```

As I said before table has only 250 rows. Size of table is 96Kib.
I tested also with empty table and its slow too.

答:
Wrap your query in EXPLAIN  and  see if it's running a sequential select, not using indexes.   EXPLAIN would be my first stop in determining if I have a data model problem (bad / missing indexes would be one model issue).

About EXPLAIN:  https://dev.mysql.com/doc/refman/5.7/en/explain.html

Another tool I'd recommend is running  'mytop' and looking at the server activity/load during those times when it's bogging down.    http://jeremy.zawodny.com/mysql/mytop/

Body:
I have table with 5 simple fields. Total rows in table is cca 250.

When I use PHPmyAdmin with one DELETE query it is processed in 0.05 sec. (always).

Problem is that my PHP application (PDO connection) processing same query between other queries and this query is extremely slow (cca 10 sec.). And another SELECT query on table with 5 rows too (cca 1 sec.). It happened only sometimes!
Other queries (cca 100) are always OK with normal time response.

What problem should be or how to find what is the problem?

Table:

CREATE TABLE `list_ip` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`type` CHAR(20) NOT NULL DEFAULT '',
`address` CHAR(50) NOT NULL DEFAULT '',
`description` VARCHAR(50) NOT NULL DEFAULT '',
`datetime` DATETIME NOT NULL DEFAULT '1000-01-01 00:00:00',
PRIMARY KEY (`id`),
INDEX `address` (`address`),
INDEX `type` (`type`),
INDEX `datetime` (`datetime`) ) COLLATE='utf8_general_ci' ENGINE=InnoDB;

Query:

DELETE FROM list_ip WHERE address='1.2.3.4' AND type='INT' AND datetime<='2017-12-06 08:04:30';

As I said before table has only 250 rows. Size of table is 96Kib.
I tested also with empty table and its slow too.


问:
Which information gets sent in each API request using OIDC
I'm writing an API back-end that I want to use OpenID Connect (OIDC) to secure.  I've been reading the documentation but I'm still a bit confused what process applies to each and every API request.  The Open ID Connect code flow appears to be:

Which I'm fine with, as a one-time process.  My back-end API sees an authorization code in the HTTP headers, and sends a request to the authorization server to get the id token.  Assuming this validates OK, the data requested is returned in the API response.

But assuming the same user will then be making lots of requests to this API, what happens in subsequent requests?  Is there some sort of session created in this mechanism?  Do I continue to receive the same authorization code?  Do I have to keep sending these back channel requests to the authorization server?

Or should I even output the JWT id token as a cookie?  In this way I get the self contained id token coming back in future requests, with no need of a server side session, or further round trips.

答: Typically you'd secure a (pure) API with OAuth 2.0, not OpenID Connect. The Client accessing your API should obtain an OAuth 2.0 access token and in order to do that it may choose to use OpenID Connect to obtain that token. That is all independent of the API, which will only see the access token. The API (or Resource Server in OAuth 2.0 terminology) is not depicted in your diagram.</p>


问:
Count Number of Lines of Code Older Than 1 Year
Is it possible to count the number of lines in a repository that are older than some timestamp (say, 1 year)?

CLOC seemed fine for total lines of code, but wasn't clear if I could add a where filter and the below post was a bit confusingly written.

POST: Count the number of lines of code changed between time periods

答: I guess you could do a blame of each file showing the date of each line as seconds since UNIX epoch (--date=raw) and then you can know if it's more than one year old.</p>


问:
Python paramiko elliptic curve
i'm using python 2.7.12 on a ubuntu16.04
trying to use the Paramiko package ( just need remote ssh command execution)

my code is

```<code>   import paramiko

    host = "random_host"
    ssh = paramiko.SSHCLient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host)
</code>```

and the error i get is:

```<code>crypthography.exceptions.UnsupportedAlgorithm: this backend does not support this elliptic curve.
</code>```

please help

and if there is a better alternative for just remote ssh commands , do tell ( i tried fabric but it still fails when i try to connect)

答:
problem here

1) u are using host in double quotes

Try below code with IP first ,instead of host and let us know if it works

```<code>import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.26',port=22,username='root',password='default')
</code>```

Title: Python paramiko elliptic curve

Body:
i'm using python 2.7.12 on a ubuntu16.04
trying to use the Paramiko package ( just need remote ssh command execution)

my code is

   import paramiko

    host = "random_host"
    ssh = paramiko.SSHCLient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host)

and the error i get is:

crypthography.exceptions.UnsupportedAlgorithm: this backend does not support this elliptic curve.

please help

and if there is a better alternative for just remote ssh commands , do tell ( i tried fabric but it still fails when i try to connect)

Body:
problem here

1) u are using host in double quotes

Try below code with IP first ,instead of host and let us know if it works

import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.1.26',port=22,username='root',password='default')


问:
How to logout a user from the database with flask-login
I have a web application made with python/flask, and I use flask-login to authenticate users. In the user interface a user can logout. But the user can also be logged out by the database (when a session expires, or when the user expires).

My user loader looks like this:

```<code>@login_manager.user_loader
def user_loader(id):
    user = SessionUser.find_by_session_id(id) #hits the database
    if user is None:
        flash('You have been automatically logged out')
        #flask_login.logout_user() #RecursionError: maximum recursion depth exceeded
        session['user_id'] = None
    return user
</code>```

When the database can't find the id, I want the user to be logged out. Reasons are: there is no need to hit the SessionUser.find_by_session_id-call more than once if an id can't be found. Also, I want show a message the user has been logged out (and I only want to show this once). Finally, when a user is logged out of the database, I want to user the unauthenticated templates.

If I don't have the if user is None: code, the user loader it hit with every request. There are two problems with this:

I can't flash the message "You have been automatically logged out" (because it will keep on showing)

There is an unnecessary database hit.

I fixed this by clearing the session-variable user_id, but this is an unwanted solution, since it users the internals of flask_login, not an API.

What would be the best approach?

答:
Like @Sraw said, don't manually logout users from user_loader. That should only return the user for given id or None:

```<code>@login_manager.user_loader
def user_loader(user_id):
    return SessionUser.find_by_session_id(user_id)  # hits the database
</code>```

The above answers your quesion:

When the database can't find the id, I want the user to be logged out.

Now, to answer your second question:

I want show a message the user has been logged out (and I only want to
  show this once)

Here's the ways a user can be logged out:

user_id is not in your database (the user was deleted)

user_id is not in the user's browser cookie session (has not logged in yet, or cleared their cookies)

You called flask_login.logout_user, which removes user_id from session

Here's a working mini-app that flashes a message when the user is logged out:

```<code>from flask import current_app as app, flash, redirect, render_template, session
from flask_login import login_manager, login_required, logout_user

@login_manager.user_loader
def user_loader(user_id):
    return SessionUser.find_by_session_id(user_id)

@app.route('/logout')
@login_required
def logout():
    logout_user()
    if session.get('was_once_logged_in'):
        # prevent flashing automatically logged out message
        del session['was_once_logged_in']
    flash('You have successfully logged yourself out.')
    return redirect('/login')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if app.current_user.is_authenticated:  # already logged in
        return redirect('/home')
    if request.method == 'POST':
        user = SessionUser.find_by_session_id(request.data['user_id'])
        if user:
            login_user(user)
            session['was_once_logged_in'] = True
            return redirect('/home')
        flash('That user was not found in the database.')
    if session.get('was_once_logged_in'):
        flash('You have been automatically logged out.')
        del session['was_once_logged_in']
    return render_template('/login.html')

@app.route('/home')
@login_required
def home():
    return 'You are logged in as {0}.'.format(app.current_user.id)
</code>```

Contents of login.html:

```<code>{% with messages = get_flashed_messages() %}
  {% if messages %}
    <ul class=flashes>
    {% for message in messages %}
      <li>{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}

<form method="post">
  User ID: <input type="text" name="user_id" /><br />
  <button type="submit">Login</button>
</form>
</code>```

Body:
I have a web application made with python/flask, and I use flask-login to authenticate users. In the user interface a user can logout. But the user can also be logged out by the database (when a session expires, or when the user expires).

My user loader looks like this:

@login_manager.user_loader
def user_loader(id):
    user = SessionUser.find_by_session_id(id) #hits the database
    if user is None:
        flash('You have been automatically logged out')
        #flask_login.logout_user() #RecursionError: maximum recursion depth exceeded
        session['user_id'] = None
    return user

When the database can't find the id, I want the user to be logged out. Reasons are: there is no need to hit the SessionUser.find_by_session_id-call more than once if an id can't be found. Also, I want show a message the user has been logged out (and I only want to show this once). Finally, when a user is logged out of the database, I want to user the unauthenticated templates.

If I don't have the if user is None: code, the user loader it hit with every request. There are two problems with this:

I can't flash the message "You have been automatically logged out" (because it will keep on showing)

There is an unnecessary database hit.

I fixed this by clearing the session-variable user_id, but this is an unwanted solution, since it users the internals of flask_login, not an API.

What would be the best approach?

Body:
Like @Sraw said, don't manually logout users from user_loader. That should only return the user for given id or None:

@login_manager.user_loader
def user_loader(user_id):
    return SessionUser.find_by_session_id(user_id)  # hits the database

The above answers your quesion:

When the database can't find the id, I want the user to be logged out.

Now, to answer your second question:

I want show a message the user has been logged out (and I only want to
  show this once)

Here's the ways a user can be logged out:

user_id is not in your database (the user was deleted)

user_id is not in the user's browser cookie session (has not logged in yet, or cleared their cookies)

You called flask_login.logout_user, which removes user_id from session

Here's a working mini-app that flashes a message when the user is logged out:

from flask import current_app as app, flash, redirect, render_template, session
from flask_login import login_manager, login_required, logout_user

@login_manager.user_loader
def user_loader(user_id):
    return SessionUser.find_by_session_id(user_id)

@app.route('/logout')
@login_required
def logout():
    logout_user()
    if session.get('was_once_logged_in'):
        # prevent flashing automatically logged out message
        del session['was_once_logged_in']
    flash('You have successfully logged yourself out.')
    return redirect('/login')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if app.current_user.is_authenticated:  # already logged in
        return redirect('/home')
    if request.method == 'POST':
        user = SessionUser.find_by_session_id(request.data['user_id'])
        if user:
            login_user(user)
            session['was_once_logged_in'] = True
            return redirect('/home')
        flash('That user was not found in the database.')
    if session.get('was_once_logged_in'):
        flash('You have been automatically logged out.')
        del session['was_once_logged_in']
    return render_template('/login.html')

@app.route('/home')
@login_required
def home():
    return 'You are logged in as {0}.'.format(app.current_user.id)

Contents of login.html:

{% with messages = get_flashed_messages() %}
  {% if messages %}
    <ul class=flashes>
    {% for message in messages %}
      <li>{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}

<form method="post">
  User ID: <input type="text" name="user_id" /><br />
  <button type="submit">Login</button>
</form>


问:
Supported search queries with OneDrive
What values the 'search-text' can take in the following query?

```<code>GET /me/drive/root/search(q='{search-text}')
</code>```

From experiments, it looks like the {search-text} is a single string that would be searched in the contents of the file.  Meaning if the search text is a multiple word sentence then entire sentence is searched rather than individual works in the sentence? Is this right assumption?

Eg: Say If I would like to search 'word1' 'word2' ... 'wordn' then it looks like search query should be issued for all the n words individually.  Is there a format/way in which we can search all the n words in single query?

Thanks,
/Girish BK

答:
Searching is phrase based and does not support wildcards or similar search augmentations.

For example, the query /me/drive/search(q='pizza shop') would search for files that contain the phrase "pizza shop" in a filename, a file's metadata, and a file's content.

Title: Supported search queries with OneDrive

Body:
What values the 'search-text' can take in the following query?

GET /me/drive/root/search(q='{search-text}')

From experiments, it looks like the {search-text} is a single string that would be searched in the contents of the file.  Meaning if the search text is a multiple word sentence then entire sentence is searched rather than individual works in the sentence? Is this right assumption?

Eg: Say If I would like to search 'word1' 'word2' ... 'wordn' then it looks like search query should be issued for all the n words individually.  Is there a format/way in which we can search all the n words in single query?

Thanks,
/Girish BK


问:
Failing to get correct file path for resource in packed Chrome Extension
When developing my extension and testing it by loading unpacked extension I am able to get the correct path.

For example the following code points to one of my images and loads correctly.

```<code>theIcon.src = chrome.runtime.getUrl(goatPath); // "chrome-extension://extensionID/img/myImage.png
</code>```

I have the above code running in both a popup page and content script.

However when I upload to the Chrome Web Store and publish the packed version, I'm unable to access the resource because it is trying to look for it at

chrome-extension://extensionID/chrome-extension://extensionID/img/myImage.png

Popup page error

Failed to load resource: net::ERR_FILE_NOT_FOUND

Content Script error

Denying load of chrome-extension://kjohofijdcbjeanfinadbebghfegbhop/chrome-extension://kjohofijdcbjeanfinadbebghfegbhop/img/myimage.png. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.

Manifest File -

```<code>{
  "manifest_version": 2,

  "name": "Feed the Goat",
  "description": "Feed the Goat provides a fun way for you to stay focused so you can get more done.",
  "version": "1.5",
  "icons": { "16": "img/goat-icon16.png",
             "32": "img/goat-icon32.png",
             "128": "img/goat-icon128.png" },
  "background": {
    "scripts": ["event/background.js"]
  },
  "browser_action": {
    "default_icon": "img/goat-icon.png",
    "default_popup": "popup/authentication/authentication.html"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content/content.js"]
    }
  ],
  "web_accessible_resources": [
    "img/goat-icon128.png",
    "img/goat-icon256.png",
    "img/GarytheGoat-icon128.png",
    "img/GarytheGoat-icon256.png",
    "img/BillyBuck-icon128.png",
    "img/BillyBuck-icon256.png",
    "img/UncleUnicorn-icon128.png",
    "img/UncleUnicorn-icon256.png"

  ],
  "content_security_policy":"script-src 'self' https://cdnjs.cloudflare.com/ https://www.gstatic.com/ https://*.firebaseio.com https://www.googleapis.com https://use.fontawesome.com; object-src 'self'",
  "permissions": [
    "tabs",
    "activeTab",
    "<all_urls>",
    "identity",
    "idle",
    "notifications",
    "storage"
  ],
    }
</code>```

Thanks

答:
In your manifest.json try to add following:

```<code>"web_accessible_resources": [
  "img/*"
]
</code>```

Also, make sure that in your dist(build) folder there is img folder with images.

"goatPath" should be img/myImage.png
and funnction should have all upper-case for URL like this

chrome.runtime.getURL(goatPath)

Body:
When developing my extension and testing it by loading unpacked extension I am able to get the correct path.

For example the following code points to one of my images and loads correctly.

theIcon.src = chrome.runtime.getUrl(goatPath); // "chrome-extension://extensionID/img/myImage.png

I have the above code running in both a popup page and content script.

However when I upload to the Chrome Web Store and publish the packed version, I'm unable to access the resource because it is trying to look for it at

chrome-extension://extensionID/chrome-extension://extensionID/img/myImage.png

Popup page error

Failed to load resource: net::ERR_FILE_NOT_FOUND

Content Script error

Denying load of chrome-extension://kjohofijdcbjeanfinadbebghfegbhop/chrome-extension://kjohofijdcbjeanfinadbebghfegbhop/img/myimage.png. Resources must be listed in the web_accessible_resources manifest key in order to be loaded by pages outside the extension.

Manifest File -

{
  "manifest_version": 2,

  "name": "Feed the Goat",
  "description": "Feed the Goat provides a fun way for you to stay focused so you can get more done.",
  "version": "1.5",
  "icons": { "16": "img/goat-icon16.png",
             "32": "img/goat-icon32.png",
             "128": "img/goat-icon128.png" },
  "background": {
    "scripts": ["event/background.js"]
  },
  "browser_action": {
    "default_icon": "img/goat-icon.png",
    "default_popup": "popup/authentication/authentication.html"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content/content.js"]
    }
  ],
  "web_accessible_resources": [
    "img/goat-icon128.png",
    "img/goat-icon256.png",
    "img/GarytheGoat-icon128.png",
    "img/GarytheGoat-icon256.png",
    "img/BillyBuck-icon128.png",
    "img/BillyBuck-icon256.png",
    "img/UncleUnicorn-icon128.png",
    "img/UncleUnicorn-icon256.png"

  ],
  "content_security_policy":"script-src 'self' https://cdnjs.cloudflare.com/ https://www.gstatic.com/ https://*.firebaseio.com https://www.googleapis.com https://use.fontawesome.com; object-src 'self'",
  "permissions": [
    "tabs",
    "activeTab",
    "<all_urls>",
    "identity",
    "idle",
    "notifications",
    "storage"
  ],
    }

Thanks

Body:
In your manifest.json try to add following:

"web_accessible_resources": [
  "img/*"
]

Also, make sure that in your dist(build) folder there is img folder with images.

"goatPath" should be img/myImage.png
and funnction should have all upper-case for URL like this

chrome.runtime.getURL(goatPath)


问:
How to add tracking code in woocommerce's "thankyou" page
I'm using Woocommerce, it's up to date.

I've been looking for answers about my issue. I found quite a lot of posts about it but they don't seem to help me figure out the solution.

Found this website that describes how to hook the conversion code.

I tried quite a lot of snippets but the code doesn't fire.

Basically, I've got an iframe code that I need to add to my conversion page.
This page is created from the template thankyou.php

I added some code through a hook to function.php but the iframe doesn't show up in the conversion page.

In order to test the code, I've been checking the network tab in "inspect element". It doesn't fire, I cannot even find the code in the page.

Here's the iframe code:

```<code>[iframe src="https://lb.affilae.com/?key=59f3463ce8faceb82f8b4571-
59f345fedca96b441b37b6ce&id={UNIQUE_ID}&amount={AMOUNT}&payment=
{PAYMENT}&cv={CUSTOM_VAR}" frameborder="0" width="1" height="1"]
</code>```

It is a wordpress shortcode, the only way for it to show up on the page.

Here's the hook I've been using:

```<code>add_action( 'woocommerce_thankyou', 'bbloomer_add_content_thankyou' );

function bbloomer_add_content_thankyou() {
echo 'my iframe conversion code';
}
</code>```

Do you have any idea how to fix this?
I can provide more info if needed.

Edit:

I found a solution!

The main issue came from the fact that I didn't specified the unique ID and the amount.

Here's the code that solved it all:

```<code>add_action( 'woocommerce_thankyou', 'my_custom_tracking' );
function my_custom_tracking( $order_id ) {
$order = new WC_Order( $order_id );
$total = $order->get_subtotal();
$id = str_replace('#', '', $order->get_order_number());
echo '<iframe src="https://lb.affilae.com/?[replace with the right code]&id=' . $id . '&amount=' . $total .
'&payment=online&cv={CUSTOM_VAR}" frameborder="0" width="1" height="1">
</iframe>';
}
</code>```

I pasted this code at the top of the function.php file (after

答:
Updated - You should try this:

```<code>add_action( 'woocommerce_thankyou', 'add_custom_content_to_thankyou', 10, 1 );
function add_custom_content_to_thankyou( $order_id ) {

    // The dynamic link in your iFrame
    $src = "https://lb.affilae.com/?key=59f3463ce8faceb82f8b4571-
59f345fedca96b441b37b6ce&id={UNIQUE_ID}&amount={AMOUNT}&payment=
{PAYMENT}&cv={CUSTOM_VAR}"

    echo '<p>Tracking code:<p>'; // Just for testing

    echo do_shortcode("[iframe src=$src]");

}
</code>```

Code goes in function.php file of your active child theme (or active theme) or in any plugin file.

It will output your code just after customers details at the end of the order-received page…

Related: WooCommerce Thankyou tracking code installation placement

Body:
I'm using Woocommerce, it's up to date.

I've been looking for answers about my issue. I found quite a lot of posts about it but they don't seem to help me figure out the solution.

Found this website that describes how to hook the conversion code.

I tried quite a lot of snippets but the code doesn't fire.

Basically, I've got an iframe code that I need to add to my conversion page.
This page is created from the template thankyou.php

I added some code through a hook to function.php but the iframe doesn't show up in the conversion page.

In order to test the code, I've been checking the network tab in "inspect element". It doesn't fire, I cannot even find the code in the page.

Here's the iframe code:

[iframe src="https://lb.affilae.com/?key=59f3463ce8faceb82f8b4571-
59f345fedca96b441b37b6ce&id={UNIQUE_ID}&amount={AMOUNT}&payment=
{PAYMENT}&cv={CUSTOM_VAR}" frameborder="0" width="1" height="1"]

It is a wordpress shortcode, the only way for it to show up on the page.

Here's the hook I've been using:

add_action( 'woocommerce_thankyou', 'bbloomer_add_content_thankyou' );

function bbloomer_add_content_thankyou() {
echo 'my iframe conversion code';
}

Do you have any idea how to fix this?
I can provide more info if needed.

Edit:

I found a solution!

The main issue came from the fact that I didn't specified the unique ID and the amount.

Here's the code that solved it all:

add_action( 'woocommerce_thankyou', 'my_custom_tracking' );
function my_custom_tracking( $order_id ) {
$order = new WC_Order( $order_id );
$total = $order->get_subtotal();
$id = str_replace('#', '', $order->get_order_number());
echo '
';
}

I pasted this code at the top of the function.php file (after

Body:
Updated - You should try this:

add_action( 'woocommerce_thankyou', 'add_custom_content_to_thankyou', 10, 1 );
function add_custom_content_to_thankyou( $order_id ) {

    // The dynamic link in your iFrame
    $src = "https://lb.affilae.com/?key=59f3463ce8faceb82f8b4571-
59f345fedca96b441b37b6ce&id={UNIQUE_ID}&amount={AMOUNT}&payment=
{PAYMENT}&cv={CUSTOM_VAR}"

    echo '<p>Tracking code:<p>'; // Just for testing

    echo do_shortcode("[iframe src=$src]");

}

Code goes in function.php file of your active child theme (or active theme) or in any plugin file.

It will output your code just after customers details at the end of the order-received page…

Related: WooCommerce Thankyou tracking code installation placement


问:
Disable DES in my https server
have a light http server (embedded software solution). This http server is calling openssl functions to handle https connexions.

I want to disable the DES cipher in my https server so I find the function:

```<code>SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str);
</code>```

I m newbie in openssl and I want to find the right string to pass in the function SSL_CTX_set_cipher_list()

What's the string to use in SSL_CTX_set_cipher_list() in order to disable DES in my server?

Is it correct to call the SSL_CTX_set_cipher_list() just after ctx = SSL_CTX_new(meth); ?

答:
I found an example of SSL_CTX_set_cipher_list usage in this question.

Summarizing you should declare an string of algorithms using : as separators between them (you  can consult the algorihtm names in wiki openssl) and create the context before (as you suggested) setting the cypher list. A little example in code:

```<code>// List of allowed ciphers in a colon-separated list.
const char *allowedCiphers = "ECDHE-ECDSA-AES256-SHA384:AES256-GCM-SHA384";
int main()
{
  const SSL_METHOD *method;
  SSL_CTX *ctx;

  method = SSLv23_server_method();
  ctx = SSL_CTX_new(method);
  // Set the allowed ciphers
  if (SSL_CTX_set_cipher_list(ctx, ciphers) != 1)
  {
    //define error
  }
  SSL_CTX_free(ctx);
  cleanup_openssl();
  return 0;
}
</code>```

Finally I would suggest change your version of openSSL if the library allows DES method, because, as you can see in this proposal, DES is disabled by default except if you compile explicitly. So, I highly recommend update your openSSL version.

Title: Disable DES in my https server

Body:
have a light http server (embedded software solution). This http server is calling openssl functions to handle https connexions.

I want to disable the DES cipher in my https server so I find the function:

SSL_CTX_set_cipher_list(SSL_CTX *ctx, const char *str);

I m newbie in openssl and I want to find the right string to pass in the function SSL_CTX_set_cipher_list()

What's the string to use in SSL_CTX_set_cipher_list() in order to disable DES in my server?

Is it correct to call the SSL_CTX_set_cipher_list() just after ctx = SSL_CTX_new(meth); ?

Body:
I found an example of SSL_CTX_set_cipher_list usage in this question.

Summarizing you should declare an string of algorithms using : as separators between them (you  can consult the algorihtm names in wiki openssl) and create the context before (as you suggested) setting the cypher list. A little example in code:

// List of allowed ciphers in a colon-separated list.
const char *allowedCiphers = "ECDHE-ECDSA-AES256-SHA384:AES256-GCM-SHA384";
int main()
{
  const SSL_METHOD *method;
  SSL_CTX *ctx;

  method = SSLv23_server_method();
  ctx = SSL_CTX_new(method);
  // Set the allowed ciphers
  if (SSL_CTX_set_cipher_list(ctx, ciphers) != 1)
  {
    //define error
  }
  SSL_CTX_free(ctx);
  cleanup_openssl();
  return 0;
}

Finally I would suggest change your version of openSSL if the library allows DES method, because, as you can see in this proposal, DES is disabled by default except if you compile explicitly. So, I highly recommend update your openSSL version.


问:
Python import error "DLL load failed" | Python
I'm serving a Django app behind IIS6 web server.

The test server runs perfectly, but when running behind the web server a module failes to import I get this error:

Error loading pyodbc module: DLL load failed: The specified module could not be found

Just for the record the module is pyodbc

The site is served though isapi by using isapi-wsgi

Any ideas? It would really make my day! :)

答: This error is a PITA: it is often caused by missing symbols in dll (because a dependent dll was not found, etc...). You should check the .pyd with dependency walker, or look into the windows log which may log such errors depending on your configuration.</p>


问:
excel vba macro: copy and paste the specific column to another workbook
i am new in macro and VBA coding.
I have two workbooks. one is report.xls, another one is AT.xlsm.

In report.xls, there has the sheet called "Service".

In AT.xlsm, there has the sheet called "Worksheet".

I want to auto copy the column B,C,F,J,E,D expect first row of report to the column A,C,D,E,F,H of AT.
So, i try to record a macro and revise the code, it can copy and paste but it saved to same location.

Would you please tell me how to paste to new row?

Thank you very much.

Code:

```<code>Sub Module1()
'Hot key: Ctrl+Shift+G

Windows("report.xls").Activate
Range("B2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Windows("AT.xlsm").Activate
ActiveSheet.Paste
Windows("report.xls").Activate
Range("C2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Windows("AT.xlsm").Activate
Range("C5380").Select
ActiveSheet.Paste
Windows("report.xls").Activate
Range("F2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Windows("AT.xlsm").Activate
Range("D5380").Select
ActiveSheet.Paste
Windows("report.xls").Activate
Range("J2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Windows("AT.xlsm").Activate
Range("E5380").Select
ActiveSheet.Paste
Windows("report.xls").Activate
Range("E2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Windows("AT.xlsm").Activate
Range("F5380").Select
ActiveSheet.Paste
Windows("report.xls").Activate
Range("D2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Windows("AT.xlsm").Activate
Range("H5380").Select
ActiveSheet.Paste
Windows("report.xls").Activate
Range("G2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Windows("AT.xlsm").Activate
Range("J5380").Select
ActiveSheet.Paste
Range("F5380").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Replace What:="[S]", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False

End Sub
</code>```

答:
I will use a portion of your code.
VBA code made while you record a macro is not the best option to use, but this time I will use the code in order to don't do things complicated to you.

Original code:

```<code>Windows("report.xls").Activate
Range("B2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Windows("AT.xlsm").Activate
ActiveSheet.Paste
</code>```

Modify like:

```<code>Windows("report.xls").Activate    'This activate the report
Range("B2").Select    'This selects B2 cell
Range(Selection, Selection.End(xlDown)).Select    'This expands the selection down
Selection.Copy    'This copy the selection.
Windows("AT.xlsm").Activate    'This activate the AT file
Range("B2").Select    '**** Here you should modify to select the Paste destination cell
ActiveSheet.Paste    'This Paste the values
</code>```

Hope it helps.

Body:
i am new in macro and VBA coding.
I have two workbooks. one is report.xls, another one is AT.xlsm.

In report.xls, there has the sheet called "Service".

In AT.xlsm, there has the sheet called "Worksheet".

I want to auto copy the column B,C,F,J,E,D expect first row of report to the column A,C,D,E,F,H of AT.
So, i try to record a macro and revise the code, it can copy and paste but it saved to same location.

Would you please tell me how to paste to new row?

Thank you very much.

Code:

Sub Module1()
'Hot key: Ctrl+Shift+G

Windows("report.xls").Activate
Range("B2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Windows("AT.xlsm").Activate
ActiveSheet.Paste
Windows("report.xls").Activate
Range("C2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Windows("AT.xlsm").Activate
Range("C5380").Select
ActiveSheet.Paste
Windows("report.xls").Activate
Range("F2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Windows("AT.xlsm").Activate
Range("D5380").Select
ActiveSheet.Paste
Windows("report.xls").Activate
Range("J2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Windows("AT.xlsm").Activate
Range("E5380").Select
ActiveSheet.Paste
Windows("report.xls").Activate
Range("E2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Windows("AT.xlsm").Activate
Range("F5380").Select
ActiveSheet.Paste
Windows("report.xls").Activate
Range("D2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Windows("AT.xlsm").Activate
Range("H5380").Select
ActiveSheet.Paste
Windows("report.xls").Activate
Range("G2").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Windows("AT.xlsm").Activate
Range("J5380").Select
ActiveSheet.Paste
Range("F5380").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Replace What:="[S]", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False

End Sub

Body:
I will use a portion of your code.
VBA code made while you record a macro is not the best option to use, but this time I will use the code in order to don't do things complicated to you.

Original code:

Windows("report.xls").Activate
Range("B2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Windows("AT.xlsm").Activate
ActiveSheet.Paste

Modify like:

Windows("report.xls").Activate    'This activate the report
Range("B2").Select    'This selects B2 cell
Range(Selection, Selection.End(xlDown)).Select    'This expands the selection down
Selection.Copy    'This copy the selection.
Windows("AT.xlsm").Activate    'This activate the AT file
Range("B2").Select    '**** Here you should modify to select the Paste destination cell
ActiveSheet.Paste    'This Paste the values

Hope it helps.


问:
Microsoft Access 2016: Resetting Default Value of Combo Box (that uses equation) with Button?
I have the following code on the Reset button:

```<code>Private Sub cmdReset_Click()
    Dim ctl As Control

    For Each ctl In Me.Controls

        Select Case ctl.ControlType
            Case acComboBox
                ctl.Value = ctl.DefaultValue
        End Select
    Next
    Me.Requery
End Sub
</code>```

This is what my Default Value for the combo boxes look like:

```<code>=DLookUp("FieldName","TableName","strCriteria")
</code>```

When I click the Reset button the combo box just displays the equation as a string =DLookUp("FieldName","TableName","strCriteria") instead of actually running the function. I tried using a different Default Value =[cboName].[ItemData](#) and it's the same issue. The Form works perfectly otherwise.

I appreciate your help.

答:
The behavior is expected, since ctl.DefaultValue returns the string default value property, not the actual calculated default value.

A possible approach is to use Eval to calculate the actual default value. Note, however, that numerous problems can arise when doing this, since the default value is not VBA, but an Access expression, so it has a different scope, and is sensitive to locale settings such as the list separator setting.

You can use the following line:

```<code>ctl.Value = Eval(Right(ctl.DefaultValue, Len(ctl.DefaultValue) -1))
</code>```

Body:
I have the following code on the Reset button:

Private Sub cmdReset_Click()
    Dim ctl As Control

    For Each ctl In Me.Controls

        Select Case ctl.ControlType
            Case acComboBox
                ctl.Value = ctl.DefaultValue
        End Select
    Next
    Me.Requery
End Sub

This is what my Default Value for the combo boxes look like:

=DLookUp("FieldName","TableName","strCriteria")

When I click the Reset button the combo box just displays the equation as a string =DLookUp("FieldName","TableName","strCriteria") instead of actually running the function. I tried using a different Default Value =[cboName].[ItemData](#) and it's the same issue. The Form works perfectly otherwise.

I appreciate your help.

Body:
The behavior is expected, since ctl.DefaultValue returns the string default value property, not the actual calculated default value.

A possible approach is to use Eval to calculate the actual default value. Note, however, that numerous problems can arise when doing this, since the default value is not VBA, but an Access expression, so it has a different scope, and is sensitive to locale settings such as the list separator setting.

You can use the following line:

ctl.Value = Eval(Right(ctl.DefaultValue, Len(ctl.DefaultValue) -1))


问:
Spring MVC. Tomcat. HTTP Status 404 – Not Found
I need to configure Spring Mvc without web.xml. Use only java config

My WebConfig

```<code>@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "controllers.web")
@Import({PersistenceJPAConfig.class})
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

@Bean
public ViewResolver internalResourceViewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/view/jsp");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
    }
}
</code>```

My WebInitializer

```<code>public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(WebConfig.class);
    servletContext.addListener(new ContextLoaderListener(ctx));
    ctx.setServletContext(servletContext);
    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.setLoadOnStartup(1);
    servlet.addMapping("/");
}
}
</code>```

My controller

```<code>@Controller
@RequestMapping("/")

public class MainController {

@Autowired
BusRepository busRepository;

@RequestMapping(method = RequestMethod.GET)
public String index(ModelMap model) {
    StringBuilder sb = new StringBuilder("<br>");
    busRepository.findAll().forEach(it->sb.append(it.toString()).append("<br>"));
    model.put("msg", sb.toString());
    return "index";
}
}
</code>```

My index.jsp

```<code>    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring MVC</title>
</head>
<body>
    <h4>Spring MVC</h4>
    <span class="blue">${msg}</span>
</body>
</html>
</code>```

My pom.xml

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

    <groupId>com.intexsoft.training.manager</groupId>
    <artifactId>managers</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>managers</name>
    <url>http://localhost:8080/managers</url>
    <build>
        <plugins>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>view.Runner</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>hibernate.cfg.xml</directory>
            </resource>
        </resources>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.11.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.11.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.11.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
    </dependencies>
</project>
</code>```

I checked server's working through power shell (it works).
And when I launch server through application, I get "HTTP Status 404 – Not Found"
I tried other url.
War file was assemble.
How can I solve this problem?

thanks in advance

答:
I think you need to add value to your @RequestMapping for the index method,and make sure that your jsp page is in this directory WEB-INF/view/jsp ,then you can get your page using http://localhost:8080/managers/index

```<code>@Controller
@RequestMapping("/")

public class MainController {

@Autowired
BusRepository busRepository;

    @RequestMapping(value="index",method = RequestMethod.GET)
    public String index(ModelMap model) {
        StringBuilder sb = new StringBuilder("<br>");
        busRepository.findAll().forEach(it->sb.append(it.toString()).append("<br>"));
        model.put("msg", sb.toString());
        return "index";
    }
    }
</code>```

Body:
I need to configure Spring Mvc without web.xml. Use only java config

My WebConfig

@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "controllers.web")
@Import({PersistenceJPAConfig.class})
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

@Bean
public ViewResolver internalResourceViewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/view/jsp");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
    }
}

My WebInitializer

public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
    ctx.register(WebConfig.class);
    servletContext.addListener(new ContextLoaderListener(ctx));
    ctx.setServletContext(servletContext);
    Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
    servlet.setLoadOnStartup(1);
    servlet.addMapping("/");
}
}

My controller

@Controller
@RequestMapping("/")

public class MainController {

@Autowired
BusRepository busRepository;

@RequestMapping(method = RequestMethod.GET)
public String index(ModelMap model) {
    StringBuilder sb = new StringBuilder("
");
    busRepository.findAll().forEach(it->sb.append(it.toString()).append("
"));
    model.put("msg", sb.toString());
    return "index";
}
}

My index.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring MVC</title>

Spring MVC

    ${msg}

My pom.xml

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

    <groupId>com.intexsoft.training.manager</groupId>
    <artifactId>managers</artifactId>
    <packaging>war</packaging>
    <version>1.0</version>
    <name>managers</name>
    <url>http://localhost:8080/managers</url>
    <build>
        <plugins>
            <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addClasspath>true</addClasspath>
                            <mainClass>view.Runner</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.1.0</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>hibernate.cfg.xml</directory>
            </resource>
        </resources>
    </build>
    <dependencies>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.11.Final</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.11.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.11.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.0.11.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
    </dependencies>
</project>

I checked server's working through power shell (it works).
And when I launch server through application, I get "HTTP Status 404 – Not Found"
I tried other url.
War file was assemble.
How can I solve this problem?

thanks in advance

Body:
I think you need to add value to your @RequestMapping for the index method,and make sure that your jsp page is in this directory WEB-INF/view/jsp ,then you can get your page using http://localhost:8080/managers/index

@Controller
@RequestMapping("/")

public class MainController {

@Autowired
BusRepository busRepository;

    @RequestMapping(value="index",method = RequestMethod.GET)
    public String index(ModelMap model) {
        StringBuilder sb = new StringBuilder("<br>");
        busRepository.findAll().forEach(it->sb.append(it.toString()).append("<br>"));
        model.put("msg", sb.toString());
        return "index";
    }
    }


问:
How to set up nunit 3.9 in Jenkins using Windows batch command line?
I need to setup my Windows Visual Studio (C#) nunit 3.9 code in Jenkins. So for that, I need the details that is used for the command line process.

What we use to put in Jenkins window batch command line for nunit 3.9 ?

答:
You need to ensure that:

NUnit is installed on the machine where Jenkins lives

The Jenkins NUnit plugin is installed: https://wiki.jenkins.io/display/JENKINS/NUnit+Plugin

The documentation on the plugin page should be fairly self-explanatory from thereon in.

If you get stuck with anything, shout back.


问:
please help! i can sort items to hidden overflow!
This is my site. On the left I have a playlist, inside a container with hidden overflow (the playlist is a sortable). The playlist grows as you drag more songs to it from the search list.

The problem is that when you drag many songs to the playlist, and the playlist is larger than the container, it makes a situation where I can sort the playlist by dragging items to the hidden area. In other words, I can drag a song from the playlist to an area under the container (where the invisible part of the playlist is) and the song will still be inserted to the list.

Here's a screenshot:

答:
Good question. But yes, that would be the expected behavior. I can only think of a 'hacky' solution to the problem, which would be to place an invisible div element with a very high z-index over the part where you don't want dropping to take place. This should provide a pragmatic solution to your problem, but it isn't pretty.

In fact, a reasonably good solution would be to add that invisible element dynamically as soon as the drag action starts, so as to stop the user from dropping there. When the drag stops, you can remove it again.

Update
Ok, so learning that the first try doesn't work, I went to have a look at the jQuery docs. They specify a containment option, which is an element in which the sorting should be contained. So I'd say you can do the invisible element thing again, but this time place it exactly on top of the area you want to be able to sort in. Then, specify this element in the containment option. If that doesn't work, I'm out of advice ;)


问:
Switch to pyomo 4 expressions by default
Why Pyomo uses by default expression types from expr_coopr3.py? I found the way how it could be changed but I have doubts if it's the right way.

In the file expr_common.py

```<code>try:
  from sys import getrefcount
  _getrefcount_available = False # changed!
except ImportError:
    logger = logging.getLogger('pyomo.core')
    logger.warning(
    "This python interpreter does not support sys.getrefcount()\n"
    "Pyomo cannot automatically guarantee that expressions do not become\n"
    "entangled (multiple expressions that share common subexpressions).\n")
     getrefcount = None
     _getrefcount_available = False

class Mode(object):
    coopr3_trees = (1,)
    pyomo4_trees = (2,)
if _getrefcount_available:
    mode = _default_mode = Mode.coopr3_trees
else:
    mode = _default_mode = Mode.pyomo4_trees
</code>```

the variable _getrefcount_available could be assigned to False and after everything works with pyomo expressions 4. Is there any other way to do that?

I am using Pyomo 5.2

答:
You can switch expression tree systems with:

```<code>import pyomo.core.base.expr as EXPR
EXPR.set_expression_tree_format(EXPR.common.Mode.pyomo4_trees)
</code>```

Pyomo4 expressions have been a (long-running) development activity to simplify the expression tree system, improve performance, and most importantly to provide support for pypy.  It has not been made the default mostly because while I think it works correctly, it generates slightly different expression trees from what the coopr3 system generated.  This impacts a large number of the Pyomo tests and I haven't had the time to resolve all the (2000+) test differences to make sure that the new results are correct.

Also, I should point out that [as of Dec 2017] there is a Pyomo branch with a revised version of the pyomo4 expression system (currently dubbed pyomo5).  This system has an improved way to ensure expression correctness in the absence of getrefcount() (needed for pypy).  Unfortunately, the development of pyomo5 expressions hass diverged from the coopr3/pyomo4 systems sufficiently such that they do not cleanly coexist.  When that branch is merged (likely January 2018), both coopr3 and pyomo4 expression systems are expected to be removed from master.

Body:
Why Pyomo uses by default expression types from expr_coopr3.py? I found the way how it could be changed but I have doubts if it's the right way.

In the file expr_common.py

try:
  from sys import getrefcount
  _getrefcount_available = False # changed!
except ImportError:
    logger = logging.getLogger('pyomo.core')
    logger.warning(
    "This python interpreter does not support sys.getrefcount()\n"
    "Pyomo cannot automatically guarantee that expressions do not become\n"
    "entangled (multiple expressions that share common subexpressions).\n")
     getrefcount = None
     _getrefcount_available = False

class Mode(object):
    coopr3_trees = (1,)
    pyomo4_trees = (2,)
if _getrefcount_available:
    mode = _default_mode = Mode.coopr3_trees
else:
    mode = _default_mode = Mode.pyomo4_trees

the variable _getrefcount_available could be assigned to False and after everything works with pyomo expressions 4. Is there any other way to do that?

I am using Pyomo 5.2

Body:
You can switch expression tree systems with:

import pyomo.core.base.expr as EXPR
EXPR.set_expression_tree_format(EXPR.common.Mode.pyomo4_trees)

Pyomo4 expressions have been a (long-running) development activity to simplify the expression tree system, improve performance, and most importantly to provide support for pypy.  It has not been made the default mostly because while I think it works correctly, it generates slightly different expression trees from what the coopr3 system generated.  This impacts a large number of the Pyomo tests and I haven't had the time to resolve all the (2000+) test differences to make sure that the new results are correct.

Also, I should point out that [as of Dec 2017] there is a Pyomo branch with a revised version of the pyomo4 expression system (currently dubbed pyomo5).  This system has an improved way to ensure expression correctness in the absence of getrefcount() (needed for pypy).  Unfortunately, the development of pyomo5 expressions hass diverged from the coopr3/pyomo4 systems sufficiently such that they do not cleanly coexist.  When that branch is merged (likely January 2018), both coopr3 and pyomo4 expression systems are expected to be removed from master.