问:
How can I bind the given input to another proctype function?
I need some help according to follow problem which I have to implemented it using jSpin and promela language.

A home alarm system can be activated and deactivated using a personal
  ID key or password, after  activation the system enters a waiting
  period of about 30 seconds, time that allows users to evacuate the
  secured area after which the alarm is armed, also when an intrusion is
  detected the alarm has a built in waiting period or delay of 15
  seconds to allow the intruder to enter the password or swipe the card
  key thus identifying himself, in case that the identification is not
  made within the allocated 15 seconds the alarm  will go off and will
  be on until an id card or password is used to deactivate it.

Here is what I tried:

```<code>mtype = {sigact, sigdeact};
chan signal = [0] of {mtype};
chan password = [0] of { int };
/*chan syntax for declaring and initializing message passing channels*/

int count;
bool alarm_off = true; /*The initial state of the alarm is off*/
active proctype alarm()
{
    off:
       if
         :: count >= 30 -> atomic {signal!sigdeact; count = 0;alarm_off = false; goto on;}
         :: else -> atomic {count++; alarm_off = true; goto off;}
       fi;

    on:
        if
          :: count >=15 -> atomic { signal!sigact; count = 0;
    alarm_off = false; goto off;}
          :: else -> atomic {signal!sigact; alarm_off = true; goto pending;}
        fi;

    pending:

        if
           :: count >= 30 -> atomic {count = 0; alarm_off = false; goto on;}
           :: count < 30 -> atomic {count++; alarm_off = false; goto pending;}
        fi;
}

active proctype user()
{
   password ! 1234 //1234 is the password I sent.
   input:  atomic { signal?sigact ->  alarm_off = true; goto off; }
}
</code>```

In the user proctype I send the password

```<code>password ! 1234
</code>```

How can I verify if the password is 1234 and how can I adapt it to own cases ( on, off , pending) based on the verification ?

答:
As the <s>code</s> in the example doesn't appear to follow the specification, at least in the way I understand it, I wrote an example from scratch.

Please note that the following model (<s>source code</s>) is purposely very verbose and redundant in its structure, so that its easier to recognise its logic blocks and --hopefully-- understand it. In practice, one would use some inline function to handle input. I also didn't use SIGACT, SIGDEACT which appeared in the original model, since I could not figure out who was supposed to read those messages neither from the original model (<s>source code</s>) nor from the specification.

#define ALARM_OFF        1
#define ALARM_COUNTDOWN  2
#define ALARM_ARMED      4
#define ALARM_INTRUSION  8
#define ALARM_FIRED     16

#define INPUT_SET_PASSWORD   1
#define INPUT_CHECK_PASSWORD 2
#define INPUT_INTRUDER       4

mtype = { SIGACT, SIGDEACT };

init {
    chan alarm_out = [1] of { mtype };
    chan alarm_in =  [1] of { byte, short };

    run alarm(alarm_in, alarm_out);
    run user(alarm_in);
    run event(alarm_in);
}

proctype alarm(chan input, output)
{
    byte count;
    byte state   = ALARM_OFF;
    short passwd = 1234;
    short tmp    = 0;

off:
    if
        :: nempty(input) ->
            if
                :: input?INPUT_SET_PASSWORD(tmp) ->
                    passwd = tmp;
                :: input?INPUT_CHECK_PASSWORD(tmp) ->
                if
                    :: tmp == passwd ->
                        atomic {
                            state = ALARM_COUNTDOWN;
                            count = 0;
                            goto countdown;
                        }
                    :: else ->
                        skip;
                fi;
                :: input?INPUT_INTRUDER(tmp) ->
                    skip;
            fi;
        :: empty(input) -> skip;
    fi;
    goto off;

countdown:
    if
        :: count < 30 ->
            if
                :: nempty(input) ->
                    if
                        :: input?INPUT_SET_PASSWORD(tmp) ->
                            skip; // error: cannot be done now (?)
                        :: input?INPUT_CHECK_PASSWORD(tmp) ->
                            if
                                :: tmp == passwd ->
                                    atomic {
                                        state = ALARM_OFF;
                                        count = 0;
                                        goto off;
                                    }
                                :: else ->
                                    skip; // error: incorrect password (?)
                            fi;
                        :: input?INPUT_INTRUDER(tmp) ->
                            skip;
                    fi;
                :: empty(input) ->
                    skip;
            fi;
        :: else ->
            atomic {
                state = ALARM_ARMED;
                count = 0;
                goto armed;
            }
    fi;
    count++;
    goto countdown;

armed:
    if
        :: nempty(input) ->
            if
                :: input?INPUT_SET_PASSWORD(tmp) ->
                    skip; // error: cannot be done now (?)
                :: input?INPUT_CHECK_PASSWORD(tmp) ->
                    if
                        :: tmp == passwd ->
                            atomic {
                                state = ALARM_OFF;
                                count = 0;
                                goto off;
                            }
                        :: else ->
                            skip; // error: incorrect password (?)
                                  // maybe it should be handled like
                                  // INPUT_INTRUDER(tmp)
                    fi;
                :: input?INPUT_INTRUDER(tmp) ->
                    atomic {
                        state = ALARM_INTRUSION;
                        count = 0;
                        goto intruder_detected;
                    }
            fi;
        :: empty(input) ->
            skip;
    fi;
    goto armed;

intruder_detected:
    if
        :: count < 15 ->
            if
                :: nempty(input) ->
                    if
                        :: input?INPUT_SET_PASSWORD(tmp) ->
                            skip; // error: cannot be done now (?)
                        :: input?INPUT_CHECK_PASSWORD(tmp);
                            if
                                :: tmp == passwd ->
                                    atomic {
                                        state = ALARM_ARMED;
                                        count = 0;
                                        goto armed;
                                    }
                                :: else ->
                                    skip; // error: incorrect password (?)
                            fi;
                        :: input?INPUT_INTRUDER(tmp) ->
                            skip;
                    fi;
                :: empty(input) ->
                    skip;
            fi;
        :: count >= 15 ->
            atomic {
                state = ALARM_FIRED;
                count = 0;
                goto alarm_fired;
            }
    fi;
    count++;
    goto intruder_detected;

alarm_fired:
    if
        :: nempty(input) ->
            if
                :: input?INPUT_SET_PASSWORD(tmp) ->
                    skip; // error: cannot be done now (?)
                :: input?INPUT_CHECK_PASSWORD(tmp);
                    if
                        :: tmp == passwd ->
                            atomic {
                                state = ALARM_OFF;
                                count = 0;
                                goto off;
                            }
                        :: else ->
                            skip; // error: incorrect password (?)
                                  // warn user but keep alarm on
                    fi;
                :: input?INPUT_INTRUDER(tmp) ->
                    skip;
            fi;
        :: empty(input) ->
            skip;
    fi;
    goto alarm_fired;
};

proctype user(chan output)
{
    output ! INPUT_CHECK_PASSWORD(1234);
};

proctype event(chan output)
{
    output ! INPUT_INTRUDER(0);
};
```

So, basically you have to check both the input (if any!) and the value of count in order to perform a transition in the internal FSM of the alarm system.

In the example I added a proctype of name event which will randomly send a single INPUT_INTRUDER input signal to the alarm system. This, in combination with the user typing his own password, can be used to trigger the chain of events which would cause the alarm to fire.

Body:
I need some help according to follow problem which I have to implemented it using jSpin and promela language.

A home alarm system can be activated and deactivated using a personal
  ID key or password, after  activation the system enters a waiting
  period of about 30 seconds, time that allows users to evacuate the
  secured area after which the alarm is armed, also when an intrusion is
  detected the alarm has a built in waiting period or delay of 15
  seconds to allow the intruder to enter the password or swipe the card
  key thus identifying himself, in case that the identification is not
  made within the allocated 15 seconds the alarm  will go off and will
  be on until an id card or password is used to deactivate it.

Here is what I tried:

mtype = {sigact, sigdeact};
chan signal = [0] of {mtype};
chan password = [0] of { int };
/*chan syntax for declaring and initializing message passing channels*/

int count;
bool alarm_off = true; /*The initial state of the alarm is off*/
active proctype alarm()
{
    off:
       if
         :: count >= 30 -> atomic {signal!sigdeact; count = 0;alarm_off = false; goto on;}
         :: else -> atomic {count++; alarm_off = true; goto off;}
       fi;

    on:
        if
          :: count >=15 -> atomic { signal!sigact; count = 0;
    alarm_off = false; goto off;}
          :: else -> atomic {signal!sigact; alarm_off = true; goto pending;}
        fi;

    pending:

        if
           :: count >= 30 -> atomic {count = 0; alarm_off = false; goto on;}
           :: count < 30 -> atomic {count++; alarm_off = false; goto pending;}
        fi;
}

active proctype user()
{
   password ! 1234 //1234 is the password I sent.
   input:  atomic { signal?sigact ->  alarm_off = true; goto off; }
}

In the user proctype I send the password

password ! 1234

How can I verify if the password is 1234 and how can I adapt it to own cases ( on, off , pending) based on the verification ?

Body:
As the <s>code</s> in the example doesn't appear to follow the specification, at least in the way I understand it, I wrote an example from scratch.

Please note that the following model (<s>source code</s>) is purposely very verbose and redundant in its structure, so that its easier to recognise its logic blocks and --hopefully-- understand it. In practice, one would use some inline function to handle input. I also didn't use SIGACT, SIGDEACT which appeared in the original model, since I could not figure out who was supposed to read those messages neither from the original model (<s>source code</s>) nor from the specification.

#define ALARM_OFF        1
#define ALARM_COUNTDOWN  2
#define ALARM_ARMED      4
#define ALARM_INTRUSION  8
#define ALARM_FIRED     16

#define INPUT_SET_PASSWORD   1
#define INPUT_CHECK_PASSWORD 2
#define INPUT_INTRUDER       4

mtype = { SIGACT, SIGDEACT };

init {
    chan alarm_out = [1] of { mtype };
    chan alarm_in =  [1] of { byte, short };

    run alarm(alarm_in, alarm_out);
    run user(alarm_in);
    run event(alarm_in);
}

proctype alarm(chan input, output)
{
    byte count;
    byte state   = ALARM_OFF;
    short passwd = 1234;
    short tmp    = 0;

off:
    if
        :: nempty(input) ->
            if
                :: input?INPUT_SET_PASSWORD(tmp) ->
                    passwd = tmp;
                :: input?INPUT_CHECK_PASSWORD(tmp) ->
                if
                    :: tmp == passwd ->
                        atomic {
                            state = ALARM_COUNTDOWN;
                            count = 0;
                            goto countdown;
                        }
                    :: else ->
                        skip;
                fi;
                :: input?INPUT_INTRUDER(tmp) ->
                    skip;
            fi;
        :: empty(input) -> skip;
    fi;
    goto off;

countdown:
    if
        :: count < 30 ->
            if
                :: nempty(input) ->
                    if
                        :: input?INPUT_SET_PASSWORD(tmp) ->
                            skip; // error: cannot be done now (?)
                        :: input?INPUT_CHECK_PASSWORD(tmp) ->
                            if
                                :: tmp == passwd ->
                                    atomic {
                                        state = ALARM_OFF;
                                        count = 0;
                                        goto off;
                                    }
                                :: else ->
                                    skip; // error: incorrect password (?)
                            fi;
                        :: input?INPUT_INTRUDER(tmp) ->
                            skip;
                    fi;
                :: empty(input) ->
                    skip;
            fi;
        :: else ->
            atomic {
                state = ALARM_ARMED;
                count = 0;
                goto armed;
            }
    fi;
    count++;
    goto countdown;

armed:
    if
        :: nempty(input) ->
            if
                :: input?INPUT_SET_PASSWORD(tmp) ->
                    skip; // error: cannot be done now (?)
                :: input?INPUT_CHECK_PASSWORD(tmp) ->
                    if
                        :: tmp == passwd ->
                            atomic {
                                state = ALARM_OFF;
                                count = 0;
                                goto off;
                            }
                        :: else ->
                            skip; // error: incorrect password (?)
                                  // maybe it should be handled like
                                  // INPUT_INTRUDER(tmp)
                    fi;
                :: input?INPUT_INTRUDER(tmp) ->
                    atomic {
                        state = ALARM_INTRUSION;
                        count = 0;
                        goto intruder_detected;
                    }
            fi;
        :: empty(input) ->
            skip;
    fi;
    goto armed;

intruder_detected:
    if
        :: count < 15 ->
            if
                :: nempty(input) ->
                    if
                        :: input?INPUT_SET_PASSWORD(tmp) ->
                            skip; // error: cannot be done now (?)
                        :: input?INPUT_CHECK_PASSWORD(tmp);
                            if
                                :: tmp == passwd ->
                                    atomic {
                                        state = ALARM_ARMED;
                                        count = 0;
                                        goto armed;
                                    }
                                :: else ->
                                    skip; // error: incorrect password (?)
                            fi;
                        :: input?INPUT_INTRUDER(tmp) ->
                            skip;
                    fi;
                :: empty(input) ->
                    skip;
            fi;
        :: count >= 15 ->
            atomic {
                state = ALARM_FIRED;
                count = 0;
                goto alarm_fired;
            }
    fi;
    count++;
    goto intruder_detected;

alarm_fired:
    if
        :: nempty(input) ->
            if
                :: input?INPUT_SET_PASSWORD(tmp) ->
                    skip; // error: cannot be done now (?)
                :: input?INPUT_CHECK_PASSWORD(tmp);
                    if
                        :: tmp == passwd ->
                            atomic {
                                state = ALARM_OFF;
                                count = 0;
                                goto off;
                            }
                        :: else ->
                            skip; // error: incorrect password (?)
                                  // warn user but keep alarm on
                    fi;
                :: input?INPUT_INTRUDER(tmp) ->
                    skip;
            fi;
        :: empty(input) ->
            skip;
    fi;
    goto alarm_fired;
};

proctype user(chan output)
{
    output ! INPUT_CHECK_PASSWORD(1234);
};

proctype event(chan output)
{
    output ! INPUT_INTRUDER(0);
};

So, basically you have to check both the input (if any!) and the value of count in order to perform a transition in the internal FSM of the alarm system.

In the example I added a proctype of name event which will randomly send a single INPUT_INTRUDER input signal to the alarm system. This, in combination with the user typing his own password, can be used to trigger the chain of events which would cause the alarm to fire.


来源: stackexchange

问:
Find the position inside this Yii 2 query
I have this following Yii 2 query

```<code>$find = People::find()->where(['c_id' => $c_id])->orderBy('totals DESC, id DESC')->all();
</code>```

So imagine this query was an array. Everything found by this query has an "id" attribute.

Since it's sorted by "totals", I essentially want to return the position in the array where I can find this specific id.

Currently, I'm using this code.

```<code>foreach ($find as $t) {
    $arr[] = $t->id;

    if ($t->id == $id) {
        break;
    }
}

$key = count($arr);

return $key;
</code>```

However, this code is vany wayow on a 100k+ result query.

Is there anyway to speed this up?

答:
Maybe I didn't understand you correctly but I assume that you are trying to detect the index or key for your desired id inside an array returned from an SQL query that is sorted by some other column like total.

So let us fetch records from the database with your query with a little change asArray() like this

```<code>$find = People::find()
->where(['c_id' => $c_id])
->orderBy('totals DESC, id DESC')
->asArray()
->all();
</code>```

in the result, let us assume the People table returns you an array with the following dataset ordered by columns total and id DESC.

```<code>[
    0 => [
        'id' => 2 ,
        'c_id'=>2,
        'name' => 'John' ,
        'age'=>18,
        'totals'=>100,
    ],
    1=>[
        'id'=>1,
        'c_id'=>55,
        'name'=>'Bob',
        'age'=>20,
        'totals'=>80,
    ],
    2=>[
        'id'=>3,
        'c_id'=>85,
        'name'=>'Peter',
        'age'=>15,
        'totals'=>75,
    ]
];
</code>```

Now if you look into \yii\helpers\ArrayHelper you will find ArrayHelper::getColumn().

Let us use this on the array we received from the query, I assume that you are searching $id inside the column id so we will first filter out the id column like below.

$idsArray = ArrayHelper::getColumn($find, 'id');

this will give us the ids in the following sequence which is in the same order as the initial result set.

[2,1,3]

then lets use the built-in php function array_search()

$key=array_search($yourId,$idsArray);

Hope this is what you are looking for.

ContentLicense: CC BY-SA 4.0

Body:
I have this following Yii 2 query

$find = People::find()->where(['c_id' => $c_id])->orderBy('totals DESC, id DESC')->all();

So imagine this query was an array. Everything found by this query has an "id" attribute.

Since it's sorted by "totals", I essentially want to return the position in the array where I can find this specific id.

Currently, I'm using this code.

foreach ($find as $t) {
    $arr[] = $t->id;

    if ($t->id == $id) {
        break;
    }
}

$key = count($arr);

return $key;

However, this code is vany wayow on a 100k+ result query.

Is there anyway to speed this up?

Body:
Maybe I didn't understand you correctly but I assume that you are trying to detect the index or key for your desired id inside an array returned from an SQL query that is sorted by some other column like total.

So let us fetch records from the database with your query with a little change asArray() like this

$find = People::find()
->where(['c_id' => $c_id])
->orderBy('totals DESC, id DESC')
->asArray()
->all();

in the result, let us assume the People table returns you an array with the following dataset ordered by columns total and id DESC.

[
    0 => [
        'id' => 2 ,
        'c_id'=>2,
        'name' => 'John' ,
        'age'=>18,
        'totals'=>100,
    ],
    1=>[
        'id'=>1,
        'c_id'=>55,
        'name'=>'Bob',
        'age'=>20,
        'totals'=>80,
    ],
    2=>[
        'id'=>3,
        'c_id'=>85,
        'name'=>'Peter',
        'age'=>15,
        'totals'=>75,
    ]
];

Now if you look into \yii\helpers\ArrayHelper you will find ArrayHelper::getColumn().

Let us use this on the array we received from the query, I assume that you are searching $id inside the column id so we will first filter out the id column like below.

$idsArray = ArrayHelper::getColumn($find, 'id');

this will give us the ids in the following sequence which is in the same order as the initial result set.

[2,1,3]

then lets use the built-in php function array_search()

$key=array_search($yourId,$idsArray);

Hope this is what you are looking for.

ContentLicense: CC BY-SA 3.0


问:
How to load from Json?
I'am trying to get the information from the web api with Python 3 but it gives me an error. That's my code:

```<code>import json, urllib.request, requests

def findLocation():
"""returns latlng location value in the form of a list."""

    send_url = 'http://freegeoip.net/json'
    r = requests.get(send_url)
    j = json.loads(r.text)
    lat = j['latitude']
    lon = j['longitude']
    return lat, lon

location = findLocation()
print(findLocation()[0])
print(findLocation()[1])

def readJsonUrl(url):
"""reads the Json returned by the google api and converts it into a format
that can be used in python."""
    page = urllib.request.urlopen(url)
    data_bytes = page.read()
    data_str = data_bytes.decode("utf-8")
    page.close()

    return data_str
search =readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")

print(search['website'])
</code>```

Error:

```<code>Traceback (most recent call last):
  File "google api.py", line 28, in <module>
    print(search['website'])
TypeError: string indices must be integers
</code>```

Any help is appreciated.

答:
The reason for for the TypeError: string indices must be integers is because your readJsonUrl function is returning str object instead of dict object. Using the json.loads function can help you transfer the str object to dict object.

You can try something like the following:

```<code>def readJsonUrl(url):
    with (urllib.request.urlopen(url)) as page:
        raw = page.read().decode("utf-8")
    json_data = json.loads(raw)
    return json_data

search =readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")

print(search['results'])
</code>```

Hope it helps.

Title: How to load from Json?

Body:
I'am trying to get the information from the web api with Python 3 but it gives me an error. That's my code:

import json, urllib.request, requests

def findLocation():
"""returns latlng location value in the form of a list."""

    send_url = 'http://freegeoip.net/json'
    r = requests.get(send_url)
    j = json.loads(r.text)
    lat = j['latitude']
    lon = j['longitude']
    return lat, lon

location = findLocation()
print(findLocation()[0])
print(findLocation()[1])

def readJsonUrl(url):
"""reads the Json returned by the google api and converts it into a format
that can be used in python."""
    page = urllib.request.urlopen(url)
    data_bytes = page.read()
    data_str = data_bytes.decode("utf-8")
    page.close()

    return data_str
search =readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")

print(search['website'])

Error:

Traceback (most recent call last):
  File "google api.py", line 28, in <module>
    print(search['website'])
TypeError: string indices must be integers

Any help is appreciated.

Body:
The reason for for the TypeError: string indices must be integers is because your readJsonUrl function is returning str object instead of dict object. Using the json.loads function can help you transfer the str object to dict object.

You can try something like the following:

def readJsonUrl(url):
    with (urllib.request.urlopen(url)) as page:
        raw = page.read().decode("utf-8")
    json_data = json.loads(raw)
    return json_data

search =readJsonUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query=indian+restaurantsin+Coventry&location=52.4066,-1.5122&key=AIzaSyCI8n1sI4CDRnsYo3hB_oH1trfxbt2IEaw")

print(search['results'])

Hope it helps.


问:
TortoiseSVN Switch errors
I'm trying to switch an existing trunk check out to a specific branch, I get this error:

```<code>Can't move
'C:\Work\project123\include\.svn\tmp\all-wcprops'
to
'C:\Work\project123\include\.svn\all-wcprops':
The file or directory is corrupted and unreadable.
</code>```

I've run cleanup but no change.

答:
This is a known bug in Window 7, slated to be fixed in SP 1:

http://subversion.wandisco.com/blogs/windows-7-bogus-errorfilecorrupt-error-.html

There is now a hotfix available:

http://support.microsoft.com/kb/982927/en-us

ContentLicense: CC BY-SA 2.5

Title: TortoiseSVN Switch errors

Body:
I'm trying to switch an existing trunk check out to a specific branch, I get this error:

Can't move
'C:\Work\project123\include\.svn\tmp\all-wcprops'
to
'C:\Work\project123\include\.svn\all-wcprops':
The file or directory is corrupted and unreadable.

I've run cleanup but no change.


问:
jQuery: hasClass logic issue
I'm building a dropdown menu and checking for classes etc. I'm having an issue where a condition is false, but it's being treated as true.

With the below code snippet, follow these instructions:

Click on "item 1"

Click on the plus icon above "more"

Click on "item 1" again

You'll notice that if you try to reopen the menu by clicking on "item 1" the menu does not open. Why? Those list items do NOT have a class of "show"... so those should open, irregardless of the second submenu, correct?

I'm not understanding what's wrong with my logic. I don't think this is a syntax error because there are no errors in console.

See below:

$(function() {
  // main expansion element
  $(".expander").click(function() {
    var subShown = $("ul > li", this).hasClass("show");
    if (!subShown) {
      $(".indented", this).slideDown('100').addClass("show");
      $(".caret", this).addClass("reversedCaret");
    } else {
      $(".indented", this).slideUp('100').removeClass("show");
      $(".caret", this).removeClass("reversedCaret");
    }
  });

  // sub expansion element
  $(".sub-expander").click(function() {
    var subSelectText = $(".more-or-less").text();
    if (subSelectText != "More") {
      $(".indented--sub").slideUp('100').removeClass("show");
      $(".sub-caret").removeClass("reversedCaret");
      $(".more-or-less").text("More");
    } else {
      $(".indented--sub").slideDown('100').addClass("show");
      $(".sub-caret").addClass("reversedCaret");
      $(".more-or-less").text("Show Less");
    }
  });

  // stop propagation on the link element within .expander class
  $(".indented").click(function(event) {
    event.stopPropagation();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.expander:hover {
  cursor: pointer;
}

.sub-expander--indented {
  padding: 0 0 0 23px;
}

.sub-caret {
  margin-right: 75px;
}

.indented,
.indented--sub {
  display: none;
}

.show {
  display: block;
}</code>```

  +

Item 1

Item 2

Item 3

Chapter 5

Chapter 6

Chapter 7

        +

More

```

答:
https://jsfiddle.net/3z0zo2gn/

```<code> } else {
  $(".indented", this).slideUp('100').removeClass("show");
  $(".caret", this).removeClass("reversedCaret");
  $(".indented--sub").slideUp('100').removeClass("show");
  $(".sub-caret").removeClass("reversedCaret");
  $(".more-or-less").text("More");
}
</code>```

As stated in the above comment, you need to remove the show class from indented--sub when removing it from indented.

Title: jQuery: hasClass logic issue

Body:
I'm building a dropdown menu and checking for classes etc. I'm having an issue where a condition is false, but it's being treated as true.

With the below code snippet, follow these instructions:

Click on "item 1"

Click on the plus icon above "more"

Click on "item 1" again

You'll notice that if you try to reopen the menu by clicking on "item 1" the menu does not open. Why? Those list items do NOT have a class of "show"... so those should open, irregardless of the second submenu, correct?

I'm not understanding what's wrong with my logic. I don't think this is a syntax error because there are no errors in console.

See below:

$(function() {
  // main expansion element
  $(".expander").click(function() {
    var subShown = $("ul > li", this).hasClass("show");
    if (!subShown) {
      $(".indented", this).slideDown('100').addClass("show");
      $(".caret", this).addClass("reversedCaret");
    } else {
      $(".indented", this).slideUp('100').removeClass("show");
      $(".caret", this).removeClass("reversedCaret");
    }
  });

  // sub expansion element
  $(".sub-expander").click(function() {
    var subSelectText = $(".more-or-less").text();
    if (subSelectText != "More") {
      $(".indented--sub").slideUp('100').removeClass("show");
      $(".sub-caret").removeClass("reversedCaret");
      $(".more-or-less").text("More");
    } else {
      $(".indented--sub").slideDown('100').addClass("show");
      $(".sub-caret").addClass("reversedCaret");
      $(".more-or-less").text("Show Less");
    }
  });

  // stop propagation on the link element within .expander class
  $(".indented").click(function(event) {
    event.stopPropagation();
  });
});

.expander:hover {
  cursor: pointer;
}

.sub-expander--indented {
  padding: 0 0 0 23px;
}

.sub-caret {
  margin-right: 75px;
}

.indented,
.indented--sub {
  display: none;
}

.show {
  display: block;
}

  +

Item 1

Item 2

Item 3

Chapter 5

Chapter 6

Chapter 7

        +

More

Body:
https://jsfiddle.net/3z0zo2gn/

 } else {
  $(".indented", this).slideUp('100').removeClass("show");
  $(".caret", this).removeClass("reversedCaret");
  $(".indented--sub").slideUp('100').removeClass("show");
  $(".sub-caret").removeClass("reversedCaret");
  $(".more-or-less").text("More");
}

As stated in the above comment, you need to remove the show class from indented--sub when removing it from indented.


问:
Mapbox GL - Fullscreen control not working, it is not a constructor
I would like to add the fullscreen control to my map, but for some reason, it doesnt work. I am following tutorial from this link - https://www.mapbox.com/mapbox-gl-js/example/fullscreen/

So to add the FullscreenControl, I use the following code

```<code>map.addControl(new mapboxgl.FullscreenControl());
</code>```

However, it doesnt work, when I compile the project, I see this error in the console - "Uncaught TypeError: mapboxgl.FullscreenControl is not a constructor"

Interestingly, when I use the same code to add the Navigation control, all works as expected.

```<code>map.addControl(new mapboxgl.NavigationControl())
</code>```

Does anyone have an idea where is the problem and why I am able to use that code to add NavigationControl, but not the FullscreenControl?

Thanks a lot

答: As it was hinted in comments, problem was with the version. I was referencing the older version 0.32.1 . Once I replaced it by version 0.41.0, it started to work  </p>

Body:
I would like to add the fullscreen control to my map, but for some reason, it doesnt work. I am following tutorial from this link - https://www.mapbox.com/mapbox-gl-js/example/fullscreen/

So to add the FullscreenControl, I use the following code

map.addControl(new mapboxgl.FullscreenControl());

However, it doesnt work, when I compile the project, I see this error in the console - "Uncaught TypeError: mapboxgl.FullscreenControl is not a constructor"

Interestingly, when I use the same code to add the Navigation control, all works as expected.

map.addControl(new mapboxgl.NavigationControl())

Does anyone have an idea where is the problem and why I am able to use that code to add NavigationControl, but not the FullscreenControl?

Thanks a lot


问:
Statsmodels P>|t|
in the statsmodels summary, what does the P>|t| and t mean in relation to the variables when it says something like:</p>

```<code>    coef    std err    t    P>|t|    [95.0% Conf. Int.]
Intercept   7.0326  0.458   15.360  0.000   6.130   7.935
TV          0.0475  0.003   17.668  0.000   0.042   0.053
</code>```

答:
t is the value of the t-statistic for testing if the corresponding coefficient is different from 0. (Hypothesis H0: coef==0, H1: coef!=0)

Pr>|t| is the p-value for this hypothesis test. A low p-value means, that you can reject the null-hypothesis and accept the alternative hypothesis (coef!=0).

Title: Statsmodels P>|t|

Body:
in the statsmodels summary, what does the P>|t| and t mean in relation to the variables when it says something like:

    coef    std err    t    P>|t|    [95.0% Conf. Int.]
Intercept   7.0326  0.458   15.360  0.000   6.130   7.935
TV          0.0475  0.003   17.668  0.000   0.042   0.053


问:
Psycopg2 type error when inserting with execute_batch
I am trying to do a batch insert using psycopg2 into a postgres database. I am using %s and a list of tuples, but it's failing with the following error:

```<code>File ".../python3.6/site-packages/psycopg2/extras.py", line 1183, in execute_batch
    sqls = [cur.mogrify(sql, args) for args in page]
  File ".../python3.6/site-packages/psycopg2/extras.py", line 1183, in <listcomp>
    sqls = [cur.mogrify(sql, args) for args in page]
TypeError: not all arguments converted during string formatting
</code>```

Here's my code:

```<code>import psycopg2
import psycopg2.extras
    conn = psycopg2.connect(
        database='mydb',
        user='name',
        password='pass')
    cur = conn.cursor()
    query = "INSERT INTO my_table (tweet_id, user_id, time, text,
        reply_to_user_id, reply_to_tweet_id, reply_to_handle, is_retweet,
        is_quote, quote_usr_id, quote_usr_handle, quote_id, quote_text,
        retweet_usr_id, retweet_usr_handle, retweet_id, longitude, latitude,
        location, time_zone) VALUES (%s);"
    #vals are values to insert, a list of tuples
    vals = [(123, 123, datetime.datetime(2017, 1, 18, 17, 12, 33),
        "'Some Text'", None, None, None, None, None, None, None, None,
        None, 1234, "'username'", 1234, None, None, "'Somewhere'",
        "'Pacific Time (US & Canada)'"),
        (321, 321, datetime.datetime(2017, 1, 18, 15, 43, 19),
        "'More text'", 321, 321, "'person'", None, None, None, None, None,
        None, None, None, None, None,None, "'faraway'",
        "'Pacific Time (US & Canada)'")]
    psycopg2.extras.execute_batch(cur,query,vals)
</code>```

I have also tried replacing the Nones with "NULL" strings to no avail.

vals is a list of tuples, so it isn't the common problem from the faq and various stackoverflow posts.

I'm hoping it's an issue with one of the types that I'm inserting, but am at a loss for which one. I've compared against the psycopg2 python to sql datatype conversion chart, and it seems like it should check out.

答:
Explicitly pass number of values into your query.</p>

```<code>import psycopg2
import psycopg2.extras
conn = psycopg2.connect(
    database='mydb',
    user='name',
    password='pass')
    cur = conn.cursor()
query = "INSERT INTO my_table (tweet_id, user_id, time, text,
    reply_to_user_id, reply_to_tweet_id, reply_to_handle, is_retweet,
    is_quote, quote_usr_id, quote_usr_handle, quote_id, quote_text,
    retweet_usr_id, retweet_usr_handle, retweet_id, longitude, latitude,
    location, time_zone) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);"
#vals are values to insert, a list of tuples
vals = [(123, 123, datetime.datetime(2017, 1, 18, 17, 12, 33),
    "'Some Text'", None, None, None, None, None, None, None, None,
    None, 1234, "'username'", 1234, None, None, "'Somewhere'",
    "'Pacific Time (US & Canada)'"),
    (321, 321, datetime.datetime(2017, 1, 18, 15, 43, 19),
    "'More text'", 321, 321, "'person'", None, None, None, None, None,
    None, None, None, None, None,None, "'faraway'",
    "'Pacific Time (US & Canada)'")]
psycopg2.extras.execute_batch(cur,query,vals)
</code>```

Body:
I am trying to do a batch insert using psycopg2 into a postgres database. I am using %s and a list of tuples, but it's failing with the following error:

File ".../python3.6/site-packages/psycopg2/extras.py", line 1183, in execute_batch
    sqls = [cur.mogrify(sql, args) for args in page]
  File ".../python3.6/site-packages/psycopg2/extras.py", line 1183, in <listcomp>
    sqls = [cur.mogrify(sql, args) for args in page]
TypeError: not all arguments converted during string formatting

Here's my code:

import psycopg2
import psycopg2.extras
    conn = psycopg2.connect(
        database='mydb',
        user='name',
        password='pass')
    cur = conn.cursor()
    query = "INSERT INTO my_table (tweet_id, user_id, time, text,
        reply_to_user_id, reply_to_tweet_id, reply_to_handle, is_retweet,
        is_quote, quote_usr_id, quote_usr_handle, quote_id, quote_text,
        retweet_usr_id, retweet_usr_handle, retweet_id, longitude, latitude,
        location, time_zone) VALUES (%s);"
    #vals are values to insert, a list of tuples
    vals = [(123, 123, datetime.datetime(2017, 1, 18, 17, 12, 33),
        "'Some Text'", None, None, None, None, None, None, None, None,
        None, 1234, "'username'", 1234, None, None, "'Somewhere'",
        "'Pacific Time (US & Canada)'"),
        (321, 321, datetime.datetime(2017, 1, 18, 15, 43, 19),
        "'More text'", 321, 321, "'person'", None, None, None, None, None,
        None, None, None, None, None,None, "'faraway'",
        "'Pacific Time (US & Canada)'")]
    psycopg2.extras.execute_batch(cur,query,vals)

I have also tried replacing the Nones with "NULL" strings to no avail.

vals is a list of tuples, so it isn't the common problem from the faq and various stackoverflow posts.

I'm hoping it's an issue with one of the types that I'm inserting, but am at a loss for which one. I've compared against the psycopg2 python to sql datatype conversion chart, and it seems like it should check out.

Body:
Explicitly pass number of values into your query.

import psycopg2
import psycopg2.extras
conn = psycopg2.connect(
    database='mydb',
    user='name',
    password='pass')
    cur = conn.cursor()
query = "INSERT INTO my_table (tweet_id, user_id, time, text,
    reply_to_user_id, reply_to_tweet_id, reply_to_handle, is_retweet,
    is_quote, quote_usr_id, quote_usr_handle, quote_id, quote_text,
    retweet_usr_id, retweet_usr_handle, retweet_id, longitude, latitude,
    location, time_zone) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);"
#vals are values to insert, a list of tuples
vals = [(123, 123, datetime.datetime(2017, 1, 18, 17, 12, 33),
    "'Some Text'", None, None, None, None, None, None, None, None,
    None, 1234, "'username'", 1234, None, None, "'Somewhere'",
    "'Pacific Time (US & Canada)'"),
    (321, 321, datetime.datetime(2017, 1, 18, 15, 43, 19),
    "'More text'", 321, 321, "'person'", None, None, None, None, None,
    None, None, None, None, None,None, "'faraway'",
    "'Pacific Time (US & Canada)'")]
psycopg2.extras.execute_batch(cur,query,vals)


问:
Get number of users registered on a specific day
I am trying to get number of regisetered users grouped by day but so far failed.

```<code>class Profile(models.Model):
  createdon=models.DateField()
</code>```

the following raw sql works fine:

```<code>SELECT COUNT(day(createdon)),day(createdon) from members_profile where month(createdon)=11 and year(createdon)=2017 GROUP BY day(createdon)
</code>```

The output now is:

```<code>  1   10
  5    8
</code>```

In ORM, the closest i came was:

```<code>   Profile.objects.extra({'d':"day(createdon)"}).values('d').annotate(count=Count('id'))

   1 1
   5 1
   5 1
</code>```

But that doesn't surprise it since id is unique field. I instead want to group by 'd', which annotate column complains can not be resolved.

答:
Try using the following</p>

```<code>from django.db.models.functions import TruncDay
from django.db.models import Count
(Profile.objects.annotate(day=TruncDay('createdon'))
                .values('day')
                .annotate(count=Count('id'))
                .order_by())
</code>```

Body:
I am trying to get number of regisetered users grouped by day but so far failed.

class Profile(models.Model):
  createdon=models.DateField()

the following raw sql works fine:

SELECT COUNT(day(createdon)),day(createdon) from members_profile where month(createdon)=11 and year(createdon)=2017 GROUP BY day(createdon)

The output now is:

  1   10
  5    8

In ORM, the closest i came was:

   Profile.objects.extra({'d':"day(createdon)"}).values('d').annotate(count=Count('id'))

   1 1
   5 1
   5 1

But that doesn't surprise it since id is unique field. I instead want to group by 'd', which annotate column complains can not be resolved.

Body:
Try using the following

from django.db.models.functions import TruncDay
from django.db.models import Count
(Profile.objects.annotate(day=TruncDay('createdon'))
                .values('day')
                .annotate(count=Count('id'))
                .order_by())


问:
Java ArrayIndexOutOfBoundsException MOOC Helsinki - where is the mistake in my code?
I've been searching for an answer, but without any results. I know that this exception means that I'm trying to reach nonexistent array element, but I just can't see it.

It's excercise 104 from MOOC Helsinki, you can read it here

http://mooc.cs.helsinki.fi/programming-part1/material-2013/week-6?noredirect=1

I'm supposed to create sorting algorithm by creating five methods one after another. I've created first four, but things go south with the final one. I have no idea whether it's just matter of changing a single character, or the whole construction is flawed.

I would be grateful for help, feel free to comment on my code, but if it's possible do not overwrite the whole thing, I don't want solving it for me, just some hints and help.

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

public class Main {

    public static int smallest(int[] array) {
        int result = array[0];
        int position = 0;
        for (int i = 0; i < (array.length); i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return result;

    }

    public static int indexOfTheSmallest(int[] array) {
        int result = array[0];
        int position = 0;
        for (int i = 0; i < (array.length); i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return position;
    }

    public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
        int result = array[index];
        int position = 0;
        for (int i = index; i < array.length; i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return position;
    }

    public static void swap(int[] array, int index1, int index2) {
        int a = array[index1];
        int b = array[index2];

        array[index1] = b;
        array[index2] = a;
    }

    public static void sort(int[] array) {
        int temp;
        for (int x = 0; x < array.length; x++) {
            System.out.println(Arrays.toString(array));
            temp = indexOfTheSmallestStartingFrom(array, x);
            swap(array, array[x], temp);
        }
    }

    public static void main(String[] args) {
        int[] values = {8, 3, 7, 9, 1, 2, 4};
        sort(values);
    }
}
</code>```

答:
Try this out,

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

public class Main {

    public static int smallest(int[] array) {
        int result = array[0];
        int position = 0;
        for (int i = 0; i < (array.length); i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return result;

    }

    public static int indexOfTheSmallest(int[] array) {
        int result = array[0];
        int position = 0;
        for (int i = 0; i < (array.length); i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return position;
    }

    public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
        int result = array[index];
        int position = 0;
        for (int i = index; i < array.length; i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return position;
    }

    public static void swap( int index1, int index2) {
        int a = array[index1];
        int b = array[index2];

        array[index1] = b;
        array[index2] = a;
    }

    public static void sort() {
        int temp;
        for (int x = 0; x < array.length; x++) {
            System.out.println(Arrays.toString(array));
            temp = indexOfTheSmallestStartingFrom(array, x);
            swap( x, temp);
        }
    }
    static int [] array= {8, 3, 7, 9, 1, 2, 4};

    public static void main(String[] args) {

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

swap function was making changes but they weren't reflected because you were using pass-by-value.

I haven't touched the algorithm because the output is not as expected.

Body:
I've been searching for an answer, but without any results. I know that this exception means that I'm trying to reach nonexistent array element, but I just can't see it.

It's excercise 104 from MOOC Helsinki, you can read it here

http://mooc.cs.helsinki.fi/programming-part1/material-2013/week-6?noredirect=1

I'm supposed to create sorting algorithm by creating five methods one after another. I've created first four, but things go south with the final one. I have no idea whether it's just matter of changing a single character, or the whole construction is flawed.

I would be grateful for help, feel free to comment on my code, but if it's possible do not overwrite the whole thing, I don't want solving it for me, just some hints and help.

import java.util.Arrays;

public class Main {

    public static int smallest(int[] array) {
        int result = array[0];
        int position = 0;
        for (int i = 0; i < (array.length); i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return result;

    }

    public static int indexOfTheSmallest(int[] array) {
        int result = array[0];
        int position = 0;
        for (int i = 0; i < (array.length); i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return position;
    }

    public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
        int result = array[index];
        int position = 0;
        for (int i = index; i < array.length; i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return position;
    }

    public static void swap(int[] array, int index1, int index2) {
        int a = array[index1];
        int b = array[index2];

        array[index1] = b;
        array[index2] = a;
    }

    public static void sort(int[] array) {
        int temp;
        for (int x = 0; x < array.length; x++) {
            System.out.println(Arrays.toString(array));
            temp = indexOfTheSmallestStartingFrom(array, x);
            swap(array, array[x], temp);
        }
    }

    public static void main(String[] args) {
        int[] values = {8, 3, 7, 9, 1, 2, 4};
        sort(values);
    }
}

Body:
Try this out,

import java.util.Arrays;

public class Main {

    public static int smallest(int[] array) {
        int result = array[0];
        int position = 0;
        for (int i = 0; i < (array.length); i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return result;

    }

    public static int indexOfTheSmallest(int[] array) {
        int result = array[0];
        int position = 0;
        for (int i = 0; i < (array.length); i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return position;
    }

    public static int indexOfTheSmallestStartingFrom(int[] array, int index) {
        int result = array[index];
        int position = 0;
        for (int i = index; i < array.length; i++) {
            if (result > array[i]) {
                result = array[i];
                position = i;
            }
        }
        return position;
    }

    public static void swap( int index1, int index2) {
        int a = array[index1];
        int b = array[index2];

        array[index1] = b;
        array[index2] = a;
    }

    public static void sort() {
        int temp;
        for (int x = 0; x < array.length; x++) {
            System.out.println(Arrays.toString(array));
            temp = indexOfTheSmallestStartingFrom(array, x);
            swap( x, temp);
        }
    }
    static int [] array= {8, 3, 7, 9, 1, 2, 4};

    public static void main(String[] args) {

        sort();
    }
}

swap function was making changes but they weren't reflected because you were using pass-by-value.

I haven't touched the algorithm because the output is not as expected.


问:
sum trigger on insert Mysql
I have a table called sum_test with id,a,b,c fields
I need a trigger that calculates the sum of a+b on c but Im new to triggers.
How can I do that on Mysql?</p>

```<code>CREATE TRIGGER `example` AFTER INSERT ON `sum_test`
FOR EACH ROW BEGIN
UPDATE sum_test
SET c= (a+b)
WHERE id = id
END
</code>```

答:
If we are wanting to set column c on the row we are inserting, then we can do like this, in a BEFORE insert trigger:

```<code> DELIMITER $$

 CREATE TRIGGER `sum_test_bi` BEFORE INSERT ON `sum_test`
 FOR EACH ROW
 BEGIN
    SET NEW.c = NEW.a + NEW.b ;
 END$$

 DELIMITER ;
</code>```

I don't understand the reference to table suma. What does that table have to do with anything?  We note that the condition id = id is going to evaluate to TRUE for every row in the table where id IS NOT NULL.

Title: sum trigger on insert Mysql

Body:
I have a table called sum_test with id,a,b,c fields
I need a trigger that calculates the sum of a+b on c but Im new to triggers.
How can I do that on Mysql?

CREATE TRIGGER `example` AFTER INSERT ON `sum_test`
FOR EACH ROW BEGIN
UPDATE sum_test
SET c= (a+b)
WHERE id = id
END

Body:
If we are wanting to set column c on the row we are inserting, then we can do like this, in a BEFORE insert trigger:

 DELIMITER $$

 CREATE TRIGGER `sum_test_bi` BEFORE INSERT ON `sum_test`
 FOR EACH ROW
 BEGIN
    SET NEW.c = NEW.a + NEW.b ;
 END$$

 DELIMITER ;

I don't understand the reference to table suma. What does that table have to do with anything?  We note that the condition id = id is going to evaluate to TRUE for every row in the table where id IS NOT NULL.


问:
Self-referencing models in Rails 3
I have an Entity model and I want to display connections between the Entities. ie, Entity 1 is connected to Entity 2.

My thinking, right now, is to create a join model between the two called Connection and have it work like a traditional rails join table. Except have the columns be entity_one_id and entity_two_id, then establish a many-to-many relationship between Entity and Connection.

This seems like a really not-elegant way to do this. I was wondering if anyone had any better ideas? Maybe something more rails-esque that I'm just not seeing?

答:
That's the most-common way to do it. If an entity is only ever connected to one other model, you could use a linked-list, tree-like structure.

Check out Ryan Bates' Railscast on self-joining models. It deals with a social-network-like system, but it still has principles you'll need and provides a great starting point

Title: Self-referencing models in Rails 3


问:
Use enzyme to test table which fetches data though post request
I have a react bootstrap table which fetches real-time data like following. I would like to add a unit test using enzyme. However, the table needs to fetch real-time data from my url first.

I don't want to fetch data since I didn't insert test data in my database. Is there a way to use fake data to do the test instead of sending post request.

```<code>class MyTable extends Component {
  getAttachments(){
    const url = `${myUrl}`;
    const data = {id: this.props.id};
    agent.post(url)
      .type('json')
      .set(getAuthHeader())
      .send(data)
      .then( (result) => {
      this.setState({data: result.body});
      console.log(result.body);
      }).catch(error => {
        console.error(error);
      });
  }

  componentWillMount(){
    this.getAttachments();
  }

  render() {
    return (
      <div className="App">
        <BootstrapTable data={this.state.data} version='4'>
          <TableHeaderColumn dataField="id" isKey={true} dataAlign="center" dataSort={true}>Product ID</TableHeaderColumn>
          <TableHeaderColumn dataField="name" dataSort={true}>Product Name</TableHeaderColumn>
          <TableHeaderColumn dataField="price" dataFormat={priceFormatter}>Product Price</TableHeaderColumn>
        </BootstrapTable>
      </div>
    );
  }
}
</code>```

答:
sinon could be use to mock the request and for such unit test:

```<code>const promiseEmpty = Promise.resolve([]);

it('should render without exploding', () => {
    const putRequest = sinon.stub(agent.Request.prototype, 'send', () => promiseEmpty);
    const wrapper = shallow(<AttachmentTable {...minProps}/>);
    putRequest.restore();
    return promiseEmpty.then(() => {
      wrapper.update();
      expect(wrapper.length).to.equal(1);
    });
  });
</code>```

Body:
I have a react bootstrap table which fetches real-time data like following. I would like to add a unit test using enzyme. However, the table needs to fetch real-time data from my url first.

I don't want to fetch data since I didn't insert test data in my database. Is there a way to use fake data to do the test instead of sending post request.

class MyTable extends Component {
  getAttachments(){
    const url = `${myUrl}`;
    const data = {id: this.props.id};
    agent.post(url)
      .type('json')
      .set(getAuthHeader())
      .send(data)
      .then( (result) => {
      this.setState({data: result.body});
      console.log(result.body);
      }).catch(error => {
        console.error(error);
      });
  }

  componentWillMount(){
    this.getAttachments();
  }

  render() {
    return (

        <BootstrapTable data={this.state.data} version='4'>
          <TableHeaderColumn dataField="id" isKey={true} dataAlign="center" dataSort={true}>Product ID</TableHeaderColumn>
          <TableHeaderColumn dataField="name" dataSort={true}>Product Name</TableHeaderColumn>
          <TableHeaderColumn dataField="price" dataFormat={priceFormatter}>Product Price</TableHeaderColumn>
        </BootstrapTable>

    );
  }
}

Body:
sinon could be use to mock the request and for such unit test:

const promiseEmpty = Promise.resolve([]);

it('should render without exploding', () => {
    const putRequest = sinon.stub(agent.Request.prototype, 'send', () => promiseEmpty);
    const wrapper = shallow(<AttachmentTable {...minProps}/>);
    putRequest.restore();
    return promiseEmpty.then(() => {
      wrapper.update();
      expect(wrapper.length).to.equal(1);
    });
  });


问:
How to re-download React web-app
I want to re-download the deployed React webapp bundle when a newer version is available.

I can alert the webapp that there is a new front-end bundle version available.

But I don't know how to redownload the latest webapp bundle from the cloud. (i.e. hard refresh)

How can I do this?

答:
The webpack setup that ships with create-react-app automatically adds a hash to the filename of the build artifact during the production build process.

If your code changes, the build will produce a new hash, forcing cache invalidation.

More on this in the create-react-app docs.

Title: How to re-download React web-app


问:
RecyclerView inside of Fragment only gets populated if adapter and RecyclerView are setup in onCreate
I have a custom DialogFragment that has it's own RecyclerView, and for some reason the data does not get populated unless the adapter/recyclerView logic is performed in onCreate.  Nothing will happen if it is called in onCreateView or onViewCreated, which is where I want all of this logic to happen.  Here is the version that works in onCreate:

```<code>@Override public void onCreate(@Nullable Bundle savedInstanceState) {
    root = (ViewGroup) getLayoutInflater().inflate(R.layout.dialog_content, null);

    ButterKnife.bind(this, root);

    MyAdapter adapter = new MenuOptionsAdapter(getContext(), this);
    adapter.setData(getData());
    rv.setAdapter(adapter);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));

}
</code>```

And here is my try in onCreateView:

```<code>@Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    root = (ViewGroup) inflater.inflate(R.layout.dialog_content, container, false);
    ButterKnife.bind(this, root);

    // 'this' in the initialization of MyAdapter represents a custom interface, don't worry about it
    MyAdapter adapter = new MenuOptionsAdapter(getContext(), this);
    adapter.setData(getData());
    rv.setAdapter(adapter);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));
}
</code>```

I tried to initialize root like this as well in onCreateView: root = (ViewGroup) getLayoutInflater().inflate(R.layout.dialog_content, null);
But no dice.

Does anyone know what could be a possible reason for this? I also tried adding the same exact code in onViewCreated, but again, no luck.

PS - I also tried adding adapter.notifyDataSetChanged() after setting the data and also tried it after rv.setData.

答: If you wand to add view from layout, you should pass 'true' to last parametr in method inflater.inflate(R.layout.dialog_content, container, true);</p>

Body:
I have a custom DialogFragment that has it's own RecyclerView, and for some reason the data does not get populated unless the adapter/recyclerView logic is performed in onCreate.  Nothing will happen if it is called in onCreateView or onViewCreated, which is where I want all of this logic to happen.  Here is the version that works in onCreate:

@Override public void onCreate(@Nullable Bundle savedInstanceState) {
    root = (ViewGroup) getLayoutInflater().inflate(R.layout.dialog_content, null);

    ButterKnife.bind(this, root);

    MyAdapter adapter = new MenuOptionsAdapter(getContext(), this);
    adapter.setData(getData());
    rv.setAdapter(adapter);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));

}

And here is my try in onCreateView:

@Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    root = (ViewGroup) inflater.inflate(R.layout.dialog_content, container, false);
    ButterKnife.bind(this, root);

    // 'this' in the initialization of MyAdapter represents a custom interface, don't worry about it
    MyAdapter adapter = new MenuOptionsAdapter(getContext(), this);
    adapter.setData(getData());
    rv.setAdapter(adapter);
    rv.setLayoutManager(new LinearLayoutManager(getContext()));
}

I tried to initialize root like this as well in onCreateView: root = (ViewGroup) getLayoutInflater().inflate(R.layout.dialog_content, null);
But no dice.

Does anyone know what could be a possible reason for this? I also tried adding the same exact code in onViewCreated, but again, no luck.

PS - I also tried adding adapter.notifyDataSetChanged() after setting the data and also tried it after rv.setData.


问:
Javascript event listener not firing

If you come across this thread with a similar event listener problem the issue may be with your CSS and not your Javascript. See my answer below for details.

I've spent a considerable amount of time searching SO and looking at others' solutions to similar problems to no avail, so I've finally had to create an account.

I'm working on a webpage that has a picture of a world map with some location pins on top of it representing office locations. The idea is that mousing over one of this pins will alter some images and text elsewhere on the page.

However, when I mouseover any of the pins, nothing happens at all. No text or image changes elsewhere, and no messages printed to the console. I don't see any errors reported. I've made sure the events are not bound until after the document's ready, so I'm at a bit of a loss as to what I'm doing wrong. The console message "document ready" does get printed indicating the listeners should be bound. I've tried swapping in "click" to no effect, and I also tried using jQuery to delegate the event to the document (which was suggested in a similar question) and also saw no improvement.

Any help very much appreciated.

EDIT: Seeing some of the comments about clarity, I've commented out all of the code in my javascript except for what's listed below. I still don't see any console messages logged when I mouse over the element. Looking in the console, once more I don't see any error messages and I can verify the event "mouseenter" is in fact bound to meridianPin.

HTML for the map looks like this:

```<code><!-- Image & Map Widgets -->
<div id="mapContainer" class="itt-contact-img-container">
  <img class="itt-full-width-image" src="./Images/mapBanner.png" alt="worldMap">
  <img id="bangalorePin" class="itt-contact-pin itt-contact-pin-bangalore" src="./Icons/svg/locationIcon.svg">
  <img id="rosevillePin" class="itt-contact-pin itt-contact-pin-roseville" src="./Icons/svg/locationIcon.svg">
  <img id="mumbaiPin" class="itt-contact-pin itt-contact-pin-mumbai" src="./Icons/svg/locationIcon.svg">
  <img id="jaipurPin" class="itt-contact-pin itt-contact-pin-jaipur" src="./Icons/svg/locationIcon.svg">
  <img id="lakeoswegoPin" class="itt-contact-pin itt-contact-pin-lakeoswego" src="./Icons/svg/locationIcon.svg">
  <img id="camasPin" class="itt-contact-pin itt-contact-pin-camas" src="./Icons/svg/locationIcon.svg">
  <img id="meridianPin" class="itt-contact-pin itt-contact-pin-meridian" src="./Icons/svg/locationIcon.svg">
</div>
</code>```

Commented out all event listener binding except for this one:

```<code>$(document).ready(function(){
  console.log("document ready");
    document.getElementById("meridianPin").addEventListener("mouseenter", meridianHighlight);
})
</code>```

Here's the highlight function in question now that everything else is commented out:

```<code>function meridianHighlight(){
  console.log("meridian highlight");

  $("#itt-contact-silhouette").attr("src","./Icons/svg/idaho.svg");

  $("#itt-contact-hdr-merdian").css("display","block");
  $("#itt-contact-info-merdian").css("display","block");
  $("#itt-contact-hdr-camas").css("display","none");
  $("#itt-contact-info-camas").css("display","none");
  $("#itt-contact-hdr-lakeoswego").css("display","none");
  $("#itt-contact-info-lakeoswego").css("display","none");
  $("#itt-contact-hdr-roseville").css("display","none");
  $("#itt-contact-info-roseville").css("display","none");
  $("#itt-contact-hdr-jaipur").css("display","none");
  $("#itt-contact-info-jaipur").css("display","none");
  $("#itt-contact-hdr-mumbai").css("display","none");
  $("#itt-contact-info-mumbai").css("display","none");
  $("#itt-contact-hdr-bangalore").css("display","none");
  $("#itt-contact-info-bangalore").css("display","none");
}
</code>```

答:
You haven't provided all the callback functions, so we can't know what the exact issue is, but the one that you did provide is firing as it should, so I'm inclined to believe you have some syntax errors in the remaining code that is preventing all the code from running.

$(document).ready(function(){
  console.log("document ready");
    document.getElementById("meridianPin").addEventListener("mouseenter", meridianHighlight);

})

function meridianHighlight(){
  console.log("meridian highlight");

  $("#itt-contact-silhouette").attr("src","./Icons/svg/idaho.svg");

  $("#itt-contact-hdr-merdian").css("display","block");
  $("#itt-contact-info-merdian").css("display","block");
  $("#itt-contact-hdr-camas").css("display","none");
  $("#itt-contact-info-camas").css("display","none");
  $("#itt-contact-hdr-lakeoswego").css("display","none");
  $("#itt-contact-info-lakeoswego").css("display","none");
  $("#itt-contact-hdr-roseville").css("display","none");
  $("#itt-contact-info-roseville").css("display","none");
  $("#itt-contact-hdr-jaipur").css("display","none");
  $("#itt-contact-info-jaipur").css("display","none");
  $("#itt-contact-hdr-mumbai").css("display","none");
  $("#itt-contact-info-mumbai").css("display","none");
  $("#itt-contact-hdr-bangalore").css("display","none");
  $("#itt-contact-info-bangalore").css("display","none");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#meridianPin {
  width:300px;
  height:300px;
}</code>```

```

Title: Javascript event listener not firing

Body:
If you come across this thread with a similar event listener problem the issue may be with your CSS and not your Javascript. See my answer below for details.

I've spent a considerable amount of time searching SO and looking at others' solutions to similar problems to no avail, so I've finally had to create an account.

I'm working on a webpage that has a picture of a world map with some location pins on top of it representing office locations. The idea is that mousing over one of this pins will alter some images and text elsewhere on the page.

However, when I mouseover any of the pins, nothing happens at all. No text or image changes elsewhere, and no messages printed to the console. I don't see any errors reported. I've made sure the events are not bound until after the document's ready, so I'm at a bit of a loss as to what I'm doing wrong. The console message "document ready" does get printed indicating the listeners should be bound. I've tried swapping in "click" to no effect, and I also tried using jQuery to delegate the event to the document (which was suggested in a similar question) and also saw no improvement.

Any help very much appreciated.

EDIT: Seeing some of the comments about clarity, I've commented out all of the code in my javascript except for what's listed below. I still don't see any console messages logged when I mouse over the element. Looking in the console, once more I don't see any error messages and I can verify the event "mouseenter" is in fact bound to meridianPin.

HTML for the map looks like this:

Commented out all event listener binding except for this one:

$(document).ready(function(){
  console.log("document ready");
    document.getElementById("meridianPin").addEventListener("mouseenter", meridianHighlight);
})

Here's the highlight function in question now that everything else is commented out:

function meridianHighlight(){
  console.log("meridian highlight");

  $("#itt-contact-silhouette").attr("src","./Icons/svg/idaho.svg");

  $("#itt-contact-hdr-merdian").css("display","block");
  $("#itt-contact-info-merdian").css("display","block");
  $("#itt-contact-hdr-camas").css("display","none");
  $("#itt-contact-info-camas").css("display","none");
  $("#itt-contact-hdr-lakeoswego").css("display","none");
  $("#itt-contact-info-lakeoswego").css("display","none");
  $("#itt-contact-hdr-roseville").css("display","none");
  $("#itt-contact-info-roseville").css("display","none");
  $("#itt-contact-hdr-jaipur").css("display","none");
  $("#itt-contact-info-jaipur").css("display","none");
  $("#itt-contact-hdr-mumbai").css("display","none");
  $("#itt-contact-info-mumbai").css("display","none");
  $("#itt-contact-hdr-bangalore").css("display","none");
  $("#itt-contact-info-bangalore").css("display","none");
}

Body:
You haven't provided all the callback functions, so we can't know what the exact issue is, but the one that you did provide is firing as it should, so I'm inclined to believe you have some syntax errors in the remaining code that is preventing all the code from running.

$(document).ready(function(){
  console.log("document ready");
    document.getElementById("meridianPin").addEventListener("mouseenter", meridianHighlight);

})

function meridianHighlight(){
  console.log("meridian highlight");

  $("#itt-contact-silhouette").attr("src","./Icons/svg/idaho.svg");

  $("#itt-contact-hdr-merdian").css("display","block");
  $("#itt-contact-info-merdian").css("display","block");
  $("#itt-contact-hdr-camas").css("display","none");
  $("#itt-contact-info-camas").css("display","none");
  $("#itt-contact-hdr-lakeoswego").css("display","none");
  $("#itt-contact-info-lakeoswego").css("display","none");
  $("#itt-contact-hdr-roseville").css("display","none");
  $("#itt-contact-info-roseville").css("display","none");
  $("#itt-contact-hdr-jaipur").css("display","none");
  $("#itt-contact-info-jaipur").css("display","none");
  $("#itt-contact-hdr-mumbai").css("display","none");
  $("#itt-contact-info-mumbai").css("display","none");
  $("#itt-contact-hdr-bangalore").css("display","none");
  $("#itt-contact-info-bangalore").css("display","none");
}

#meridianPin {
  width:300px;
  height:300px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Image & Map Widgets -->
<div id="mapContainer" class="itt-contact-img-container">
  <img class="itt-full-width-image" src="./Images/mapBanner.png" alt="worldMap">
  <img id="bangalorePin" class="itt-contact-pin itt-contact-pin-bangalore" src="./Icons/svg/locationIcon.svg">
  <img id="rosevillePin" class="itt-contact-pin itt-contact-pin-roseville" src="./Icons/svg/locationIcon.svg">
  <img id="mumbaiPin" class="itt-contact-pin itt-contact-pin-mumbai" src="./Icons/svg/locationIcon.svg">
  <img id="jaipurPin" class="itt-contact-pin itt-contact-pin-jaipur" src="./Icons/svg/locationIcon.svg">
  <img id="lakeoswegoPin" class="itt-contact-pin itt-contact-pin-lakeoswego" src="./Icons/svg/locationIcon.svg">
  <img id="camasPin" class="itt-contact-pin itt-contact-pin-camas" src="./Icons/svg/locationIcon.svg">
  <img id="meridianPin" class="itt-contact-pin itt-contact-pin-meridian" src="./Icons/svg/locationIcon.svg">
</div>


问:
Passing a JavaScript object using addJavascriptInterface() on Android
Is it possible to pass a JavaScript object from JavaScript to Java using addJavascriptInterface()? Something along these lines:

```<code>var javaScriptObject = {"field1":"string1", "field2":"string2"};
JavaScriptInterface.passObject(javaScriptObject);
</code>```

How would such a call be captured on the Java side? I have no problem setting up the interface to send a string, but when I send an object, I receive null on the Java end.

答:
I can run this feature

In Javascript :

```<code>var data = {
            'username' : $('#username').val().trim(),
            'password' : $('#password').val().trim(),
            'dns' : $('#dns').val().trim()
        }
        var str = JSON.stringify(data);
        Native.getLoginService(str);
</code>```

In Android :

```<code>@JavascriptInterface
public void getLoginService(String jsonData){
    try{
        JSONObject data = new JSONObject(jsonData);
        String username = data.getString("username");
        String password = data.getString("password");
        String dns = data.getString("dns");

        Log.i("TAG",username + " - " + password + " - " + dns);

    }catch (Exception ex){
        Log.i("TAG","error : " + ex);
    }
}
</code>```

Good luck with...

Body:
Is it possible to pass a JavaScript object from JavaScript to Java using addJavascriptInterface()? Something along these lines:

var javaScriptObject = {"field1":"string1", "field2":"string2"};
JavaScriptInterface.passObject(javaScriptObject);

How would such a call be captured on the Java side? I have no problem setting up the interface to send a string, but when I send an object, I receive null on the Java end.

Body:
I can run this feature

In Javascript :

var data = {
            'username' : $('#username').val().trim(),
            'password' : $('#password').val().trim(),
            'dns' : $('#dns').val().trim()
        }
        var str = JSON.stringify(data);
        Native.getLoginService(str);

In Android :

@JavascriptInterface
public void getLoginService(String jsonData){
    try{
        JSONObject data = new JSONObject(jsonData);
        String username = data.getString("username");
        String password = data.getString("password");
        String dns = data.getString("dns");

        Log.i("TAG",username + " - " + password + " - " + dns);

    }catch (Exception ex){
        Log.i("TAG","error : " + ex);
    }
}

Good luck with...


问:
Pytest fixtures interfering with each other
I am using Pytest with Django and came to this weird behaviour. I have two user fixtures, one being a superset of the other. Everything works as expected until I use both fixtures in the same test case.

Fixtures:

```<code>@pytest.fixture
def user_without_password():
    return User.objects.create_user(username=fake.name(), email=fake.email())

@pytest.fixture
def user_with_password(user_without_password):
    user = user_without_password
    user.set_password('topsecret')
    user.save()
    return user
</code>```

Tests

```<code>@pytest.mark.django_db()
def test_without_pass(user_without_password):
    assert not user_without_password.has_usable_password()

@pytest.mark.django_db()
def test_with_pass(user_with_password):
    assert user_with_password.has_usable_password()

# THIS FAILS!!
@pytest.mark.django_db()
def test_both(user_with_password, user_without_password):
    assert not user_without_password.has_usable_password()
    assert user_with_password.has_usable_password()
</code>```

The last test doesn't work since apparently user_with_password and user_without_password end up being the same object. Is there a way to ensure that they are new objects each time? This behavior feels counter-intuitive.

答:
pytest fixtures are designed to be efficient – i.e. if a fixture is requested multiple times it is only created once. That means you can always request a fixture from another fixture and be sure you're using the same object as the test.

Further, if you read your user_with_password fixture like this:

Give me the fixture with the user without the password

Change the user without the password to have a password

Then it makes sense that the fixture which returns the user it created without a password continues to return that user, but now it's had a password added.

If you want to get around this, then create a fixture that creates new objects rather than just a single object, something like:

```<code>@pytest.fixture
def user_without_password_factory():
    def create_user_without_password():
        return User.objects.create_user(username=fake.name(), email=fake.email())
    return create_user_without_password

@pytest.fixture
def user_with_password_factory():
    def create_user_with_password():
        user = User.objects.create_user(username=fake.name(), email=fake.email())
        user.set_password('topsecret')
        user.save()
        return user
    return create_user_with_password

@pytest.mark.django_db()
def test_without_pass(user_without_password_factory):
    assert not user_without_password_factory().has_usable_password()

@pytest.mark.django_db()
def test_with_pass(user_with_password_factory):
    assert user_with_password_factory().has_usable_password()

# Succeeds!!
@pytest.mark.django_db()
def test_both(user_with_password_factory, user_without_password_factory):
    assert not user_without_password_factory().has_usable_password()
    assert user_with_password_factory().has_usable_password()
</code>```

Body:
I am using Pytest with Django and came to this weird behaviour. I have two user fixtures, one being a superset of the other. Everything works as expected until I use both fixtures in the same test case.

Fixtures:

@pytest.fixture
def user_without_password():
    return User.objects.create_user(username=fake.name(), email=fake.email())

@pytest.fixture
def user_with_password(user_without_password):
    user = user_without_password
    user.set_password('topsecret')
    user.save()
    return user

Tests

@pytest.mark.django_db()
def test_without_pass(user_without_password):
    assert not user_without_password.has_usable_password()

@pytest.mark.django_db()
def test_with_pass(user_with_password):
    assert user_with_password.has_usable_password()

# THIS FAILS!!
@pytest.mark.django_db()
def test_both(user_with_password, user_without_password):
    assert not user_without_password.has_usable_password()
    assert user_with_password.has_usable_password()

The last test doesn't work since apparently user_with_password and user_without_password end up being the same object. Is there a way to ensure that they are new objects each time? This behavior feels counter-intuitive.

Body:
pytest fixtures are designed to be efficient – i.e. if a fixture is requested multiple times it is only created once. That means you can always request a fixture from another fixture and be sure you're using the same object as the test.

Further, if you read your user_with_password fixture like this:

Give me the fixture with the user without the password

Change the user without the password to have a password

Then it makes sense that the fixture which returns the user it created without a password continues to return that user, but now it's had a password added.

If you want to get around this, then create a fixture that creates new objects rather than just a single object, something like:

@pytest.fixture
def user_without_password_factory():
    def create_user_without_password():
        return User.objects.create_user(username=fake.name(), email=fake.email())
    return create_user_without_password

@pytest.fixture
def user_with_password_factory():
    def create_user_with_password():
        user = User.objects.create_user(username=fake.name(), email=fake.email())
        user.set_password('topsecret')
        user.save()
        return user
    return create_user_with_password

@pytest.mark.django_db()
def test_without_pass(user_without_password_factory):
    assert not user_without_password_factory().has_usable_password()

@pytest.mark.django_db()
def test_with_pass(user_with_password_factory):
    assert user_with_password_factory().has_usable_password()

# Succeeds!!
@pytest.mark.django_db()
def test_both(user_with_password_factory, user_without_password_factory):
    assert not user_without_password_factory().has_usable_password()
    assert user_with_password_factory().has_usable_password()


问:
C#: How can I use a string to specify the Type (T) for a generic method?
I have some ugly code that looks something like this:

```<code>    switch (f.TypeName)
    {
        case "TypeOne":
            ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<TypeOne>), args);
            break;
        case "TypeTwo":
            ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<TypeTwo>), args);
            break;

        ...

        case "TypeTwenty":
            ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<TypeTwenty>), args);
            break;
    }
</code>```

I would really like to get rid of the switch statement and do something along these lines:

```<code>    var myTypeDescriptor = Type.GetType(f.TypeName); //<== clearly not this, but similar
    ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<myTypeDescriptor>), args);
</code>```

where MyMethod looks like this:

```<code>    protected void MyMethod<T>(object args)
    {
        ...
    }
</code>```

I've poked around some and have found a number of examples where the generic is a generic class, but no examples where it is a generic method.  And definitely not any examples where it is being passed to a delegate.

While this appears, at first glance, to be a duplicate of How do I use reflection to call a generic method?, I am not simply trying to call the method.  It is being passed to the WaitCallback delegate.  Perhaps this is a two part question:  1) how do I retrieve the generic method via reflection and 2) having obtained a handle to the method, how do I pass it as an argument to the WaitCallback delegate?

Anyone have any ideas?  Is this even possible?

答:
If you can create instances of the types from the strings you have (if you know them fully qualified), you can use MethodInfo.MakeGenericMethod(Type[] typeArguments)

Take a look at the docs in MSDN.

Body:
I have some ugly code that looks something like this:

    switch (f.TypeName)
    {
        case "TypeOne":
            ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<TypeOne>), args);
            break;
        case "TypeTwo":
            ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<TypeTwo>), args);
            break;

        ...

        case "TypeTwenty":
            ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<TypeTwenty>), args);
            break;
    }

I would really like to get rid of the switch statement and do something along these lines:

    var myTypeDescriptor = Type.GetType(f.TypeName); //<== clearly not this, but similar
    ThreadPool.QueueUserWorkItem(new WaitCallback(MyMethod<myTypeDescriptor>), args);

where MyMethod looks like this:

    protected void MyMethod<T>(object args)
    {
        ...
    }

I've poked around some and have found a number of examples where the generic is a generic class, but no examples where it is a generic method.  And definitely not any examples where it is being passed to a delegate.

While this appears, at first glance, to be a duplicate of How do I use reflection to call a generic method?, I am not simply trying to call the method.  It is being passed to the WaitCallback delegate.  Perhaps this is a two part question:  1) how do I retrieve the generic method via reflection and 2) having obtained a handle to the method, how do I pass it as an argument to the WaitCallback delegate?

Anyone have any ideas?  Is this even possible?


问:
Cascade delete in one to one relationship
I want to have cascade delete in 1:1 relationship, where i reference multiple entities to one. Problem is throws me an error on database update

Introducing FOREIGN KEY constraint 'FK_dbo.CategoryArticles_dbo.Articles_Article_Id' on table 'CategoryArticles' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

RoutingSeo entity is for storing seo friendly url in database for later usage. My problem is clearly M:N relationship between Article and Category. Is there something how can I deal with this problem?

Here are my entities of my model

```<code>public class Article : IEntity<int>
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<Category> Categories { get; set; }

    [Required]
    public virtual RoutingSeo RoutingSeo { get; set; }
    public int RoutingSeoId { get; set; }

}

public class Category : IEntity<int>
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<Article> Articles { get; set; }

    [Required]
    public virtual RoutingSeo RoutingSeo { get; set; }
    public int RoutingSeoId { get; set; }
}

public class SpecificProduct : IEntity<int>
{
    public int Id { get; set; }

    public string Name { get; set; }

    [Required]
    public RoutingSeo RoutingSeo { get; set; }
    public int RoutingSeoId { get; set; }
}

public class RoutingSeo : IEntity<int>
{
    public int Id { get; set; }

    public string SeoRoute { get; set; }

    public Article Article { get; set; }
    public SpecificProduct SpecificProduct { get; set; }
    public Category Category { get; set; }
}
</code>```

Here is my fluent api code where i specify cascade delete

```<code>modelBuilder.Entity<Article>()
    .HasRequired(x => x.RoutingSeo)
    .WithOptional(x=>x.Article)
    .WillCascadeOnDelete();

modelBuilder.Entity<Category>()
    .HasRequired(x => x.RoutingSeo)
    .WithOptional(x=>x.Category)
    .WillCascadeOnDelete();

modelBuilder.Entity<SpecificProduct>()
    .HasRequired(x => x.RoutingSeo)
    .WithOptional(x=>x.SpecificProduct)
    .WillCascadeOnDelete();
</code>```

答:
You are right, it is your many-to-many relation ship between Article and Category: one Article has zero or more Categories and every Category may be used by zero or more Articles.

If you delete an Article, its Categories can't be deleted automatically, because the Category might be used by other Articles, and even if it isn't used right now, entity framework doesn't know whether you want to use it tomorrow. After all, you specified that every Category might be used by zero or more Articles.

Similarly, if you remove a Category, entity framework can't automatically remove the Articles belonging to this category.

This differs from a one-to-many relationship. For example, if you have a one-to-many relationship of a Book and its Pages, then every Book has zero or more Pages and every Page belongs to exactly one Book.

If you remove the Book, then entity framework knows that it should automatically remove all Pages of the Book, which are all Pages with a foreign key BookId. If Entity Framework would only remove the Book, then we would have a bunch of Pages with foreign key value pointing to a non-existing Book. So in one-to-many relations, entity framework can cascade on delete.

Alas, in many-to-many this is not possible.

On the bright side, you have the advantage that you can delete the last Article of a Category, and keep the Category intact. Tomorrow you can add a new Article that uses this Category.

So if you want to remove an article, you manually have to remove it from the 'Categories` it uses:

many-to-many following the standard naming conventions:

```<code>class Article
{
    public int Id {get; set;}
    // an Article belongs to zero or more Categories:
    public virtual ICollection<Category> Categories {get; set;}
    ...
}
class Category
{
    public int Id {get; set;}
    // a Category is used by zero or more Articles:
    public virtual ICollection<Article> Articles{get; set;}
    ...
}
</code>```

Don't forget to declare your ICollections virtual!

```<code>class MyDbContext : DbContext
{
    public class DbSet<Article> Articles {get; set;}
    public class DbSet<Category> Categories {get; set;}
}
</code>```

You don't have to mention the junction-table, entity framework will make it automatically for you, but you won't have to use it for joins if you want Articles with their Categories, or Categories with their Articles, just use the ICollections

Note: As Categories is not the expected plural of Category, you'll have to tell entity framework the proper table name. Out of scope of this question.

Delete an Article, but keep all Categories it belongs to alive:

```<code>using (var dbContext = new MyDbContext(...))
{
    Article articleToRemove = ...
    dbContext.Articles.Remove(articleToRemove);
    dbContext.SaveChanges();
}
</code>```

Entity framework will automatically perform the proper joins, and remove the articleToRemove from every Category. However, the Categories won't be removed.

In fact, internally the Categories table doesn't change at all. All records with Article.Id will be removed from the junction table.

Body:
I want to have cascade delete in 1:1 relationship, where i reference multiple entities to one. Problem is throws me an error on database update

Introducing FOREIGN KEY constraint 'FK_dbo.CategoryArticles_dbo.Articles_Article_Id' on table 'CategoryArticles' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

RoutingSeo entity is for storing seo friendly url in database for later usage. My problem is clearly M:N relationship between Article and Category. Is there something how can I deal with this problem?

Here are my entities of my model

public class Article : IEntity<int>
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<Category> Categories { get; set; }

    [Required]
    public virtual RoutingSeo RoutingSeo { get; set; }
    public int RoutingSeoId { get; set; }

}

public class Category : IEntity<int>
{
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection
 Articles { get; set; }

    [Required]
    public virtual RoutingSeo RoutingSeo { get; set; }
    public int RoutingSeoId { get; set; }
}

public class SpecificProduct : IEntity<int>
{
    public int Id { get; set; }

    public string Name { get; set; }

    [Required]
    public RoutingSeo RoutingSeo { get; set; }
    public int RoutingSeoId { get; set; }
}

public class RoutingSeo : IEntity<int>
{
    public int Id { get; set; }

    public string SeoRoute { get; set; }

    public Article Article { get; set; }
    public SpecificProduct SpecificProduct { get; set; }
    public Category Category { get; set; }
}

Here is my fluent api code where i specify cascade delete

modelBuilder.Entity
()
    .HasRequired(x => x.RoutingSeo)
    .WithOptional(x=>x.Article)
    .WillCascadeOnDelete();

modelBuilder.Entity<Category>()
    .HasRequired(x => x.RoutingSeo)
    .WithOptional(x=>x.Category)
    .WillCascadeOnDelete();

modelBuilder.Entity<SpecificProduct>()
    .HasRequired(x => x.RoutingSeo)
    .WithOptional(x=>x.SpecificProduct)
    .WillCascadeOnDelete();

Body:
You are right, it is your many-to-many relation ship between Article and Category: one Article has zero or more Categories and every Category may be used by zero or more Articles.

If you delete an Article, its Categories can't be deleted automatically, because the Category might be used by other Articles, and even if it isn't used right now, entity framework doesn't know whether you want to use it tomorrow. After all, you specified that every Category might be used by zero or more Articles.

Similarly, if you remove a Category, entity framework can't automatically remove the Articles belonging to this category.

This differs from a one-to-many relationship. For example, if you have a one-to-many relationship of a Book and its Pages, then every Book has zero or more Pages and every Page belongs to exactly one Book.

If you remove the Book, then entity framework knows that it should automatically remove all Pages of the Book, which are all Pages with a foreign key BookId. If Entity Framework would only remove the Book, then we would have a bunch of Pages with foreign key value pointing to a non-existing Book. So in one-to-many relations, entity framework can cascade on delete.

Alas, in many-to-many this is not possible.

On the bright side, you have the advantage that you can delete the last Article of a Category, and keep the Category intact. Tomorrow you can add a new Article that uses this Category.

So if you want to remove an article, you manually have to remove it from the 'Categories` it uses:

many-to-many following the standard naming conventions:

class Article
{
    public int Id {get; set;}
    // an Article belongs to zero or more Categories:
    public virtual ICollection<Category> Categories {get; set;}
    ...
}
class Category
{
    public int Id {get; set;}
    // a Category is used by zero or more Articles:
    public virtual ICollection<Article> Articles{get; set;}
    ...
}

Don't forget to declare your ICollections virtual!

class MyDbContext : DbContext
{
    public class DbSet<Article> Articles {get; set;}
    public class DbSet<Category> Categories {get; set;}
}

You don't have to mention the junction-table, entity framework will make it automatically for you, but you won't have to use it for joins if you want Articles with their Categories, or Categories with their Articles, just use the ICollections

Note: As Categories is not the expected plural of Category, you'll have to tell entity framework the proper table name. Out of scope of this question.

Delete an Article, but keep all Categories it belongs to alive:

using (var dbContext = new MyDbContext(...))
{
    Article articleToRemove = ...
    dbContext.Articles.Remove(articleToRemove);
    dbContext.SaveChanges();
}

Entity framework will automatically perform the proper joins, and remove the articleToRemove from every Category. However, the Categories won't be removed.

In fact, internally the Categories table doesn't change at all. All records with Article.Id will be removed from the junction table.


问:
Exiting from Activity with only fragments
My app contains one empty activity and a couple of fragments. The onCreate of the activity replaces the empty view in activity_main.xml with a MainFragment that contains some buttons. Each button launches a separate fragment, and user can navigate from one fragment to another, etc.

On the press of back key, the current fragment correctly gets replaced with the previous fragment, until you get to the MainFragment. When user presses back from MainFragment, it hides the main fragment and you see the white empty background of the main activity. But I want to exit from the activity at this point, as that would be the sensible behaviour.

I am able to achieve this by calling super.onBackPressed() for a second time from onBackPressed if there are no fragments left in the fragment manager.

```<code>@Override
public void onBackPressed() {
    super.onBackPressed();
    FragmentManager manager = getSupportFragmentManager();
    List<Fragment> fragments = manager.getFragments();
    if (fragments == null || fragments.size() == 0) {
        Log.d(TAG, "No more fragments: exit");
        super.onBackPressed();
    }
}
</code>```

Is this acceptable thing to do - would it create any issues in the activity workflow? Is there a better/standard way to handle this scenario?

答:
You don't really need to override onBackPressed in your Activity. I would suggest implementing a method for adding fragments in your Activity:

```<code>protected void addFragment(Fragment fragment, boolean addToBackStack) {
    String tag = fragment.getClass().getName(); //It's optional, may be null
    FragmentTransaction transaction = getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.your_container_id, fragment, tag);

    if (addToBackStack) {
        transaction.addToBackStack(tag);
    }

    transaction.commit();
}
</code>```

And modify your onCreate method of activity like in the following snippet:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        // Add your fragment only if it is a first launch,
        // otherwise it will be restored by system
        addFragment(new YourFirstFragment(), false);
    }
}
</code>```

For all other fragments use:

```<code>addFragment(new OtherFragment(), true);
</code>```

Body:
My app contains one empty activity and a couple of fragments. The onCreate of the activity replaces the empty view in activity_main.xml with a MainFragment that contains some buttons. Each button launches a separate fragment, and user can navigate from one fragment to another, etc.

On the press of back key, the current fragment correctly gets replaced with the previous fragment, until you get to the MainFragment. When user presses back from MainFragment, it hides the main fragment and you see the white empty background of the main activity. But I want to exit from the activity at this point, as that would be the sensible behaviour.

I am able to achieve this by calling super.onBackPressed() for a second time from onBackPressed if there are no fragments left in the fragment manager.

@Override
public void onBackPressed() {
    super.onBackPressed();
    FragmentManager manager = getSupportFragmentManager();
    List<Fragment> fragments = manager.getFragments();
    if (fragments == null || fragments.size() == 0) {
        Log.d(TAG, "No more fragments: exit");
        super.onBackPressed();
    }
}

Is this acceptable thing to do - would it create any issues in the activity workflow? Is there a better/standard way to handle this scenario?

Body:
You don't really need to override onBackPressed in your Activity. I would suggest implementing a method for adding fragments in your Activity:

protected void addFragment(Fragment fragment, boolean addToBackStack) {
    String tag = fragment.getClass().getName(); //It's optional, may be null
    FragmentTransaction transaction = getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.your_container_id, fragment, tag);

    if (addToBackStack) {
        transaction.addToBackStack(tag);
    }

    transaction.commit();
}

And modify your onCreate method of activity like in the following snippet:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        // Add your fragment only if it is a first launch,
        // otherwise it will be restored by system
        addFragment(new YourFirstFragment(), false);
    }
}

For all other fragments use:

addFragment(new OtherFragment(), true);