问:
MSAL library sign in without response
I'm trying an application that is able to display all and create new events for the Outlook calendar. I am using the MSAL library to get the authentication code. The problem is that although the login screen appears when I touch the buttons enter or cancel I do not notice any reaction. This is my code:</p>

```<code>class OutlookManagerController: BaseViewController {
    let oClientKey = "a07745a5-3b90-4385-a2b2-8223dbf68688"
    let authScopes = ["openid+https://outlook.office.com/contacts.read+offline_access"]

    func getAcessToken(){
        if let application = try? MSALPublicClientApplication.init(clientId: oClientKey) {
            application.acquireToken(forScopes: authScopes) { (result, error) in
                if result != nil {
                    let userToken = result!.accessToken!
                    print(userToken)

                } else {
                    print(error!.localizedDescription)
                }
            }
        }
        else {
            print("Unable to create application.")
        }
    }
}
</code>```

答:
It would appear that you are not listening for the return of the auth code from the SFSafariViewController which MSAL launches when you call AcquireToken(). MSAL uses the SFSafariViewControllerfor login in order to enable better security and provide Single Sign-On across applications. You just need to set up a redirect URI that has the ability to call back your application and use the correct Issuer for your tenant.

That is the problem you are running in to. Sign in is successful, but Azure can't find it's way back to your app!

First, some groundwork.

System Webviews

Most modern OAuth2 libraries now use the System Webview for signing a user in. A System Webview is a browser component that an application can launch that appears to be part of the application but is actually an isolated process which runs the operating system's web browser. For iOS this is the SFSafariViewController and on Android it is Chrome Custom Tabs.

The benefit of the System Webview for singing a user in are numerous, including:

Better security. An application can not access the credentials typed in to a System Webview as it's an isolated browser process.

Today many applications use a username and password form or an embedded webview to get credentials. This allows an application to listen in and grab these credentials. Many companies have begun disallowing applications that have this kind of sign in. System Webviews ensures your app doesn't have this problem.

Single Sign-On. Once a user has signed in with the System Webview, a cookie is placed in the browser and that account is available to any application, preventing the need for a user to sign in to every app separately.

As more consumers and businesses leverage phone SMS and other factors as additional steps, having to redo this step as well as use your password is getting very annoying for customers. System Webviews remove this problem.

Better control. A user can choose which account to provide the application, or add a brand new account in the System Webview if supported.

You've seen Google and Microsoft make the transition to this System Webview with our latest SDKs as well as update our identity services, and it's to give the customer these protections and features. App Auth from the OpenID project, which has code contributed by both Google and Microsoft engineers among others, also provides this support.

System Webview Needs To Return Back To Your App

One of the things that might have occurred to you reading the above is this:

If an application now calls a System Webview for sign-in, and has no control over it, how do I get the tokens I need back from the System Webview?

The answer is that you must leverage the mechanisms each operating system has to call back the application, and then use the redirectURI from the OAuth2 protocol to return the response back to that application using that mechanism. It's almost exactly like how this works in a web browser. You get redirected away from the website to an identity provider for sign in, and then the identity provider uses the redirectURI to return the user back to the website with tokens in the response somewhere.

For iOS this done through Custom URL Schemes. A URL scheme is in the format of CFBundleURLScheme:\\CFBundleURLSchemes and is defined as:

CFBundleURLName
A string containing the abstract name of the URL scheme. To ensure uniqueness, it is recommended that you specify a reverse-DNS style of identifier, for example, com.acme.myscheme.
The string you specify is also used as a key in your app’s InfoPlist.strings file. The value of the key is the human-readable scheme name.

CFBundleURLSchemes
An array of strings containing the URL scheme names—for example, http, mailto, tel, and sms.

To register a URL type for your app, include the CFBundleURLTypes key in your app’s Info.plist file. The CFBundleURLTypes key contains an array of dictionaries, each of which defines a URL scheme the app supports.

How To Get A System Webview To Return To Your App

So, combining these two things, it's fairly simple what you need to do:

Figure out what your URL scheme will be for your app (e.g. appauth://abc123.

Tell Azure AD what your new URL scheme is, adding it as another  redirectURI for your application.

Configure your application to listen for this URL scheme and launch the app

Configure the application itself to grab the token once this URL scheme launches your app (App Auth, as well our own MSAL libraries, do this for you!)

1. Figure out what your URL scheme will be for your app

You can read up on how to make URL schemes from Apple's Inter-App Communication documentation, but we recommend you use the scheme of appauth://<client id> (e.g. appauth://ab032846-efee-481f-b6bc-493aae92c432)

2. Tell Azure AD what your new URL scheme is

You need to add this URL scheme as a RedirectURI to your app. This is easy to do. Just visit https://apps.dev.microsoft.com/ and select your application. Scroll down to Custom App URIs under Native Applications and add your new redirectURI!

3. Configure your application to listen for this URL scheme

Add the following to your info.plist file as per Apple's instructions in Inter-App Communication. It should look something like this, although different apps will have different and additional URL schemes registered:

```<code>  <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>ab032846-efee-481f-b6bc-493aae92c432</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>app-auth</string>
            </array>
        </dict>
    </array>
</code>```

4. Configure the application itself to grab the token

Although listening for a response back from a web browser to an application is a well known pattern for all iOS apps, the actual implementation varies by the identity SDK you use. For MSAL put the following code in your AppDelegate.m file:

```<code>func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {

    print("Received callback!")

    MSALPublicClientApplication.handleMSALResponse(url)

    return true
}
</code>```

The code is rather easy to understand once you know the background above. This is all about receiving a response from the identity service by grabbing the URL that is returned and then giving everything in that URL back to the app so it can grab the tokens it needs to continue it's work.

That's it!

Your app should now work with Azure Active Directory. This pattern of the System Webview is common both across many Identity Providers (Microsoft, Google, Facebook) and mobile platforms.

This is documented in our sample application here.

Title: MSAL library sign in without response

Body:
I'm trying an application that is able to display all and create new events for the Outlook calendar. I am using the MSAL library to get the authentication code. The problem is that although the login screen appears when I touch the buttons enter or cancel I do not notice any reaction. This is my code:

class OutlookManagerController: BaseViewController {
    let oClientKey = "a07745a5-3b90-4385-a2b2-8223dbf68688"
    let authScopes = ["openid+https://outlook.office.com/contacts.read+offline_access"]

    func getAcessToken(){
        if let application = try? MSALPublicClientApplication.init(clientId: oClientKey) {
            application.acquireToken(forScopes: authScopes) { (result, error) in
                if result != nil {
                    let userToken = result!.accessToken!
                    print(userToken)

                } else {
                    print(error!.localizedDescription)
                }
            }
        }
        else {
            print("Unable to create application.")
        }
    }
}

Body:
It would appear that you are not listening for the return of the auth code from the SFSafariViewController which MSAL launches when you call AcquireToken(). MSAL uses the SFSafariViewControllerfor login in order to enable better security and provide Single Sign-On across applications. You just need to set up a redirect URI that has the ability to call back your application and use the correct Issuer for your tenant.

That is the problem you are running in to. Sign in is successful, but Azure can't find it's way back to your app!

First, some groundwork.

System Webviews

Most modern OAuth2 libraries now use the System Webview for signing a user in. A System Webview is a browser component that an application can launch that appears to be part of the application but is actually an isolated process which runs the operating system's web browser. For iOS this is the SFSafariViewController and on Android it is Chrome Custom Tabs.

The benefit of the System Webview for singing a user in are numerous, including:

Better security. An application can not access the credentials typed in to a System Webview as it's an isolated browser process.

Today many applications use a username and password form or an embedded webview to get credentials. This allows an application to listen in and grab these credentials. Many companies have begun disallowing applications that have this kind of sign in. System Webviews ensures your app doesn't have this problem.

Single Sign-On. Once a user has signed in with the System Webview, a cookie is placed in the browser and that account is available to any application, preventing the need for a user to sign in to every app separately.

As more consumers and businesses leverage phone SMS and other factors as additional steps, having to redo this step as well as use your password is getting very annoying for customers. System Webviews remove this problem.

Better control. A user can choose which account to provide the application, or add a brand new account in the System Webview if supported.

You've seen Google and Microsoft make the transition to this System Webview with our latest SDKs as well as update our identity services, and it's to give the customer these protections and features. App Auth from the OpenID project, which has code contributed by both Google and Microsoft engineers among others, also provides this support.

System Webview Needs To Return Back To Your App

One of the things that might have occurred to you reading the above is this:

If an application now calls a System Webview for sign-in, and has no control over it, how do I get the tokens I need back from the System Webview?

The answer is that you must leverage the mechanisms each operating system has to call back the application, and then use the redirectURI from the OAuth2 protocol to return the response back to that application using that mechanism. It's almost exactly like how this works in a web browser. You get redirected away from the website to an identity provider for sign in, and then the identity provider uses the redirectURI to return the user back to the website with tokens in the response somewhere.

For iOS this done through Custom URL Schemes. A URL scheme is in the format of CFBundleURLScheme:\\CFBundleURLSchemes and is defined as:

CFBundleURLName
A string containing the abstract name of the URL scheme. To ensure uniqueness, it is recommended that you specify a reverse-DNS style of identifier, for example, com.acme.myscheme.
The string you specify is also used as a key in your app’s InfoPlist.strings file. The value of the key is the human-readable scheme name.

CFBundleURLSchemes
An array of strings containing the URL scheme names—for example, http, mailto, tel, and sms.

To register a URL type for your app, include the CFBundleURLTypes key in your app’s Info.plist file. The CFBundleURLTypes key contains an array of dictionaries, each of which defines a URL scheme the app supports.

How To Get A System Webview To Return To Your App

So, combining these two things, it's fairly simple what you need to do:

Figure out what your URL scheme will be for your app (e.g. appauth://abc123.

Tell Azure AD what your new URL scheme is, adding it as another  redirectURI for your application.

Configure your application to listen for this URL scheme and launch the app

Configure the application itself to grab the token once this URL scheme launches your app (App Auth, as well our own MSAL libraries, do this for you!)

1. Figure out what your URL scheme will be for your app

You can read up on how to make URL schemes from Apple's Inter-App Communication documentation, but we recommend you use the scheme of appauth://<client id> (e.g. appauth://ab032846-efee-481f-b6bc-493aae92c432)

2. Tell Azure AD what your new URL scheme is

You need to add this URL scheme as a RedirectURI to your app. This is easy to do. Just visit https://apps.dev.microsoft.com/ and select your application. Scroll down to Custom App URIs under Native Applications and add your new redirectURI!

3. Configure your application to listen for this URL scheme

Add the following to your info.plist file as per Apple's instructions in Inter-App Communication. It should look something like this, although different apps will have different and additional URL schemes registered:

  <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleTypeRole</key>
            <string>Editor</string>
            <key>CFBundleURLName</key>
            <string>ab032846-efee-481f-b6bc-493aae92c432</string>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>app-auth</string>
            </array>
        </dict>
    </array>

4. Configure the application itself to grab the token

Although listening for a response back from a web browser to an application is a well known pattern for all iOS apps, the actual implementation varies by the identity SDK you use. For MSAL put the following code in your AppDelegate.m file:

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {

    print("Received callback!")

    MSALPublicClientApplication.handleMSALResponse(url)

    return true
}

The code is rather easy to understand once you know the background above. This is all about receiving a response from the identity service by grabbing the URL that is returned and then giving everything in that URL back to the app so it can grab the tokens it needs to continue it's work.

That's it!

Your app should now work with Azure Active Directory. This pattern of the System Webview is common both across many Identity Providers (Microsoft, Google, Facebook) and mobile platforms.

This is documented in our sample application here.


来源: stackexchange

问:
Ansible 2.x: ec2_remote_facts
I'm trying to tackle how to list and do something with EC2 stopped instances. ec2_remote_facts is my friend and I can get results from it. But as an ansible noob I cannot for the life of me work out how to get at the 'id' componenent of the returned object. The documentation is sketchy and does not cover what type of thing is returned nor how to use it.

Here is the very basic playbook I'm experimenting with:

```<code>---
- name: remote facts
  hosts: localhost

  tasks:

   - ec2_remote_facts:
      region: ap-southeast-2
     register: info

   - name: print
     debug: var=info
</code>```

This works just fine.

This also works:

```<code>---
- name: remote facts
  hosts: localhost

  tasks:

   - ec2_remote_facts:
      region: ap-southeast-2
     register: info

   - name: print
     debug: var=info.instances[0].id
</code>```

What I can't get my head around is the incantation to give me just the 'id' element for all current instances (3) so I can do something else with all of them--remove, configure, start, whatever. I've had a look at all the looping constructs and with_* options and I can't get any of them to do what I want.

No doubt this will be a 'd'oh!' problem to anyone who knows the answer but I'm afraid at the moment I just don't get it. The returned object looks like this:

```<code>ok: [localhost] => {
    "info": {
        "changed": false,
        "instances": [
            {
                "ami_launch_index": "0",
                "architecture": "x86_64",
            "client_token": "vpOGxxxxxxxxxxxxxx",
            "ebs_optimized": false,
            "groups": [
                {
                    "id": "sg-xxxxxxxx",
                    "name": "launch-wizard-3"
                }
            ],
            "hypervisor": "xen",
            "id": "i-01xxxxxxxxxxxxxxxx",
</code>```

[...]

```<code>        "tags": {},
        "virtualization_type": "hvm",
        "vpc_id": "vpc-xxxxxxxx"
    },
        {
            "ami_launch_index": "1",
            "architecture": "x86_64",
</code>```

[snip, 2 more instances]

Any thoughts people?

答:
You had it on your second attempt, funnily enough I had the exact same issue but it took your JSON experience for me to see it.

Your second code snippet:

```<code>---
- name: remote facts
  hosts: localhost

  tasks:

   - ec2_remote_facts:
      region: ap-southeast-2
     register: info

   - name: print
     debug: var=info.instances[0].id
</code>```

My addition:

```<code>---
- name: remote facts
  hosts: localhost

  tasks:

   - ec2_remote_facts:
      region: ap-southeast-2
     register: info

   - name: print
     debug: var=info.instances[0].id

   - name: Create AMI from Instance ID
     ec2_ami:
       aws_access_key: "{{ aws_access_key }}"
       aws_secret_key: "{{ aws_secret_key }}"
       region: "{{ region }}"
       instance_id: "{{ ec2_remote_facts.instances[0].id }}"
</code>```

Cheers for helping me work this one out haha.

Output from Ansible:

```<code> (ansible27) user@user:/etc/ansible/playbooks$ sudo ansible-playbook ec2_facts.yml
 [WARNING]: Found both group and host with same name: localhost

PLAY [localhost] ***************************************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [EC2 Remote Facts.] *******************************************************
ok: [localhost]

TASK [Display results in JSON format.] *****************************************
ok: [localhost] => {
    "changed": false,
    "msg": "Most upto date instance is: i-1234567abcdefg "
}

TASK [Create AMI from instance ID.] ********************************************
changed: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=4    changed=1    unreachable=0    failed=0
</code>```

For your problem of the loop, I assume it will just be a case of passing in the [1] and [2] element specifiers.

ContentLicense: CC BY-SA 3.0

Title: Ansible 2.x: ec2_remote_facts

Body:
I'm trying to tackle how to list and do something with EC2 stopped instances. ec2_remote_facts is my friend and I can get results from it. But as an ansible noob I cannot for the life of me work out how to get at the 'id' componenent of the returned object. The documentation is sketchy and does not cover what type of thing is returned nor how to use it.

Here is the very basic playbook I'm experimenting with:

---
- name: remote facts
  hosts: localhost

  tasks:

   - ec2_remote_facts:
      region: ap-southeast-2
     register: info

   - name: print
     debug: var=info

This works just fine.

This also works:

---
- name: remote facts
  hosts: localhost

  tasks:

   - ec2_remote_facts:
      region: ap-southeast-2
     register: info

   - name: print
     debug: var=info.instances[0].id

What I can't get my head around is the incantation to give me just the 'id' element for all current instances (3) so I can do something else with all of them--remove, configure, start, whatever. I've had a look at all the looping constructs and with_* options and I can't get any of them to do what I want.

No doubt this will be a 'd'oh!' problem to anyone who knows the answer but I'm afraid at the moment I just don't get it. The returned object looks like this:

ok: [localhost] => {
    "info": {
        "changed": false,
        "instances": [
            {
                "ami_launch_index": "0",
                "architecture": "x86_64",
            "client_token": "vpOGxxxxxxxxxxxxxx",
            "ebs_optimized": false,
            "groups": [
                {
                    "id": "sg-xxxxxxxx",
                    "name": "launch-wizard-3"
                }
            ],
            "hypervisor": "xen",
            "id": "i-01xxxxxxxxxxxxxxxx",

[...]

        "tags": {},
        "virtualization_type": "hvm",
        "vpc_id": "vpc-xxxxxxxx"
    },
        {
            "ami_launch_index": "1",
            "architecture": "x86_64",

[snip, 2 more instances]

Any thoughts people?

Body:
You had it on your second attempt, funnily enough I had the exact same issue but it took your JSON experience for me to see it.

Your second code snippet:

---
- name: remote facts
  hosts: localhost

  tasks:

   - ec2_remote_facts:
      region: ap-southeast-2
     register: info

   - name: print
     debug: var=info.instances[0].id

My addition:

---
- name: remote facts
  hosts: localhost

  tasks:

   - ec2_remote_facts:
      region: ap-southeast-2
     register: info

   - name: print
     debug: var=info.instances[0].id

   - name: Create AMI from Instance ID
     ec2_ami:
       aws_access_key: "{{ aws_access_key }}"
       aws_secret_key: "{{ aws_secret_key }}"
       region: "{{ region }}"
       instance_id: "{{ ec2_remote_facts.instances[0].id }}"

Cheers for helping me work this one out haha.

Output from Ansible:

 (ansible27) user@user:/etc/ansible/playbooks$ sudo ansible-playbook ec2_facts.yml
 [WARNING]: Found both group and host with same name: localhost

PLAY [localhost] ***************************************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [EC2 Remote Facts.] *******************************************************
ok: [localhost]

TASK [Display results in JSON format.] *****************************************
ok: [localhost] => {
    "changed": false,
    "msg": "Most upto date instance is: i-1234567abcdefg "
}

TASK [Create AMI from instance ID.] ********************************************
changed: [localhost]

PLAY RECAP *********************************************************************
localhost                  : ok=4    changed=1    unreachable=0    failed=0

For your problem of the loop, I assume it will just be a case of passing in the [1] and [2] element specifiers.


问:
Khatri product of matrices using np.tensordot
I'm trying to decompose a Tensor (m, n, o) into matrices A(m, r), B (n, r) and C (k, r). This is known as PARAFAC decomposition. Tensorly already does this kind of a decomposition.

An important step is to multiply A, B, and C to get a tensor of shape (m, n, o).

Tensorly does this as follows:

```<code>def kt_to_tensor(A, B, C):
    factors = [A, B, C]
    for r in range(factors[0].shape[1]):
        vecs = np.ix_(*[u[:, r] for u in factors])
        if r:
            res += reduce(np.multiply, vecs)
        else:
            res = reduce(np.multiply, vecs)
    return res
</code>```

However, the package I'm using (Autograd) does not support np.ix_ operations. I thus wrote a simpler definition as follows:

```<code>def new_kt_to_tensor(A, B, C):
    m, n, o = A.shape[0], B.shape[0], C.shape[0]
    out = np.zeros((m, n, o))
    k_max = A.shape[1]
    for alpha in range(0, m):
        for beta in range(0, n):
            for delta in range(0, o):
                for k in range(0, k_max):
                    out[alpha, beta, delta]=out[alpha, beta, delta]+ A[alpha, k]*B[beta, k]*C[delta, k]
    return out
</code>```

However, it turns out that this implementation also has some aspects that autograd does not support. However, autograd does support np.tensordot.

I was wondering how to use np.tensordot to obtain this multiplication. I think that Tensorflow's tf.tensordot would also have a similar functionality.

Intended solution should be something like:

```<code>def tensordot_multplication(A, B, C):
    """
    use np.tensordot
    """
</code>```

答:
The code you refer to isn't actually how TensorLy implements it but simply an alternative implementation given in the doc.

The actual code used in TensorLy is:

```<code>def kruskal_to_tensor(factors):
    shape = [factor.shape[0] for factor in factors]
    full_tensor = np.dot(factors[0], khatri_rao(factors[1:]).T)
    return fold(full_tensor, 0, shape)
</code>```

where the khatri_rao is implemented using numpy.einsum in a way that generalizes what Divakar suggested.

Body:
I'm trying to decompose a Tensor (m, n, o) into matrices A(m, r), B (n, r) and C (k, r). This is known as PARAFAC decomposition. Tensorly already does this kind of a decomposition.

An important step is to multiply A, B, and C to get a tensor of shape (m, n, o).

Tensorly does this as follows:

def kt_to_tensor(A, B, C):
    factors = [A, B, C]
    for r in range(factors[0].shape[1]):
        vecs = np.ix_(*[u[:, r] for u in factors])
        if r:
            res += reduce(np.multiply, vecs)
        else:
            res = reduce(np.multiply, vecs)
    return res

However, the package I'm using (Autograd) does not support np.ix_ operations. I thus wrote a simpler definition as follows:

def new_kt_to_tensor(A, B, C):
    m, n, o = A.shape[0], B.shape[0], C.shape[0]
    out = np.zeros((m, n, o))
    k_max = A.shape[1]
    for alpha in range(0, m):
        for beta in range(0, n):
            for delta in range(0, o):
                for k in range(0, k_max):
                    out[alpha, beta, delta]=out[alpha, beta, delta]+ A[alpha, k]*B[beta, k]*C[delta, k]
    return out

However, it turns out that this implementation also has some aspects that autograd does not support. However, autograd does support np.tensordot.

I was wondering how to use np.tensordot to obtain this multiplication. I think that Tensorflow's tf.tensordot would also have a similar functionality.

Intended solution should be something like:

def tensordot_multplication(A, B, C):
    """
    use np.tensordot
    """

Body:
The code you refer to isn't actually how TensorLy implements it but simply an alternative implementation given in the doc.

The actual code used in TensorLy is:

def kruskal_to_tensor(factors):
    shape = [factor.shape[0] for factor in factors]
    full_tensor = np.dot(factors[0], khatri_rao(factors[1:]).T)
    return fold(full_tensor, 0, shape)

where the khatri_rao is implemented using numpy.einsum in a way that generalizes what Divakar suggested.


问:
replacing list items that fit condition in lambda
I've been stuck on a line of my code for a while, and I'm at a loss as to why it returns as it does.

```<code>guess = 'a'
word = ['a', 'b', 'c']
board = ['_', '_', '_']
board = list(map(lambda x: guess if word[board.index(x)] == guess else x, board))

print(board)
</code>```

This returns

```<code>['a', 'a', 'a']
</code>```

Whereas my goal is a return of

```<code>['a', '_', '_']
</code>```

My previous solution was to loop through the list with an increasing value for the index, and to individually check each entry in word against the guess, and to replace the board list at the same index, but I feel that there is a more concise and pythonic way using lambda, I just can't quite get it.

答:
You can use list comprehension:

```<code>guess = 'a'

word = ['a', 'b', 'c']

new_word = [i if i == guess else "_" for i in word]
</code>```

This will give you:

```<code>["a", "_", "_"]
</code>```

Body:
I've been stuck on a line of my code for a while, and I'm at a loss as to why it returns as it does.

guess = 'a'
word = ['a', 'b', 'c']
board = ['_', '_', '_']
board = list(map(lambda x: guess if word[board.index(x)] == guess else x, board))

print(board)

This returns

['a', 'a', 'a']

Whereas my goal is a return of

['a', '_', '_']

My previous solution was to loop through the list with an increasing value for the index, and to individually check each entry in word against the guess, and to replace the board list at the same index, but I feel that there is a more concise and pythonic way using lambda, I just can't quite get it.

Body:
You can use list comprehension:

guess = 'a'

word = ['a', 'b', 'c']

new_word = [i if i == guess else "_" for i in word]

This will give you:

["a", "_", "_"]


问:
SQL Server extract specific value from string which can contain duplicates/nulls
I am trying to find the best way to extract specific values from a string which can contain nulls/duplicates for the values. The issue is I have to do this in a query and pull those values into a view for use down the line.

Example of the string:

```<code>ABCD: 123 EFG: 03 HIJ: NGAB XYZ:  XYZ: 133
EFG: 03 HIJ: NGAB XYZ: 133
</code>```

I am trying to extract the values for ABCD, EFG, HIJ, and XYZ.

For example, the first string should return:

```<code>123 (for value of ABCD)
03 (for value of EFG)
NGAB (for value of HIJ)
133 (for value of XYZ)
</code>```

Second string should return:

```<code>NULL (for value of ABCD)
03 (for value of EFG)
NGAB (for value of HIJ)
133 (for value of XYZ)
</code>```

The length of the values to return are always static (i.e. ABCD will always be ABCD and 123 will always be the length of the value to return - i.e 3 characters. Same applies for EFG and 03 - EFG will always be EFG and 03 will always be 2 characters and so on).

I am trying to use below to try and return my values:

```<code>SELECT substring(replace(replace(TEMPFIELD,' ',''),':',''), charindex('XYZ',replace(replace(TEMPFIELD,' ',''),':',''))+3,3) AS XYZ FROM MYTABLE
</code>```

I change my query per field and adjust the length on the substring as needed. The issue is that when there are duplicates, I return the wrong values and when there are nulls, I return the wrong value.

For example, my query returns XYZ as the value of XYZ in the first string instead of 123. It also returns 03H as the value of ABCD in the second string instead of NULL. Is there a better function for me to use in this case to handle both scenarios of nulls/duplicates?

Updated query:

```<code>SELECT CASE WHEN TEMPFIELD LIKE '%XYZ%XYZ%'
            THEN     substring(stuff(replace(replace(TEMPFIELD ,' ',''),':',''),charindex('XYZ',replace(replace(TEMPFIELD ,' ',''),':','')),3,''), charindex('XYZ',stuff(replace(replace(TEMPFIELD ,' ',''),':',''),charindex('XYZ',replace(replace(TEMPFIELD ,' ',''),':','')),3,''))+3,3)
       WHEN TEMPFIELD LIKE '%XYZ%'
            THEN  substring(replace(replace(TEMPFIELD ,' ',''),':',''), charindex('XYZ',replace(replace(TEMPFIELD ,' ',''),':',''))+3,3)
       ELSE NULL
  END AS XYZ
</code>```

答:
Ideally if you can you would want to sort out the string you are trying to pass as this could get very messy, but I can offer you this solution, based on the following assumptions:

Duplicated keys only occur twice as per your example

The values cannot contain the key

That when the keys are duplicated that the last one is the value you want.

```<code>  CASE WHEN TEMPFIELD LIKE '%XYZ%XYZ%'
            THEN SUBSTRING(TEMPFIELD, CHARINDEX('XYZ: ', TEMPFIELD, CHARINDEX('XYZ: ', TEMPFIELD) + 1) + 5, 3)
       WHEN TEMPFIELD LIKE '%XYZ%'
            THEN SUBSTRING(TEMPFIELD, CHARINDEX('XYZ: ', TEMPFIELD) + 5, 3)
       ELSE NULL
  END AS XYZ
</code>```

Add in the replacements if you really need to but if you know the format is reliable enough you shouldn't need to do this as it will just add processing time.

To explain what this does a bit: the first case statement will deal with the duplicated values by getting the CHARINDEX of the second key, if that case criteria does not match then it will fall to the second case and do something similar to what you were already doing and finally if the string does not match either of those it simply gives you null.

Body:
I am trying to find the best way to extract specific values from a string which can contain nulls/duplicates for the values. The issue is I have to do this in a query and pull those values into a view for use down the line.

Example of the string:

ABCD: 123 EFG: 03 HIJ: NGAB XYZ:  XYZ: 133
EFG: 03 HIJ: NGAB XYZ: 133

I am trying to extract the values for ABCD, EFG, HIJ, and XYZ.

For example, the first string should return:

123 (for value of ABCD)
03 (for value of EFG)
NGAB (for value of HIJ)
133 (for value of XYZ)

Second string should return:

NULL (for value of ABCD)
03 (for value of EFG)
NGAB (for value of HIJ)
133 (for value of XYZ)

The length of the values to return are always static (i.e. ABCD will always be ABCD and 123 will always be the length of the value to return - i.e 3 characters. Same applies for EFG and 03 - EFG will always be EFG and 03 will always be 2 characters and so on).

I am trying to use below to try and return my values:

SELECT substring(replace(replace(TEMPFIELD,' ',''),':',''), charindex('XYZ',replace(replace(TEMPFIELD,' ',''),':',''))+3,3) AS XYZ FROM MYTABLE

I change my query per field and adjust the length on the substring as needed. The issue is that when there are duplicates, I return the wrong values and when there are nulls, I return the wrong value.

For example, my query returns XYZ as the value of XYZ in the first string instead of 123. It also returns 03H as the value of ABCD in the second string instead of NULL. Is there a better function for me to use in this case to handle both scenarios of nulls/duplicates?

Updated query:

SELECT CASE WHEN TEMPFIELD LIKE '%XYZ%XYZ%'
            THEN     substring(stuff(replace(replace(TEMPFIELD ,' ',''),':',''),charindex('XYZ',replace(replace(TEMPFIELD ,' ',''),':','')),3,''), charindex('XYZ',stuff(replace(replace(TEMPFIELD ,' ',''),':',''),charindex('XYZ',replace(replace(TEMPFIELD ,' ',''),':','')),3,''))+3,3)
       WHEN TEMPFIELD LIKE '%XYZ%'
            THEN  substring(replace(replace(TEMPFIELD ,' ',''),':',''), charindex('XYZ',replace(replace(TEMPFIELD ,' ',''),':',''))+3,3)
       ELSE NULL
  END AS XYZ

Body:
Ideally if you can you would want to sort out the string you are trying to pass as this could get very messy, but I can offer you this solution, based on the following assumptions:

Duplicated keys only occur twice as per your example

The values cannot contain the key

That when the keys are duplicated that the last one is the value you want.

  CASE WHEN TEMPFIELD LIKE '%XYZ%XYZ%'
            THEN SUBSTRING(TEMPFIELD, CHARINDEX('XYZ: ', TEMPFIELD, CHARINDEX('XYZ: ', TEMPFIELD) + 1) + 5, 3)
       WHEN TEMPFIELD LIKE '%XYZ%'
            THEN SUBSTRING(TEMPFIELD, CHARINDEX('XYZ: ', TEMPFIELD) + 5, 3)
       ELSE NULL
  END AS XYZ

Add in the replacements if you really need to but if you know the format is reliable enough you shouldn't need to do this as it will just add processing time.

To explain what this does a bit: the first case statement will deal with the duplicated values by getting the CHARINDEX of the second key, if that case criteria does not match then it will fall to the second case and do something similar to what you were already doing and finally if the string does not match either of those it simply gives you null.


问:
Refresh Datagrid after adding a new Customer MVVM WPF
This my view Main:

XAML View Main :

```<code><DataGrid AutoGenerateColumns="false"
          SelectedItem="{Binding Selectedrole}"
          ItemsSource="{Binding RoleList}">
  <Button Content="Add Role"
          Command="{Binding  AddRole}"
          Height="35"/>
</DataGrid>
</code>```

The ViewModel Main:

```<code>public RoleManagementViewModel()
{
    roleList = new ObservableCollection<UserRoleClass>(WCFclient.GetAllRoles());
    _addRole = new RelayCommand<string>(AddRoleFunction);
}

private void AddRoleFunction(object obj)
{
    if (!Application.Current.Windows.OfType<SelectionCompartementView>().Any())
    {
        AddRoleView winAddRole = new AddRoleView();
        winAddRole.DataContext = new AddRoleViewModel();
        winAddRole.Show();
        winAddRole.Topmost = true;
        winAddRole.Focus();
    }
}

public ObservableCollection<UserRoleClass> RoleList
{
    get { return roleList; }
    set
    {
        roleList = value;
        OnPropertyChanged("RoleList");
    }
}
</code>```

The view Add Role:

Xaml Add-Role:

```<code><Button x:Name="button1"
        Command="{Binding SaveRole}"
        CommandParameter="{Binding ElementName=AddRole}"/>
</code>```

ViewModel Add-Role:

```<code>public AddRoleViewModel()
{
    _addOrUpdate = new UserRoleClass();
    _addOrUpdate = new UserRoleClass();
    saveRole = new RelayCommand<Window>(addFunc);
}

private void addFunc(Window window)
{
    UserRoleClass newRole = new UserRoleClass()
    {
        name = AddOrUpdate.name,
        description = AddOrUpdate.description,
    };
    int resultSave = WCFclient.saveRole(newRole);
    if (resultSave == 0)
    {
        String UpdateInformation0 = "Role is saved successfully";
        string sCaption = "Save Role";
        MessageBoxButton btnMessageBox = MessageBoxButton.OK;
        MessageBoxImage icnMessageBox = MessageBoxImage.Information;
        MessageBoxResult rsltMessageBox = MessageBox.Show(
            UpdateInformation0, sCaption, btnMessageBox, icnMessageBox);
    }
    if (window != null)
    {
        window.Close();
    }
}

private ICommand saveRole;
public ICommand SaveRole
{
    get { return saveRole; }
}
</code>```

It works fine: when I add a new Role, the view of Add-Role closes and returns to the view Main, and I have a result in database... but not in the DataGrid in MainView.

How can I refresh directly?

答:
First, why do you have two of the following line?
_addOrUpdate = new UserRoleClass();

Second, when you save your new role, it seems you're calling a WCF service that saves it to the DB.

You're using an observable collection which should update when you add to it, but I don't see your code adding the new role into the RoleList.

Body:
This my view Main:

XAML View Main :

<DataGrid AutoGenerateColumns="false"
          SelectedItem="{Binding Selectedrole}"
          ItemsSource="{Binding RoleList}">
  <Button Content="Add Role"
          Command="{Binding  AddRole}"
          Height="35"/>
</DataGrid>

The ViewModel Main:

public RoleManagementViewModel()
{
    roleList = new ObservableCollection<UserRoleClass>(WCFclient.GetAllRoles());
    _addRole = new RelayCommand<string>(AddRoleFunction);
}

private void AddRoleFunction(object obj)
{
    if (!Application.Current.Windows.OfType<SelectionCompartementView>().Any())
    {
        AddRoleView winAddRole = new AddRoleView();
        winAddRole.DataContext = new AddRoleViewModel();
        winAddRole.Show();
        winAddRole.Topmost = true;
        winAddRole.Focus();
    }
}

public ObservableCollection<UserRoleClass> RoleList
{
    get { return roleList; }
    set
    {
        roleList = value;
        OnPropertyChanged("RoleList");
    }
}

The view Add Role:

Xaml Add-Role:

<Button x:Name="button1"
        Command="{Binding SaveRole}"
        CommandParameter="{Binding ElementName=AddRole}"/>

ViewModel Add-Role:

public AddRoleViewModel()
{
    _addOrUpdate = new UserRoleClass();
    _addOrUpdate = new UserRoleClass();
    saveRole = new RelayCommand<Window>(addFunc);
}

private void addFunc(Window window)
{
    UserRoleClass newRole = new UserRoleClass()
    {
        name = AddOrUpdate.name,
        description = AddOrUpdate.description,
    };
    int resultSave = WCFclient.saveRole(newRole);
    if (resultSave == 0)
    {
        String UpdateInformation0 = "Role is saved successfully";
        string sCaption = "Save Role";
        MessageBoxButton btnMessageBox = MessageBoxButton.OK;
        MessageBoxImage icnMessageBox = MessageBoxImage.Information;
        MessageBoxResult rsltMessageBox = MessageBox.Show(
            UpdateInformation0, sCaption, btnMessageBox, icnMessageBox);
    }
    if (window != null)
    {
        window.Close();
    }
}

private ICommand saveRole;
public ICommand SaveRole
{
    get { return saveRole; }
}

It works fine: when I add a new Role, the view of Add-Role closes and returns to the view Main, and I have a result in database... but not in the DataGrid in MainView.

How can I refresh directly?


问:
Issues Uploading JSON to s3 using node.js
I am new to amazon s3 and am trying to use node.js to upload JSON into a file. My object is users, and it has a bunch of keys and values in it. Here is how I'm uploading it:

```<code> s3.putObject({Bucket: 'currenteventstest',Key: 'users.json',Body: users, ContentType: "application/json"});
</code>```

However, when I re download it, it's just an empty object.

答:
Adding a callback function fixes the problem:</p>

```<code>s3.putObject({
  Bucket: 'currenteventstest',
  Key: 'users.json',
  Body: JSON.stringify(users),
  ContentType: "application/json"},
  function (err,data) {
    console.log(JSON.stringify(err) + " " + JSON.stringify(data));
  }
);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to amazon s3 and am trying to use node.js to upload JSON into a file. My object is users, and it has a bunch of keys and values in it. Here is how I'm uploading it:

 s3.putObject({Bucket: 'currenteventstest',Key: 'users.json',Body: users, ContentType: "application/json"});

However, when I re download it, it's just an empty object.

Body:
Adding a callback function fixes the problem:

s3.putObject({
  Bucket: 'currenteventstest',
  Key: 'users.json',
  Body: JSON.stringify(users),
  ContentType: "application/json"},
  function (err,data) {
    console.log(JSON.stringify(err) + " " + JSON.stringify(data));
  }
);


问:
Run bat file from different disk with java
Im trying to run a bat from C:/abc/def/coolBat.bat but my java workspace is in D:/

I've tried with :

```<code>String cmd = "cmd /c /start C:/abc/def/coolBat.bat";
Runtime.getRuntime().exec(cmd);
</code>```

But didn't work, so I tried this

```<code>String[] command = { "cmd.exe", "/C", "C:/abc/def/coolBat.bat" };
Runtime.getRuntime().exec(cmd);
</code>```

didnt work either. Tried this too

```<code>Executor exec = new DefaultExecutor();
exec.setWorkingDirectory(new File("C:/abc/def"));
CommandLine cl = new CommandLine("coolBat.bat");
int exitvalue = exec.execute(cl);
</code>```

Says it cant find the file.

Tried something like this too:

```<code>Runtime.getRuntime().exec("cmd cd /d C:/abc/def/ && coolBat.bat");
</code>```

And nothing. The weird thing is that this command:

```<code>cd /d C:/abc/def/ && coolBat.bat
</code>```

Works when i do it in cmd. Its worth saying that the bat file copies some files to another directory, all inside C:/

EDITED N°1

```<code>CD C:\abc\def\MN
copy almn + ctmn + bamn C:\abc\def\mn_sf.txt
CD C:\abc\def\ME
copy alme + ctme + bame  C:\abc\def\me_sf.txt
CD C:\abc\def\
if exist MN.txt del MN.txt
if exist ME.txt del ME.txt
if exist JUZ.txt del JUZ.txt
if exist FUNC.txt del FUNC.txt
if exist AHO.txt del AHO.txt
CD C:\
</code>```

答:
Well I finally got it to work, just had to change my workspace to C:/

Apparently the problem was that it couldn't change from D:/ to C:/ to execute. I ran the same commands I tried before and there was no problem.

Guess the question remains, why it couldn't change from D:/ to C:/ when running commands from Java.

Thanks to everyone for the help

Body:
Im trying to run a bat from C:/abc/def/coolBat.bat but my java workspace is in D:/

I've tried with :

String cmd = "cmd /c /start C:/abc/def/coolBat.bat";
Runtime.getRuntime().exec(cmd);

But didn't work, so I tried this

String[] command = { "cmd.exe", "/C", "C:/abc/def/coolBat.bat" };
Runtime.getRuntime().exec(cmd);

didnt work either. Tried this too

Executor exec = new DefaultExecutor();
exec.setWorkingDirectory(new File("C:/abc/def"));
CommandLine cl = new CommandLine("coolBat.bat");
int exitvalue = exec.execute(cl);

Says it cant find the file.

Tried something like this too:

Runtime.getRuntime().exec("cmd cd /d C:/abc/def/ && coolBat.bat");

And nothing. The weird thing is that this command:

cd /d C:/abc/def/ && coolBat.bat

Works when i do it in cmd. Its worth saying that the bat file copies some files to another directory, all inside C:/

EDITED N°1

CD C:\abc\def\MN
copy almn + ctmn + bamn C:\abc\def\mn_sf.txt
CD C:\abc\def\ME
copy alme + ctme + bame  C:\abc\def\me_sf.txt
CD C:\abc\def\
if exist MN.txt del MN.txt
if exist ME.txt del ME.txt
if exist JUZ.txt del JUZ.txt
if exist FUNC.txt del FUNC.txt
if exist AHO.txt del AHO.txt
CD C:\


问:
Creating & using ContentProvider for android
When I call an Android ContentProvider I get the following exception:

java.lang.RuntimeException: Unable to
  start activity
  ComponentInfo{de.harm.android.couchone/de.harm.android.couchone.CouchContactClient}:
  java.lang.IllegalArgumentException:
  Unknown URL
  content://de.harm.android.couchone.provider/test2

These are the projects:

https://github.com/der-harm/CouchOneProvider

.../CouchOneContacts

Android uses the so-called ContentResolver to communicate with ContentProvider which in turn handles the persistence functionality - accessing the database.

The ContentProvider registers itself with a unique Uri. The ContentResolver calls the ContentProvider with this Uri and passes additional data, like a SQL query string and/or data to be saved.

In the CouchOneProvider/AndroidManifest.xml I have the following:

```<code><provider android:authorities="de.harm.android.couchone.provider"
   android:name=".Provider" />
</code>```

The Provider uses

```<code>static {
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    uriMatcher.addURI(PROVIDER_NAME, DB_Name, URI_COLLECTION);
    uriMatcher.addURI(PROVIDER_NAME, DB_Name + "/#", URI_ENTITY);
}
</code>```

and

```<code>public static boolean isCollectionUri(Uri uri) {
    return uriMatcher.match(uri) == URI_COLLECTION;
}
</code>```

to process the CONTENT_URI used by the ContentResolver to call the ContentProvider:

Am I missing permissions in any of both AndroidManifest.xml?

Am I defining the authority in AndroidManifest.xml wrongly?

Is the CONTENT_URI wrong?

Update:

I have additional information:

Logcat says:

Failed to find provider info for
  de.harm.android.couchone.provider

This should be the starting point. But so far I couldn't find any solution.

The fully qualified classname of the ContentProvider implementation is:

```<code>de.harm.android.couchone.Provider
</code>```

In AndroidManifext.xml exactly this is specified as authority, except for the name being to lower case, but this should be fine.

The package name is defined previously in the xml file, so ".Provider" should be ok, too.

As to be seen in the exception, the client calls:

content://de.harm.android.couchone.provider/test2
```

Logcats answer is:

Failed to find provider info for de.harm.android.couchone.provider

I don't see what's missing, perhaps it's Eclipse or emulator problem?

I install the provider as "run project as Android application".

答:
I have resolved this problem:

Both projects had the same package structure. I changed de.harm.android.couchone to de.harm.android.couchone.provider and de.harm.android.couchone.client.

Body:
When I call an Android ContentProvider I get the following exception:

java.lang.RuntimeException: Unable to
  start activity
  ComponentInfo{de.harm.android.couchone/de.harm.android.couchone.CouchContactClient}:
  java.lang.IllegalArgumentException:
  Unknown URL
  content://de.harm.android.couchone.provider/test2

These are the projects:

https://github.com/der-harm/CouchOneProvider

.../CouchOneContacts

Android uses the so-called ContentResolver to communicate with ContentProvider which in turn handles the persistence functionality - accessing the database.

The ContentProvider registers itself with a unique Uri. The ContentResolver calls the ContentProvider with this Uri and passes additional data, like a SQL query string and/or data to be saved.

In the CouchOneProvider/AndroidManifest.xml I have the following:

<provider android:authorities="de.harm.android.couchone.provider"
   android:name=".Provider" />

The Provider uses

static {
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    uriMatcher.addURI(PROVIDER_NAME, DB_Name, URI_COLLECTION);
    uriMatcher.addURI(PROVIDER_NAME, DB_Name + "/#", URI_ENTITY);
}

and

public static boolean isCollectionUri(Uri uri) {
    return uriMatcher.match(uri) == URI_COLLECTION;
}

to process the CONTENT_URI used by the ContentResolver to call the ContentProvider:

Am I missing permissions in any of both AndroidManifest.xml?

Am I defining the authority in AndroidManifest.xml wrongly?

Is the CONTENT_URI wrong?

Update:

I have additional information:

Logcat says:

Failed to find provider info for
  de.harm.android.couchone.provider

This should be the starting point. But so far I couldn't find any solution.

The fully qualified classname of the ContentProvider implementation is:

de.harm.android.couchone.Provider

In AndroidManifext.xml exactly this is specified as authority, except for the name being to lower case, but this should be fine.

The package name is defined previously in the xml file, so ".Provider" should be ok, too.

As to be seen in the exception, the client calls:

content://de.harm.android.couchone.provider/test2

Logcats answer is:

Failed to find provider info for de.harm.android.couchone.provider

I don't see what's missing, perhaps it's Eclipse or emulator problem?

I install the provider as "run project as Android application".


问:
I want to get all links from a certain webpage using python
i want to be able to pull all urls from the following webpage using python https://yeezysupply.com/pages/all i tried using some other suggestions i found but they didn't seem to work with this particular website. i would end up not finding any urls at all.</p>

```<code>import urllib
import lxml.html
connection = urllib.urlopen('https://yeezysupply.com/pages/all')

dom =  lxml.html.fromstring(connection.read())

for link in dom.xpath('//a/@href'):
    print link
</code>```

答: There are no links in the page source; they are inserted using Javascript after the page is loaded int the browser.</p>

Body:
i want to be able to pull all urls from the following webpage using python https://yeezysupply.com/pages/all i tried using some other suggestions i found but they didn't seem to work with this particular website. i would end up not finding any urls at all.

import urllib
import lxml.html
connection = urllib.urlopen('https://yeezysupply.com/pages/all')

dom =  lxml.html.fromstring(connection.read())

for link in dom.xpath('//a/@href'):
    print link


问:
Don't work servlet. Issue with servlet mapping in web.xml
I have home page and when I click on reference Servlet don't work and I get error 404. I think issue in web.xml mapping, but a don't understand where. Please help me correct this issue. Thank you.

My web.xml

```<code><!--Homepage.-->
<servlet>
    <servlet-name>HomePageServlet</servlet-name>
    <servlet-class>ru.pravvich.servlets.HomePageServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>HomePageServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<!--Add user in database.-->
<servlet>
    <servlet-name>AddUserServlet</servlet-name>
    <servlet-class>ru.pravvich.servlets.AddUserServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>AddUserServlet</servlet-name>
    <url-pattern>/addition</url-pattern>
</servlet-mapping>
</code>```

My jsp homepage:

```<code><body>
    <ul>
        <li><a href="addition.jsp">addition</a></li>
    </ul>
</body>
</code>```

And servlet with doGet method for it:

```<code>public class HomePageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF8");
        req.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(req,resp);
    }
}
</code>```

And by http://localhost:8080/items/ I get my home page.

But, when I click on reference from index.jsp, return: HTTP Status [404] – [Not Found]

My addition.jsp same lie in /WEB-INF/views/addition.jsp

My Servlet for work with addition.jsp :

```<code>public class AddUserServlet extends HttpServlet {

    private DBJoint db;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        db = (DBJoint) getServletContext().getAttribute("db");

        db.getDBExecutor().addUser(
            new User(req.getParameter("name"),
                     req.getParameter("login"),
                     req.getParameter("email")));

        req.setAttribute("serverAnswer", "Add ok!");
        req.getRequestDispatcher("/WEB-INF/views/answer.jsp").forward(req, resp);

    }
}
</code>```

And addition.jsp:

```<code><body>
    <form method="post" action="addition">
        <input type="text" required placeholder="name" name="name"><br>
        <input type="text" required placeholder="login" name="login"><br>
        <input type="text" required placeholder="email" name="email"><br>
        <input type="submit" value="add">
    </form>
</body>
</code>```

答:
I would suggest to use try/catch and debugger mode.

And try to use like this your getRequestDispatcher

```<code>request.getRequestDispatcher("answer.jsp").forward(request, response);
</code>```

or

```<code>req.getRequestDispatcher("~/WEB-INF/views/answer.jsp").forward(req, resp);
</code>```

I think you need to get parameter for each of one, and than set. Try this;

```<code>public class AddUserServlet extends HttpServlet {

private DBJoint db;

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    db = (DBJoint) getServletContext().getAttribute("db");

    String Name = request.getParameter("name");
    String Login= request.getParameter("login");
    String Email= request.getParameter("email");

    db.getDBExecutor().addUser(
        new User(Name, Login, Email);

    //And you need to 'serverAnswer' item in your 'answer.jsp' you know.
    request.setAttribute("serverAnswer", "Add ok!");
    request.getRequestDispatcher("answer.jsp").forward(req, resp);
    }
}
</code>```

And then you can use getAttribute like this in your answer.jsp,

<%String Answer= (String)request.getAttribute("serverAnswer"); %><%= Answer%>

Don't blame me, just i wanna help to you, i hope so it can be help to you, if you wanna you can look my trial project; https://github.com/anymaa/GNOHesap

Have a nice coding :)

Body:
I have home page and when I click on reference Servlet don't work and I get error 404. I think issue in web.xml mapping, but a don't understand where. Please help me correct this issue. Thank you.

My web.xml

<servlet>
    <servlet-name>HomePageServlet</servlet-name>
    <servlet-class>ru.pravvich.servlets.HomePageServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>HomePageServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<servlet>
    <servlet-name>AddUserServlet</servlet-name>
    <servlet-class>ru.pravvich.servlets.AddUserServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>AddUserServlet</servlet-name>
    <url-pattern>/addition</url-pattern>
</servlet-mapping>

My jsp homepage:

addition

And servlet with doGet method for it:

public class HomePageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF8");
        req.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(req,resp);
    }
}

And by http://localhost:8080/items/ I get my home page.

But, when I click on reference from index.jsp, return: HTTP Status [404] – [Not Found]

My addition.jsp same lie in /WEB-INF/views/addition.jsp

My Servlet for work with addition.jsp :

public class AddUserServlet extends HttpServlet {

    private DBJoint db;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        db = (DBJoint) getServletContext().getAttribute("db");

        db.getDBExecutor().addUser(
            new User(req.getParameter("name"),
                     req.getParameter("login"),
                     req.getParameter("email")));

        req.setAttribute("serverAnswer", "Add ok!");
        req.getRequestDispatcher("/WEB-INF/views/answer.jsp").forward(req, resp);

    }
}

And addition.jsp:

    <form method="post" action="addition">
        <input type="text" required placeholder="name" name="name">

        <input type="text" required placeholder="login" name="login">

        <input type="text" required placeholder="email" name="email">

        <input type="submit" value="add">
    </form>

Body:
I would suggest to use try/catch and debugger mode.

And try to use like this your getRequestDispatcher

request.getRequestDispatcher("answer.jsp").forward(request, response);

or

req.getRequestDispatcher("~/WEB-INF/views/answer.jsp").forward(req, resp);

I think you need to get parameter for each of one, and than set. Try this;

public class AddUserServlet extends HttpServlet {

private DBJoint db;

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    db = (DBJoint) getServletContext().getAttribute("db");

    String Name = request.getParameter("name");
    String Login= request.getParameter("login");
    String Email= request.getParameter("email");

    db.getDBExecutor().addUser(
        new User(Name, Login, Email);

    //And you need to 'serverAnswer' item in your 'answer.jsp' you know.
    request.setAttribute("serverAnswer", "Add ok!");
    request.getRequestDispatcher("answer.jsp").forward(req, resp);
    }
}

And then you can use getAttribute like this in your answer.jsp,

<%String Answer= (String)request.getAttribute("serverAnswer"); %><%= Answer%>

Don't blame me, just i wanna help to you, i hope so it can be help to you, if you wanna you can look my trial project; https://github.com/anymaa/GNOHesap

Have a nice coding :)


问:
Vue.js application using Viddler's video player
Hello fellow developers!

I started learning Vue.js yesterday, and loved it! Now I'm trying to build a little application that uses Vue (1.0.28) to display a small online course. There is a JSFiddle link in the bottom of this post, but first, let me explain my problem:

In this application's javascript file I first create a const called course_bundle, that contains the course's information such as title, chapters and files. Then, using Vue I display the course on the screen.

All chapters contains videos, and inside my Vue instance I initiate the player (the video is hosted on viddler) using Viddler's API:

```<code>let embed = new ViddlerEmbed({
    videoId: this.active,
    target: '#player',
    autoplay: 'true',
    type: 'video',
    width: '100%'
  });
</code>```

So far, so good. The problem is when I try to load another video, by clicking on the chapter's title, the video gets duplicated. I wanted to stop the active video and then start the next one.

I might be doing something wrong, so any ideas would be very very welcome.

Here's what I have so far: https://jsfiddle.net/grpaiva/bkadrz9h/

Cheers!

答:
Playing around with your fiddle I was able to get the video to swap using a component, but I converted it to Vue 2 in the process. If that's not what you want, carry on :)

```<code>Vue.component("video-player",{
    props:["video_id"],
    template: `<div ref="player"></div>`,
  mounted(){
    this.embed = new ViddlerEmbed({
        videoId: this.video_id,
        target: this.$refs.player,
        autoplay: 'true',
        type: 'video',
        width: '100%'
    });
    this.embed.manager.events.on('videoPlayer:ended', function(){
        alert('video ended');
    });
  }
})

// creates Vue instance
new Vue({
  el: '#app',
  data: {
    courseTitle: course_bundle.general[0].title,
    chapters: course_bundle.chapters,
    active: course_bundle.chapters[0].video_id,
    files: course_bundle.files,
  },
});
</code>```

Template

```<code><div id="app" class="container">
    <div class="row">
      <video-player v-for="video in chapters"
                    :key="video.video_id"
                    :video_id="video.video_id"
                    v-if="active === video.video_id">
      </video-player>
    </div>
    <div class="row">
      <div class="list-group">

        <h5 class="list-group-item">{{ courseTitle }}</h5>

        <div @click="active = chapter.video_id" class="list-group-item" v-for="chapter in chapters">

          {{ chapter.title }}

        </div>

      </div>
    </div>
    <div class="row">
      <a :href="file.url" target="_blank" v-for="file in files">
        <button class="btn btn-md btn-info">
          <i class="fa fa-file"></i>  {{ file.title }}
        </button>
      </a>
    </div>
  </div>
</code>```

Updated fiddle.

Body:
Hello fellow developers!

I started learning Vue.js yesterday, and loved it! Now I'm trying to build a little application that uses Vue (1.0.28) to display a small online course. There is a JSFiddle link in the bottom of this post, but first, let me explain my problem:

In this application's javascript file I first create a const called course_bundle, that contains the course's information such as title, chapters and files. Then, using Vue I display the course on the screen.

All chapters contains videos, and inside my Vue instance I initiate the player (the video is hosted on viddler) using Viddler's API:

let embed = new ViddlerEmbed({
    videoId: this.active,
    target: '#player',
    autoplay: 'true',
    type: 'video',
    width: '100%'
  });

So far, so good. The problem is when I try to load another video, by clicking on the chapter's title, the video gets duplicated. I wanted to stop the active video and then start the next one.

I might be doing something wrong, so any ideas would be very very welcome.

Here's what I have so far: https://jsfiddle.net/grpaiva/bkadrz9h/

Cheers!

Body:
Playing around with your fiddle I was able to get the video to swap using a component, but I converted it to Vue 2 in the process. If that's not what you want, carry on :)

Vue.component("video-player",{
    props:["video_id"],
    template: `<div ref="player"></div>`,
  mounted(){
    this.embed = new ViddlerEmbed({
        videoId: this.video_id,
        target: this.$refs.player,
        autoplay: 'true',
        type: 'video',
        width: '100%'
    });
    this.embed.manager.events.on('videoPlayer:ended', function(){
        alert('video ended');
    });
  }
})

// creates Vue instance
new Vue({
  el: '#app',
  data: {
    courseTitle: course_bundle.general[0].title,
    chapters: course_bundle.chapters,
    active: course_bundle.chapters[0].video_id,
    files: course_bundle.files,
  },
});

Template

<div id="app" class="container">
    <div class="row">
      <video-player v-for="video in chapters"
                    :key="video.video_id"
                    :video_id="video.video_id"
                    v-if="active === video.video_id">
      </video-player>
    </div>
    <div class="row">
      <div class="list-group">

        <h5 class="list-group-item">{{ courseTitle }}</h5>

        <div @click="active = chapter.video_id" class="list-group-item" v-for="chapter in chapters">

          {{ chapter.title }}

        </div>

      </div>
    </div>
    <div class="row">
      <a :href="file.url" target="_blank" v-for="file in files">
        <button class="btn btn-md btn-info">
          <i class="fa fa-file"></i>&nbsp;&nbsp;{{ file.title }}
        </button>
      </a>
    </div>
  </div>

Updated fiddle.


问:
What is the difference between docker service and stack?
I am wondering what the difference between such things. They have got almost the same commands and give the same result.</p>

答:
The docker service is used when managing individual service on a docker swarm cluster. It is the client command line to access the docker swarm manager.

The docker stack can be used to manage a multi-service application. It also moves many of the options you would enter on the docker service into the .yml file (such as docker-cloud.yml or docker-compose.yml) for easier reuse. It works as a front end "script" on top of the docker swarm  manager used by docker swarm cluster, so you can do everything docker stack does with docker service.

Last but not least, you can consider the docker service vs docker stack is the same as docker run vs docker compose, but in the docker swarm cluster.


问:
Live content edit on screen chrome dev tool
I had read a blog around 4 or 5 months ago about tips and tricks of chrome dev tool. I am not sure what exact keyword I used but I land to a blog and it was awesome.

In that blog there were some tips of chrome dev tools. One of the most liked feature was live content edit on screen directly without editing content on Element tab of chrome.

According to that blog we first need to activate that feature via typing some `keyword.mode = on' and it activates it.

Can anyone share that what is the exact keyword to activate the live content edit on screen directly ?

Thanks

答: From dev tools, simply open up the console and run document.body.contentEditable = true


问:
unable to connect to Genymotion server. please check your internet connection
When I am trying to open Genymotion, this dialogue appear:

How can I solve this?

答: So check your email, since you verified it opens Genymotion again and now if it is connected to the server.</p>


问:
Azure search not returning documents that contain query
I'm trying to have azure search return documents that contain a search query like Veri for example. Right now it only returns documents that only have Veri in them, I want it to return documents that have Veriz, Verizo, and Verizon etc.

My URL looks like so
const url = config.DEFAULT_AZURE_SEARCH_URL + '/indexes/temp/docs?api-version=2015-02-28-Preview&searchMode=all&queryType=simple&search=' + terms + '&$skip=' + skip + '&$top=' + limit

and terms = Veri*

答:
Which language analyzer are you using to analyze the text?

Generally, Lucene analyzers perform stemming of the tokens. This may change the token before it is stored in the index.
eg:'Eating', 'Eat', 'Eaten' can all be stemmed and stored as 'eat' in the Lucene index.

Can you try to switch to Microsoft English analyzer 'en.microsoft', and see if it solves the issue.


问:
Parent fragment to Child Fragment communication
I have been searching and haven't found the best way for nested fragments to communicate with parent fragment. The Android documentation states that:

All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

Suppose I have a Gallery app, there is a ViewPagerFragment (parent) and ImageFragment(child) that is used to show images full screen when they are clicked. I need to pass an ArrayList of Files from my parent fragment to the child fragment. What is a proper way to do it?

1) Create a getter for the ArrayList in parent fragment and use the getParentFragment() in a child fragment to access this method?

2) Implement an interface and go through the Activity, but how will I locate the child fragment from the Activity if it doesn't have an ID?

3) Or use this in parent fragment:

ChildFragment fragment =(ChildFragment)getChildFragmentManager().findFragmentById(R.id.child_fragment_id);

And just use a setter in child fragment.

But again how do I get the ID of the childFragment?

Thanks everyone in advance

答:
I understand that the Fragment to Fragment communication through the activity is for sibling fragments which are coordinated by the same activity.

In this case the siblign fragments are coordinated by a parent fragment, so I would say that the communication should be managed by the parent fragment.

If you are working directly with the fragments then you do that using the ChildFragmentManager().

If you are working with a ViewPager you pass the ChildFragmentManager to the ViewPager insted of passing it the FragmentManager.

If you have to pass a List, I think the easiest is for the ChildFragment to request it when it is ready to receive it by calling a method on the ParentFragment. It can allways get its instace with getParentFragment().

I am not sure where is the safest place to call getParentFrament() to get the list but you can try in onCreateView() ,in onActivityCreated(), o in onResume().

To call the method that returns the list, you can cast the parent Fragment to the specific Fragment class you have extended, or else you can define an interface with the method that returns the List and make your extended parent Fragment implement it.

Then in the child Fragment, you refert to the parent by the interface to call the method and get the list.


答:
The fastest way to do it is with something like this.

```<code> public AddRoleViewModel(Action<UserRoleClass> onAdded = null)
    {
        _addOrUpdate = new UserRoleClass();
        _addOrUpdate = new UserRoleClass();
        _onAdded = onAdded;
        saveRole = new RelayCommand<Window>(addFunc);
    }

    private void addFunc(Window window)
    {
        UserRoleClass newRole = new UserRoleClass()
        {
            name = AddOrUpdate.name,
            description = AddOrUpdate.description,
        };
             int resultSave = WCFclient.saveRole(newRole);
            if (resultSave == 0)
             {
                 String UpdateInformation0 = "Role is saved successfully";
                 string sCaption = "Save Role";
                 MessageBoxButton btnMessageBox = MessageBoxButton.OK;
                 MessageBoxImage icnMessageBox = MessageBoxImage.Information;
                 MessageBoxResult rsltMessageBox = MessageBox.Show(UpdateInformation0, sCaption, btnMessageBox, icnMessageBox);
             }

         }
         _onAdded?.Invoke(newRole);
         if (window != null)
         {

             window.Close();
         }
</code>```

And when you create the ViewModel

```<code> new AddRoleViewModel(newItem=>{ RoleList.Add(newItem); });
</code>```

But I can't say I like the architecture all that much. If might want to look at some sort of a messenger service

Title: Refresh Datagrid after adding a new Customer MVVM WPF

Body:
The fastest way to do it is with something like this.

 public AddRoleViewModel(Action<UserRoleClass> onAdded = null)
    {
        _addOrUpdate = new UserRoleClass();
        _addOrUpdate = new UserRoleClass();
        _onAdded = onAdded;
        saveRole = new RelayCommand<Window>(addFunc);
    }

    private void addFunc(Window window)
    {
        UserRoleClass newRole = new UserRoleClass()
        {
            name = AddOrUpdate.name,
            description = AddOrUpdate.description,
        };
             int resultSave = WCFclient.saveRole(newRole);
            if (resultSave == 0)
             {
                 String UpdateInformation0 = "Role is saved successfully";
                 string sCaption = "Save Role";
                 MessageBoxButton btnMessageBox = MessageBoxButton.OK;
                 MessageBoxImage icnMessageBox = MessageBoxImage.Information;
                 MessageBoxResult rsltMessageBox = MessageBox.Show(UpdateInformation0, sCaption, btnMessageBox, icnMessageBox);
             }

         }
         _onAdded?.Invoke(newRole);
         if (window != null)
         {

             window.Close();
         }

And when you create the ViewModel

 new AddRoleViewModel(newItem=>{ RoleList.Add(newItem); });

But I can't say I like the architecture all that much. If might want to look at some sort of a messenger service


问:
How to manage presenter dependencies while using Dagger/MVP?
I have a Presenter which has multiple dependencies that are provided by the ApplicationComponent. Now the general pattern I've used is to use an @Inject constructor for the presenter.

But I have a case where the presenter has around 6 dependencies.
Is constructor injection still the best practice in this case? I find the constructor to become very unwieldily in such a situation. Is there another way that I'm missing?

答:
As in the comment by EpicPandaForce having a lot of dependencies in a Presenter may be a sign that the presenter does too much. Indeed, in MVP it is easy for the Presenter to degenerate into a "god object". Still, it seems that a multi-parameter constructor is preferable to mutable classes with getters and setters or to property injection which, as in the comment, hides the number of dependencies.

If you cannot refactor your presenter e.g., by finding a higher-level abstraction for it to depend on, the types of issues that arise from constructors with a large number of parameters are addressed in Chapter 2 of Effective Java by Joshua Bloch.

One option is to convert the constructor to a builder (Effective Java Item 2). So instead of:

```<code>public Foo(Bar bar, Baz baz, Zap zap) {
    this.bar = bar;
    this.baz = baz;
    this.zap = zap;
}
</code>```

You have:

```<code>public class FooBuilder {
    private Bar bar;
    private Baz baz;
    private Zap zap;

    public FooBuilder setBar(Bar bar) {
        this.bar = bar;
        return this;
    }

    public FooBuilder setBaz(Baz baz) {
        this.baz = baz;
        return this;
    }

    public FooBuilder setZap(Zap zap) {
        this.zap = zap;
        return this;
    }

    public Foo createFoo() {
        return new Foo(bar, baz, zap);
    }
}
</code>```

This is just the auto-generated Builder you get from using Android Studio's Refactor/Replace constructor with builder function.

Alternative, you can extract a parameter object however you would arguably be violating the Law of Demeter in doing so:

```<code>class FooParams {
    final Bar bar;
    final Baz baz;
    final Zap zap;

    FooParams(Bar bar, Baz baz, Zap zap) {
        this.bar = bar;
        //etc
    }
}

public Foo(FooParams fooParams) {
    this.fooParams = fooParams;
    fooParams.baz.doBazThings(); //etc
}
</code>```

Body:
As in the comment by EpicPandaForce having a lot of dependencies in a Presenter may be a sign that the presenter does too much. Indeed, in MVP it is easy for the Presenter to degenerate into a "god object". Still, it seems that a multi-parameter constructor is preferable to mutable classes with getters and setters or to property injection which, as in the comment, hides the number of dependencies.

If you cannot refactor your presenter e.g., by finding a higher-level abstraction for it to depend on, the types of issues that arise from constructors with a large number of parameters are addressed in Chapter 2 of Effective Java by Joshua Bloch.

One option is to convert the constructor to a builder (Effective Java Item 2). So instead of:

public Foo(Bar bar, Baz baz, Zap zap) {
    this.bar = bar;
    this.baz = baz;
    this.zap = zap;
}

You have:

public class FooBuilder {
    private Bar bar;
    private Baz baz;
    private Zap zap;

    public FooBuilder setBar(Bar bar) {
        this.bar = bar;
        return this;
    }

    public FooBuilder setBaz(Baz baz) {
        this.baz = baz;
        return this;
    }

    public FooBuilder setZap(Zap zap) {
        this.zap = zap;
        return this;
    }

    public Foo createFoo() {
        return new Foo(bar, baz, zap);
    }
}

This is just the auto-generated Builder you get from using Android Studio's Refactor/Replace constructor with builder function.

Alternative, you can extract a parameter object however you would arguably be violating the Law of Demeter in doing so:

class FooParams {
    final Bar bar;
    final Baz baz;
    final Zap zap;

    FooParams(Bar bar, Baz baz, Zap zap) {
        this.bar = bar;
        //etc
    }
}

public Foo(FooParams fooParams) {
    this.fooParams = fooParams;
    fooParams.baz.doBazThings(); //etc
}


问:
MS Access VBA acImport sheet name with spaces and range
I'm building a form with a button called "Go" to import a specific range of a specific excel sheet from an excel file. Another sub/function takes care of having the file name on the form in the field called text_filepathdata.

I've discovered that spaces in the sheet names are problematic, however it can be resolved by using special quotation.

```<code>Dim sheetname As String
sheetname = "'Commit Volumes!'"
DoCmd.Transferspreadsheet acImport, acSpreadsheetTypeExcel12, _
    "lcl_ImportedFile", text_filepathdata, True, sheetname
</code>```

That works, but I can't specify a range in addition to the sheet name because of the special quotation... (ie. "'Commit Volumes!A6:Z5000'" doesn't work and neither does a concatenation of the two pieces like "'Commit Volumes'" & "A6:Z5000")

I've tried all manner of quotations and concatenations, but the only things that work are:

```<code>sheetname = "'Commit Volumes!'"
sheetname = "'Commit Volumes$'"
sheetname = "CommitVolumes!A6:Z5000"
</code>```

The excel sheet cannot be modified because it comes from another system and the file (after being updated) must be uploaded back to that system.

Here is my code:

```<code>Private Sub button_Go_Click()
On Error GoTo Err_button_Go_Click

Dim sheetname As String
sheetname = "'Commit Volumes!'"

If IsNull(text_filepathdata) Or text_filepathdata = "" Then
    MsgBox "Please browse and select a valid file to import.", _
        vbCritical, "Invalid File"
Else
    DoCmd.OpenForm "f_PleaseWait_Processing", acNormal, , , acFormReadOnly, acWindowNormal
    If ifTableExists("lcl_ImportedFile") = True Then
        DoCmd.DeleteObject acTable, "lcl_ImportedFile"
    End If
    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12,_
        "lcl_ImportedFile", text_filepathdata, True, sheetname

'Call module to process the imported data
        Call MainProcess
    End If

Exit_button_Go_Click:
    Exit Sub

Err_button_Go_Click:
    MsgBox Err.Number & " - " & Err.Description
    Resume Exit_button_Go_Click

End Sub
</code>```

I get two different error messages depending on the issue.

If there's a space in the name I get: Run-time error 3129: Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.

If there's a problem with the name otherwise I get: Run-time error 3011: The Microsoft Access database engine could not find the object "Commit Volumes$A1:Z5000". Make sure the object exists and that you spell its name and the path correctly. If "Commit Volumes$A1:Z5000" is not a local object, check your network connection or contact the server administrator.

Any help would be greatly appreciated!

Bill

Variations I've Tried:

```<code>sheetname = "'Commit Volumes'!A6:Z5000";
sheetname = "'Commit Volumes!'A6:Z5000"
sheetname = "'Commit Volumes$'A6:Z5000"
sheetname = "'Commit Volumes'$A6:Z5000"
sheetname = "'Commit Volumes'$A$6:$Z$5000"
sheetname = "'Commit Volumes!'$A$6:$Z$5000"
sheetname = "'Commit Volumes$'$A$6:$Z$5000"
</code>```

答:
I tried the above proposed solutions and unfortunately it did not work in my case: indeed the import method of Access does not like it when the worksheets have spaces in their names.

I did a workaround: renaming the worksheets during the code to something short and without spaces, for instance: from "Data Q1 2016"  to "WS1". In this way, you can pass the value "WS1$" to the Range argument of the import function, and Access will import the used range of the given worksheet

When importing the second worksheet, I again used the code and renamed it to "WS2"... and so forth.

in summary:  rename the worksheets during code runtime to short names without spaces, and add the '$' symbol at the end to make it grab the used range.

Body:
I'm building a form with a button called "Go" to import a specific range of a specific excel sheet from an excel file. Another sub/function takes care of having the file name on the form in the field called text_filepathdata.

I've discovered that spaces in the sheet names are problematic, however it can be resolved by using special quotation.

Dim sheetname As String
sheetname = "'Commit Volumes!'"
DoCmd.Transferspreadsheet acImport, acSpreadsheetTypeExcel12, _
    "lcl_ImportedFile", text_filepathdata, True, sheetname

That works, but I can't specify a range in addition to the sheet name because of the special quotation... (ie. "'Commit Volumes!A6:Z5000'" doesn't work and neither does a concatenation of the two pieces like "'Commit Volumes'" & "A6:Z5000")

I've tried all manner of quotations and concatenations, but the only things that work are:

sheetname = "'Commit Volumes!'"
sheetname = "'Commit Volumes$'"
sheetname = "CommitVolumes!A6:Z5000"

The excel sheet cannot be modified because it comes from another system and the file (after being updated) must be uploaded back to that system.

Here is my code:

Private Sub button_Go_Click()
On Error GoTo Err_button_Go_Click

Dim sheetname As String
sheetname = "'Commit Volumes!'"

If IsNull(text_filepathdata) Or text_filepathdata = "" Then
    MsgBox "Please browse and select a valid file to import.", _
        vbCritical, "Invalid File"
Else
    DoCmd.OpenForm "f_PleaseWait_Processing", acNormal, , , acFormReadOnly, acWindowNormal
    If ifTableExists("lcl_ImportedFile") = True Then
        DoCmd.DeleteObject acTable, "lcl_ImportedFile"
    End If
    DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12,_
        "lcl_ImportedFile", text_filepathdata, True, sheetname

'Call module to process the imported data
        Call MainProcess
    End If

Exit_button_Go_Click:
    Exit Sub

Err_button_Go_Click:
    MsgBox Err.Number & " - " & Err.Description
    Resume Exit_button_Go_Click

End Sub

I get two different error messages depending on the issue.

If there's a space in the name I get: Run-time error 3129: Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.

If there's a problem with the name otherwise I get: Run-time error 3011: The Microsoft Access database engine could not find the object "Commit Volumes$A1:Z5000". Make sure the object exists and that you spell its name and the path correctly. If "Commit Volumes$A1:Z5000" is not a local object, check your network connection or contact the server administrator.

Any help would be greatly appreciated!

Bill

Variations I've Tried:

sheetname = "'Commit Volumes'!A6:Z5000";
sheetname = "'Commit Volumes!'A6:Z5000"
sheetname = "'Commit Volumes$'A6:Z5000"
sheetname = "'Commit Volumes'$A6:Z5000"
sheetname = "'Commit Volumes'$A$6:$Z$5000"
sheetname = "'Commit Volumes!'$A$6:$Z$5000"
sheetname = "'Commit Volumes$'$A$6:$Z$5000"


问:
How to properly implement a custom session persister in PHP + MySQL?
I'm trying to implement a custom session persister in PHP + MySQL. Most of the stuff is trivial - create your DB table, make your read/write functions, call session_set_save_hander(), etc. There are even several tutorials out there that offer sample implementations for you. But somehow all these tutorials have conveniently overlooked one tiny detail about session persisters - locking. And now that's where the real fun starts!

I looked at the implementation of session_mysql PECL extension of PHP. That uses MySQL's functions get_lock() and release_lock(). Seems nice, but I don't like the way it's doing it. The lock is acquired in the read function, and released in the write function. But what if the write function never gets called? What if the script somehow crashes, but the MySQL connection stays open (due to pooling or something)? Or what if it the script enters a deadly deadlock?

I just had a problem where a script opened a session and then tried to flock() a file over an NFS share, while the other computer (that hosted the file) was also doing the same thing. The result was that the flock()-over-NFS call was blocking the script for about 30 seconds on each call. And it was in a loop of 20 iterations! Since that was an external operation, PHP's script timeouts didn't apply, and the session got locked for over 10 minutes every time this script was accessed. And, as luck would have it, this was the script that got polled by an AJAX shoutbox every 5 seconds... Major showstopper.

I already have some ideas on how to implement it in a better way, but I would really like to hear what other people suggest. I haven't had that much experience with PHP to know what subtle edge cases loom in the shadows which could one day jeopardize the whole thing.

Added:

OK, seems that nobody has anything to suggest. OK then, here's my idea. I'd like some opinon on where this could go wrong.

Create a session table with InnoDB storage engine. This should ensure some proper locking of rows even under clustered scenarios. The table should have the columns ID, Data, LastAccessTime, LockTime, LockID. I'm omitting the datatypes here because they follow quite directly from the data that needs to be stored in them. The ID will be the ID of the PHP session. Data will of course contain the session data. LastAccessTime will be a timestamp which will be updated on each read/write operation and will be used by GC to delete old sessions. LockTime will be a timestamp of the last lock that was acquired on the session, and LockID will be a GUID of the lock.

When a read operation is requested, there will be the following actions taken:

Execute INSERT IGNORE INTO sessions (id, data, lastaccesstime, locktime, lockid) values ($sessid, null, now(), null, null); - this will create the session row if it is not there, but do nothing if it is already present;

Generate a random lock id in the variable $guid;

Execute UPDATE sessions SET (lastaccesstime, locktime, lockid) values (now(), now(), $guid) where id=$sessid and (lockid is null or locktime < date_add(now(), INTERVAL -30 seconds)); - this is an atomic operation which will either obtain a lock on the session row (if it's not locked or the lock is expired), or will do nothing.

Check with mysql_affected_rows() if the lock was obtained or not. If it was obtained - proceed. If not - re-attempt the operation every 0.5 seconds. If in 40 seconds the lock is still not obtained, throw an exception.

When a write operation is requested, execute UPDATE sessions SET (lastaccesstime, data, locktime, lockid) values (now(), $data, null, null) where id=$sessid and lockid=$guid; This is another atomic operation which will update the session row with the new data and remove the lock if it still has the lock, but do nothing if the lock was already taken away.

When a gc operation is requested, simply delete all rows with lastaccesstime too old.

Can anyone see flaws with this?

答: My question is why lock at all?  Why not just let the last write succeed?  You shouldn't be using session data as a cache, so writes tend to be infrequent, and in practice never trample each other. </p>

ContentLicense: CC BY-SA 2.5


问:
How can I generate a random number within a certain range with Java?
I want to generate a random number in Java. It can be of integer, byte or float type, but all I really need it is to generate a random number. This is what I'm doing:

Generate a random number within a certain range (e.g. 5 through 20).

Take the number and store it within a variable.

Perform arithmetic on it.

Here's the code:

```<code>import java.util.HashMap;

public class Attack {
    public static void main(String[] args) {
        HashMap<String, Integer> attacks = new HashMap<String, Integer>();
        attacks.put("Punch", 1);
        attacks.put("Uppercut", 3);
        attacks.put("Roundhouse Kick", 5);

        int actionPoints = // Code for random number generation

        System.out.println("A brigade integrant appeared!");
        System.out.println("What do you do?");
        System.out.println("1: Punch [1 AP], 2: Uppercut [3 AP], 3: Roundhouse Kick [5 AP]");
        System.out.println("You have " + actionPoints + " Action Points.");
        Scanner reader = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int n = reader.nextInt();
        reader.close();

        if n == 1 {
            System.out.println("The brigade integrant takes 2 HP of damage!");
        }
        else if n == 2 {
            System.out.println("The brigade integrant takes 5 HP of damage!");
        }
        else if n == 3 {
            System.out.println("The brigade integrant takes 8 HP of damage!");
        }
    }
}
</code>```

答:
Try this :  </p>

```<code>int lower = 12;
int higher = 29;

int random = (int)(Math.random() * (higher-lower)) + lower;
</code>```

Body:
I want to generate a random number in Java. It can be of integer, byte or float type, but all I really need it is to generate a random number. This is what I'm doing:

Generate a random number within a certain range (e.g. 5 through 20).

Take the number and store it within a variable.

Perform arithmetic on it.

Here's the code:

import java.util.HashMap;

public class Attack {
    public static void main(String[] args) {
        HashMap<String, Integer> attacks = new HashMap<String, Integer>();
        attacks.put("Punch", 1);
        attacks.put("Uppercut", 3);
        attacks.put("Roundhouse Kick", 5);

        int actionPoints = // Code for random number generation

        System.out.println("A brigade integrant appeared!");
        System.out.println("What do you do?");
        System.out.println("1: Punch [1 AP], 2: Uppercut [3 AP], 3: Roundhouse Kick [5 AP]");
        System.out.println("You have " + actionPoints + " Action Points.");
        Scanner reader = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int n = reader.nextInt();
        reader.close();

        if n == 1 {
            System.out.println("The brigade integrant takes 2 HP of damage!");
        }
        else if n == 2 {
            System.out.println("The brigade integrant takes 5 HP of damage!");
        }
        else if n == 3 {
            System.out.println("The brigade integrant takes 8 HP of damage!");
        }
    }
}

Body:
Try this :

int lower = 12;
int higher = 29;

int random = (int)(Math.random() * (higher-lower)) + lower;


问:
Counter contain 10 digits
I am working on a basic Java app. I want to assign an ID to each person. The ID should contain 10 digits.
for example:
0000000001
0000000002

how should I set my count

```<code>  private static int count= 0;
  private int id;
  private String Name;
</code>```

答:
Just change your id to String and then calculate it in constructor using String.format()

```<code>String id = String.format("%010d", count);
</code>```

where first "0" in "%010d" tells method to pad given in argument number with zeros, and "10" is a length of the result.

Title: Counter contain 10 digits

Body:
I am working on a basic Java app. I want to assign an ID to each person. The ID should contain 10 digits.
for example:
0000000001
0000000002

how should I set my count

  private static int count= 0;
  private int id;
  private String Name;

Body:
Just change your id to String and then calculate it in constructor using String.format()

String id = String.format("%010d", count);

where first "0" in "%010d" tells method to pad given in argument number with zeros, and "10" is a length of the result.


问:
Remove submenu page "customize.php" in WordPress 4.0
When I was running WP 3.9.2 I was able to use the following code to remove the Customize menu item from Appearance in the admin menu.

```<code>function remove_customize() {
  remove_submenu_page('themes.php', 'customize.php');
}
add_action('admin_init', 'remove_customize', 999);
</code>```

Once I updated to 4.0 this is no longer working.

答:
The accepted answer by @rjb didn't work for my spanish wordpress, but just changing the Customize to customize did the trick.

```<code>/**
 * Remove Admin Menu Link to Theme Customizer
 */
add_action( 'admin_menu', function () {
    global $submenu;

    if ( isset( $submenu[ 'themes.php' ] ) ) {
        foreach ( $submenu[ 'themes.php' ] as $index => $menu_item ) {
            if ( in_array( 'customize', $menu_item ) ) {
                unset( $submenu[ 'themes.php' ][ $index ] );
            }
        }
    }
});
</code>```

Body:
When I was running WP 3.9.2 I was able to use the following code to remove the Customize menu item from Appearance in the admin menu.

function remove_customize() {
  remove_submenu_page('themes.php', 'customize.php');
}
add_action('admin_init', 'remove_customize', 999);

Once I updated to 4.0 this is no longer working.

Body:
The accepted answer by @rjb didn't work for my spanish wordpress, but just changing the Customize to customize did the trick.

/**
 * Remove Admin Menu Link to Theme Customizer
 */
add_action( 'admin_menu', function () {
    global $submenu;

    if ( isset( $submenu[ 'themes.php' ] ) ) {
        foreach ( $submenu[ 'themes.php' ] as $index => $menu_item ) {
            if ( in_array( 'customize', $menu_item ) ) {
                unset( $submenu[ 'themes.php' ][ $index ] );
            }
        }
    }
});


问:
req.body empty on posts
All of a sudden this has been happening to all my projects.

Whenever I make a post in nodejs using express and body-parser req.body is an empty object.

```<code>var express    = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded())

// parse application/json
app.use(bodyParser.json())

app.listen(2000);

app.post("/", function (req, res) {
  console.log(req.body) // populated!
  res.send(200, req.body);
});
</code>```

Via ajax and postman it's always empty.

However via curl

```<code>$ curl -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:2000/
</code>```

it works as intended.

I tried manually setting Content-type :  application/json in the former but I then always get 400 bad request

This has been driving me crazy.

I thought it was that something updated in body-parser but I downgraded and it didn't help.

Any help appreciated, thanks.

答:
I discovered, that it works when sending with content type

"application/json"

in combination with server-side

app.use(express.json())

(As @marcelocra pointed out, the 2022 version would use)

(old version for reference)

app.use(bodyParser.json());

Now I can send via

```<code>var data = {name:"John"}
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", theUrl, false); // false for synchronous request
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(data);
</code>```

and the result is available in request.body.name on the server.

Title: req.body empty on posts

Body:
All of a sudden this has been happening to all my projects.

Whenever I make a post in nodejs using express and body-parser req.body is an empty object.

var express    = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded())

// parse application/json
app.use(bodyParser.json())

app.listen(2000);

app.post("/", function (req, res) {
  console.log(req.body) // populated!
  res.send(200, req.body);
});

Via ajax and postman it's always empty.

However via curl

$ curl -H "Content-Type: application/json" -d '{"username":"xyz","password":"xyz"}' http://localhost:2000/

it works as intended.

I tried manually setting Content-type :  application/json in the former but I then always get 400 bad request

This has been driving me crazy.

I thought it was that something updated in body-parser but I downgraded and it didn't help.

Any help appreciated, thanks.

Body:
I discovered, that it works when sending with content type

"application/json"

in combination with server-side

app.use(express.json())

(As @marcelocra pointed out, the 2022 version would use)

(old version for reference)

app.use(bodyParser.json());

Now I can send via

var data = {name:"John"}
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", theUrl, false); // false for synchronous request
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(data);

and the result is available in request.body.name on the server.