问:
How to enable drag and drop and allow the user custom sorting?
I have a RecyclerView that is a list of user-inputted "Steps" and these steps can be in any order the user wants by drag and drop. I have a TextView that shows the adapter position(the step ordering), but I'm having a hard time keeping it updated after drag and drop.

Using ItemTouchHelper, I have the following:

```<code>override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean
{
    val fromPosition = viewHolder.adapterPosition
    val toPosition = target.adapterPosition
    if(fromPosition < toPosition)
    {
        for(i in fromPosition until toPosition)
        {
            Collections.swap(data, i, i + 1)
            data[toPosition].number = toPosition.toLong()
            data[fromPosition].number = fromPosition.toLong()
        }
    }
    else
    {
        for(i in toPosition downTo fromPosition)
        {
            Collections.swap(data, i, i - 1)
            data[toPosition].number = toPosition.toLong()
            data[fromPosition].number = fromPosition.toLong()
        }
    }
    notifyItemMoved(fromPosition, toPosition)
    notifyItemChanged(toPosition)
    notifyItemChanged(fromPosition)
    return true
}
</code>```

But, it throws an IndexOutOfBoundsException if I drag any item to the first position, and the data inside the EditText isn't maintained across moves or copies itself into the other EditText.

答:
SOLUTION

I was being an idiot and trying to fly before I ran. The above code from this article would have worked perfectly had I not modified it before testing and running it, apart from calling notifyItemChanged() after notifyItemMoved() because the number relies on the ViewHolder's adapter position. All I had to do was not put any code after Collections.swap(). Now the ordering feature works perfectly.

```<code>if (fromPosition < toPosition)
    {
        for (i in fromPosition until toPosition)
        {
            swap(data, i, i + 1)
        }
    } else
    {
        for (i in fromPosition downTo toPosition + 1)
        {
            swap(data, i, i - 1)
        }
    }
    notifyItemMoved(fromPosition, toPosition)
    notifyItemChanged(toPosition)
    notifyItemChanged(fromPosition)
    return true
</code>```

Body:
I have a RecyclerView that is a list of user-inputted "Steps" and these steps can be in any order the user wants by drag and drop. I have a TextView that shows the adapter position(the step ordering), but I'm having a hard time keeping it updated after drag and drop.

Using ItemTouchHelper, I have the following:

override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean
{
    val fromPosition = viewHolder.adapterPosition
    val toPosition = target.adapterPosition
    if(fromPosition < toPosition)
    {
        for(i in fromPosition until toPosition)
        {
            Collections.swap(data, i, i + 1)
            data[toPosition].number = toPosition.toLong()
            data[fromPosition].number = fromPosition.toLong()
        }
    }
    else
    {
        for(i in toPosition downTo fromPosition)
        {
            Collections.swap(data, i, i - 1)
            data[toPosition].number = toPosition.toLong()
            data[fromPosition].number = fromPosition.toLong()
        }
    }
    notifyItemMoved(fromPosition, toPosition)
    notifyItemChanged(toPosition)
    notifyItemChanged(fromPosition)
    return true
}

But, it throws an IndexOutOfBoundsException if I drag any item to the first position, and the data inside the EditText isn't maintained across moves or copies itself into the other EditText.

Body:
SOLUTION

I was being an idiot and trying to fly before I ran. The above code from this article would have worked perfectly had I not modified it before testing and running it, apart from calling notifyItemChanged() after notifyItemMoved() because the number relies on the ViewHolder's adapter position. All I had to do was not put any code after Collections.swap(). Now the ordering feature works perfectly.

if (fromPosition < toPosition)
    {
        for (i in fromPosition until toPosition)
        {
            swap(data, i, i + 1)
        }
    } else
    {
        for (i in fromPosition downTo toPosition + 1)
        {
            swap(data, i, i - 1)
        }
    }
    notifyItemMoved(fromPosition, toPosition)
    notifyItemChanged(toPosition)
    notifyItemChanged(fromPosition)
    return true


来源: stackexchange

问:
Why is the Ajax response adding the post details WP
For some reason the below Ajax response is adding the post details, and that is not the intended application.

I want to use only the post id that returns in the end.
Furthermore I tried to figure out why is my Ajax returning the details in text type and not in JSON type as I wished for?.

This is the outcome of the response

Here is my JS code:

```<code>createRate(){
    var ourNewPost = {
        'title': $(".new-rate-title").val(),
        'content': $('.new-rate-body').val(),
        'rate': $('.custom-star:checked').val(),
        'productId': $('.submit-rate').data('id')
    }

    $.ajax({
        // adding nonce key to make wordpress know we are looged in and has the permision to do that method.
        beforeSend: (xhr) => {
            xhr.setRequestHeader('X-WP-Nonce', ylsData.nonce);
        },
        url: ylsData.root_url + '/wp-json/yls/v1/rating/',
        type: 'POST',
        data: ourNewPost,
        dataType:"text",
        success: (response) => {

            console.log('congrats');
            console.log(response);
        },
        error: (response) => {
            console.log('failed');
            console.log(response);

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

and here is my php route code:

```<code>add_action('rest_api_init','ylsRateRoute');

function ylsRateRoute(){
    register_rest_route('yls/v1','rating',array(
        'methods' => 'POST',
        'callback'=> 'createLike'
    ));

}

function createLike($data){
    if(is_user_logged_in()){
        $title = sanitize_text_field($data['title']);
        $content = sanitize_text_field($data['content']);
        $rateNum = sanitize_text_field($data['rate']);
        $productId = sanitize_text_field($data['productId']);
        if(get_post_type($productId) == 'product'){
            return wp_insert_post(array(
                'post_title' => $title,
                'post_type' => 'rate',
                'post_content' => $content,
                'post_status' => 'publish',
                'meta_input' => array(
                    'rate_related_product' => $productId,
                    'rating_rate' => $rateNum
                )
              ));
        }else{
            die("Invalid product id");
        }
      }else{
        die("you must be logged in first");
      }
}
</code>```

答: Solved!, the problem was the name ‘rate’ of my custom post type.. probably one of my plugins uses the same name so it affects the outcome of the ajax.</p>

ContentLicense: CC BY-SA 4.0

Body:
For some reason the below Ajax response is adding the post details, and that is not the intended application.

I want to use only the post id that returns in the end.
Furthermore I tried to figure out why is my Ajax returning the details in text type and not in JSON type as I wished for?.

This is the outcome of the response

Here is my JS code:

createRate(){
    var ourNewPost = {
        'title': $(".new-rate-title").val(),
        'content': $('.new-rate-body').val(),
        'rate': $('.custom-star:checked').val(),
        'productId': $('.submit-rate').data('id')
    }

    $.ajax({
        // adding nonce key to make wordpress know we are looged in and has the permision to do that method.
        beforeSend: (xhr) => {
            xhr.setRequestHeader('X-WP-Nonce', ylsData.nonce);
        },
        url: ylsData.root_url + '/wp-json/yls/v1/rating/',
        type: 'POST',
        data: ourNewPost,
        dataType:"text",
        success: (response) => {

            console.log('congrats');
            console.log(response);
        },
        error: (response) => {
            console.log('failed');
            console.log(response);

        }
    });
}

and here is my php route code:

add_action('rest_api_init','ylsRateRoute');

function ylsRateRoute(){
    register_rest_route('yls/v1','rating',array(
        'methods' => 'POST',
        'callback'=> 'createLike'
    ));

}

function createLike($data){
    if(is_user_logged_in()){
        $title = sanitize_text_field($data['title']);
        $content = sanitize_text_field($data['content']);
        $rateNum = sanitize_text_field($data['rate']);
        $productId = sanitize_text_field($data['productId']);
        if(get_post_type($productId) == 'product'){
            return wp_insert_post(array(
                'post_title' => $title,
                'post_type' => 'rate',
                'post_content' => $content,
                'post_status' => 'publish',
                'meta_input' => array(
                    'rate_related_product' => $productId,
                    'rating_rate' => $rateNum
                )
              ));
        }else{
            die("Invalid product id");
        }
      }else{
        die("you must be logged in first");
      }
}


问:
Iterating over a list of objects to collect information, while calculating averages
What I've Done: I have an array of objects that represent baseball players. I've created a new array, years to collect needed information that I'm collecting while iterating through the array. I need to create an object for each year that each player played (referencing firstSeason and lastSeason), and then I have an array within the same object to collect each player's batting average from each year they played. If the year already exists in the array, it's appended to that object in the array--if it's not, a new object is created for that year and added to the array.

What I'm having trouble with: Along with an object for each year played, and the array with each player's batting average for that year, I also want to have another property in the years array that will show the overall average for each year--so essentially every avg array item in years added together and divided by the length of the avg array.

I know how to do this by re-looping over the years array, but I'm trying to accomplish this during the initial iteration... within the for (var season in baseballSeasons) { }. So, if needed, perhaps a running average while the loop is running that continues compiling the averages as they come in, if that makes sense.

Code:

    var baseballSeasons = [
        {
            PlayerName: "Dave",
            FirstSeason: 2013,
            LastSeason: 2016,
            BattingAverageRecord: [340, 210, 220, 300]
        },
        {
            PlayerName: "Dennis",
            FirstSeason: 2013,
            LastSeason: 2016,
            BattingAverageRecord: [230, 221, 312, 240]
        },
        {
            PlayerName: "Mary",
            FirstSeason: 2010,
            LastSeason: 2013,
            BattingAverageRecord: [330, 123, 151, 307]
        }

    ];

    var years = [];

    for (var season in baseballSeasons) {

        var firstYear = baseballSeasons[season].FirstSeason;
        var numberOfYears = baseballSeasons[season].BattingAverageRecord.length;

        for (var x = 0; x < numberOfYears; x++) {

            const yearExists = years.some(el => el.year === firstYear);
            var avgForYear = baseballSeasons[season].BattingAverageRecord[x];

            if (!yearExists) {
                years.push({ year: firstYear, avg: [avgForYear] })
            } else {
                let obj = years.find(o => o.year === firstYear);
                obj.avg.push(avgForYear);
            }

            firstYear++;
        }

    }

    console.log(years);```
</div>
</div>
</p>

<p>Example of the output:</p>

```0:
   year: 2013
   avg: (3) [340, 230, 307]
```

<p>Desired output:</p>

```0:
   year: 2013
   avg: (3) [340, 230, 307]
   yearAverage: 292
```

yearAverage is just the sum of the avg array divided by the array length. I'm unsure how to collect this in my existing loop.

Any help would be much appreciated. Thanks.

答:
Since computing the average requires all of the numbers, the only way to do it in the loop would be to keep running totals per year somewhere and recompute the average whenever a new number is added to a year. Instead of managing this extra state, it's not much more or less complicated or efficient to run another loop at the end.

const baseballSeasons = [{ PlayerName: "Dave", FirstSeason: 2013, LastSeason: 2016, BattingAverageRecord: [340, 210, 220, 300] }, { PlayerName: "Dennis", FirstSeason: 2013, LastSeason: 2016, BattingAverageRecord: [230, 221, 312, 240] }, { PlayerName: "Mary", FirstSeason: 2010, LastSeason: 2013, BattingAverageRecord: [330, 123, 151, 307] } ];

const years = baseballSeasons.reduce((a, e) =>
  e.BattingAverageRecord.forEach((avg, i) => {
    a[e.FirstSeason+i] = (a[e.FirstSeason+i] || []).concat(avg);
  }) || a
, {});

const result = Object.entries(years).map(([year, avg]) =>
  ({year, avg, yearAverage: avg.reduce((a, e) => a + e) / avg.length | 0})
);

console.log(result);```

Other thoughts:

The output array format is unusual. I'd think an object with year keys pointing to their data is easier to use. The lookup is O(1) vs O(n) and more idiomatic: years[2012].avg rather than years.find(e => e.year === 2012).avg.

Similarly, while building the years array, .some and .find search the entire structure. Using an object to group the years during this intermediate step would have a much more significant performance impact than avoiding a second loop for computing averages. This approach builds the more useful result structure on the spot.

Object keys should be camelCased, not TitleCased (but you mentioned the data is from an API, so that's probably a non-issue).

Body:
What I've Done: I have an array of objects that represent baseball players. I've created a new array, years to collect needed information that I'm collecting while iterating through the array. I need to create an object for each year that each player played (referencing firstSeason and lastSeason), and then I have an array within the same object to collect each player's batting average from each year they played. If the year already exists in the array, it's appended to that object in the array--if it's not, a new object is created for that year and added to the array.

What I'm having trouble with: Along with an object for each year played, and the array with each player's batting average for that year, I also want to have another property in the years array that will show the overall average for each year--so essentially every avg array item in years added together and divided by the length of the avg array.

I know how to do this by re-looping over the years array, but I'm trying to accomplish this during the initial iteration... within the for (var season in baseballSeasons) { }. So, if needed, perhaps a running average while the loop is running that continues compiling the averages as they come in, if that makes sense.

Code:

    var baseballSeasons = [
        {
            PlayerName: "Dave",
            FirstSeason: 2013,
            LastSeason: 2016,
            BattingAverageRecord: [340, 210, 220, 300]
        },
        {
            PlayerName: "Dennis",
            FirstSeason: 2013,
            LastSeason: 2016,
            BattingAverageRecord: [230, 221, 312, 240]
        },
        {
            PlayerName: "Mary",
            FirstSeason: 2010,
            LastSeason: 2013,
            BattingAverageRecord: [330, 123, 151, 307]
        }

    ];

    var years = [];

    for (var season in baseballSeasons) {

        var firstYear = baseballSeasons[season].FirstSeason;
        var numberOfYears = baseballSeasons[season].BattingAverageRecord.length;

        for (var x = 0; x < numberOfYears; x++) {

            const yearExists = years.some(el => el.year === firstYear);
            var avgForYear = baseballSeasons[season].BattingAverageRecord[x];

            if (!yearExists) {
                years.push({ year: firstYear, avg: [avgForYear] })
            } else {
                let obj = years.find(o => o.year === firstYear);
                obj.avg.push(avgForYear);
            }

            firstYear++;
        }

    }

    console.log(years);

Example of the output:

0:
   year: 2013
   avg: (3) [340, 230, 307]

Desired output:

0:
   year: 2013
   avg: (3) [340, 230, 307]
   yearAverage: 292

yearAverage is just the sum of the avg array divided by the array length. I'm unsure how to collect this in my existing loop.

Any help would be much appreciated. Thanks.

Body:
Since computing the average requires all of the numbers, the only way to do it in the loop would be to keep running totals per year somewhere and recompute the average whenever a new number is added to a year. Instead of managing this extra state, it's not much more or less complicated or efficient to run another loop at the end.

const baseballSeasons = [{ PlayerName: "Dave", FirstSeason: 2013, LastSeason: 2016, BattingAverageRecord: [340, 210, 220, 300] }, { PlayerName: "Dennis", FirstSeason: 2013, LastSeason: 2016, BattingAverageRecord: [230, 221, 312, 240] }, { PlayerName: "Mary", FirstSeason: 2010, LastSeason: 2013, BattingAverageRecord: [330, 123, 151, 307] } ];

const years = baseballSeasons.reduce((a, e) =>
  e.BattingAverageRecord.forEach((avg, i) => {
    a[e.FirstSeason+i] = (a[e.FirstSeason+i] || []).concat(avg);
  }) || a
, {});

const result = Object.entries(years).map(([year, avg]) =>
  ({year, avg, yearAverage: avg.reduce((a, e) => a + e) / avg.length | 0})
);

console.log(result);

Other thoughts:

The output array format is unusual. I'd think an object with year keys pointing to their data is easier to use. The lookup is O(1) vs O(n) and more idiomatic: years[2012].avg rather than years.find(e => e.year === 2012).avg.

Similarly, while building the years array, .some and .find search the entire structure. Using an object to group the years during this intermediate step would have a much more significant performance impact than avoiding a second loop for computing averages. This approach builds the more useful result structure on the spot.

Object keys should be camelCased, not TitleCased (but you mentioned the data is from an API, so that's probably a non-issue).


问:
How do I bind to a right-click event inside a Class object based on a Frame
I'm working on a Class which supports a multi-font Button by embedding multiple widgets inside a Frame. Now I'm trying to be able to handle the class instance calling the bind() method, but I can't get it to work. I thought that the Class would simply inherit the bind() method from the Frame, but it doesn't seem to be working in this instance. When I right-click on the second Button (a class instance), I do not get my printed statement. What am I doing wrong?
Sample to reproduce issue:

```<code>import tkinter as tk

class ButtonF(tk.Frame):

    def __init__(self, master=None, **options):
        self.command = options.pop('command', None)
        text = options.pop('text', '')
        tk.Frame.__init__(self, master, **options)
        self.b = tk.Button(master, text=text, command=self.command)
        self.bind('<Button-1>', self._click)
        self.bind('<ButtonRelease-1>', self._release)
        self.b.pack()

    def _click(self):
        self.config(relief=tk.SUNKEN)
        if self.command:
            self.command()

    def _release(self):
        self.config(relief=tk.RAISED)

    def bind(self, *a, **kw):
        tk.Frame.bind(self, *a, **kw)

if __name__ == '__main__':
    root = tk.Tk()
    root.title('Frame Button')
    root.but1 = tk.Button(root, text='Button 1 (Regular)', command=lambda *a:print('Button 1 Click!'))
    root.but1.pack(side=tk.LEFT)
    root.but2 = ButtonF(root, text='Button 2 (ButtonF)', command=lambda *a:print('Button 2 Click!')) #
    root.but2.pack(side=tk.LEFT)
    root.but1.bind('<Button-3>', lambda *a: print('Button 1 Right-Click!'))
    root.but2.bind('<Button-3>', lambda *a: print('Button 2 Right-Click!')) #### THIS DOESN'T WORK ####
    root.mainloop()
</code>```

答:
The final trick was to bind to both the frame and the button. So, binding to both self and self.b.
Why? Well, you have to bind to the frame in case you click on part of the frame that is not under the button. And you have to bind to the button in case you click on the button itself (i.e. not on part of the frame).
So, two bindings are necessary for a proper solution.

Body:
I'm working on a Class which supports a multi-font Button by embedding multiple widgets inside a Frame. Now I'm trying to be able to handle the class instance calling the bind() method, but I can't get it to work. I thought that the Class would simply inherit the bind() method from the Frame, but it doesn't seem to be working in this instance. When I right-click on the second Button (a class instance), I do not get my printed statement. What am I doing wrong?
Sample to reproduce issue:

import tkinter as tk

class ButtonF(tk.Frame):

    def __init__(self, master=None, **options):
        self.command = options.pop('command', None)
        text = options.pop('text', '')
        tk.Frame.__init__(self, master, **options)
        self.b = tk.Button(master, text=text, command=self.command)
        self.bind('<Button-1>', self._click)
        self.bind('<ButtonRelease-1>', self._release)
        self.b.pack()

    def _click(self):
        self.config(relief=tk.SUNKEN)
        if self.command:
            self.command()

    def _release(self):
        self.config(relief=tk.RAISED)

    def bind(self, *a, **kw):
        tk.Frame.bind(self, *a, **kw)

if __name__ == '__main__':
    root = tk.Tk()
    root.title('Frame Button')
    root.but1 = tk.Button(root, text='Button 1 (Regular)', command=lambda *a:print('Button 1 Click!'))
    root.but1.pack(side=tk.LEFT)
    root.but2 = ButtonF(root, text='Button 2 (ButtonF)', command=lambda *a:print('Button 2 Click!')) #
    root.but2.pack(side=tk.LEFT)
    root.but1.bind('<Button-3>', lambda *a: print('Button 1 Right-Click!'))
    root.but2.bind('<Button-3>', lambda *a: print('Button 2 Right-Click!')) #### THIS DOESN'T WORK ####
    root.mainloop()


问:
How to pass a selected key to a function and set a value for it using Vue.js?

I tried to pass a selected key to a function and set a value for it. Already Vue data has the key(htxt) and I passed the key on edit button event and get the passed key and tried to set prompt dialog's value to it but it's not working.

        <title>Vue.js Table Edit</title>

        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3.3.1/dist/css/uikit.min.css" />

{{ htxt }}

            {{ stxt }}

```

答:
        <title>Vue.js Table Edit</title>

        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3.3.1/dist/css/uikit.min.css" />

{{ htxt }}

            {{ stxt }}

```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data =  {
  htxt: 'How to change h3 text?',
  stxt: 'How to change span text?'
}

// ok
console.log(data['htxt'])
console.log(data.htxt)

// error, You are using this method
// console.log(data.'htxt')</code>```

Body:
<html>
    <head>
        <title>Vue.js Table Edit</title>
        <!-- UIkit CSS -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3.3.1/dist/css/uikit.min.css" />

        <!-- UIkit JS -->
        <script src="https://cdn.jsdelivr.net/npm/uikit@3.3.1/dist/js/uikit.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/uikit@3.3.1/dist/js/uikit-icons.min.js"></script>
    </head>
    <body>
        <div id="Edit">
            <h3>{{ htxt }}<span uk-icon="icon: pencil" @click="onEdit('htxt')"></span></h3>
            <span>{{ stxt }}<span uk-icon="icon: pencil" @click="onEdit('stxt')"></span></span>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <script>
            var edits = new Vue({
                el: '#Edit',
                data: {
                    htxt: 'How to change h3 text?',
                    stxt: 'How to change span text?'
                },
                methods:{
                    onEdit: function(val){
                        console.log("passed val:",val)
                        var retVal = prompt("Enter your name : ", "your name here");
                        this[val] = retVal;
                        // I passed key to hold the value in onedit function and
                        // I tried to set value to that key like this.val = retVal
                    }
                }

            })
        </script>
    </body>
</html>

var data =  {
  htxt: 'How to change h3 text?',
  stxt: 'How to change span text?'
}

// ok
console.log(data['htxt'])
console.log(data.htxt)

// error, You are using this method
// console.log(data.'htxt')


问:
After animating my text with CSS3, why does it not completely disappear?
When the words Front End finishes animating, a little bit of it can be seen on the top portion of the div with a class of .wrapper. The only thing I've been able to figure out how to fix the issue is by making it a smaller font size. How can I fix the issue with keeping the element the size that it currently is?

body{
 background: lightblue;
}
.wrapper{
 width: 50%;
 height: auto;
 padding:5%;
}
.frontEnd{
 -webkit-animation: move 2s ease-in-out normal;
   animation: move 2s ease-in-out normal;
}
@-webkit-keyframes move{
 0% {transform: translate(100%, 25%);}
 100%{transform: translate(7%, 25%);}
}
.webDeveloper{
 transform: translate(0%, 45%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>header animations</title>
 <link rel="stylesheet" type="text/css" href="styles.css">
</head>

<body>
 <div class="wrapper">
  <h1>
   <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 818 323.15">
    <defs>
     <style>
      .frontEnd {
       font-size: 101px;
       fill: #a4844e;
       font-family: BrandonGrotesque-Thin, Brandon Grotesque;
       font-weight: 200;
      }

      .webDeveloper {
       font-size: 70px;
       fill: #336699;
       font-family: BrandonGrotesque-Medium, Brandon Grotesque;
       font-weight: 500;
      }

      .webGraphics {
       font-size: 55px;
       fill: #a4844e;
       font-family: BrandonGrotesque-Thin, Brandon Grotesque;
       font-weight: 200;
      }
     </style>
    </defs>
    <title>creativeCogAnimation</title>
    <g><text class="frontEnd">FRONT END</text></g>
    <g><text class="webDeveloper">
      <tspan class="webDeveloper">WEB DEVELOPER</tspan>
     </text></g>
    <g><text class="webGraphics" transform="translate(313 274.65)">web & graphic design</text></g>
   </svg>
  </h1>
 </div>

</body>
</html></code>```

答:
Hope this help you.

body {
  background: lightblue;
}

.wrapper {
  width: 50%;
  height: auto;
  padding: 5%;
}

.frontEnd {
  -webkit-animation: move 2s ease-in-out normal;
  animation: move 2s ease-in-out normal;
  transform: translate(0%, 25%);
}

@-webkit-keyframes move {
  0% {
    transform: translate(100%, 25%);
  }
  100% {
    transform: translate(0%, 25%);
  }
}

.webDeveloper {
  transform: translate(0%, 45%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <h1>
    <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 818 323.15">
    <defs>
     <style>
      .frontEnd {
       font-size: 101px;
       fill: #a4844e;
       font-family: BrandonGrotesque-Thin, Brandon Grotesque;
       font-weight: 200;
      }

      .webDeveloper {
       font-size: 70px;
       fill: #336699;
       font-family: BrandonGrotesque-Medium, Brandon Grotesque;
       font-weight: 500;
      }

      .webGraphics {
       font-size: 55px;
       fill: #a4844e;
       font-family: BrandonGrotesque-Thin, Brandon Grotesque;
       font-weight: 200;
      }
     </style>
    </defs>
    <title>creativeCogAnimation</title>
    <g><text class="frontEnd" >FRONT END</text></g>

    <g><text class="webDeveloper">
      <tspan class="webDeveloper">WEB DEVELOPER</tspan>
     </text></g>
    <g><text class="webGraphics" transform="translate(313 274.65)">web & graphic design</text></g>
   </svg>
  </h1>
</div></code>```

Body:
When the words Front End finishes animating, a little bit of it can be seen on the top portion of the div with a class of .wrapper. The only thing I've been able to figure out how to fix the issue is by making it a smaller font size. How can I fix the issue with keeping the element the size that it currently is?

body{
 background: lightblue;
}
.wrapper{
 width: 50%;
 height: auto;
 padding:5%;
}
.frontEnd{
 -webkit-animation: move 2s ease-in-out normal;
   animation: move 2s ease-in-out normal;
}
@-webkit-keyframes move{
 0% {transform: translate(100%, 25%);}
 100%{transform: translate(7%, 25%);}
}
.webDeveloper{
 transform: translate(0%, 45%);
}

<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>header animations</title>
 <link rel="stylesheet" type="text/css" href="styles.css">

   <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 818 323.15">
    <defs>

    </defs>
    <title>creativeCogAnimation</title>
    <g><text class="frontEnd">FRONT END</text></g>
    <g><text class="webDeveloper">
      <tspan class="webDeveloper">WEB DEVELOPER</tspan>
     </text></g>
    <g><text class="webGraphics" transform="translate(313 274.65)">web & graphic design</text></g>
   </svg>

Body:
Hope this help you.

body {
  background: lightblue;
}

.wrapper {
  width: 50%;
  height: auto;
  padding: 5%;
}

.frontEnd {
  -webkit-animation: move 2s ease-in-out normal;
  animation: move 2s ease-in-out normal;
  transform: translate(0%, 25%);
}

@-webkit-keyframes move {
  0% {
    transform: translate(100%, 25%);
  }
  100% {
    transform: translate(0%, 25%);
  }
}

.webDeveloper {
  transform: translate(0%, 45%);
}

<div class="wrapper">
  <h1>
    <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 818 323.15">
    <defs>
     <style>
      .frontEnd {
       font-size: 101px;
       fill: #a4844e;
       font-family: BrandonGrotesque-Thin, Brandon Grotesque;
       font-weight: 200;
      }

      .webDeveloper {
       font-size: 70px;
       fill: #336699;
       font-family: BrandonGrotesque-Medium, Brandon Grotesque;
       font-weight: 500;
      }

      .webGraphics {
       font-size: 55px;
       fill: #a4844e;
       font-family: BrandonGrotesque-Thin, Brandon Grotesque;
       font-weight: 200;
      }
     </style>
    </defs>
    <title>creativeCogAnimation</title>
    <g><text class="frontEnd" >FRONT END</text></g>

    <g><text class="webDeveloper">
      <tspan class="webDeveloper">WEB DEVELOPER</tspan>
     </text></g>
    <g><text class="webGraphics" transform="translate(313 274.65)">web &amp; graphic design</text></g>
   </svg>
  </h1>
</div>


问:
How does the client knows which transport protocol to use?
Let's assume that I start a server at one of the computers in my private network (192.168.10.10:9900).

Now when making a request from some other computer in the same network, how does the client computer (OS?) knows which protocol to use / which protocol the server follows ? [TCP or UDP]

EDIT: As mentioned in the answers, I was basically looking for a default protocol which will be used by the client in the absence of any transport protocol information.

答: There is no reason any client would make a request to your server, so why would it care what protocol it follows? Clients don't just randomly connect to things to see if there's a server there. So it doesn't make any difference to any client.</p>


问:
Why can't char works but int does
```<code>char array[]= {1,2,3,4,5,6,7,8,9,1,2,3,6,7};
printf("%c\n", array[5]);
</code>```

This returns "  ". Nothing but when I change the char to int it prints "5". I tot char can accept numbers from -128 to 127?

```<code>int array[]= {1,2,3,4,5,6,7,8,9,1,2,3,6,7};
printf("%i\n", array[5]);
</code>```

答:
When you print the char, C assumes the value stored is supposed to represent ASCII encoded text. Accessing array[5] yields the value 6, which corresponds the ASCII value ACK. This character is not printable, which is why you see no output.

The character 6 is represented by the ASCII value 54. To produce this value, use the char literal '6'.

For example, try initializing your array as:

```<code>char array[]= {'1','2','3','4','5','6','7','8','9','1','2','3','6','7'};
</code>```

This will result in the behavior you expect.

Alternatively, you can print the character as a formatted integer by using the flag %i in place of %c in your first snippet.

Title: Why can't char works but int does

Body:
char array[]= {1,2,3,4,5,6,7,8,9,1,2,3,6,7};
printf("%c\n", array[5]);

This returns "  ". Nothing but when I change the char to int it prints "5". I tot char can accept numbers from -128 to 127?

int array[]= {1,2,3,4,5,6,7,8,9,1,2,3,6,7};
printf("%i\n", array[5]);

Body:
When you print the char, C assumes the value stored is supposed to represent ASCII encoded text. Accessing array[5] yields the value 6, which corresponds the ASCII value ACK. This character is not printable, which is why you see no output.

The character 6 is represented by the ASCII value 54. To produce this value, use the char literal '6'.

For example, try initializing your array as:

char array[]= {'1','2','3','4','5','6','7','8','9','1','2','3','6','7'};

This will result in the behavior you expect.

Alternatively, you can print the character as a formatted integer by using the flag %i in place of %c in your first snippet.


问:
Parallel Task advice
I am trying to use the parallel task library to kick off a number of tasks like this:

```<code>var workTasks = _schedules.Where(x => x.Task.Enabled);
_tasks = new Task[workTasks.Count()];
_cancellationTokenSource = new CancellationTokenSource();
_cancellationTokenSource.Token.ThrowIfCancellationRequested();

int i = 0;
foreach (var schedule in _schedules.Where(x => x.Task.Enabled))
{
    _log.InfoFormat("Reading task information for task {0}", schedule.Task.Name);
    if(!schedule.Task.Enabled)
    {
        _log.InfoFormat("task {0} disabled.", schedule.Task.Name);
        i++;
        continue;
    }

    schedule.Task.ServiceStarted = true;
    _tasks[i] = Task.Factory.StartNew(() =>
            schedule.Task.Run()
        , _cancellationTokenSource.Token);
    i++;
    _log.InfoFormat("task {0} has been added to the worker threads and has been started.", schedule.Task.Name);
}
</code>```

I want these tasks to sleep and then wake up every 5 minutes and do their stuff, at the moment I am using Thread.Sleep in the Schedule object whose Run method is the Action that is passed into StartNew as an argument like this:

```<code>_tasks[i] = Task.Factory.StartNew(() =>
        schedule.Task.Run()
    , _cancellationTokenSource.Token);
</code>```

I read somewhere that Thread.Sleep is a bad solution for this.  Can anyone recommend a better approach?

答:
By my understanding, Thread.Sleep is bad generally, because it force-shifts everything out of memory even when that's not necessary.  It won't be a big deal in most cases, but it could be a performance issue.

I'm in the habit of using this snippet instead:

```<code>new System.Threading.EventWaitHandle(false, EventResetMode.ManualReset).WaitOne(1000);
</code>```

Fits on one line, and isn't overly complicated -- it creates an event handle that will never be set, and then waits for the full timeout period before continuing.

Anyway, if you're just trying to have something repeat every 5 minutes, a better approach would probably be to use a Timer.  You could even make a class to neatly wrap everything if your repeated work methods are already factored out:

```<code>using System.Threading;
using System.Threading.Tasks;
public class WorkRepeater
{
    Timer m_Timer;

    WorkRepeater(Action workToRepeat, TimeSpan interval)
    {
        m_Timer = new System.Timers.Timer((double)Interval.Milliseconds);
        m_Timer.Elapsed +=
            new System.Timers.ElapsedEventHandler((o, ea) => WorkToRepeat());
    }

    public void Start()
    {
        m_Timer.Start();
    }

    public void Stop()
    {
        m_Timer.Stop();
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Parallel Task advice

Body:
I am trying to use the parallel task library to kick off a number of tasks like this:

var workTasks = _schedules.Where(x => x.Task.Enabled);
_tasks = new Task[workTasks.Count()];
_cancellationTokenSource = new CancellationTokenSource();
_cancellationTokenSource.Token.ThrowIfCancellationRequested();

int i = 0;
foreach (var schedule in _schedules.Where(x => x.Task.Enabled))
{
    _log.InfoFormat("Reading task information for task {0}", schedule.Task.Name);
    if(!schedule.Task.Enabled)
    {
        _log.InfoFormat("task {0} disabled.", schedule.Task.Name);
        i++;
        continue;
    }

    schedule.Task.ServiceStarted = true;
    _tasks[i] = Task.Factory.StartNew(() =>
            schedule.Task.Run()
        , _cancellationTokenSource.Token);
    i++;
    _log.InfoFormat("task {0} has been added to the worker threads and has been started.", schedule.Task.Name);
}

I want these tasks to sleep and then wake up every 5 minutes and do their stuff, at the moment I am using Thread.Sleep in the Schedule object whose Run method is the Action that is passed into StartNew as an argument like this:

_tasks[i] = Task.Factory.StartNew(() =>
        schedule.Task.Run()
    , _cancellationTokenSource.Token);

I read somewhere that Thread.Sleep is a bad solution for this.  Can anyone recommend a better approach?

Body:
By my understanding, Thread.Sleep is bad generally, because it force-shifts everything out of memory even when that's not necessary.  It won't be a big deal in most cases, but it could be a performance issue.

I'm in the habit of using this snippet instead:

new System.Threading.EventWaitHandle(false, EventResetMode.ManualReset).WaitOne(1000);

Fits on one line, and isn't overly complicated -- it creates an event handle that will never be set, and then waits for the full timeout period before continuing.

Anyway, if you're just trying to have something repeat every 5 minutes, a better approach would probably be to use a Timer.  You could even make a class to neatly wrap everything if your repeated work methods are already factored out:

using System.Threading;
using System.Threading.Tasks;
public class WorkRepeater
{
    Timer m_Timer;

    WorkRepeater(Action workToRepeat, TimeSpan interval)
    {
        m_Timer = new System.Timers.Timer((double)Interval.Milliseconds);
        m_Timer.Elapsed +=
            new System.Timers.ElapsedEventHandler((o, ea) => WorkToRepeat());
    }

    public void Start()
    {
        m_Timer.Start();
    }

    public void Stop()
    {
        m_Timer.Stop();
    }
}


问:
How to add commas into a char array in C
So I have a char array that currently holds a struct of a person's information.
For example,

```<code>struct Person{
char first_name[100];
char last_name[100];
char phone[13];
};

struct Person* arr[] = {("John", "Doe", "831.563.3642"), ("Julie", "Dee", "542.865.4644") };
</code>```

And I am trying to have it end up printing to a file to look like this...

```<code>John, Doe, 831.563.3642
Julie, Dee, 542.865.4644
</code>```

So far this is the code I have (to try and add the commas while putting into a file)

```<code>void print(FILE* file_out, struct Person* p1[]){
   size_t len = sizeof(p1) / sizeof(p1[0]);
   for(i = 0; i < len; i++){
      fprintf(file_out, "%s, %s, %s\n", p1[i].first, p1[i].last, p1[i].phone);
   }
}
return;
</code>```

答:
struct Person* arr[1] is equivalent to Person arr is also equivalent to Person** arr
I don't think that is what you meant. get rid of the pointer :D

Now some really important things about strings... The strlen function is the #1 reason for buffer overflow bugs - NEVER use strlen without some kind of limitation.

Also, internally string length looks like this...

```<code>int strlen(char* str) {
    int count = 0;
    while (str[count]) {
        count++;
    }
    return count;
}
</code>```

notice that is almost your function?
Your function could be changed to...

```<code>char* makeString(char* str) {
    char out[] = ""
    int count = 0;
    while (str[count]) {
        out[count] = str[count];
        count++;
    }
    out[count] = ',';
    out[count + 1] = 0;
    return out;
}
</code>```

Lets talk about the major problems with this though - first, notice the while loop that only ends when it finds a 0? That is a GREAT way to make a bug. All somebody has to do is give a name just a little too long and boom! there is no ending 0.

Now imagine I call your function multiple times in a row...
You are looping through the string each time!!!
In other words, I iterate through the loop for the string "john". that is 4 times through the while loop. it also makes a char[6] to hold those things - since john is 4, and the ',' is 1, and the "end of the string" marker is a 0.

Now we add to the string again. we iterate over "john" the ",", and add "Joe". This means we need a new longer char[] of length 9. now we iterate over "john, " and "doe" for 9 while loop hits. Then we do this again and again. We iterate over john a HUGE number of times. Way too many times.

Now for the safe way to do this :D

```<code>//Create a string of a known length that can hold all the data
//Now we only need to create a char buffer once instead of multiple times
//In a regular computer, it is better to waste space than CPU time :D (in this case anyway...)
char printString[sizeof(arr.first_name) + 2 + sizeof(arr.last_name) + 2 + sizeof(arr.phone) + 1];
//Remember where we last wrote, and where we are in our current copy
int position = 0;
int i = 0;
//While it is not the end of the string, and we have not gone over the longest possible length...
while (arr[0].first_name[i] && i < sizeof(arr[0].first_name)) {
    //Copy the character
    printString[position] = arr.first_name[i];
    //Move to the next spot in both character buffers
    position++;
    i++;
}
//Add our comma and space
prinstString[position] = ',';
printtString[position + 1] = ' ';
position = position + 2;
int i = 0;
while (arr[0].last_name[i] && i < sizeof(arr[0].last_name)) {
    printString[position] = arr.last_name[i];
    position++;
    i++;
}
prinstString[position] = ',';
printtString[position + 1] = ' ';
position = position + 2;
int i = 0;
while (arr[0].phone[i] && i < sizeof(arr[0].phone)) {
    printString[position] = arr.phone[i];
    position++;
    i++;
}
prinstString[position] = 0;
</code>```

Now for the benefits.

We only iterate through each string once. This avoids the problem above where we iterate over John a million times. (Look here to see a funny way to see it XD)

The biggest benefit is checking that we have not gone over the end. Nobody can exploit out strings anymore!!!

And also, we only need to alocate a char buffer ONCE to hold all this cumulative string concatenation stuff.

We also have some really nice information for the next guy if we wanted to pass it on, and notice it almost is the form of an algo? How awesome - it can almost be a function!

Now for the grand finale! All of that hard work has been done by someone so much smarter than both of us ;)

```<code>printf("%s, %s, %s", arr[0].first_name, arr[0].last_name, arr[0].phone);
</code>```

I think I am done editing now!!

Body:
So I have a char array that currently holds a struct of a person's information.
For example,

struct Person{
char first_name[100];
char last_name[100];
char phone[13];
};

struct Person* arr[] = {("John", "Doe", "831.563.3642"), ("Julie", "Dee", "542.865.4644") };

And I am trying to have it end up printing to a file to look like this...

John, Doe, 831.563.3642
Julie, Dee, 542.865.4644

So far this is the code I have (to try and add the commas while putting into a file)

void print(FILE* file_out, struct Person* p1[]){
   size_t len = sizeof(p1) / sizeof(p1[0]);
   for(i = 0; i < len; i++){
      fprintf(file_out, "%s, %s, %s\n", p1[i].first, p1[i].last, p1[i].phone);
   }
}
return;

Body:
struct Person* arr[1] is equivalent to Person arr is also equivalent to Person** arr
I don't think that is what you meant. get rid of the pointer :D

Now some really important things about strings... The strlen function is the #1 reason for buffer overflow bugs - NEVER use strlen without some kind of limitation.

Also, internally string length looks like this...

int strlen(char* str) {
    int count = 0;
    while (str[count]) {
        count++;
    }
    return count;
}

notice that is almost your function?
Your function could be changed to...

char* makeString(char* str) {
    char out[] = ""
    int count = 0;
    while (str[count]) {
        out[count] = str[count];
        count++;
    }
    out[count] = ',';
    out[count + 1] = 0;
    return out;
}

Lets talk about the major problems with this though - first, notice the while loop that only ends when it finds a 0? That is a GREAT way to make a bug. All somebody has to do is give a name just a little too long and boom! there is no ending 0.

Now imagine I call your function multiple times in a row...
You are looping through the string each time!!!
In other words, I iterate through the loop for the string "john". that is 4 times through the while loop. it also makes a char[6] to hold those things - since john is 4, and the ',' is 1, and the "end of the string" marker is a 0.

Now we add to the string again. we iterate over "john" the ",", and add "Joe". This means we need a new longer char[] of length 9. now we iterate over "john, " and "doe" for 9 while loop hits. Then we do this again and again. We iterate over john a HUGE number of times. Way too many times.

Now for the safe way to do this :D

//Create a string of a known length that can hold all the data
//Now we only need to create a char buffer once instead of multiple times
//In a regular computer, it is better to waste space than CPU time :D (in this case anyway...)
char printString[sizeof(arr.first_name) + 2 + sizeof(arr.last_name) + 2 + sizeof(arr.phone) + 1];
//Remember where we last wrote, and where we are in our current copy
int position = 0;
int i = 0;
//While it is not the end of the string, and we have not gone over the longest possible length...
while (arr[0].first_name[i] && i < sizeof(arr[0].first_name)) {
    //Copy the character
    printString[position] = arr.first_name[i];
    //Move to the next spot in both character buffers
    position++;
    i++;
}
//Add our comma and space
prinstString[position] = ',';
printtString[position + 1] = ' ';
position = position + 2;
int i = 0;
while (arr[0].last_name[i] && i < sizeof(arr[0].last_name)) {
    printString[position] = arr.last_name[i];
    position++;
    i++;
}
prinstString[position] = ',';
printtString[position + 1] = ' ';
position = position + 2;
int i = 0;
while (arr[0].phone[i] && i < sizeof(arr[0].phone)) {
    printString[position] = arr.phone[i];
    position++;
    i++;
}
prinstString[position] = 0;

Now for the benefits.

We only iterate through each string once. This avoids the problem above where we iterate over John a million times. (Look here to see a funny way to see it XD)

The biggest benefit is checking that we have not gone over the end. Nobody can exploit out strings anymore!!!

And also, we only need to alocate a char buffer ONCE to hold all this cumulative string concatenation stuff.

We also have some really nice information for the next guy if we wanted to pass it on, and notice it almost is the form of an algo? How awesome - it can almost be a function!

Now for the grand finale! All of that hard work has been done by someone so much smarter than both of us ;)

printf("%s, %s, %s", arr[0].first_name, arr[0].last_name, arr[0].phone);

I think I am done editing now!!


问:
Is it possible to reload the page on key press in javascript (without focusing the page)?
I want to reload my page on key press in JavaScript. I already use this code,

```<code>document.addEventListener('keyup', function (e) {
    if (e.keyCode == 13)
        window.location.reload();
});
</code>```

from this post-Refresh page on ENTER / RETURN key press

But the problem is when the current page is not in focus it does not work. For example when I open the developer tools or click on it. Then the keypress event is not working for focus out (I think so).

Is it possible to do it without focusing on the page using JavaScript?

答: It's not possible in javascript, What you used is good(don't need to improve)</p>

Body:
I want to reload my page on key press in JavaScript. I already use this code,

document.addEventListener('keyup', function (e) {
    if (e.keyCode == 13)
        window.location.reload();
});

from this post-Refresh page on ENTER / RETURN key press

But the problem is when the current page is not in focus it does not work. For example when I open the developer tools or click on it. Then the keypress event is not working for focus out (I think so).

Is it possible to do it without focusing on the page using JavaScript?


问:
Why does hello world print twice only and why is a's largest value 2
```<code>#include <stdio.h>
#include <unistd.h>

int main() {
    int a=0;
    int rc=fork();
    a++;
    if(rc=0)
    {
        rc=fork();

        a++;
    }
    else
    {
       a++;
    }
    printf("Hello World");
    printf("%d",a);

    return 0;
}
</code>```

答:
Why does hello world print twice only and why is a's largest value 2

To answer your question (after correcting your (rc = 0) vs. (rc == 0) issue), it may help to diagram what is happening in your code. For example:

```<code>    parent
      |
      a = 1
      if (rc == 0)
      +--------------- child 1
      |                   |
      else                +--------------- child 2
        a++               a++              a++
      a = 2               a = 2            a = 2
      Hello World2        Hello World2     Hello World2
</code>```

In the parent process, you fork and then increment a with a++ before your test of if (rc == 0) to give direction to the child process. The original parent sees a++ again due to the else and "Hello World2" is the result.

In the first-child, you fork again, but the child-1 (as parent) and child-2 both increment a++; before dropping out of the conditional with "Hello World2" the result for both.

It appears you were attempting something similar to:

```<code>#include <stdio.h>
#include <unistd.h>

int main (void) {

    int a = 1,
        rc = fork();

    if (rc == 0) {
        a++;
        rc = fork();

        if (rc == 0)
            a++;
    }

    printf ("Hello World %d\n", a);
}
</code>```

Example Use/Output

```<code>$ ./bin/forkcount
Hello World 1
Hello World 2
Hello World 3
</code>```

Sometimes a pencil and paper is as helpful as a keyboard. Let me know if you have further questions.

Body:
Why does hello world print twice only and why is a's largest value 2

To answer your question (after correcting your (rc = 0) vs. (rc == 0) issue), it may help to diagram what is happening in your code. For example:

    parent
      |
      a = 1
      if (rc == 0)
      +--------------- child 1
      |                   |
      else                +--------------- child 2
        a++               a++              a++
      a = 2               a = 2            a = 2
      Hello World2        Hello World2     Hello World2

In the parent process, you fork and then increment a with a++ before your test of if (rc == 0) to give direction to the child process. The original parent sees a++ again due to the else and "Hello World2" is the result.

In the first-child, you fork again, but the child-1 (as parent) and child-2 both increment a++; before dropping out of the conditional with "Hello World2" the result for both.

It appears you were attempting something similar to:

#include <stdio.h>
#include <unistd.h>

int main (void) {

    int a = 1,
        rc = fork();

    if (rc == 0) {
        a++;
        rc = fork();

        if (rc == 0)
            a++;
    }

    printf ("Hello World %d\n", a);
}

Example Use/Output

$ ./bin/forkcount
Hello World 1
Hello World 2
Hello World 3

Sometimes a pencil and paper is as helpful as a keyboard. Let me know if you have further questions.


问:
How to prevent wrong values in an initializer list?
When you write a constructor, you have the opportunity to test the values of the arguments from out of range or other unwanted situations in its body.

```<code>class a
{
  int b;
public:
  a(int c)
  {
    if(c < MIN_ALLOWED || c > MAX_ALLOWED)
    {
      // Take some measure
    }
    else
    {
      b = c;
    }
  }
};
</code>```

But when you're dealing with const members, they should be initialized by means of an initializer list, so, in this case, how to prevent unwanted values?

```<code>class a
{
  const int b;
public:
  a(int c) : b(c)
  {
    // How to control "c" value?!...
  }
};
</code>```

答:
All of the above answers are good and work... but lest we forget, you can also do:

```<code>class a
{
    public:
        a(int c) : b([=]() -> int {
            if (c < MIN_ALLOWED || c > MAX_ALLOWED)
                throw std::logic_error("b");
            return c;
        }()) {}
    private:
        int b;
</code>```

};

It looks awful in my opinion though, having a lambda in an initializer list, but it's still possible.

Body:
When you write a constructor, you have the opportunity to test the values of the arguments from out of range or other unwanted situations in its body.

class a
{
  int b;
public:
  a(int c)
  {
    if(c < MIN_ALLOWED || c > MAX_ALLOWED)
    {
      // Take some measure
    }
    else
    {
      b = c;
    }
  }
};

But when you're dealing with const members, they should be initialized by means of an initializer list, so, in this case, how to prevent unwanted values?

class a
{
  const int b;
public:
  a(int c) : b(c)
  {
    // How to control "c" value?!...
  }
};

Body:
All of the above answers are good and work... but lest we forget, you can also do:

class a
{
    public:
        a(int c) : b([=]() -> int {
            if (c < MIN_ALLOWED || c > MAX_ALLOWED)
                throw std::logic_error("b");
            return c;
        }()) {}
    private:
        int b;

};

It looks awful in my opinion though, having a lambda in an initializer list, but it's still possible.


问:
Android R8 fragments implements but actually matches extends
Currently used version is: androidx.fragment:fragment-ktx:1.2.1. When I try to build release version, proguard (R8) show warnings like:

```<code>R8: The rule `-neverclassinline public class ** implements androidx.fragment.app.Fragment` uses implements but actually matches extends.

R8: The rule `-keep public class ** implements androidx.fragment.app.Fragment {
  public <init>();
}` uses implements but actually matches extends.
</code>```

I didnt find any related issues on bug trackers. What maybe the reason, and how I can fix it?

答: This is issue 148963981, which is already marked as fixed for the (upcoming, as of the time of writing this answer) Fragment 1.2.2 release.</p>

Body:
Currently used version is: androidx.fragment:fragment-ktx:1.2.1. When I try to build release version, proguard (R8) show warnings like:

R8: The rule `-neverclassinline public class ** implements androidx.fragment.app.Fragment` uses implements but actually matches extends.

R8: The rule `-keep public class ** implements androidx.fragment.app.Fragment {
  public <init>();
}` uses implements but actually matches extends.

I didnt find any related issues on bug trackers. What maybe the reason, and how I can fix it?


问:
Whats wrong with my If-Else conditional code that receives user input and categorizes the data by "hot" or "cold"
```<code>HighTemp1= input()
print(‘Temperature 1:’ +  HighTemp1)
LowTemp2= input()
print(‘Temperature 2:’ + LowTemp2)
if (HighTemp1>80):
   print( ‘The high temperature was Hot’)
elif(HighTemp1> 40 and <80):
   print(‘The high temperature was Average’)
else:
   print(‘The high temperature was Cold’)

if (LowTemp2>80):
   print( ‘The low temperature was Hot’)
elif(LowTemp2> 40 and <80):
   print(‘The low temperature was Average’)
else:
   print(‘The low temperature was Cold’)
</code>```

So, i'm suppose to Determine the category of two user-input temperatures for a day and output it in the following way:

Temp        Category
>80         Hot
40 to 80    Average
<40         Cold
```

Example#1:
Temperature 1: 81
Temperature 2: 37
The high temperature was Hot
The low temperature was Cold

I've gotten so many errors on this code and I'm not sure what's wrong. The code won't run in IDLE because as I run it line by line(since I get a multiple statement error), there's either a type error "cannot use > operator with both int and string" or a syntax error. What am I not understanding that's preventing my code from running?

答:
I assume you're using Python3. You're having a number of errors in your code

```<code>HighTemp1= int(input())  #to take int input, you need to parse it to int. as input() directly reads a string
print("Temperature 1:" +  str(HighTemp1)) #print in python3 assumes string in ""
LowTemp2= int(input())
print("Temperature 2:" + str(LowTemp2)) #int can't be directly concatenated to string. You need to parse it to string using str() to concat it with string
if (HighTemp1>80):
    print( "The high temperature was Hot")
elif(HighTemp1> 40 and  <80):
    print("The high temperature was Average")
else:
    print("The high temperature was Cold")

if (LowTemp2>80):
    print( "The low temperature was Hot")
elif(LowTemp2> 40 and <80):
    print("The low temperature was Average")
else:
    print("The low temperature was Cold")
</code>```

Body:
HighTemp1= input()
print(‘Temperature 1:’ +  HighTemp1)
LowTemp2= input()
print(‘Temperature 2:’ + LowTemp2)
if (HighTemp1>80):
   print( ‘The high temperature was Hot’)
elif(HighTemp1> 40 and <80):
   print(‘The high temperature was Average’)
else:
   print(‘The high temperature was Cold’)

if (LowTemp2>80):
   print( ‘The low temperature was Hot’)
elif(LowTemp2> 40 and <80):
   print(‘The low temperature was Average’)
else:
   print(‘The low temperature was Cold’)

So, i'm suppose to Determine the category of two user-input temperatures for a day and output it in the following way:

Temp        Category
>80         Hot
40 to 80    Average
<40         Cold

Example#1:
Temperature 1: 81
Temperature 2: 37
The high temperature was Hot
The low temperature was Cold

I've gotten so many errors on this code and I'm not sure what's wrong. The code won't run in IDLE because as I run it line by line(since I get a multiple statement error), there's either a type error "cannot use > operator with both int and string" or a syntax error. What am I not understanding that's preventing my code from running?

Body:
I assume you're using Python3. You're having a number of errors in your code

HighTemp1= int(input())  #to take int input, you need to parse it to int. as input() directly reads a string
print("Temperature 1:" +  str(HighTemp1)) #print in python3 assumes string in ""
LowTemp2= int(input())
print("Temperature 2:" + str(LowTemp2)) #int can't be directly concatenated to string. You need to parse it to string using str() to concat it with string
if (HighTemp1>80):
    print( "The high temperature was Hot")
elif(HighTemp1> 40 and  <80):
    print("The high temperature was Average")
else:
    print("The high temperature was Cold")

if (LowTemp2>80):
    print( "The low temperature was Hot")
elif(LowTemp2> 40 and <80):
    print("The low temperature was Average")
else:
    print("The low temperature was Cold")


问:
C# Generics: Reference types vs. Value Types
I've faced a lot of confusion with regards to differences between generic reference types vs. generic value types whilst writing my API.

What are the differences with regards to constraints and functionalities (most important/easily overlooked) between the two?

```<code>class ReferenceGeneric <T> where ???
{

}
</code>```

and

```<code>struct ValueGeneric <T>: where ???
{

}
</code>```

Edit #1 Just to clarify the question and what I am after: I want to know what you can do with Generic reference types AND cannot do with generic value types (and vice versa)

Edit #2 Further clarifications: How can T be constrained if generic type is reference or value type? Are there differences as to how each type can be constrained?

答:
In response to Edit2: You can limit the types allowed to reference or value by the following:

Reference:

```<code>class ReferenceGeneric <T> where T: class
{

}
</code>```

Value:

```<code>struct ValueGeneric <T> where T: struct
{

}
</code>```

From the following page on MSDN
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

OwnerDisplayName: Sasha

LastEditorDisplayName: Sasha

Body:
I've faced a lot of confusion with regards to differences between generic reference types vs. generic value types whilst writing my API.

What are the differences with regards to constraints and functionalities (most important/easily overlooked) between the two?

class ReferenceGeneric <T> where ???
{

}

and

struct ValueGeneric <T>: where ???
{

}

Edit #1 Just to clarify the question and what I am after: I want to know what you can do with Generic reference types AND cannot do with generic value types (and vice versa)

Edit #2 Further clarifications: How can T be constrained if generic type is reference or value type? Are there differences as to how each type can be constrained?

Body:
In response to Edit2: You can limit the types allowed to reference or value by the following:

Reference:

class ReferenceGeneric <T> where T: class
{

}

Value:

struct ValueGeneric <T> where T: struct
{

}

From the following page on MSDN
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

OwnerDisplayName: C. Ross

ContentLicense: CC BY-SA 2.5


问:
How to decouple relational MVC data
Consider this Scenario:

I want to build an MVC application for Northwind Database. I want to have a view that list some orders and I want to create links for CustomerID and EmployeeID and a details link for [OrderDetails] so that when a user clicks any of these links related data will appear in the same page.

My problem is how to decouple this data that is interrelated into views and controllers that show related data in a page, and controllers responsible for individual parts of the information.

Also, how do I configure routing for this sample?

```<code><table width="500px">
    <tr>
        <th></th>
        <th>
            OrderID
        </th>
        <th>
            CustomerID
        </th>
        <th>
            EmployeeID
        </th>
        <th>
            OrderDate
        </th>
        <th>
            RequiredDate
        </th>
        <th>
            ShippedDate
        </th>
        <th>
            ShipVia
        </th>
        <th>
            OrderDetails
        </th>
    </tr>

<% foreach (var item in Model) { %>

    <tr>
        <td>
            <%: Html.ActionLink("Edit", "Edit", new { id=item.OrderID }) %> |
            <%: Html.ActionLink("Details", "Details", new { id=item.OrderID })%> |
            <%: Html.ActionLink("Delete", "Delete", new { id=item.OrderID })%>
        </td>
        <td>
            <%: item.OrderID %>
        </td>
        <td>
            <%: item.CustomerID %>
        </td>
        <td>
            <%: item.EmployeeID %>
        </td>
        <td>
            <%: String.Format("{0:g}", item.OrderDate) %>
        </td>
        <td>
            <%: String.Format("{0:g}", item.RequiredDate) %>
        </td>
        <td>
            <%: String.Format("{0:g}", item.ShippedDate) %>
        </td>
        <td>
            <%: item.ShipVia %>
        </td>
        <td>
            <%: Html.ActionLink("OrderDetails", "GetOrderDetails", new { id = item.OrderID })%>
        </td>
    </tr>

<% } %>

</table>

<p>
    <%: Html.ActionLink("Create New", "Create") %>
</p>

<div>
    <p>
        <% Html.RenderPartial("GetOrderDetails"); %>
    </p>
    <%--<uc1:GetOrderDetails ID="GetOrderDetails1" runat="server" />--%>
</div>
</code>```

and Order Details partial view:

```<code><table>
    <tr>
        <th></th>
        <th>
            OrderID
        </th>
        <th>
            ProductID
        </th>
        <th>
            UnitPrice
        </th>
        <th>
            Quantity
        </th>
        <th>
            Discount
        </th>
    </tr>

<% foreach (var item in Model) { %>

    <tr>
        <td>
            <%: Html.ActionLink("Edit", "Edit", new { id=item.OrderID }) %> |
            <%: Html.ActionLink("Details", "Details", new { id=item.OrderID })%> |
            <%: Html.ActionLink("Delete", "Delete", new { id=item.OrderID })%>
        </td>
        <td>
            <%: item.OrderID %>
        </td>
        <td>
            <%: item.ProductID %>
        </td>
        <td>
            <%: String.Format("{0:F}", item.UnitPrice) %>
        </td>
        <td>
            <%: item.Quantity %>
        </td>
        <td>
            <%: item.Discount %>
        </td>
    </tr>

<% } %>

</table>

<p>
    <%: Html.ActionLink("Create New", "Create") %>
</p>
</code>```

global.asax:

```<code>public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default2", // Route name
            "{controller}/{action}/{OrderId}/{CustomerID}", // URL with parameters
            new { controller = "NorthwindOrders", action = "Index", OrderId = UrlParameter.Optional, CustomerID = UrlParameter.Optional } // Parameter defaults
        );

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
    }
</code>```

Given this structure; how I can display order details under the order list when any of the OrderDetails links are clicked?

And, why is the URL displayed like this when I click on OrderDetails links:

```<code>http://localhost:49444/NorthwindOrders/GetOrderDetails?id=10250
</code>```

I want the URL to display this way:

```<code>http://localhost:49444/NorthwindOrders/GetOrderDetails/10250
</code>```

答:
Nima,

you can do it via partial views or render action, and json to display data

the basic example is as example here:
http://www.asp.net/mvc/tutorials/iteration-7-add-ajax-functionality-cs

or very popular option is display action for the task in jquery.dialog()

depends on you what way you want to proceed
cpo

revised:

My bad.
From logic point of view, it is as this:

It depends only on you, which way you want to go.
(From my point of view)

Benefits of separating the logic is :

simple to understand as controller is related only to actions for eg: orders

Can be used on more places if you need

Easy to test only small items, eg one testcase/fixture to controller for only orders

Usefull for more complicated projects

On the other hand

Keep everything in one controller and split the logic by regions

Eveything is together, easy to see other methods and what they do

Hope this is what you were looking for

cpo

Title: How to decouple relational MVC data

Body:
Consider this Scenario:

I want to build an MVC application for Northwind Database. I want to have a view that list some orders and I want to create links for CustomerID and EmployeeID and a details link for [OrderDetails] so that when a user clicks any of these links related data will appear in the same page.

My problem is how to decouple this data that is interrelated into views and controllers that show related data in a page, and controllers responsible for individual parts of the information.

Also, how do I configure routing for this sample?

            OrderID

            CustomerID

            EmployeeID

            OrderDate

            RequiredDate

            ShippedDate

            ShipVia

            OrderDetails

<% foreach (var item in Model) { %>

            <%: Html.ActionLink("Edit", "Edit", new { id=item.OrderID }) %> |
            <%: Html.ActionLink("Details", "Details", new { id=item.OrderID })%> |
            <%: Html.ActionLink("Delete", "Delete", new { id=item.OrderID })%>

            <%: item.OrderID %>

            <%: item.CustomerID %>

            <%: item.EmployeeID %>

            <%: String.Format("{0:g}", item.OrderDate) %>

            <%: String.Format("{0:g}", item.RequiredDate) %>

            <%: String.Format("{0:g}", item.ShippedDate) %>

            <%: item.ShipVia %>

            <%: Html.ActionLink("OrderDetails", "GetOrderDetails", new { id = item.OrderID })%>

<% } %>

    <%: Html.ActionLink("Create New", "Create") %>

        <% Html.RenderPartial("GetOrderDetails"); %>

    <%--<uc1:GetOrderDetails ID="GetOrderDetails1" runat="server" />--%>

and Order Details partial view:

            OrderID

            ProductID

            UnitPrice

            Quantity

            Discount

<% foreach (var item in Model) { %>

            <%: Html.ActionLink("Edit", "Edit", new { id=item.OrderID }) %> |
            <%: Html.ActionLink("Details", "Details", new { id=item.OrderID })%> |
            <%: Html.ActionLink("Delete", "Delete", new { id=item.OrderID })%>

            <%: item.OrderID %>

            <%: item.ProductID %>

            <%: String.Format("{0:F}", item.UnitPrice) %>

            <%: item.Quantity %>

            <%: item.Discount %>

<% } %>

    <%: Html.ActionLink("Create New", "Create") %>

global.asax:

public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default2", // Route name
            "{controller}/{action}/{OrderId}/{CustomerID}", // URL with parameters
            new { controller = "NorthwindOrders", action = "Index", OrderId = UrlParameter.Optional, CustomerID = UrlParameter.Optional } // Parameter defaults
        );

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );
    }

Given this structure; how I can display order details under the order list when any of the OrderDetails links are clicked?

And, why is the URL displayed like this when I click on OrderDetails links:

http://localhost:49444/NorthwindOrders/GetOrderDetails?id=10250

I want the URL to display this way:

http://localhost:49444/NorthwindOrders/GetOrderDetails/10250


问:
All values are null when posting to controller in ASP.NET Core
When I insert values into view model and debug, all of the values are null in the controller, I have an
[HttpGet]
public IActionResult CreatePrescription(int id) that gets the view model and then I have

```<code>[HttpPost]
public IActionResult CreatePrescription(ViewModel model){
        try
        {
            Prescription prescription = new Prescription
            {
                PatientId = model.Patient.Id,
                MedicationId = model.Prescription.MedicationId,
                RxNumber = model.Prescription.RxNumber,
                Frequency = model.Prescription.Frequency,
                Quantity = model.Prescription.Quantity,
                Copay = model.Prescription.Copay,
                RefillsRemaining = model.Prescription.RefillsRemaining,
                FolderStatusId = model.Prescription.FolderStatusId,
                PrescriberId = model.Prescription.PrescriberId,
                OriginalRxDate = model.Prescription.OriginalRxDate,
                DateFilled = model.Prescription.DateFilled,
                ExpiryDate = model.Prescription.ExpiryDate,
                DeliveryDate = model.Prescription.DeliveryDate,
                DeliveryTime = model.Prescription.DeliveryTime,
                BillDate = model.Prescription.BillDate,
                ApplicationUserId = user,
                CreatedOn = DateTime.Now,
                IsActive = true
            };

            _context.Add(prescription);

            _context.SaveChanges();

        }
        catch (Exception)
        {

            throw;
        }
        return View();
    }
</code>```

Here is part of the view

```<code>@model Systemz.Models.ViewModels.ViewModel
<div class="modal-body">
    <form asp-action="CreatePrescription" asp-controller="Patients" method="post">
        <input asp-for="Prescription.Id" type="hidden" />
        <input asp-for="Patient.Id" type="hidden" />
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <div class="row">
                <div class="col-sm-3">
                    <label asp-for="Prescription.RxNumber" class="custom-label"></label>
                </div>
                <div class="col-sm-7">
                    <input asp-for="Prescription.RxNumber" class="form-control" />
                </div>
                <span asp-validation-for="Prescription.RxNumber" class="text-danger"></span>
            </div>
        </div>
<div class="form-group">
            <div class="row">
                <div class="col-sm-3">
                    <label asp-for="Prescription.Frequency" class="custom-label"></label>
                </div>
                <div class="col-sm-7">
                    <input asp-for="Prescription.Frequency" class="form-control" />
                </div>
                <span asp-validation-for="Prescription.Frequency" class="text-danger"></span>
            </div>
        </div>

        <div class="form-group">
            <div class="row">
                <div class="col-sm-3">
                    <label asp-for="Prescription.Quantity" class="custom-label"></label>
                </div>
                <div class="col-sm-7">
                    <input asp-for="Prescription.Quantity" class="form-control" />
                </div>
                <span asp-validation-for="Prescription.Quantity" class="text-danger"></span>
            </div>
        </div>
</code>```

And here is the class

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Systemz.Models,ViewModels
{
    public class ViewModel
    {
        public Prescription Prescription {get;set;}
        public IEnumerable<Prescription> Prescriptions {get;set;}
    }
}
</code>```

Here is my db context

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Systemz.Models;

namespace Systemz.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
        {
        }

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext>
    options)
        : base(options)
    {
    }

    public DbSet<Patient> Patients { get; set; }
    public DbSet<Address> Addresses { get; set; }
    public DbSet<PhoneNumber> PhoneNumbers { get; set; }
    public DbSet<Prescriber> Prescribers { get; set; }
    public DbSet<Prescription> Prescriptions { get; set; }
    protected override void OnModelCreating(ModelBuilder builder)
    {
         builder.Entity<PatientPrescriber>()
             .HasKey(bc => new { bc.PatientId, bc. PrescriberID });
         builder.Entity<PatientPrescriber>()
             .HasOne(bc => bc.Patient)
            .WithMany(b => b.PatientPrescribers)
            .HasForeignKey(bc => bc.PatientId);
        builder.Entity<PatientPrescriber>()
            .HasOne(bc => bc.Prescriber)
            .WithMany(c => c.PatientPrescribers)
            .HasForeignKey(bc => bc.PrescriberId);
        base.OnModelCreating(builder);
    }
}
</code>```

All of the values that are in IEnumerable<Prescription> Prescriptions {get;set;} are in a class called Prescription,
Here is the debug that shows a PatientId being accepted but all other properties are null
PAtientId, and Null Properties,
why are my values not being passed into the controller and not saving to the database?

答:
Here are the three observations I have made by reviewing portions of your code

In yourPost method of  CreatePrescription  its good practice to check ModelState.IsValid

```<code> [HttpPost]
 public IActionResult CreatePrescription(ViewModel model){
 if(ModelState.IsValid)
 {
   try
   { Prescription prescription = new Prescription{ ....   } }
 }
</code>```

In your Get method of CreatePrescription make sure you're returning model to View.

```<code>
 [HttpGet]
 public IActionResult CreatePrescription(int id)
 {
   //Any other business logic
    var model = new ViewModel();
    return View(model)
 }
</code>```

Namespace of your ViewModel class is defined as Systemz.Models,ViewModels with a comma and in Your View you have referred to it as Systemz.Models.ViewModels.ViewModel.

Body:
When I insert values into view model and debug, all of the values are null in the controller, I have an
[HttpGet]
public IActionResult CreatePrescription(int id) that gets the view model and then I have

[HttpPost]
public IActionResult CreatePrescription(ViewModel model){
        try
        {
            Prescription prescription = new Prescription
            {
                PatientId = model.Patient.Id,
                MedicationId = model.Prescription.MedicationId,
                RxNumber = model.Prescription.RxNumber,
                Frequency = model.Prescription.Frequency,
                Quantity = model.Prescription.Quantity,
                Copay = model.Prescription.Copay,
                RefillsRemaining = model.Prescription.RefillsRemaining,
                FolderStatusId = model.Prescription.FolderStatusId,
                PrescriberId = model.Prescription.PrescriberId,
                OriginalRxDate = model.Prescription.OriginalRxDate,
                DateFilled = model.Prescription.DateFilled,
                ExpiryDate = model.Prescription.ExpiryDate,
                DeliveryDate = model.Prescription.DeliveryDate,
                DeliveryTime = model.Prescription.DeliveryTime,
                BillDate = model.Prescription.BillDate,
                ApplicationUserId = user,
                CreatedOn = DateTime.Now,
                IsActive = true
            };

            _context.Add(prescription);

            _context.SaveChanges();

        }
        catch (Exception)
        {

            throw;
        }
        return View();
    }

Here is part of the view

@model Systemz.Models.ViewModels.ViewModel

    <form asp-action="CreatePrescription" asp-controller="Patients" method="post">
        <input asp-for="Prescription.Id" type="hidden" />
        <input asp-for="Patient.Id" type="hidden" />

                    <input asp-for="Prescription.RxNumber" class="form-control" />

                    <input asp-for="Prescription.Frequency" class="form-control" />

                    <input asp-for="Prescription.Quantity" class="form-control" />

And here is the class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Systemz.Models,ViewModels
{
    public class ViewModel
    {
        public Prescription Prescription {get;set;}
        public IEnumerable<Prescription> Prescriptions {get;set;}
    }
}

Here is my db context

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Systemz.Models;

namespace Systemz.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
        {
        }

        public ApplicationDbContext(DbContextOptions<ApplicationDbContext>
    options)
        : base(options)
    {
    }

    public DbSet<Patient> Patients { get; set; }
    public DbSet<Address> Addresses { get; set; }
    public DbSet<PhoneNumber> PhoneNumbers { get; set; }
    public DbSet<Prescriber> Prescribers { get; set; }
    public DbSet<Prescription> Prescriptions { get; set; }
    protected override void OnModelCreating(ModelBuilder builder)
    {
         builder.Entity<PatientPrescriber>()
             .HasKey(bc => new { bc.PatientId, bc. PrescriberID });
         builder.Entity<PatientPrescriber>()
             .HasOne(bc => bc.Patient)
            .WithMany(b => b.PatientPrescribers)
            .HasForeignKey(bc => bc.PatientId);
        builder.Entity<PatientPrescriber>()
            .HasOne(bc => bc.Prescriber)
            .WithMany(c => c.PatientPrescribers)
            .HasForeignKey(bc => bc.PrescriberId);
        base.OnModelCreating(builder);
    }
}

All of the values that are in IEnumerable<Prescription> Prescriptions {get;set;} are in a class called Prescription,
Here is the debug that shows a PatientId being accepted but all other properties are null
PAtientId, and Null Properties,
why are my values not being passed into the controller and not saving to the database?

Body:
Here are the three observations I have made by reviewing portions of your code

In yourPost method of  CreatePrescription  its good practice to check ModelState.IsValid

 [HttpPost]
 public IActionResult CreatePrescription(ViewModel model){
 if(ModelState.IsValid)
 {
   try
   { Prescription prescription = new Prescription{ ....   } }
 }

In your Get method of CreatePrescription make sure you're returning model to View.

 [HttpGet]
 public IActionResult CreatePrescription(int id)
 {
   //Any other business logic
    var model = new ViewModel();
    return View(model)
 }

Namespace of your ViewModel class is defined as Systemz.Models,ViewModels with a comma and in Your View you have referred to it as Systemz.Models.ViewModels.ViewModel.


问:
How do I add an OnClickListener And An Animation In A RecyclerView?
Okay so I have RecyclerView in which I retrieve some data from Firebase realtime database and I have a SearchView which filters my database. Now I want two things

I want an OnClicListener in my activity with which I could open a fragment by clicking on of the items.

I want to apply animation to my RecyclerView every time I scroll down.

Note: The OnClickListener should also work after filtering the data.

So far I am unable to achieve this. Here is my code

Adapter Class -> AdapterClass.java

public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>{
    ArrayList<Deal> list;

    public AdapterClass(ArrayList<Deal> list)
    {
        this.list = list;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_holder,viewGroup,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) {
        myViewHolder.id.setText(list.get(i).getDealId());
        myViewHolder.desc.setText(list.get(i).getDealDisc());

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    static class MyViewHolder extends RecyclerView.ViewHolder{

        TextView id,desc;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            id= itemView.findViewById(R.id.dealId);
            desc=itemView.findViewById(R.id.description);
        }
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>Model Class -> Deal.java

public class Deal {
    private String dealDisc;
    private String dealId;
    private String dealImage;
    private String price;

    public Deal() {
    }

    public Deal(String dealDisc, String dealId, String dealImage, String price) {
        this.dealDisc = dealDisc;
        this.dealId = dealId;
        this.dealImage = dealImage;
        this.price = price;
    }

    public String getDealDisc() {
        return dealDisc;
    }

    public void setDealDisc(String dealDisc) {
        this.dealDisc = dealDisc;
    }

    public String getDealId() {
        return dealId;
    }

    public void setDealId(String dealId) {
        this.dealId = dealId;
    }

    public String getDealImage() {
        return dealImage;
    }

    public void setDealImage(String dealImage) {
        this.dealImage = dealImage;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }
}</code>```

Main Activity -> MainActivity.java

public class MainActivity extends AppCompatActivity {

    DatabaseReference ref;
    ArrayList<Deal> list;
    RecyclerView recyclerView;
    SearchView searchView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ref= FirebaseDatabase.getInstance().getReference().child("rana");
        recyclerView = findViewById(R.id.rv);
        searchView=findViewById(R.id.searchView);

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (ref != null)
        {
            ref.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists())
                    {
                        list = new ArrayList<>();
                        for (DataSnapshot ds : dataSnapshot.getChildren())
                        {
                            list.add(ds.getValue(Deal.class));

                        }
                        AdapterClass adapterClass = new AdapterClass(list);
                        recyclerView.setAdapter(adapterClass);

                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

            if (searchView != null)
            {
                searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                    @Override
                    public boolean onQueryTextSubmit(String s) {
                        return false;
                    }

                    @Override
                    public boolean onQueryTextChange(String s) {
                        search(s);
                        return true;
                    }
                });
            }
        }
    }

    private void search(String str) {
        ArrayList<Deal> myList = new ArrayList<>();
        for (Deal object : list)
        {
            if (object.getDealDisc().toLowerCase().contains(str.toLowerCase()) || object.getDealId().toLowerCase().contains(str.toLowerCase()))
            {
                myList.add(object);
            }
        }

        AdapterClass adapterClass = new AdapterClass(myList);
        recyclerView.setAdapter(adapterClass);
    }
}```

Body:
Okay so I have RecyclerView in which I retrieve some data from Firebase realtime database and I have a SearchView which filters my database. Now I want two things

I want an OnClicListener in my activity with which I could open a fragment by clicking on of the items.

I want to apply animation to my RecyclerView every time I scroll down.

Note: The OnClickListener should also work after filtering the data.

So far I am unable to achieve this. Here is my code

Adapter Class -> AdapterClass.java

public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>{
    ArrayList<Deal> list;

    public AdapterClass(ArrayList<Deal> list)
    {
        this.list = list;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_holder,viewGroup,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) {
        myViewHolder.id.setText(list.get(i).getDealId());
        myViewHolder.desc.setText(list.get(i).getDealDisc());

    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    static class MyViewHolder extends RecyclerView.ViewHolder{

        TextView id,desc;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            id= itemView.findViewById(R.id.dealId);
            desc=itemView.findViewById(R.id.description);
        }
    }
}

Model Class -> Deal.java

public class Deal {
    private String dealDisc;
    private String dealId;
    private String dealImage;
    private String price;

    public Deal() {
    }

    public Deal(String dealDisc, String dealId, String dealImage, String price) {
        this.dealDisc = dealDisc;
        this.dealId = dealId;
        this.dealImage = dealImage;
        this.price = price;
    }

    public String getDealDisc() {
        return dealDisc;
    }

    public void setDealDisc(String dealDisc) {
        this.dealDisc = dealDisc;
    }

    public String getDealId() {
        return dealId;
    }

    public void setDealId(String dealId) {
        this.dealId = dealId;
    }

    public String getDealImage() {
        return dealImage;
    }

    public void setDealImage(String dealImage) {
        this.dealImage = dealImage;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }
}

Main Activity -> MainActivity.java

public class MainActivity extends AppCompatActivity {

    DatabaseReference ref;
    ArrayList<Deal> list;
    RecyclerView recyclerView;
    SearchView searchView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ref= FirebaseDatabase.getInstance().getReference().child("rana");
        recyclerView = findViewById(R.id.rv);
        searchView=findViewById(R.id.searchView);

    }

    @Override
    protected void onStart() {
        super.onStart();
        if (ref != null)
        {
            ref.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if (dataSnapshot.exists())
                    {
                        list = new ArrayList<>();
                        for (DataSnapshot ds : dataSnapshot.getChildren())
                        {
                            list.add(ds.getValue(Deal.class));

                        }
                        AdapterClass adapterClass = new AdapterClass(list);
                        recyclerView.setAdapter(adapterClass);

                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    Toast.makeText(MainActivity.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });

            if (searchView != null)
            {
                searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                    @Override
                    public boolean onQueryTextSubmit(String s) {
                        return false;
                    }

                    @Override
                    public boolean onQueryTextChange(String s) {
                        search(s);
                        return true;
                    }
                });
            }
        }
    }

    private void search(String str) {
        ArrayList<Deal> myList = new ArrayList<>();
        for (Deal object : list)
        {
            if (object.getDealDisc().toLowerCase().contains(str.toLowerCase()) || object.getDealId().toLowerCase().contains(str.toLowerCase()))
            {
                myList.add(object);
            }
        }

        AdapterClass adapterClass = new AdapterClass(myList);
        recyclerView.setAdapter(adapterClass);
    }
}

Body: myViewHolder.id.setonclickListener()


问:
What does this block of JS code mean?

Possible Duplicate:

  What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I came across a JS file that can be summarized to the code below:

```<code>   (function(window){
              // some codes here
                    })(window);
</code>```

I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?

Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?

答:
The first window is formal parameter, while the second one  is  actual parameter that actually invokes the function. This type of function called self-invoking functions.
The benefit of it is that wrapping functions this way doesn't clutter global scope..</p>

Title: What does this block of JS code mean?

Body:
Possible Duplicate:

  What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

I came across a JS file that can be summarized to the code below:

   (function(window){
              // some codes here
                    })(window);

I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?

Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?


问:
Convert factor value into numeric in a column of dataframe
I have a data frame that has two string characters stored in each row

```<code>s   ['64.0', '2']
a   ['63.0', '2']
b   ['63.0', '1']
</code>```

How to convert the first character string into numeric value,and omit the second character string,which results into data frame as follows :

```<code>s    64.0
a    63.0
b    63.0
</code>```

答:
We can use extract from tidyr

```<code>tidyr::extract(df, col2, into = c('col2', 'col3'), "(\\d+\\.\\d+).*(\\d)")

#  col1 col2 col3
#1    s 64.0    2
#2    a 63.0    2
#3    b 63.0    1
</code>```

You can then remove the columns which you don't need.

Body:
I have a data frame that has two string characters stored in each row

s   ['64.0', '2']
a   ['63.0', '2']
b   ['63.0', '1']

How to convert the first character string into numeric value,and omit the second character string,which results into data frame as follows :

s    64.0
a    63.0
b    63.0

Body:
We can use extract from tidyr

tidyr::extract(df, col2, into = c('col2', 'col3'), "(\\d+\\.\\d+).*(\\d)")

#  col1 col2 col3
#1    s 64.0    2
#2    a 63.0    2
#3    b 63.0    1

You can then remove the columns which you don't need.


问:
why test data is also involved in lightGBM train() and also used for calculate prediction error?
I would like to use lightGBM to do a machine learning model training.

I checked the example at https://github.com/microsoft/LightGBM/blob/master/examples/python-guide/advanced_example.py

I have some questions about the correctness of the code.

(1) What kind models can be created from lightgbm.train() ?

        https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.train.html
    It is a regressor or classifier ?

(2) Why test dataset is also used for training ? How this can assure that the test results are still valid ?

```<code>  # line 31
  lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train,
                   weight=W_test, free_raw_data=False)
  # line 52
  gbm = lgb.train(params,
            lgb_train,
            num_boost_round=10,
            valid_sets=lgb_train,  # eval training data with test data !!!
            feature_name=feature_name,
            categorical_feature=[21])

   # line 84
  y_pred = bst.predict(X_test) # why x_test is also used to predict y? X_test has been involved in training the model !!!
</code>```

Thanks

答:
You can train both regression and classifier models using lgb.train. It depends on the parameters, which you define, namely objective.

Test set (valid_sets) is used only for validation, it isn't used for training.

Body:
I would like to use lightGBM to do a machine learning model training.

I checked the example at https://github.com/microsoft/LightGBM/blob/master/examples/python-guide/advanced_example.py

I have some questions about the correctness of the code.

(1) What kind models can be created from lightgbm.train() ?

        https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.train.html
    It is a regressor or classifier ?

(2) Why test dataset is also used for training ? How this can assure that the test results are still valid ?

  # line 31
  lgb_eval = lgb.Dataset(X_test, y_test, reference=lgb_train,
                   weight=W_test, free_raw_data=False)
  # line 52
  gbm = lgb.train(params,
            lgb_train,
            num_boost_round=10,
            valid_sets=lgb_train,  # eval training data with test data !!!
            feature_name=feature_name,
            categorical_feature=[21])

   # line 84
  y_pred = bst.predict(X_test) # why x_test is also used to predict y? X_test has been involved in training the model !!!

Thanks