问:
How could I implement a multilevel menu (dropdown) in android
I have to implement a menu like the following:

I am currently using a nested menu in an item, but I can not make it look like the image.

Need to know how I can perform that cascade submenu effect shown to the right of the library menu item

How could I approach this problem?

I'm sorry for my English.

答:
Change your xml.
This is my xml for camera menu. One of the options allow changing the white balance. Within the white balance button, there a submenu of all the possible white balance settings. Hope this helped!</p>

```<code><item
        android:id="@+id/changeWhiteBalance"
        android:title="White Balance">

        <menu>
            <item
                android:id="@+id/changeToAutoWB"
                android:title="Auto">
            </item>
            <item
                android:id="@+id/lockWB"
                android:title="Lock White Balance">
            </item>
            <item
                android:id="@+id/changeToDirectSunlight"
                android:title="Direct Sunlight">
            </item>
            <item
                android:id="@+id/changeToCloudy"
                android:title="Cloudy">
            </item>
            <item
                android:id="@+id/changeToIncandescent"
                android:title="Incandescent">
            </item>
            <item
                android:id="@+id/changeToFluorescent"
                android:title="Fluorescent">
            </item>
            <item
                android:id="@+id/changeToTwilight"
                android:title="Twilight" />
            <item
                android:id="@+id/changeToShade"
                android:title="Shade" />
            <item
                android:id="@+id/changeToWarmFluorescent"
                android:title="Warm Fluorescent"/>
        </menu>
    </item>
</code>```

Body:
Change your xml.
This is my xml for camera menu. One of the options allow changing the white balance. Within the white balance button, there a submenu of all the possible white balance settings. Hope this helped!

<item
        android:id="@+id/changeWhiteBalance"
        android:title="White Balance">

        <menu>
            <item
                android:id="@+id/changeToAutoWB"
                android:title="Auto">
            </item>
            <item
                android:id="@+id/lockWB"
                android:title="Lock White Balance">
            </item>
            <item
                android:id="@+id/changeToDirectSunlight"
                android:title="Direct Sunlight">
            </item>
            <item
                android:id="@+id/changeToCloudy"
                android:title="Cloudy">
            </item>
            <item
                android:id="@+id/changeToIncandescent"
                android:title="Incandescent">
            </item>
            <item
                android:id="@+id/changeToFluorescent"
                android:title="Fluorescent">
            </item>
            <item
                android:id="@+id/changeToTwilight"
                android:title="Twilight" />
            <item
                android:id="@+id/changeToShade"
                android:title="Shade" />
            <item
                android:id="@+id/changeToWarmFluorescent"
                android:title="Warm Fluorescent"/>
        </menu>
    </item>


来源: stackexchange

问:
How to call C++ funtion from Fortran 77 using std::vector as arguments?
I have to replace some Fortran subroutines with C++ functions. Since the literature is poor, I am stuck with a problem like the following one.

My code always throws an error:

Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

This is my Fortran code:

```<code>  PROGRAM vector_adder
  IMPLICIT NONE

  INTEGER,DIMENSION(3) :: a,b,c
  INTEGER :: i

  !C fill vectors with values
  DO i = 1,3
      a(i) = i
      b(i) = i
  END DO

  CALL ADD_VECTORS(a,b,c)

  WRITE(*,'(I5,I5,I5)') (c(i),i =1,3)

  STOP
  END PROGRAM
</code>```

A working C code:

```<code>void add_vectors_(int (*a)[3], int (*b)[3], int (*c)[3])
{
    for(int i = 0; i<3 ; i++)
    {
        (*c)[i] =(*a)[i] + (*b)[i];
    }
}
</code>```

And I would like a similar one in C++:

```<code>extern "C" void add_vectors_(std::vector<int> *a, std::vector<int> *b, std::vector<int> *c)
{
    for(int i = 0; i<a->size() ; i++)
    {
        (*c)[i] =(*a)[i] + (*b)[i];
    }
}
</code>```

答:
Here is C++ code you can call from FORTRAN

```<code>extern "C" void add_vectors_(int(*a)[3], int(*b)[3], int(*c)[3])
{
    for (size_t i = 0; i<3; i++)
    {
        (*c)[i] = (*a)[i] + (*b)[i];
    }
}
</code>```

std::vector<> does not have a portable interface to allow it to be called from other non-C++ code; since it's a template, doing so would be difficult.  (In fact, there can even be problems with std::vector compatibility between different versions of a compiler, or different compilers on the same system.)

You might like something similar to C++17's string_view for vector<>, but such a thing isn't part of the Standard Library.  Note that many of the Standard Library routines take begin and end arguments which work well with C-style code.

ContentLicense: CC BY-SA 3.0

Body:
I have to replace some Fortran subroutines with C++ functions. Since the literature is poor, I am stuck with a problem like the following one.

My code always throws an error:

Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

This is my Fortran code:

  PROGRAM vector_adder
  IMPLICIT NONE

  INTEGER,DIMENSION(3) :: a,b,c
  INTEGER :: i

  !C fill vectors with values
  DO i = 1,3
      a(i) = i
      b(i) = i
  END DO

  CALL ADD_VECTORS(a,b,c)

  WRITE(*,'(I5,I5,I5)') (c(i),i =1,3)

  STOP
  END PROGRAM

A working C code:

void add_vectors_(int (*a)[3], int (*b)[3], int (*c)[3])
{
    for(int i = 0; i<3 ; i++)
    {
        (*c)[i] =(*a)[i] + (*b)[i];
    }
}

And I would like a similar one in C++:

extern "C" void add_vectors_(std::vector<int> *a, std::vector<int> *b, std::vector<int> *c)
{
    for(int i = 0; isize() ; i++)
    {
        (*c)[i] =(*a)[i] + (*b)[i];
    }
}

Body:
Here is C++ code you can call from FORTRAN

extern "C" void add_vectors_(int(*a)[3], int(*b)[3], int(*c)[3])
{
    for (size_t i = 0; i<3; i++)
    {
        (*c)[i] = (*a)[i] + (*b)[i];
    }
}

std::vector<> does not have a portable interface to allow it to be called from other non-C++ code; since it's a template, doing so would be difficult.  (In fact, there can even be problems with std::vector compatibility between different versions of a compiler, or different compilers on the same system.)

You might like something similar to C++17's string_view for vector<>, but such a thing isn't part of the Standard Library.  Note that many of the Standard Library routines take begin and end arguments which work well with C-style code.


问:
How to debug Kubernetes on the proper way?
I would like to run Istio to play around, but I facing issues with my local kubernetes installation and I am successfuly stack with a way of debug my installation

That is a my current situation:

```<code>root@node1:/tmp/istio-0.1.5# kubectl get svc
NAME            CLUSTER-IP      EXTERNAL-IP   PORT(S)                       AGE
grafana         10.233.2.70     <pending>     3000:31202/TCP                1h
istio-egress    10.233.39.101   <none>        80/TCP                        1h
istio-ingress   10.233.48.51    <pending>     80:30982/TCP,443:31195/TCP    1h
istio-manager   10.233.2.109    <none>        8080/TCP,8081/TCP             1h
istio-mixer     10.233.39.58    <none>        9091/TCP,9094/TCP,42422/TCP   1h
kubernetes      10.233.0.1      <none>        443/TCP                       4h
prometheus      10.233.63.20    <pending>     9090:32170/TCP                1h
servicegraph    10.233.39.104   <pending>     8088:30814/TCP                1h

root@node1:/tmp/istio-0.1.5# kubectl get pods
NAME                             READY     STATUS    RESTARTS   AGE
grafana-1261931457-3hx2p         0/1       Pending   0          1h
istio-ca-3887035158-6p3b0        0/1       Pending   0          1h
istio-egress-1920226302-vmlx1    0/1       Pending   0          1h
istio-ingress-2112208289-ctxj5   0/1       Pending   0          1h
istio-manager-2910860705-z28dp   0/2       Pending   0          1h
istio-mixer-2335471611-rsrhb     0/1       Pending   0          1h
prometheus-3067433533-l2m48      0/1       Pending   0          1h
servicegraph-3127588006-1k5rg    0/1       Pending   0          1h

 kubectl get rs
NAME                       DESIRED   CURRENT   READY     AGE
grafana-1261931457         1         1         0         1h
istio-ca-3887035158        1         1         0         1h
istio-egress-1920226302    1         1         0         1h
istio-ingress-2112208289   1         1         0         1h
istio-manager-2910860705   1         1         0         1h
istio-mixer-2335471611     1         1         0         1h
prometheus-3067433533      1         1         0         1h
servicegraph-3127588006    1         1         0         1h

kubectl get pods --show-labels
NAME                             READY     STATUS    RESTARTS   AGE       LABELS
grafana-1261931457-3hx2p         0/1       Pending   0          1h        app=grafana,pod-template-hash=1261931457
istio-ca-3887035158-6p3b0        0/1       Pending   0          1h        istio=istio-ca,pod-template-hash=3887035158
istio-egress-1920226302-vmlx1    0/1       Pending   0          1h        istio=egress,pod-template-hash=1920226302
istio-ingress-2112208289-ctxj5   0/1       Pending   0          1h        istio=ingress,pod-template-hash=2112208289
istio-manager-2910860705-z28dp   0/2       Pending   0          1h        istio=manager,pod-template-hash=2910860705
istio-mixer-2335471611-rsrhb     0/1       Pending   0          1h        istio=mixer,pod-template-hash=2335471611
prometheus-3067433533-l2m48      0/1       Pending   0          1h        app=prometheus,pod-template-hash=3067433533
servicegraph-3127588006-1k5rg    0/1       Pending   0          1h        app=servicegraph,pod-template-hash=3127588006

root@node1:/tmp/istio-0.1.5# kubectl get nodes --show-labels
NAME      STATUS    AGE       VERSION           LABELS
node1     Ready     5h        v1.6.4+coreos.0   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node1,node-role.kubernetes.io/master=true,node-role.kubernetes.io/node=true
node2     Ready     5h        v1.6.4+coreos.0   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node2,node-role.kubernetes.io/master=true,node-role.kubernetes.io/node=true
node3     Ready     5h        v1.6.4+coreos.0   app=prometeus,beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node3,node-role.kubernetes.io/node=true
node4     Ready     5h        v1.6.4+coreos.0   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node4,node-role.kubernetes.io/node=true
</code>```

Unfortunately, after I read out most of documentation, I found out only few way to debug an installation

```<code>journalctl -r -u kubelet
kubectl get events
kubectl describe deployment
</code>```

Is there any common workflow to debug Kubernetes installation?

答:
Its in the documentation. follow the POD troubleshooting steps

https://kubernetes.io/docs/tasks/debug-application-cluster/debug-application/

Body:
I would like to run Istio to play around, but I facing issues with my local kubernetes installation and I am successfuly stack with a way of debug my installation

That is a my current situation:

root@node1:/tmp/istio-0.1.5# kubectl get svc
NAME            CLUSTER-IP      EXTERNAL-IP   PORT(S)                       AGE
grafana         10.233.2.70     <pending>     3000:31202/TCP                1h
istio-egress    10.233.39.101   <none>        80/TCP                        1h
istio-ingress   10.233.48.51    <pending>     80:30982/TCP,443:31195/TCP    1h
istio-manager   10.233.2.109    <none>        8080/TCP,8081/TCP             1h
istio-mixer     10.233.39.58    <none>        9091/TCP,9094/TCP,42422/TCP   1h
kubernetes      10.233.0.1      <none>        443/TCP                       4h
prometheus      10.233.63.20    <pending>     9090:32170/TCP                1h
servicegraph    10.233.39.104   <pending>     8088:30814/TCP                1h

root@node1:/tmp/istio-0.1.5# kubectl get pods
NAME                             READY     STATUS    RESTARTS   AGE
grafana-1261931457-3hx2p         0/1       Pending   0          1h
istio-ca-3887035158-6p3b0        0/1       Pending   0          1h
istio-egress-1920226302-vmlx1    0/1       Pending   0          1h
istio-ingress-2112208289-ctxj5   0/1       Pending   0          1h
istio-manager-2910860705-z28dp   0/2       Pending   0          1h
istio-mixer-2335471611-rsrhb     0/1       Pending   0          1h
prometheus-3067433533-l2m48      0/1       Pending   0          1h
servicegraph-3127588006-1k5rg    0/1       Pending   0          1h

 kubectl get rs
NAME                       DESIRED   CURRENT   READY     AGE
grafana-1261931457         1         1         0         1h
istio-ca-3887035158        1         1         0         1h
istio-egress-1920226302    1         1         0         1h
istio-ingress-2112208289   1         1         0         1h
istio-manager-2910860705   1         1         0         1h
istio-mixer-2335471611     1         1         0         1h
prometheus-3067433533      1         1         0         1h
servicegraph-3127588006    1         1         0         1h

kubectl get pods --show-labels
NAME                             READY     STATUS    RESTARTS   AGE       LABELS
grafana-1261931457-3hx2p         0/1       Pending   0          1h        app=grafana,pod-template-hash=1261931457
istio-ca-3887035158-6p3b0        0/1       Pending   0          1h        istio=istio-ca,pod-template-hash=3887035158
istio-egress-1920226302-vmlx1    0/1       Pending   0          1h        istio=egress,pod-template-hash=1920226302
istio-ingress-2112208289-ctxj5   0/1       Pending   0          1h        istio=ingress,pod-template-hash=2112208289
istio-manager-2910860705-z28dp   0/2       Pending   0          1h        istio=manager,pod-template-hash=2910860705
istio-mixer-2335471611-rsrhb     0/1       Pending   0          1h        istio=mixer,pod-template-hash=2335471611
prometheus-3067433533-l2m48      0/1       Pending   0          1h        app=prometheus,pod-template-hash=3067433533
servicegraph-3127588006-1k5rg    0/1       Pending   0          1h        app=servicegraph,pod-template-hash=3127588006

root@node1:/tmp/istio-0.1.5# kubectl get nodes --show-labels
NAME      STATUS    AGE       VERSION           LABELS
node1     Ready     5h        v1.6.4+coreos.0   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node1,node-role.kubernetes.io/master=true,node-role.kubernetes.io/node=true
node2     Ready     5h        v1.6.4+coreos.0   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node2,node-role.kubernetes.io/master=true,node-role.kubernetes.io/node=true
node3     Ready     5h        v1.6.4+coreos.0   app=prometeus,beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node3,node-role.kubernetes.io/node=true
node4     Ready     5h        v1.6.4+coreos.0   beta.kubernetes.io/arch=amd64,beta.kubernetes.io/os=linux,kubernetes.io/hostname=node4,node-role.kubernetes.io/node=true

Unfortunately, after I read out most of documentation, I found out only few way to debug an installation

journalctl -r -u kubelet
kubectl get events
kubectl describe deployment

Is there any common workflow to debug Kubernetes installation?


问:
Programmatically navigate using React router
With react-router I can use the Link element to create links which are natively handled by react router.

I see internally it calls this.context.transitionTo(...).

I want to do a navigation. Not from a link, but from a dropdown selection (as an example). How can I do this in code? What is this.context?

I saw the Navigation mixin, but can I do this without mixins?

答:
React-Router 4.x answer

On my end, I like to have a single history object that I can carry even outside components. I like to have a single history.js file that I import on demand, and just manipulate it.

You just have to change BrowserRouter to Router, and specify the history prop. This doesn't change anything for you, except that you have your own history object that you can manipulate as you want.

You need to install history, the library used by react-router.

Example usage, ES6 notation:

history.js

import createBrowserHistory from 'history/createBrowserHistory'
export default createBrowserHistory()
```
<p><strong>BasicComponent.js</strong></p>
<pre class="lang-js prettyprint-override"><code>import React, { Component } from 'react';
import history from './history';

class BasicComponent extends Component {

    goToIndex(e){
        e.preventDefault();
        history.push('/');
    }

    render(){
        return Previous;
    }
}
</code>```

If you have to navigate from a component that is actually rendered from a Route component, you can also access history from props, like that:

BasicComponent.js

import React, { Component } from 'react';

class BasicComponent extends Component {

    navigate(e){
        e.preventDefault();
        this.props.history.push('/url');
    }

    render(){
        return Previous;
    }
}
```

ContentLicense: CC BY-SA 4.0

Body:
React-Router 4.x answer

On my end, I like to have a single history object that I can carry even outside components. I like to have a single history.js file that I import on demand, and just manipulate it.

You just have to change BrowserRouter to Router, and specify the history prop. This doesn't change anything for you, except that you have your own history object that you can manipulate as you want.

You need to install history, the library used by react-router.

Example usage, ES6 notation:

history.js

import createBrowserHistory from 'history/createBrowserHistory'
export default createBrowserHistory()

BasicComponent.js

import React, { Component } from 'react';
import history from './history';

class BasicComponent extends Component {

    goToIndex(e){
        e.preventDefault();
        history.push('/');
    }

    render(){
        return <a href="#" onClick={this.goToIndex}>Previous</a>;
    }
}

If you have to navigate from a component that is actually rendered from a Route component, you can also access history from props, like that:

BasicComponent.js

import React, { Component } from 'react';

class BasicComponent extends Component {

    navigate(e){
        e.preventDefault();
        this.props.history.push('/url');
    }

    render(){
        return <a href="#" onClick={this.navigate}>Previous</a>;
    }
}


问:
AWS Route 53 Domain not working on my wifi but okay on LTE
Route 53 Issue? server DNS address could not be found.

Everything was working fine until this morning. I bought  from amazon a few weeks back and had deployed a personal webpage, no issues. Today, I made a small change and added a favicon to the page. Then I redeployed, everything is working. http://34.211.101.154/

Now I'm having issues with route 53. I've checked and double checked my name servers (ns) to make sure that the registered ns match the hosted ns. I have a health check running and it shows that all the endpoints terminate with a success 200.

```<code>Success: HTTP Status Code 200, OK. Resolved IP: 34.211.101.154
</code>```

But still, when i go to the domain name, the request won't resolve on wifi but it is okay on LTE. Does anybody know the issue? Please help!

答: Actually, turns out everything was working fine. It's just AWS needed time to process the request... I waited like 2 hours and it started working. Thanks </p>

Body:
Route 53 Issue? server DNS address could not be found.

Everything was working fine until this morning. I bought  from amazon a few weeks back and had deployed a personal webpage, no issues. Today, I made a small change and added a favicon to the page. Then I redeployed, everything is working. http://34.211.101.154/

Now I'm having issues with route 53. I've checked and double checked my name servers (ns) to make sure that the registered ns match the hosted ns. I have a health check running and it shows that all the endpoints terminate with a success 200.

Success: HTTP Status Code 200, OK. Resolved IP: 34.211.101.154

But still, when i go to the domain name, the request won't resolve on wifi but it is okay on LTE. Does anybody know the issue? Please help!


问:
Dynamics CRM Plugin Shared variables - Object or Array
We have a scenario where we need to calculate multiple fee components & share between Pre & Post stages of a Plugin. So we created the object like this.

```<code>class FeeCalculation
    {
        public string TotalFee { get; set; }
        public string FilingFee { get; set; }
        public string LegalFee { get; set; }
        public string RecordFee { get; set; }
    }
</code>```

So far we have used single fee component & shared variable worked nicely. When tried to assign the whole object - the result is not fruitful.

```<code>context.SharedVariables.Add("fees", fcObject);
</code>```

Is there a way to achieve this expected result?

答:
The plugin infrastructure must be able to serialize/deserialize the objects that are in your SharedVariables collection. It has no knowledge of custom types like the FeeCalculation class and therefore cannot serialize it.

Use primitive types, common .NET types (e.g. a List of decimals should work) or CRM types (Entity, Money etc.). It's good to note that the SharedVariables collection is a key value pair collection. So, why not just add items to it with keys like "TotalFee", "FilingFee" etc?

Body:
We have a scenario where we need to calculate multiple fee components & share between Pre & Post stages of a Plugin. So we created the object like this.

class FeeCalculation
    {
        public string TotalFee { get; set; }
        public string FilingFee { get; set; }
        public string LegalFee { get; set; }
        public string RecordFee { get; set; }
    }

So far we have used single fee component & shared variable worked nicely. When tried to assign the whole object - the result is not fruitful.

context.SharedVariables.Add("fees", fcObject);

Is there a way to achieve this expected result?


问:
Get the center of an element using jquery using .position().left()
Hello I am using a jQuery snippet that uses .position().left()

This finds the position of the left of the element.

Is there any way to find the center of the element?

I did some research and theres no such thing as .position().center()

so I would like to do something like this

jQuery(this).position().center() but this obviously doesnt work

Anyone have an idea on the correct syntax?

Thanks!

答:
You can use this</p>

```<code>jQuery.fn.center = function () {
    return $(this).position().left() + $(this)[0].width/2;
}

jQuery(this).center(); // returns center of an element
</code>```

Body:
You can use this

jQuery.fn.center = function () {
    return $(this).position().left() + $(this)[0].width/2;
}

jQuery(this).center(); // returns center of an element


问:
Jquery form only working the first time you submit it, and not the second
I have a form that you can add data to a database. It is all done with jquery and ajax so when you press submit it validates the code and then if everything is correct it submits the post data with out refreshing the page. The problem is the form works the first time, but then when you go to submit another entry with the form it doesn't work. I thought it had something to do with the

```<code>$(document).ready(function(){
</code>```

But I really have no idea. I've pasted some of the code below. It is pretty long, but this should give enough info to know what it's doing.
The entire js file is at http://www.myfirealert.com/callresponse/js/AddUser.js

```<code>$(document).ready(function(){
$('#AddCaller').click(function(e){

    //stop the form from being submitted
    e.preventDefault();

    /* declare the variables, var error is the variable that we use on the end
    to determine if there was an error or not */
    var error = false;
    var Firstname = $('#Firstname').val();
    ...OTHER FORM FIELDS HERE

    /* in the next section we do the checking by using VARIABLE.length
    where VARIABLE is the variable we are checking (like name, email),
    length is a javascript function to get the number of characters.
    And as you can see if the num of characters is 0 we set the error
    variable to true and show the name_error div with the fadeIn effect.
    if it's not 0 then we fadeOut the div( that's if the div is shown and
    the error is fixed it fadesOut. */

    if(Firstname.length == 0){
        var error = true;
        $('#Firstname_error').fadeIn(500);
    }else{
        $('#Firstname_error').fadeOut(500);
    }
    if(Lastname.length == 0){
        var error = true;
        $('#Lastname_error').fadeIn(500);
    }else{
        $('#Lastname_error').fadeOut(500);
    }
    ...MORE CONDITIONAL STATEMENTS HERE

    //now when the validation is done we check if the error variable is false (no errors)
    if(error == false){
        //disable the submit button to avoid spamming
        //and change the button text to Sending...
        $('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });

        /* using the jquery's post(ajax) function and a lifesaver
        function serialize() which gets all the data from the form
        we submit it to send_email.php */
        $.post("doadd.php", $("#AddCaller_form").serialize(),function(result){
            //and after the ajax request ends we check the text returned
            if(result == 'added'){

                 //$('#cf_submit_p').remove();
                //and show the success div with fadeIn
                $('#Add_success').fadeIn(500);
                 $('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
                 document.getElementById('Firstname').value = "";
                 document.getElementById('Lastname').value = "";
                 document.getElementById('PhoneNumber').value = "";
                 document.getElementById('DefaultETA').value = "";
                 document.getElementById('Apparatus').value = "";
                 document.getElementById('DefaultLocation').value = "";

                 setTimeout(" $('#Add_success').fadeOut(500);",5000);

            }else if(result == 'alreadythere'){
                                    //checks database to see if the user is already there
                $('#Alreadythere').fadeIn(500);
                $('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
            }
            else{
                //show the failed div
                $('#Add_fail').fadeIn(500);
                //reenable the submit button by removing attribute disabled and change the text back to Send The Message
                $('#AddCaller').removeAttr('disabled').attr('value', 'Send The Message');

            }
        });
    }
});
});
</code>```

Right now, the first time you use the form it works great. and the button is reenabled, but then when you try to make another entry and click the button nothing happens.

Thanks for the help!

EDIT: After the form submits the first time the button is still enabled and you can click on it, but when you click on it nothing happens... even if you don't fill in the form. It's like the click event of the form isn't firing the first time.

EDIT2 As requested, I'm going to post the HTML, it's behind a password protected site, so I can't send you the page link.

```<code><form action='addcallers.php' method='post' id='AddCaller_form'>

 <h2>Add Callers</h2>
 <p>
 First Name:
 <div id='Firstname_error' class='error'> Please Enter a First Name</div>
 <div><input type='text' name='Firstname' id='Firstname'></div>
 </p>

 <p>
 Last Name:
 <div id='Lastname_error' class='error'> Please Enter a Last Name</div>
 <div><input type='text' name='Lastname' id='Lastname'></div>
 </p>
 ...MORE FORM FIELDS HERE

 <div style="display:none;">
 <input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing"      readonly=readonly >

 </div>
 </p>

 <p>

 <div id='Add_success' class='success'> The user has been added</div>
 <div id='Alreadythere' class='error'> That user is already in the database</div>
 <div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
 <p id='cf_submit_p'>
 <input type='submit' id='AddCaller' value='Send The Message'>
 </p>
 </form>

 </div>
</code>```

EDIT3 There is other ajax on the page too, but it's written in straight javascript. I'm not sure if that would affect the functionality in any way. But if needed I can post that ajax as well.

EDIT4 I got the original tutorial from http://web.enavu.com/tutorials/create-an-amazing-contact-form-with-no-ready-made-plugins/ and modified it

EDIT After putting in some different alerts, I found out that it does not do the conditional statement if(error==false)... Any Idea why?

答:
Try to change this:
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
into that:
$('#AddCaller').attr({'value' : 'Adding...' });

This should make it work.

ContentLicense: CC BY-SA 2.5

Body:
I have a form that you can add data to a database. It is all done with jquery and ajax so when you press submit it validates the code and then if everything is correct it submits the post data with out refreshing the page. The problem is the form works the first time, but then when you go to submit another entry with the form it doesn't work. I thought it had something to do with the

$(document).ready(function(){

But I really have no idea. I've pasted some of the code below. It is pretty long, but this should give enough info to know what it's doing.
The entire js file is at http://www.myfirealert.com/callresponse/js/AddUser.js

$(document).ready(function(){
$('#AddCaller').click(function(e){

    //stop the form from being submitted
    e.preventDefault();

    /* declare the variables, var error is the variable that we use on the end
    to determine if there was an error or not */
    var error = false;
    var Firstname = $('#Firstname').val();
    ...OTHER FORM FIELDS HERE

    /* in the next section we do the checking by using VARIABLE.length
    where VARIABLE is the variable we are checking (like name, email),
    length is a javascript function to get the number of characters.
    And as you can see if the num of characters is 0 we set the error
    variable to true and show the name_error div with the fadeIn effect.
    if it's not 0 then we fadeOut the div( that's if the div is shown and
    the error is fixed it fadesOut. */

    if(Firstname.length == 0){
        var error = true;
        $('#Firstname_error').fadeIn(500);
    }else{
        $('#Firstname_error').fadeOut(500);
    }
    if(Lastname.length == 0){
        var error = true;
        $('#Lastname_error').fadeIn(500);
    }else{
        $('#Lastname_error').fadeOut(500);
    }
    ...MORE CONDITIONAL STATEMENTS HERE

    //now when the validation is done we check if the error variable is false (no errors)
    if(error == false){
        //disable the submit button to avoid spamming
        //and change the button text to Sending...
        $('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });

        /* using the jquery's post(ajax) function and a lifesaver
        function serialize() which gets all the data from the form
        we submit it to send_email.php */
        $.post("doadd.php", $("#AddCaller_form").serialize(),function(result){
            //and after the ajax request ends we check the text returned
            if(result == 'added'){

                 //$('#cf_submit_p').remove();
                //and show the success div with fadeIn
                $('#Add_success').fadeIn(500);
                 $('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
                 document.getElementById('Firstname').value = "";
                 document.getElementById('Lastname').value = "";
                 document.getElementById('PhoneNumber').value = "";
                 document.getElementById('DefaultETA').value = "";
                 document.getElementById('Apparatus').value = "";
                 document.getElementById('DefaultLocation').value = "";

                 setTimeout(" $('#Add_success').fadeOut(500);",5000);

            }else if(result == 'alreadythere'){
                                    //checks database to see if the user is already there
                $('#Alreadythere').fadeIn(500);
                $('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
            }
            else{
                //show the failed div
                $('#Add_fail').fadeIn(500);
                //reenable the submit button by removing attribute disabled and change the text back to Send The Message
                $('#AddCaller').removeAttr('disabled').attr('value', 'Send The Message');

            }
        });
    }
});
});

Right now, the first time you use the form it works great. and the button is reenabled, but then when you try to make another entry and click the button nothing happens.

Thanks for the help!

EDIT: After the form submits the first time the button is still enabled and you can click on it, but when you click on it nothing happens... even if you don't fill in the form. It's like the click event of the form isn't firing the first time.

EDIT2 As requested, I'm going to post the HTML, it's behind a password protected site, so I can't send you the page link.

<form action='addcallers.php' method='post' id='AddCaller_form'>

Add Callers

 First Name:

 Please Enter a First Name

<input type='text' name='Firstname' id='Firstname'>

 Last Name:

 Please Enter a Last Name

<input type='text' name='Lastname' id='Lastname'>

 ...MORE FORM FIELDS HERE

 <input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing"      readonly=readonly >

 The user has been added

 That user is already in the database

 Sorry, don't know what happened. Try later.

 <input type='submit' id='AddCaller' value='Send The Message'>

 </form>

EDIT3 There is other ajax on the page too, but it's written in straight javascript. I'm not sure if that would affect the functionality in any way. But if needed I can post that ajax as well.

EDIT4 I got the original tutorial from http://web.enavu.com/tutorials/create-an-amazing-contact-form-with-no-ready-made-plugins/ and modified it

EDIT After putting in some different alerts, I found out that it does not do the conditional statement if(error==false)... Any Idea why?


问:
Codename one Android Push Notifications being dismissed immediately
I am sending a push notification from my web application and it is working great on IOS, but on Android the notification is only noticeable for a brief second (probably more like a couple milliseconds) as the notification icon along the top blips. There is no nitrification in the notification alerts list (preview).

I have registered the app with google per the Developer guide (Android Bureaucracy). And I can tell the app is getting the notification if I show it in a dialog. I just want the system notification to stick so the user knows they need to check the app.

App Code:

```<code>public void start() {
    if(current != null){
        current.show();
        return;
    }
    Display.getInstance().callSerially(() -> {
        Display.getInstance().registerPush();
    });

    // show the splash screen
    splashScreen.show();
}

public void stop() {
    current = Display.getInstance().getCurrent();
    if(current instanceof Dialog) {
        ((Dialog)current).dispose();
        current = Display.getInstance().getCurrent();
    }
}

public void destroy() {
}

@Override
public void push(String value) {
    //Dialog.show("push", "value:" + value, "OK", "Cancel");
}

@Override
public void registeredForPush(String deviceId) {
    //String pushKey = Push.getPushKey();
    //System.out.println("deviceId:" + deviceId + ", pushKey:" + pushKey);
}

@Override
public void pushRegistrationError(String error, int errorCode) {
    //System.out.println("Unable to register push:" + errorCode + ":" + error);
}
</code>```

答: We figured out that there was a security app on the phone called Security 360 that was blocking the notification.</p>

Body:
I am sending a push notification from my web application and it is working great on IOS, but on Android the notification is only noticeable for a brief second (probably more like a couple milliseconds) as the notification icon along the top blips. There is no nitrification in the notification alerts list (preview).

I have registered the app with google per the Developer guide (Android Bureaucracy). And I can tell the app is getting the notification if I show it in a dialog. I just want the system notification to stick so the user knows they need to check the app.

App Code:

public void start() {
    if(current != null){
        current.show();
        return;
    }
    Display.getInstance().callSerially(() -> {
        Display.getInstance().registerPush();
    });

    // show the splash screen
    splashScreen.show();
}

public void stop() {
    current = Display.getInstance().getCurrent();
    if(current instanceof Dialog) {
        ((Dialog)current).dispose();
        current = Display.getInstance().getCurrent();
    }
}

public void destroy() {
}

@Override
public void push(String value) {
    //Dialog.show("push", "value:" + value, "OK", "Cancel");
}

@Override
public void registeredForPush(String deviceId) {
    //String pushKey = Push.getPushKey();
    //System.out.println("deviceId:" + deviceId + ", pushKey:" + pushKey);
}

@Override
public void pushRegistrationError(String error, int errorCode) {
    //System.out.println("Unable to register push:" + errorCode + ":" + error);
}


问:
Atmega2560 PWM on PB7
I am trying to get PWM output from PB7 pin with timer0 on Atmega2560 with no luck. It should generate tone for the connected repro.My PWM settings are:

```<code>DDRB    = 0b11100000;
PORTB   = 0b00000000;

OCR0A = 0x04;
TCCR0A = (0 << COM0A1) | (1 << COM0A0) | (1 << WGM01) | (0 << WGM00);
TCCR0B = (0 << WGM02) | (0 << CS02) | (0 << CS01) | (0 << CS00);
</code>```

and then I have this function, which should generate the sound:

```<code>void SoundOutput(unsigned int uintTone)
{
    if (uintTone != 0)
    {
        LED_2(1);
        OCR0A = uintTone;

        TCCR0B |= (1 << CS02) | (1 << CS01) | (1 << CS00);
    }
    else
    {
        TCCR0B &= ~((1 << CS02) | (1 << CS01) | (1 << CS00));
    }
}
</code>```

but nothing happens when i call it with tone parameter. Can you please help me?

答:
Based on your comments, you are using ~12MHz clock as the input to your timer, and from your code, you are using 8 bit timer 0 in CTC mode with OCR0A as your top.  You have OC0A set to toggle on a compare match.

According to the 2560 datasheet, the frequency of your timer is given by:

F_CLK/(2*(1 + OCR0A)) | F_CLK ~= 12MHz

This is an 8 bit timer, so that means that your minimum frequency that your PWM can generate is given by:

12e6/(2*(1 + 255)) ~= 20KHz

You simply aren't going to be able to generate an audible tone with that configuration unless you slow down the clock you are using for your timer or use a timer that can count higher.

1) Use a 16 bit counter (i.e. timer1).  That will give you a min frequency of ~90Hz and a max frequency of ~6MHz, which should give you plenty of range to generate tones:

```<code>/* WGM BITS = 0100: CTC Mode */
/* COMA BITS = 01: Toggle OC1A on compare match */
/* CS BITS = 111: External clock source on rising edge */

TCCR1A = (0 << COM1A1) | (1 << COM1A0) | (0 << WGM01) | (0 << WGM00);
TCCR1B = (1 << WGM12) | (1 << WGM13) | (1 << CS02) | (1 << CS01) | (1 << CS00);
</code>```

2) Use the internal clock source as the timer clock instead of an external source.  Unless you changed fuse bits or you are changing it in the code somewhere, the clock will be 1MHz.  Prescaling the clock by 8 gives you a frequency range of ~250Hz - ~60KHz.

```<code>/* WGM BITS = 010: CTC Mode */
/* COMA BITS = 01: Toggle OC1A on compare match */
/* CS BITS = 010: Prescale the internal clock by 8 */

TCCR0A = (0 << COM0A1) | (1 << COM0A0) | (1 << WGM01) | (0 << WGM00);
TCCR0B = (0 << WGM02) | (0 << CS02) | (1 << CS01) | (0 << CS00);
</code>```

Title: Atmega2560 PWM on PB7

Body:
I am trying to get PWM output from PB7 pin with timer0 on Atmega2560 with no luck. It should generate tone for the connected repro.My PWM settings are:

DDRB    = 0b11100000;
PORTB   = 0b00000000;

OCR0A = 0x04;
TCCR0A = (0 << COM0A1) | (1 << COM0A0) | (1 << WGM01) | (0 << WGM00);
TCCR0B = (0 << WGM02) | (0 << CS02) | (0 << CS01) | (0 << CS00);

and then I have this function, which should generate the sound:

void SoundOutput(unsigned int uintTone)
{
    if (uintTone != 0)
    {
        LED_2(1);
        OCR0A = uintTone;

        TCCR0B |= (1 << CS02) | (1 << CS01) | (1 << CS00);
    }
    else
    {
        TCCR0B &= ~((1 << CS02) | (1 << CS01) | (1 << CS00));
    }
}

but nothing happens when i call it with tone parameter. Can you please help me?

Body:
Based on your comments, you are using ~12MHz clock as the input to your timer, and from your code, you are using 8 bit timer 0 in CTC mode with OCR0A as your top.  You have OC0A set to toggle on a compare match.

According to the 2560 datasheet, the frequency of your timer is given by:

F_CLK/(2*(1 + OCR0A)) | F_CLK ~= 12MHz

This is an 8 bit timer, so that means that your minimum frequency that your PWM can generate is given by:

12e6/(2*(1 + 255)) ~= 20KHz

You simply aren't going to be able to generate an audible tone with that configuration unless you slow down the clock you are using for your timer or use a timer that can count higher.

1) Use a 16 bit counter (i.e. timer1).  That will give you a min frequency of ~90Hz and a max frequency of ~6MHz, which should give you plenty of range to generate tones:

/* WGM BITS = 0100: CTC Mode */
/* COMA BITS = 01: Toggle OC1A on compare match */
/* CS BITS = 111: External clock source on rising edge */

TCCR1A = (0 << COM1A1) | (1 << COM1A0) | (0 << WGM01) | (0 << WGM00);
TCCR1B = (1 << WGM12) | (1 << WGM13) | (1 << CS02) | (1 << CS01) | (1 << CS00);

2) Use the internal clock source as the timer clock instead of an external source.  Unless you changed fuse bits or you are changing it in the code somewhere, the clock will be 1MHz.  Prescaling the clock by 8 gives you a frequency range of ~250Hz - ~60KHz.

/* WGM BITS = 010: CTC Mode */
/* COMA BITS = 01: Toggle OC1A on compare match */
/* CS BITS = 010: Prescale the internal clock by 8 */

TCCR0A = (0 << COM0A1) | (1 << COM0A0) | (1 << WGM01) | (0 << WGM00);
TCCR0B = (0 << WGM02) | (0 << CS02) | (1 << CS01) | (0 << CS00);


问:
Python List IndexError: list index out of range
I try to search in an list the maximal frequency of an element.

Now I have the problem that the last checked element of the list (a[i+1]) I get an IndexError. How can I solve this problem?

With len(a)-1 the last element a[i+1] is never used thus the result of maxMode(a4) is wrong.

```<code>a1 = [5,3,6,7,2,7,3,6,2,8,7]
a2 = [5,3,6,7,2,7,3,6,2,8,7,5,2]
a3 = [5,3,6,7,2,7,3,6,2,8,2,5,2]
a4 = [5,3,6,7,2,7,3,6,2,7,2,5,1]

def maxMode(a):
  cnt = 1
  maxCnt = 0
  res = 0
  for i in range(len(a)-1):
    if a[i] == a[i+1]:
      cnt += 1
    else:
      if cnt >= maxCnt:
        maxCnt = cnt
        res = a[i]
      cnt = 1
  return res

a1.sort()
a2.sort()
a3.sort()
a4.sort()

print(a1)
print(maxMode(a1))
print(a2)
print(maxMode(a2))
print(a3)
print(maxMode(a3))
print(a4)
print(maxMode(a4))
</code>```

答:
As BluCode points out, your code runs fine for the 4 test cases you provide (or at least, it doesn't crash and returns a mode although as you point out, for the 4th test, it's not the max mode).  Also, as you alluded to, you're not counting your last element (or really, you're not checking if the last batch could be the maximal), and so if a4 was instead: [1, 2, 2, 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7], it wrongly prints out 2 (because it finds 3 2's and 3 7's and doesn't do a final check for the 7s being as good or better)

The following worked with my 4 updated test cases:

```<code>a1 = [5,3,6,7,2,7,3,6,2,8,7]
a2 = [5,3,6,7,2,7,3,6,2,8,7,5,2]
a3 = [5,3,6,7,2,7,3,6,2,8,2,5,2]
a4 = [5,3,6,7,2,7,3,6,2,7,2,5,1,7]

def maxMode(a):
  cnt = 1
  maxCnt = 0
  res = 0
  for i in range(len(a)-1):
    if a[i] == a[i+1]:
      cnt += 1
    else:
      if cnt >= maxCnt:
        maxCnt = cnt
        res = a[i]
      cnt = 1
  if cnt >= maxCnt:
    maxCnt = cnt
    res = a[i]
  return res

a1.sort()
a2.sort()
a3.sort()
a4.sort()

print(a1)
print(maxMode(a1))
print(a2)
print(maxMode(a2))
print(a3)
print(maxMode(a3))
print(a4)
print(maxMode(a4))
</code>```

Body:
I try to search in an list the maximal frequency of an element.

Now I have the problem that the last checked element of the list (a[i+1]) I get an IndexError. How can I solve this problem?

With len(a)-1 the last element a[i+1] is never used thus the result of maxMode(a4) is wrong.

a1 = [5,3,6,7,2,7,3,6,2,8,7]
a2 = [5,3,6,7,2,7,3,6,2,8,7,5,2]
a3 = [5,3,6,7,2,7,3,6,2,8,2,5,2]
a4 = [5,3,6,7,2,7,3,6,2,7,2,5,1]

def maxMode(a):
  cnt = 1
  maxCnt = 0
  res = 0
  for i in range(len(a)-1):
    if a[i] == a[i+1]:
      cnt += 1
    else:
      if cnt >= maxCnt:
        maxCnt = cnt
        res = a[i]
      cnt = 1
  return res

a1.sort()
a2.sort()
a3.sort()
a4.sort()

print(a1)
print(maxMode(a1))
print(a2)
print(maxMode(a2))
print(a3)
print(maxMode(a3))
print(a4)
print(maxMode(a4))

Body:
As BluCode points out, your code runs fine for the 4 test cases you provide (or at least, it doesn't crash and returns a mode although as you point out, for the 4th test, it's not the max mode).  Also, as you alluded to, you're not counting your last element (or really, you're not checking if the last batch could be the maximal), and so if a4 was instead: [1, 2, 2, 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7], it wrongly prints out 2 (because it finds 3 2's and 3 7's and doesn't do a final check for the 7s being as good or better)

The following worked with my 4 updated test cases:

a1 = [5,3,6,7,2,7,3,6,2,8,7]
a2 = [5,3,6,7,2,7,3,6,2,8,7,5,2]
a3 = [5,3,6,7,2,7,3,6,2,8,2,5,2]
a4 = [5,3,6,7,2,7,3,6,2,7,2,5,1,7]

def maxMode(a):
  cnt = 1
  maxCnt = 0
  res = 0
  for i in range(len(a)-1):
    if a[i] == a[i+1]:
      cnt += 1
    else:
      if cnt >= maxCnt:
        maxCnt = cnt
        res = a[i]
      cnt = 1
  if cnt >= maxCnt:
    maxCnt = cnt
    res = a[i]
  return res

a1.sort()
a2.sort()
a3.sort()
a4.sort()

print(a1)
print(maxMode(a1))
print(a2)
print(maxMode(a2))
print(a3)
print(maxMode(a3))
print(a4)
print(maxMode(a4))


问:
Inject WebDrivers in TestNG @before test with @guice
I am new with configure selenium. Looked for passing drivers find this solution https://stackoverflow.com/a/35101914/7104440 I wonder is possible to @inject many drivers from browsers in this way. Is possible to bind different drivers? I got error with this code:

```<code>encom.google.inject.CreationException: Unable to create injector, see the following errors:
</code>```

1) Binding to null instances is not allowed. Use toProvider(Providers.of(null)) if this is your intended behaviour.
  at assecobs.driver.DriverModule.configure(DriverModule.java:31)

2) A binding to org.openqa.selenium.WebDriver was already configured at assecobs.driver.DriverModule.configure(DriverModule.java:31).
  at assecobs.driver.DriverModule.configure(DriverModule.java:31)

DriverModule.class

```<code>private DriverSetup driverSetup = new DriverSetup();

@BeforeSuite
@Override
public void configure(Binder binder) {

    for (BrowserNames browserName : BrowserNames.values()) {
        System.out.println(" bind " + browserName.toString());
        WebDriver driver = driverSetup.initDriver(browserName.toString());
        binder.bind(WebDriver.class).toInstance(driver);
    }
}
}
</code>```

DriverSetup.class

```<code> @SneakyThrows
public WebDriver initDriver(String browser) {
    if (browser.equalsIgnoreCase("chrome")) {
        capabilities = chromeCapabilities();
        driver = initChromeDriver(capabilities);

    } else if (browser.equalsIgnoreCase("firefox")) {
        capabilities = firefoxCapabilities();
        driver = initFirefoxDriver(capabilities);

    } else if (browser.equalsIgnoreCase("opera")) {
        capabilities = operaCapabilities();
        driver = initOperaDriver(capabilities);

    } else {
            capabilities = firefoxCapabilities();
            return driver = initFirefoxDriver(capabilities);
        }

        return driver;
    }
</code>```

ClientTest.class

```<code>@Guice(modules = {DriverModule.class})
public class ClientTest extends DriverSetup {

@Inject
WebDriver driver;
</code>```

答:
I have been using Guice + WebDriver for a while. You can inject webdriver as you have shown in the ClientTest.java.

Check here for the detailed steps. - http://www.testautomationguru.com/selenium-webdriver-dependency-injection-using-guice/

Body:
I am new with configure selenium. Looked for passing drivers find this solution https://stackoverflow.com/a/35101914/7104440 I wonder is possible to @inject many drivers from browsers in this way. Is possible to bind different drivers? I got error with this code:

encom.google.inject.CreationException: Unable to create injector, see the following errors:

1) Binding to null instances is not allowed. Use toProvider(Providers.of(null)) if this is your intended behaviour.
  at assecobs.driver.DriverModule.configure(DriverModule.java:31)

2) A binding to org.openqa.selenium.WebDriver was already configured at assecobs.driver.DriverModule.configure(DriverModule.java:31).
  at assecobs.driver.DriverModule.configure(DriverModule.java:31)

DriverModule.class

private DriverSetup driverSetup = new DriverSetup();

@BeforeSuite
@Override
public void configure(Binder binder) {

    for (BrowserNames browserName : BrowserNames.values()) {
        System.out.println(" bind " + browserName.toString());
        WebDriver driver = driverSetup.initDriver(browserName.toString());
        binder.bind(WebDriver.class).toInstance(driver);
    }
}
}

DriverSetup.class

 @SneakyThrows
public WebDriver initDriver(String browser) {
    if (browser.equalsIgnoreCase("chrome")) {
        capabilities = chromeCapabilities();
        driver = initChromeDriver(capabilities);

    } else if (browser.equalsIgnoreCase("firefox")) {
        capabilities = firefoxCapabilities();
        driver = initFirefoxDriver(capabilities);

    } else if (browser.equalsIgnoreCase("opera")) {
        capabilities = operaCapabilities();
        driver = initOperaDriver(capabilities);

    } else {
            capabilities = firefoxCapabilities();
            return driver = initFirefoxDriver(capabilities);
        }

        return driver;
    }

ClientTest.class

@Guice(modules = {DriverModule.class})
public class ClientTest extends DriverSetup {

@Inject
WebDriver driver;


问:
Write a loop for my function in r
I am currently trying to write my first loop for lagged regressions on 30 variables. Variables are labeled as rx1, rx2.... rx3, and the data frame is called my_num_data.

I have created a loop that looks like this:

```<code>z <- zoo(my_num_data)

for (i in 1:30)
{dyn$lm(my_num_data$rx[i] ~ lag(my_num_data$rx[i], 1)
        + lag(my_num_data$rx[i], 2))
}
</code>```

But I received an error message:

Error in model.frame.default(formula = dyn(my_num_data$rx[i] ~ lag(my_num_data$rx[i],  :
        invalid type (NULL) for variable 'my_num_data$rx[i]'

Can anyone tell me what the problem is with the loop?

Thanks!

答:
First problem, I'm pretty sure the function you're looking for is dynlm(), without the $ character.  Second, using $rx[i] doesn't concatenate rx and the contents of i, it selects the (single) element in $rx with index i.  Try this... edited I don't have your data, so I can't test it on my machine:

```<code>results <- list()
for (i in 1:30) {
  results[[i]] <- dynlm(my_num_data[,i] ~ lag(my_num_data[,i], 1)
    + lag(my_num_data[,i], 2))
}
</code>```

and then list element results[[1]] will be the results from the first regresssion, and so on.

Note that this assumes your my_num_data data.frame ONLY consists of columns rx1, rx2, etc.

Title: Write a loop for my function in r

Body:
I am currently trying to write my first loop for lagged regressions on 30 variables. Variables are labeled as rx1, rx2.... rx3, and the data frame is called my_num_data.

I have created a loop that looks like this:

z <- zoo(my_num_data)

for (i in 1:30)
{dyn$lm(my_num_data$rx[i] ~ lag(my_num_data$rx[i], 1)
        + lag(my_num_data$rx[i], 2))
}

But I received an error message:

Error in model.frame.default(formula = dyn(my_num_data$rx[i] ~ lag(my_num_data$rx[i],  :
        invalid type (NULL) for variable 'my_num_data$rx[i]'

Can anyone tell me what the problem is with the loop?

Thanks!

Body:
First problem, I'm pretty sure the function you're looking for is dynlm(), without the $ character.  Second, using $rx[i] doesn't concatenate rx and the contents of i, it selects the (single) element in $rx with index i.  Try this... edited I don't have your data, so I can't test it on my machine:

results <- list()
for (i in 1:30) {
  results[[i]] <- dynlm(my_num_data[,i] ~ lag(my_num_data[,i], 1)
    + lag(my_num_data[,i], 2))
}

and then list element results[[1]] will be the results from the first regresssion, and so on.

Note that this assumes your my_num_data data.frame ONLY consists of columns rx1, rx2, etc.


问:
Bash Script - Check mounted devices
What I'm trying to do -
In the end, I want a script that checks for 3 devices, an SD card, Backup1 & Backup2. They've all been set to auto-mount at their respective mountpoints. The script should check for SD card first, if this fails, then a warning should be sent, and nothing more. If SD is okay, but only one backup is mounted, then ask for confirmation to go ahead with rsync to mounted backup. If all devices are mounted, then rsync from SD card to both backups.

Currently I'm just trying to get the device check nailed, using echo commands. Here's what I have (after multiple attempts) -

```<code>if ! mount | grep /media/card >/dev/null
then
    echo "ERROR: SD card not mounted, aborting"
else
    if ! mount | grep /media/backup >/dev/null
        then
            if ! mount | grep /media/backup2 >/dev/null
            then
                echo "ERROR: No backup devices"
            else
                echo "CAUTION: Backup_2 missing, Backup_1 OKAY"
            fi
    else
        if ! mount | grep /media/backup2 /dev/null
        then
            echo "CAUTION: Backup_1 missing, Backup_2 OKAY"
        else
            echo "SUCCESS: All devices OKAY"
        fi
    fi
fi
</code>```

Which isn't working. I'm getting confused by all the nested 'if's and surely there's a simpler way? Perhaps something that checks each device independently, then returns values that equate to the various combinations (0=no devices, 1=sd only, 2=sd & backup1, 3=sd & backup 2, 4 = all okay) which then is read and decides next part of script to run? If not, where has this way gone wrong?

Any help is appreciated

答:
Use mountpoint, which returns success (0) if the path is a mounted device, and 1 otherwise:

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

check_mountpoint(){
if  mountpoint -q $1
  then
                printf "%s\n" "$1 is mounted"
                return 0
            else
                printf "%s\n" "$1 is not mounted"
                return 1
fi
}

check_mountpoint /media/sd
if [ $? -gt 0 ]
  then
    printf "%s\n" "aborting"
    exit 0
fi
check_mountpoint /media/backup1
check_mountpoint /media/backup2
</code>```

this is your code corrected, i hope it will help.

```<code>if mountpoint -q /media/sd
  then
    if mountpoint -q /media/backup
      then
        if mountpoint -q /media/backup2
          then
            echo "SUCCESS: All devices OKAY"
            # run your command here
          else
            echo "CAUTION: Backup_2 missing, Backup_1 OKAY, SD OKAY"
            # run your command here
        fi
      else
       if mountpoint -q /media/backup2
          then
            echo "CAUTION: Backup_1 missing, Backup_2 OKAY, SD OKAY"
            # run your command here
          else
            echo "SD OKAY , BACKUP Devices missing"
        fi
    fi
  else
    echo "SD is missing , Exit"
fi
</code>```

Title: Bash Script - Check mounted devices

Body:
What I'm trying to do -
In the end, I want a script that checks for 3 devices, an SD card, Backup1 & Backup2. They've all been set to auto-mount at their respective mountpoints. The script should check for SD card first, if this fails, then a warning should be sent, and nothing more. If SD is okay, but only one backup is mounted, then ask for confirmation to go ahead with rsync to mounted backup. If all devices are mounted, then rsync from SD card to both backups.

Currently I'm just trying to get the device check nailed, using echo commands. Here's what I have (after multiple attempts) -

if ! mount | grep /media/card >/dev/null
then
    echo "ERROR: SD card not mounted, aborting"
else
    if ! mount | grep /media/backup >/dev/null
        then
            if ! mount | grep /media/backup2 >/dev/null
            then
                echo "ERROR: No backup devices"
            else
                echo "CAUTION: Backup_2 missing, Backup_1 OKAY"
            fi
    else
        if ! mount | grep /media/backup2 /dev/null
        then
            echo "CAUTION: Backup_1 missing, Backup_2 OKAY"
        else
            echo "SUCCESS: All devices OKAY"
        fi
    fi
fi

Which isn't working. I'm getting confused by all the nested 'if's and surely there's a simpler way? Perhaps something that checks each device independently, then returns values that equate to the various combinations (0=no devices, 1=sd only, 2=sd & backup1, 3=sd & backup 2, 4 = all okay) which then is read and decides next part of script to run? If not, where has this way gone wrong?

Any help is appreciated

Body:
Use mountpoint, which returns success (0) if the path is a mounted device, and 1 otherwise:

#!/bin/bash

check_mountpoint(){
if  mountpoint -q $1
  then
                printf "%s\n" "$1 is mounted"
                return 0
            else
                printf "%s\n" "$1 is not mounted"
                return 1
fi
}

check_mountpoint /media/sd
if [ $? -gt 0 ]
  then
    printf "%s\n" "aborting"
    exit 0
fi
check_mountpoint /media/backup1
check_mountpoint /media/backup2

this is your code corrected, i hope it will help.

if mountpoint -q /media/sd
  then
    if mountpoint -q /media/backup
      then
        if mountpoint -q /media/backup2
          then
            echo "SUCCESS: All devices OKAY"
            # run your command here
          else
            echo "CAUTION: Backup_2 missing, Backup_1 OKAY, SD OKAY"
            # run your command here
        fi
      else
       if mountpoint -q /media/backup2
          then
            echo "CAUTION: Backup_1 missing, Backup_2 OKAY, SD OKAY"
            # run your command here
          else
            echo "SD OKAY , BACKUP Devices missing"
        fi
    fi
  else
    echo "SD is missing , Exit"
fi


问:
How to write VBA code with UTF-8 characters in it?
I want to create some VBA code such as the following:

```<code>fndList.Add "Beat 'em up game", "Beat 'em up"
fndList.Add "Bishōjo game", "Bishōjo"
fndList.Add "Bullet hell game", "Bullet hell"
fndList.Add "Business simulation game", "Business sim"
</code>```

However, Excel converts line #2 to "Bishojo game", without the special character. How am I supposed to handle characters such as these? Thanks.

答:
You could store your values in some cells somewhere, and then read them from there:</p>

```<code>Sub test()
    Dim fndList As New Dictionary
    Dim c As Range
    Dim v As Variant
    Dim r As Long
    'Read values from A1:B4
    For Each c In Range("A1:B4").Rows
        fndList.Add c.Cells(1, 1).Value, c.Cells(1, 2).Value
    Next
    'Test that they haven't been altered by writing to C1:D4
    Range("C1:C4").Value = Application.Transpose(fndList.Keys)
    Range("D1:D4").Value = Application.Transpose(fndList.Items)
End Sub
</code>```

Body:
I want to create some VBA code such as the following:

fndList.Add "Beat 'em up game", "Beat 'em up"
fndList.Add "Bishōjo game", "Bishōjo"
fndList.Add "Bullet hell game", "Bullet hell"
fndList.Add "Business simulation game", "Business sim"

However, Excel converts line #2 to "Bishojo game", without the special character. How am I supposed to handle characters such as these? Thanks.

Body:
You could store your values in some cells somewhere, and then read them from there:

Sub test()
    Dim fndList As New Dictionary
    Dim c As Range
    Dim v As Variant
    Dim r As Long
    'Read values from A1:B4
    For Each c In Range("A1:B4").Rows
        fndList.Add c.Cells(1, 1).Value, c.Cells(1, 2).Value
    Next
    'Test that they haven't been altered by writing to C1:D4
    Range("C1:C4").Value = Application.Transpose(fndList.Keys)
    Range("D1:D4").Value = Application.Transpose(fndList.Items)
End Sub


答:
Check for 1 required mounted source AND at least 1 required mounted target

The best aproach for this is to build an array of mounted devices, then evaluate de count of elements in array.

Introduction

1. Care! Using grep -q "$dev" /proc/mounts will fail to found spaced mount points!

```<code>/media/spaced target
</code>```

in /proc/mounts will appear as

```<code>/media/spaced\040target
</code>```

command printf -v varname '%b' $varname could help!

2. Using bash array and associative array to avoid fork

Instead of doing many fork to grep, (browsing same file many time), you could use bash for the job.

3.  Parallelizing rsync on many targets

Using backgrounded jobs and wait -n -p <VARNAME>,  you could do rsync on many targets simultaneously.

4. Using /proc/self/mounts instead of /proc/mounts

After having a look at man 5 proc.

Here is a script, within:

you could configure as many backup targets you want.

if all targets are mounted, script go on

if no targets are mounted, script stop and

if at least one target is mounted but not all, user is asked for continuing.

(this could be avoided by using -y/-n optional flag)

On second part, all rsync are run as background job (parallelized),

then script wait for all rsync to be done,

then print each result code with corresponding target,

before finish

The script:

#!/bin/bash

source='/media/card'
backups=(
    /media/backup
    /media/backup2
    /media/other\ backup
)

die() {
    echo "$0[$$] ERROR: $@" >&2
    exit 1
}
warn() {
    echo "$0[$$] WARNING: $@" >&2
}
```
<pre class="lang-bash prettyprint-override"><code>declare -A tobemounted="(['$source']='source')"
for target in "${backups[@]}";do
    tobemounted["$target"]=backup
done

mountedbk=()
while read -r _ mpnt _;do
    printf -v mpnt %b $mpnt
    if [[ -v tobemounted["$mpnt"] ]] ;then
        [[ ${tobemounted["$mpnt"]} == backup ]] && mountedbk+=("$mpnt")
        unset tobemounted["$mpnt"]
    fi
done </proc/self/mounts

[[ -v tobemounted["$source"] ]] && die "Source '$source' not mounted."

for missing in "${!tobemounted[@]}";do
    warn "Backup '$missing' not mounted."
done
(( ${#mountedbk[@]} == 0 )) && die "No backup present."

if (( ${#mountedbk[@]} < ${#backups[@]} ));then
    printf -v msg 'Only %d / %d backups targets are present.' \
        ${#mountedbk[@]} ${#backups[@]}
    warn "$msg"
    case $* in
        *-n* ) die Exit now. ;;
        *-y* ) warn Process anyway. ;;
        * ) read -rsn 1 -p 'Process anyway? (N/y): ' ans
            [[ "${ans//[yY]}" ]] && { echo No; die 'User abort.';}
            echo Yes ;;
    esac
fi
</code>```

pids=() resultmsg=(success)
for target in "${mountedbk[@]}";do
    echo rsync "$source/." "$target/." &
    pids[$!]="$target"
done

while ((${#pids[@]}));do
    wait -np pid
    printf 'backup to "%s" end with %s.\n' \
        "${pids[pid]}"  "${resultmsg[$?]:-error}"
    unset 'pids[pid]'
done
```
<p>Replace line:</p>
<pre class="lang-bash prettyprint-override"><code>    echo rsync "$source/." "$target/." &
</code>```

by somethine like:

    rsync <your rsync options> "$source/SourcePath/." "$target/TargetPath/." &
```
<h3>Outputs could look like:</h3>
<p>When source not ready:</p>
<pre class="lang-none prettyprint-override"><code>$ ./backups.sh
./backups.sh[3721068] ERROR: Source '/media/card' not mounted.
</code>```

When none of the targets are ready.

$ ./backups.sh
./backups.sh[3729071] WARNING: Backup '/media/backup' not mounted.
./backups.sh[3729071] WARNING: Backup '/media/backup2' not mounted.
./backups.sh[3729071] WARNING: Backup '/media/other backup' not mounted.
./backups.sh[3729071] ERROR: No backup present.
```
<p>When some but not all targets are ready.</p>
<pre class="lang-none prettyprint-override"><code>$ ./backups.sh
./backups.sh[3725569] WARNING: Backup '/media/backup2' not mounted.
./backups.sh[3725569] WARNING: Backup '/media/other backup' not mounted.
./backups.sh[3725569] WARNING: Only 1 / 3 backups targets are present.
Process anyway? (N/y): Yes
backup to "/media/backup" end with success.
</code>```

$ ./backups.sh
./backups.sh[3729355] WARNING: Backup '/media/backup' not mounted.
./backups.sh[3729355] WARNING: Backup '/media/other backup' not mounted.
./backups.sh[3729355] WARNING: Only 1 / 3 backups targets are present.
Process anyway? (N/y): Yes
backup to "/media/backup2" end with success.
```
<pre class="lang-none prettyprint-override"><code>$ ./backups.sh
./backups.sh[3854708] WARNING: Backup '/media/backup2' not mounted.
./backups.sh[3854708] WARNING: Backup '/media/other backup' not mounted.
./backups.sh[3854708] WARNING: Only 1 / 3 backups targets are present.
Process anyway? (N/y): No
./backups.sh[3854708] ERROR: User abort.
</code>```

$ ./backups.sh -y
./backups.sh[3734321] WARNING: Backup '/media/backup' not mounted.
./backups.sh[3734321] WARNING: Backup '/media/other backup' not mounted.
./backups.sh[3734321] WARNING: Only 1 / 3 backups targets are present.
./backups.sh[3734321] Process anyway.
backup to "/media/backup2" end with success.
```
<pre class="lang-none prettyprint-override"><code>$ ./backups.sh -n
./backups.sh[3854855] WARNING: Backup '/media/backup2' not mounted.
./backups.sh[3854855] WARNING: Backup '/media/other backup' not mounted.
./backups.sh[3854855] WARNING: Only 1 / 3 backups targets are present.
./backups.sh[3854855] ERROR: Exit now.
</code>```

When all targets are ready.

$ ./backups.sh
backup to "/media/backup" end with success.
backup to "/media/backup2" end with success.
backup to "/media/other\ backup" end with success.
```

Title: Bash Script - Check mounted devices

Body:
Check for 1 required mounted source AND at least 1 required mounted target

The best aproach for this is to build an array of mounted devices, then evaluate de count of elements in array.

Introduction

1. Care! Using grep -q "$dev" /proc/mounts will fail to found spaced mount points!

/media/spaced target

in /proc/mounts will appear as

/media/spaced\040target

command printf -v varname '%b' $varname could help!

2. Using bash array and associative array to avoid fork

Instead of doing many fork to grep, (browsing same file many time), you could use bash for the job.

3.  Parallelizing rsync on many targets

Using backgrounded jobs and wait -n -p <VARNAME>,  you could do rsync on many targets simultaneously.

4. Using /proc/self/mounts instead of /proc/mounts

After having a look at man 5 proc.

Here is a script, within:

you could configure as many backup targets you want.

if all targets are mounted, script go on

if no targets are mounted, script stop and

if at least one target is mounted but not all, user is asked for continuing.

(this could be avoided by using -y/-n optional flag)

On second part, all rsync are run as background job (parallelized),

then script wait for all rsync to be done,

then print each result code with corresponding target,

before finish

The script:

#!/bin/bash

source='/media/card'
backups=(
    /media/backup
    /media/backup2
    /media/other\ backup
)

die() {
    echo "$0[$$] ERROR: $@" >&2
    exit 1
}
warn() {
    echo "$0[$$] WARNING: $@" >&2
}

declare -A tobemounted="(['$source']='source')"
for target in "${backups[@]}";do
    tobemounted["$target"]=backup
done

mountedbk=()
while read -r _ mpnt _;do
    printf -v mpnt %b $mpnt
    if [[ -v tobemounted["$mpnt"] ]] ;then
        [[ ${tobemounted["$mpnt"]} == backup ]] && mountedbk+=("$mpnt")
        unset tobemounted["$mpnt"]
    fi
done </proc/self/mounts

[[ -v tobemounted["$source"] ]] && die "Source '$source' not mounted."

for missing in "${!tobemounted[@]}";do
    warn "Backup '$missing' not mounted."
done
(( ${#mountedbk[@]} == 0 )) && die "No backup present."

if (( ${#mountedbk[@]} < ${#backups[@]} ));then
    printf -v msg 'Only %d / %d backups targets are present.' \
        ${#mountedbk[@]} ${#backups[@]}
    warn "$msg"
    case $* in
        *-n* ) die Exit now. ;;
        *-y* ) warn Process anyway. ;;
        * ) read -rsn 1 -p 'Process anyway? (N/y): ' ans
            [[ "${ans//[yY]}" ]] && { echo No; die 'User abort.';}
            echo Yes ;;
    esac
fi

pids=() resultmsg=(success)
for target in "${mountedbk[@]}";do
    echo rsync "$source/." "$target/." &
    pids[$!]="$target"
done

while ((${#pids[@]}));do
    wait -np pid
    printf 'backup to "%s" end with %s.\n' \
        "${pids[pid]}"  "${resultmsg[$?]:-error}"
    unset 'pids[pid]'
done

Replace line:

    echo rsync "$source/." "$target/." &

by somethine like:

    rsync <your rsync options> "$source/SourcePath/." "$target/TargetPath/." &

Outputs could look like:

When source not ready:

$ ./backups.sh
./backups.sh[3721068] ERROR: Source '/media/card' not mounted.

When none of the targets are ready.

$ ./backups.sh
./backups.sh[3729071] WARNING: Backup '/media/backup' not mounted.
./backups.sh[3729071] WARNING: Backup '/media/backup2' not mounted.
./backups.sh[3729071] WARNING: Backup '/media/other backup' not mounted.
./backups.sh[3729071] ERROR: No backup present.

When some but not all targets are ready.

$ ./backups.sh
./backups.sh[3725569] WARNING: Backup '/media/backup2' not mounted.
./backups.sh[3725569] WARNING: Backup '/media/other backup' not mounted.
./backups.sh[3725569] WARNING: Only 1 / 3 backups targets are present.
Process anyway? (N/y): Yes
backup to "/media/backup" end with success.

$ ./backups.sh
./backups.sh[3729355] WARNING: Backup '/media/backup' not mounted.
./backups.sh[3729355] WARNING: Backup '/media/other backup' not mounted.
./backups.sh[3729355] WARNING: Only 1 / 3 backups targets are present.
Process anyway? (N/y): Yes
backup to "/media/backup2" end with success.

$ ./backups.sh
./backups.sh[3854708] WARNING: Backup '/media/backup2' not mounted.
./backups.sh[3854708] WARNING: Backup '/media/other backup' not mounted.
./backups.sh[3854708] WARNING: Only 1 / 3 backups targets are present.
Process anyway? (N/y): No
./backups.sh[3854708] ERROR: User abort.

$ ./backups.sh -y
./backups.sh[3734321] WARNING: Backup '/media/backup' not mounted.
./backups.sh[3734321] WARNING: Backup '/media/other backup' not mounted.
./backups.sh[3734321] WARNING: Only 1 / 3 backups targets are present.
./backups.sh[3734321] Process anyway.
backup to "/media/backup2" end with success.

$ ./backups.sh -n
./backups.sh[3854855] WARNING: Backup '/media/backup2' not mounted.
./backups.sh[3854855] WARNING: Backup '/media/other backup' not mounted.
./backups.sh[3854855] WARNING: Only 1 / 3 backups targets are present.
./backups.sh[3854855] ERROR: Exit now.

When all targets are ready.

$ ./backups.sh
backup to "/media/backup" end with success.
backup to "/media/backup2" end with success.
backup to "/media/other\ backup" end with success.


问:
CSS cascading term
The cascading term in CSS is related to the fact
that having more style sources combine them together
or only to the fact to the conflict order resolution?

Thanks

答:
This might be of help. http://www.w3.org/TR/CSS2/cascade.html#cascade.

It seems that you have the right assumption.

Title: CSS cascading term


答: You are mixing your fortran, C lingo of vector which refers to a collection of ints in contiguous memory location i.e an array with C++'s std::vector. std::vector is a separate container class altogether and needs construction - refer to the documentation

Title: How to call C++ funtion from Fortran 77 using std::vector as arguments?

Body:
I have to replace some Fortran subroutines with C++ functions. Since the literature is poor, I am stuck with a problem like the following one.

My code always throws an error:

Program received signal SIGSEGV: Segmentation fault - invalid memory reference.

This is my Fortran code:

  PROGRAM vector_adder
  IMPLICIT NONE

  INTEGER,DIMENSION(3) :: a,b,c
  INTEGER :: i

  !C fill vectors with values
  DO i = 1,3
      a(i) = i
      b(i) = i
  END DO

  CALL ADD_VECTORS(a,b,c)

  WRITE(*,'(I5,I5,I5)') (c(i),i =1,3)

  STOP
  END PROGRAM

A working C code:

void add_vectors_(int (*a)[3], int (*b)[3], int (*c)[3])
{
    for(int i = 0; i<3 ; i++)
    {
        (*c)[i] =(*a)[i] + (*b)[i];
    }
}

And I would like a similar one in C++:

extern "C" void add_vectors_(std::vector<int> *a, std::vector<int> *b, std::vector<int> *c)
{
    for(int i = 0; isize() ; i++)
    {
        (*c)[i] =(*a)[i] + (*b)[i];
    }
}


问:
Handle UITapGestureRecognizer in another UIViewController
I'm trying to handle a gesture in another UIViewController, but the program crashes. I want to invoke the handleTap function in the Second UIViewController.

This is what I want to do but it crashes (Error Message: unrecognized selector sent to class):

```<code>class ViewController: UIViewController {

    override func viewDidLoad() { super.viewDidLoad()
        Second.showMenu(self)
    }

}

public class Second: UIViewController {

    static func showMenu(_ vc: ViewController) {

        let bgView = UIView(frame: vc.view.frame)
        vc.view.addSubview(bgView)

        let tap = UITapGestureRecognizer(target: self, action:#selector(self.handleTap(sender:)))
        bgView.isUserInteractionEnabled = true
        bgView.addGestureRecognizer(tap)

    }

    func handleTap(sender: UITapGestureRecognizer) {
        print("handleTap")
    }

}
</code>```

This works, but I want to be able to handle everything in the Second UIViewController:

```<code>class ViewController: UIViewController {

    override func viewDidLoad() { super.viewDidLoad()
        Second.showMenu(self)
    }

    func handleTap(sender: UITapGestureRecognizer) {
        print("handleTap")
    }

}

public class Second: UIViewController {

    static func showMenu(_ vc: ViewController) {

        let bgView = UIView(frame: vc.view.frame)
        vc.view.addSubview(bgView)

        let tap = UITapGestureRecognizer(target: vc, action:#selector(vc.handleTap(sender:)))
        bgView.isUserInteractionEnabled = true
        bgView.addGestureRecognizer(tap)

    }

}
</code>```

答:
This function:

```<code>static func showMenu(_ vc: ViewController) {}
</code>```

Is a static function. It means that it's not executed on a instance of the view controller, but on the class itself. You added a gesture recognizer:

```<code>let tap = UITapGestureRecognizer(target: self, action:#selector(self.handleTap(sender:)))
</code>```

target:self means that the selector is invoked on the class, but the handleTap function is not static. An easy workaround would be to make it a static function:

```<code>static func handleTap(sender: UITapGestureRecognizer) {
    print("handleTap")
}
</code>```

But I think that it still doesn't make sense, even if it works. I can hardly imagine a situation where you need to execute a selector as response of an event generated in another view controller.

Body:
I'm trying to handle a gesture in another UIViewController, but the program crashes. I want to invoke the handleTap function in the Second UIViewController.

This is what I want to do but it crashes (Error Message: unrecognized selector sent to class):

class ViewController: UIViewController {

    override func viewDidLoad() { super.viewDidLoad()
        Second.showMenu(self)
    }

}

public class Second: UIViewController {

    static func showMenu(_ vc: ViewController) {

        let bgView = UIView(frame: vc.view.frame)
        vc.view.addSubview(bgView)

        let tap = UITapGestureRecognizer(target: self, action:#selector(self.handleTap(sender:)))
        bgView.isUserInteractionEnabled = true
        bgView.addGestureRecognizer(tap)

    }

    func handleTap(sender: UITapGestureRecognizer) {
        print("handleTap")
    }

}

This works, but I want to be able to handle everything in the Second UIViewController:

class ViewController: UIViewController {

    override func viewDidLoad() { super.viewDidLoad()
        Second.showMenu(self)
    }

    func handleTap(sender: UITapGestureRecognizer) {
        print("handleTap")
    }

}

public class Second: UIViewController {

    static func showMenu(_ vc: ViewController) {

        let bgView = UIView(frame: vc.view.frame)
        vc.view.addSubview(bgView)

        let tap = UITapGestureRecognizer(target: vc, action:#selector(vc.handleTap(sender:)))
        bgView.isUserInteractionEnabled = true
        bgView.addGestureRecognizer(tap)

    }

}

Body:
This function:

static func showMenu(_ vc: ViewController) {}

Is a static function. It means that it's not executed on a instance of the view controller, but on the class itself. You added a gesture recognizer:

let tap = UITapGestureRecognizer(target: self, action:#selector(self.handleTap(sender:)))

target:self means that the selector is invoked on the class, but the handleTap function is not static. An easy workaround would be to make it a static function:

static func handleTap(sender: UITapGestureRecognizer) {
    print("handleTap")
}

But I think that it still doesn't make sense, even if it works. I can hardly imagine a situation where you need to execute a selector as response of an event generated in another view controller.


问:
Adding two strings together in the preprocessor
I am currently writing a header to make handling my external libs easier.

Here is the minimal code:

```<code>#pragma once

#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

#define EXTERNAL_PATH STR(C:/C++ Libraries/)

#define LUA_PATH       EXTERNAL_PATH STR(lua 5.3.4/)
#define LUA_INCLUDE       LUA_PATH       STR(include/)
</code>```

So basically, I include this header and write something like

```<code>#include LUA_INCLUDE (add this two strings) "lua.hpp"
</code>```

How can I link two strings in the preprocessor together ?

答:
Are you looking for ##? And don't stringify (quote) macro params too early because then there is no way back.

Example:

#define MY_QUOTE(a) #a

#define CONCAT_QUOTE(a,b) MY_QUOTE(a##b)

#define CONCAT(a,b) a##b

// this works OK
#include CONCAT(<iostrea, m>)

// this doesn't as iostream should be just in <> rather than "<>"
#include CONCAT_QUOTE(<iostrea, m>)
```

Body:
I am currently writing a header to make handling my external libs easier.

Here is the minimal code:

#pragma once

#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

#define EXTERNAL_PATH STR(C:/C++ Libraries/)

#define LUA_PATH       EXTERNAL_PATH STR(lua 5.3.4/)
#define LUA_INCLUDE       LUA_PATH       STR(include/)

So basically, I include this header and write something like

#include LUA_INCLUDE (add this two strings) "lua.hpp"

How can I link two strings in the preprocessor together ?


问:
R: Summarize at specific hierarchy level
Data looks like this, call it df1:

Employee ID | Manager ID | Management Level

I'm trying to generate a headcount by executive at a certain management level, let's call that level "VP". How do I summarize through multiple tiers in the management structure? I need a total headcount for each Manager at the VP level, which will include the headcount of managers at a lower level, who report to the VP level manager.

This is what I have so far:

```<code>require(dplyr)

managers <- group_by(df1, Manager.ID)
summarize(managers, count =n())
</code>```

That tells me the headcount of each manager. Now I need to roll those totals into the counts of the VP level manager.

I.E. VP is listed as manager three times, so his current count =3. Each of those three managers have 4 people they manage. So the count for the VP in question should equal 15.

How do I roll up at this level?

Data:

```<code>df1 <- structure(list(Employee.ID = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 27L
), Manager.ID = c(27L, 27L, 1L, 2L, 4L, 1L, 1L, NA), Management.Level = structure(c(5L,
5L, 1L, 1L, 3L, 3L, 4L, 2L), .Label = c("ASSOC", "CEO", "Entry",
"Etnry", "VP"), class = "factor")), .Names = c("Employee.ID",
"Manager.ID", "Management.Level"), class = "data.frame", row.names = c(NA,
-8L))
</code>```

答:
Try this:

```<code>df.c<- df1 %>%
       arrange(Manager.ID, Employee.ID) %>%
       mutate(gr = cumsum(lag(Manager.ID, default = 0) != Manager.ID &
                          lag(Employee.ID, default = 0) != Manager.ID)) %>%
       group_by(gr) %>%
       summarise(top.man.id = min(Manager.ID))

df.s<- df1 %>%
       arrange(Manager.ID, Employee.ID) %>%
       mutate(gr = cumsum(lag(Manager.ID, default = 0) != Manager.ID &
                          lag(Employee.ID, default = 0) != Manager.ID)) %>%
       group_by(gr) %>%
       summarise(count = n()) %>%
       inner_join(df.c, by = "gr")
</code>```

This results in

```<code># A tibble: 4 × 3
     gr Count top.man.id
  <int> <int>      <int>
1     1     3          1
2     2     2          2
3     3     2         27
4    NA     1         NA
</code>```

Body:
Data looks like this, call it df1:

Employee ID | Manager ID | Management Level

I'm trying to generate a headcount by executive at a certain management level, let's call that level "VP". How do I summarize through multiple tiers in the management structure? I need a total headcount for each Manager at the VP level, which will include the headcount of managers at a lower level, who report to the VP level manager.

This is what I have so far:

require(dplyr)

managers <- group_by(df1, Manager.ID)
summarize(managers, count =n())

That tells me the headcount of each manager. Now I need to roll those totals into the counts of the VP level manager.

I.E. VP is listed as manager three times, so his current count =3. Each of those three managers have 4 people they manage. So the count for the VP in question should equal 15.

How do I roll up at this level?

Data:

df1 <- structure(list(Employee.ID = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 27L
), Manager.ID = c(27L, 27L, 1L, 2L, 4L, 1L, 1L, NA), Management.Level = structure(c(5L,
5L, 1L, 1L, 3L, 3L, 4L, 2L), .Label = c("ASSOC", "CEO", "Entry",
"Etnry", "VP"), class = "factor")), .Names = c("Employee.ID",
"Manager.ID", "Management.Level"), class = "data.frame", row.names = c(NA,
-8L))

Body:
Try this:

df.c<- df1 %>%
       arrange(Manager.ID, Employee.ID) %>%
       mutate(gr = cumsum(lag(Manager.ID, default = 0) != Manager.ID &
                          lag(Employee.ID, default = 0) != Manager.ID)) %>%
       group_by(gr) %>%
       summarise(top.man.id = min(Manager.ID))

df.s<- df1 %>%
       arrange(Manager.ID, Employee.ID) %>%
       mutate(gr = cumsum(lag(Manager.ID, default = 0) != Manager.ID &
                          lag(Employee.ID, default = 0) != Manager.ID)) %>%
       group_by(gr) %>%
       summarise(count = n()) %>%
       inner_join(df.c, by = "gr")

This results in

# A tibble: 4 × 3
     gr Count top.man.id
  <int> <int>      <int>
1     1     3          1
2     2     2          2
3     3     2         27
4    NA     1         NA


问:
Opening Crystal Report in a new page in ASP.net
Is there anyway I can open the PDF in a new page instead of the same page in ASP.net.

I am calling this code on click of a button. I want this to be opened in a new page.

Below is the code

```<code>ReportDocument fpReport = new ReportDocument();
            fpReport.FileName = Server.MapPath("~/Report.rpt");

            fpReport.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, false, "MyReport");
</code>```

答: You will have to add an onclick attribute to the button which calls some JS to open a new window, there is no way to do this as you described.</p>

Body:
Is there anyway I can open the PDF in a new page instead of the same page in ASP.net.

I am calling this code on click of a button. I want this to be opened in a new page.

Below is the code

ReportDocument fpReport = new ReportDocument();
            fpReport.FileName = Server.MapPath("~/Report.rpt");

            fpReport.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, false, "MyReport");


问:
Printing the contents from powerpoint in an Excel file using VBA
Im looking for a way to copy the text of the first element of a powerpoint slide into an excel file. I got the following code that prints out the text of the first box:

```<code>Sub getText

 Dim sld As Slide
 Set sld = Application.ActiveWindow.View.Slide
 For Each sld In ActivePresentation.Slides
 With sld.Shapes(1)

  myInput = .TextFrame.TextRange.Text
  MsgBox (myInput)

 End With
Next
End sub
</code>```

Now the next step I want to take is to add the data to an excel file. Therefore I try to do the following:

```<code>Sub getText()

 Dim xlApp As Object
 Dim xlWorkBook As Object
 Set xlApp = CreateObject("Excel.Application")
 xlApp.Visible = True
 Set xlWorkBook = xlApp.Workbooks.Open("~\PROJECTEN\Lopend\office_VA\macroStore.xlsx", True, False)
 xlWorkBook.sheets(1).Range("A2").Select

Dim sld As Slide
Set sld = Application.ActiveWindow.View.Slide

For Each sld In ActivePresentation.Slides
With sld.Shapes(1)

 myInput = .TextFrame.TextRange.Text
 ActiveCell.Text = myInput

End With
Next

End Sub
</code>```

However when I try it now it get the error: "Object required". Any thoughts on how I should change my code?

答:
Your problem is that you're referencing ActiveCell.Text but VBA has no clue what that is.  Also, you haven't declared your myInput variable.

Try this macro, where instead of selecting the cell I'm just assigning the text value to it.  Also, if you're writing more than one value your code will keep writing over the same cell.  In the code below I've added a couple of lines that will write your text down column A.

```<code>Sub getText()

    Dim xlApp As Object
    Dim xlWorkBook As Object
    Set xlApp = CreateObject("Excel.Application")
    xlApp.Visible = True
    Set xlWorkBook = xlApp.Workbooks.Open("~\PROJECTEN\Lopend\office_VA\macroStore.xlsx", True, False)

    Dim xlWorkSheet As Object  ' Create a worksheet object
    xlWorkSheet = xlWorkBook.sheets(1)  ' Set the sheet you activate to that object

    Dim iRow As Long  ' Create a variable to store row number
    iRow = 1  'Set the first row that you want to start writing data on

    Dim sld As Slide
    Dim myInput As String
    Set sld = Application.ActiveWindow.View.Slide

    For Each sld In ActivePresentation.Slides
        With sld.Shapes(1)
            myInput = .TextFrame.TextRange.Text
            xlWorkSheet.Cells(iRow, "A") = myInput  'Using .Cells() you can specify the (row, column) location
            iRow = iRow + 1  'increment by one for next line of text
        End With
    Next
End Sub
</code>```

Body:
Im looking for a way to copy the text of the first element of a powerpoint slide into an excel file. I got the following code that prints out the text of the first box:

Sub getText

 Dim sld As Slide
 Set sld = Application.ActiveWindow.View.Slide
 For Each sld In ActivePresentation.Slides
 With sld.Shapes(1)

  myInput = .TextFrame.TextRange.Text
  MsgBox (myInput)

 End With
Next
End sub

Now the next step I want to take is to add the data to an excel file. Therefore I try to do the following:

Sub getText()

 Dim xlApp As Object
 Dim xlWorkBook As Object
 Set xlApp = CreateObject("Excel.Application")
 xlApp.Visible = True
 Set xlWorkBook = xlApp.Workbooks.Open("~\PROJECTEN\Lopend\office_VA\macroStore.xlsx", True, False)
 xlWorkBook.sheets(1).Range("A2").Select

Dim sld As Slide
Set sld = Application.ActiveWindow.View.Slide

For Each sld In ActivePresentation.Slides
With sld.Shapes(1)

 myInput = .TextFrame.TextRange.Text
 ActiveCell.Text = myInput

End With
Next

End Sub

However when I try it now it get the error: "Object required". Any thoughts on how I should change my code?

Body:
Your problem is that you're referencing ActiveCell.Text but VBA has no clue what that is.  Also, you haven't declared your myInput variable.

Try this macro, where instead of selecting the cell I'm just assigning the text value to it.  Also, if you're writing more than one value your code will keep writing over the same cell.  In the code below I've added a couple of lines that will write your text down column A.

Sub getText()

    Dim xlApp As Object
    Dim xlWorkBook As Object
    Set xlApp = CreateObject("Excel.Application")
    xlApp.Visible = True
    Set xlWorkBook = xlApp.Workbooks.Open("~\PROJECTEN\Lopend\office_VA\macroStore.xlsx", True, False)

    Dim xlWorkSheet As Object  ' Create a worksheet object
    xlWorkSheet = xlWorkBook.sheets(1)  ' Set the sheet you activate to that object

    Dim iRow As Long  ' Create a variable to store row number
    iRow = 1  'Set the first row that you want to start writing data on

    Dim sld As Slide
    Dim myInput As String
    Set sld = Application.ActiveWindow.View.Slide

    For Each sld In ActivePresentation.Slides
        With sld.Shapes(1)
            myInput = .TextFrame.TextRange.Text
            xlWorkSheet.Cells(iRow, "A") = myInput  'Using .Cells() you can specify the (row, column) location
            iRow = iRow + 1  'increment by one for next line of text
        End With
    Next
End Sub


问:
Indexing on Local Secondary Index in Dynamo DB
Say, I have a table with 5 columns :- A, B, C, D, E. A is a hash key and B is a sort Key. Now, I also wanted to query for A and C. Then, adding C as a local secondary index would be fine, right? I am asking because local secondary index is primarily for range queries. For my case, it would be equal query on C attribute.

Any suggestions you could give would be greatful.

答: You are correct. With a Local seconday index you cannot change the partition key.  Using this you can query = </p>


问:
How to add data from JTable to JTextArea?
I have the following issue: I am getting my data in JTable and when I click on receipt button, I want to add that table data into a JTextArea. I want to generate the receipt.

How can I get all the table data into the text area?

答: Add ListSelectionListener to your table and in its valueChanged method get selected row index by calling getFirstIndex and then get the row data by calling JTable.getModel().getValueAt and populate your JTextField value.


问:
meanjs 0.4.0 not working when deployed to Heroku
I've just tried the meanjs 0.4.0 in local host and runs fine but when I deploy to heroku link to app and try the "Sign up" option I get this in the navegator console:

```<code>POST https://meanjsapptest.herokuapp.com/api/auth/signup 503 (Service Unavailable)
</code>```

and when I write the comand heroku logs in the CLI I get:

```<code>2017-06-06T04:15:35.152983+00:00 app[web.1]: (node:16) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
2017-06-06T04:15:35.153005+00:00 app[web.1]: crypto.js:635
2017-06-06T04:15:35.153006+00:00 app[web.1]: throw new TypeError(
2017-06-06T04:15:35.153006+00:00 app[web.1]: ^
2017-06-06T04:15:35.153007+00:00 app[web.1]:
2017-06-06T04:15:35.153008+00:00 app[web.1]: TypeError: The "digest" argument is required and must not be undefined
2017-06-06T04:15:35.153009+00:00 app[web.1]: at pbkdf2 (crypto.js:635:11)
2017-06-06T04:15:35.153010+00:00 app[web.1]: at Object.exports.pbkdf2Sync (crypto.js:628:10)
2017-06-06T04:15:35.153012+00:00 app[web.1]: at model. (/app/modules/users/server/models/user.server.model.js:112:26)
2017-06-06T04:15:35.153011+00:00 app[web.1]: at model.UserSchema.methods.hashPassword (/app/modules/users/server/models/user.server.model.js:123:19)
2017-06-06T04:15:35.153013+00:00 app[web.1]: at _next (/app/node_modules/hooks-fixed/hooks.js:62:30)
2017-06-06T04:15:35.153013+00:00 app[web.1]: at fnWrapper (/app/node_modules/hooks-fixed/hooks.js:186:8)
2017-06-06T04:15:35.153014+00:00 app[web.1]: at model. (/app/node_modules/mongoose/lib/plugins/saveSubdocs.js:20:7)
2017-06-06T04:15:35.153014+00:00 app[web.1]: at _next (/app/node_modules/hooks-fixed/hooks.js:62:30)
2017-06-06T04:15:35.153015+00:00 app[web.1]: at fnWrapper (/app/node_modules/hooks-fixed/hooks.js:186:8)
2017-06-06T04:15:35.153015+00:00 app[web.1]: at /app/node_modules/mongoose/lib/plugins/validateBeforeSave.js:33:13
2017-06-06T04:15:35.153016+00:00 app[web.1]: at /app/node_modules/kareem/index.js:131:16
2017-06-06T04:15:35.153016+00:00 app[web.1]: at _combinedTickCallback (internal/process/next_tick.js:95:7)
2017-06-06T04:15:35.153017+00:00 app[web.1]: at process._tickCallback (internal/process/next_tick.js:161:9)
2017-06-06T04:15:35.167579+00:00 app[web.1]: error: Forever detected script exited with code: 1
2017-06-06T04:15:35.173500+00:00 app[web.1]: error: Script restart attempt #1
2017-06-06T04:15:35.292903+00:00 app[web.1]:
2017-06-06T04:15:35.294191+00:00 app[web.1]:
2017-06-06T04:15:35.310954+00:00 app[web.1]: + Error: Certificate file or key file is missing, falling back to non-SSL mode
2017-06-06T04:15:35.311037+00:00 app[web.1]: To create them, simply run the following from your shell: sh ./scripts/generate-ssl-certs.sh
2017-06-06T04:15:35.311039+00:00 app[web.1]:
2017-06-06T04:15:35.916892+00:00 app[web.1]: Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.
</code>```

I don't know what to do now because Heroku supports tell me thar the error is in my code but I haven't changed anything there!

CLI screenshot

答:
Just had this problem. We were able to fix it by enforcing our preferred node version in package.json > engines.

We previously had it at

```<code>"node": ">=0.10.0"
</code>```

We changed it to

```<code>"node": "6.6.0"
</code>```

And then pushed that to Heroku, and that fixed the issue.

Not entirely sure what the problem is, but we found this link which lead us to believe the node version was the issue:

https://github.com/nodejs/node/wiki/Breaking-changes-between-v4-LTS-and-v6-LTS#crypto

Body:
I've just tried the meanjs 0.4.0 in local host and runs fine but when I deploy to heroku link to app and try the "Sign up" option I get this in the navegator console:

POST https://meanjsapptest.herokuapp.com/api/auth/signup 503 (Service Unavailable)

and when I write the comand heroku logs in the CLI I get:

2017-06-06T04:15:35.152983+00:00 app[web.1]: (node:16) DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
2017-06-06T04:15:35.153005+00:00 app[web.1]: crypto.js:635
2017-06-06T04:15:35.153006+00:00 app[web.1]: throw new TypeError(
2017-06-06T04:15:35.153006+00:00 app[web.1]: ^
2017-06-06T04:15:35.153007+00:00 app[web.1]:
2017-06-06T04:15:35.153008+00:00 app[web.1]: TypeError: The "digest" argument is required and must not be undefined
2017-06-06T04:15:35.153009+00:00 app[web.1]: at pbkdf2 (crypto.js:635:11)
2017-06-06T04:15:35.153010+00:00 app[web.1]: at Object.exports.pbkdf2Sync (crypto.js:628:10)
2017-06-06T04:15:35.153012+00:00 app[web.1]: at model. (/app/modules/users/server/models/user.server.model.js:112:26)
2017-06-06T04:15:35.153011+00:00 app[web.1]: at model.UserSchema.methods.hashPassword (/app/modules/users/server/models/user.server.model.js:123:19)
2017-06-06T04:15:35.153013+00:00 app[web.1]: at _next (/app/node_modules/hooks-fixed/hooks.js:62:30)
2017-06-06T04:15:35.153013+00:00 app[web.1]: at fnWrapper (/app/node_modules/hooks-fixed/hooks.js:186:8)
2017-06-06T04:15:35.153014+00:00 app[web.1]: at model. (/app/node_modules/mongoose/lib/plugins/saveSubdocs.js:20:7)
2017-06-06T04:15:35.153014+00:00 app[web.1]: at _next (/app/node_modules/hooks-fixed/hooks.js:62:30)
2017-06-06T04:15:35.153015+00:00 app[web.1]: at fnWrapper (/app/node_modules/hooks-fixed/hooks.js:186:8)
2017-06-06T04:15:35.153015+00:00 app[web.1]: at /app/node_modules/mongoose/lib/plugins/validateBeforeSave.js:33:13
2017-06-06T04:15:35.153016+00:00 app[web.1]: at /app/node_modules/kareem/index.js:131:16
2017-06-06T04:15:35.153016+00:00 app[web.1]: at _combinedTickCallback (internal/process/next_tick.js:95:7)
2017-06-06T04:15:35.153017+00:00 app[web.1]: at process._tickCallback (internal/process/next_tick.js:161:9)
2017-06-06T04:15:35.167579+00:00 app[web.1]: error: Forever detected script exited with code: 1
2017-06-06T04:15:35.173500+00:00 app[web.1]: error: Script restart attempt #1
2017-06-06T04:15:35.292903+00:00 app[web.1]:
2017-06-06T04:15:35.294191+00:00 app[web.1]:
2017-06-06T04:15:35.310954+00:00 app[web.1]: + Error: Certificate file or key file is missing, falling back to non-SSL mode
2017-06-06T04:15:35.311037+00:00 app[web.1]: To create them, simply run the following from your shell: sh ./scripts/generate-ssl-certs.sh
2017-06-06T04:15:35.311039+00:00 app[web.1]:
2017-06-06T04:15:35.916892+00:00 app[web.1]: Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.

I don't know what to do now because Heroku supports tell me thar the error is in my code but I haven't changed anything there!

CLI screenshot

Body:
Just had this problem. We were able to fix it by enforcing our preferred node version in package.json > engines.

We previously had it at

"node": ">=0.10.0"

We changed it to

"node": "6.6.0"

And then pushed that to Heroku, and that fixed the issue.

Not entirely sure what the problem is, but we found this link which lead us to believe the node version was the issue:

https://github.com/nodejs/node/wiki/Breaking-changes-between-v4-LTS-and-v6-LTS#crypto