问:
Handle multiple button views
My question is about how to control the background and text color of multiple buttons when you read a button click in MVVM. To make my question a bit clear please have a look at the UI I have attached.

I have already implemented this on code behind i.e on button click, I am handling all of the buttons separately. The original background and text color are white and black respectively and when you click on any other button except 1W that button will be highlighted.
In the next image, 3M is clicked

```<code>            lbl3M.BackgroundColor = Color.FromHex(defaultColor);
            lbl3M.TextColor = Color.White;
            if (lbl1M.BackgroundColor != Color.White)
            {
                lbl1M.BackgroundColor = Color.White;
                lbl1M.TextColor = Color.Black;
            }
            if (lbl1W.BackgroundColor != Color.White)
            {
                lbl1W.BackgroundColor = Color.White;
                lbl1W.TextColor = Color.Black;
            }
            if (lbl6M.BackgroundColor != Color.White)
            {
                lbl6M.BackgroundColor = Color.White;
                lbl6M.TextColor = Color.Black;
            }
            if (lbl1Y.BackgroundColor != Color.White)
            {
                lbl1Y.BackgroundColor = Color.White;
                lbl1Y.TextColor = Color.Black;
            }
</code>```

I have done this on each button clicked.

I know this approach is not cost-effective and I want to learn how to implement in MVVM way

EDIT:
I have created a function which reset all the buttons to Original UI and change the UI on button clicked

```<code> void ResetButtonUI()
    {
        lbl1W.BackgroundColor = Color.White;
        lbl1W.TextColor = Color.Black;
        lbl1M.BackgroundColor = Color.White;
        lbl1M.TextColor = Color.Black;
        lbl3M.BackgroundColor = Color.White;
        lbl3M.TextColor = Color.Black;
        lbl6M.BackgroundColor = Color.White;
        lbl6M.TextColor = Color.Black;
        lbl1Y.BackgroundColor = Color.White;
        lbl1Y.TextColor = Color.Black;
    }
</code>```

and on each button i have this logic

```<code>         ResetButtonUI();
         button.BackgroundColor = Color.FromHex(defaultColor);
         button.TextColor = Color.White;
</code>```

答:
Compared with listview, CollectionView is more suitable for your needs. Listview is more complicated to place horizontally.

Here is running GIF.

Here is code.

```<code>     <CollectionView ItemsSource="{Binding Persons}" HeightRequest="50" SelectionMode="Single" SelectionChanged="CollectionView_SelectionChanged_1" >
            <CollectionView.ItemsLayout>
                <LinearItemsLayout   Orientation="Horizontal" />
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>

                    <StackLayout HorizontalOptions="Center"  VerticalOptions="Center" >
                        <Label Text="{Binding FirstName}" FontSize="20"  Margin="20,10,20,0"/>
                    </StackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
</code>```

Background code.

```<code>   BindingContext = new HomepageViewModel();
</code>```

public List Persons { get; set; }

```<code>    public HomepageViewModel() {

        Persons = new List<Person>();
        Persons.Add(new Person() { FirstName = "1W" });
        Persons.Add(new Person() { FirstName = "1M" });
        Persons.Add(new Person() { FirstName = "3M" });
        Persons.Add(new Person() { FirstName = "6M" });
        Persons.Add(new Person() { FirstName = "1Y" });
    }
</code>```

}
If you want to change the selectItem color, here is a link about it.
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/collectionview/selection#change-selected-item-color

Title: Handle multiple button views

Body:
My question is about how to control the background and text color of multiple buttons when you read a button click in MVVM. To make my question a bit clear please have a look at the UI I have attached.

I have already implemented this on code behind i.e on button click, I am handling all of the buttons separately. The original background and text color are white and black respectively and when you click on any other button except 1W that button will be highlighted.
In the next image, 3M is clicked

            lbl3M.BackgroundColor = Color.FromHex(defaultColor);
            lbl3M.TextColor = Color.White;
            if (lbl1M.BackgroundColor != Color.White)
            {
                lbl1M.BackgroundColor = Color.White;
                lbl1M.TextColor = Color.Black;
            }
            if (lbl1W.BackgroundColor != Color.White)
            {
                lbl1W.BackgroundColor = Color.White;
                lbl1W.TextColor = Color.Black;
            }
            if (lbl6M.BackgroundColor != Color.White)
            {
                lbl6M.BackgroundColor = Color.White;
                lbl6M.TextColor = Color.Black;
            }
            if (lbl1Y.BackgroundColor != Color.White)
            {
                lbl1Y.BackgroundColor = Color.White;
                lbl1Y.TextColor = Color.Black;
            }

I have done this on each button clicked.

I know this approach is not cost-effective and I want to learn how to implement in MVVM way

EDIT:
I have created a function which reset all the buttons to Original UI and change the UI on button clicked

 void ResetButtonUI()
    {
        lbl1W.BackgroundColor = Color.White;
        lbl1W.TextColor = Color.Black;
        lbl1M.BackgroundColor = Color.White;
        lbl1M.TextColor = Color.Black;
        lbl3M.BackgroundColor = Color.White;
        lbl3M.TextColor = Color.Black;
        lbl6M.BackgroundColor = Color.White;
        lbl6M.TextColor = Color.Black;
        lbl1Y.BackgroundColor = Color.White;
        lbl1Y.TextColor = Color.Black;
    }

and on each button i have this logic

         ResetButtonUI();
         button.BackgroundColor = Color.FromHex(defaultColor);
         button.TextColor = Color.White;

Body:
Compared with listview, CollectionView is more suitable for your needs. Listview is more complicated to place horizontally.

Here is running GIF.

Here is code.

     <CollectionView ItemsSource="{Binding Persons}" HeightRequest="50" SelectionMode="Single" SelectionChanged="CollectionView_SelectionChanged_1" >
            <CollectionView.ItemsLayout>
                <LinearItemsLayout   Orientation="Horizontal" />
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>

                    <StackLayout HorizontalOptions="Center"  VerticalOptions="Center" >
                        <Label Text="{Binding FirstName}" FontSize="20"  Margin="20,10,20,0"/>
                    </StackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

Background code.

   BindingContext = new HomepageViewModel();

public List Persons { get; set; }

    public HomepageViewModel() {

        Persons = new List<Person>();
        Persons.Add(new Person() { FirstName = "1W" });
        Persons.Add(new Person() { FirstName = "1M" });
        Persons.Add(new Person() { FirstName = "3M" });
        Persons.Add(new Person() { FirstName = "6M" });
        Persons.Add(new Person() { FirstName = "1Y" });
    }

}
If you want to change the selectItem color, here is a link about it.
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/collectionview/selection#change-selected-item-color


来源: stackexchange

问:
How to make absolute positioned element to don't show scrollbars in the parent?

.parent {
  width: 300px;
  height: 300px;
  background: red;
  position: relative;

}

.child-green {
  position: absolute;
  top: 10px;
  left: 250px;
  width: 100px;
  height: 100px;
  background: green;
}

.child-blue {
  background: blue;
  margin: 5px;
  width: 100px;
  height: 500px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='parent'>
  <div class='child-green'></div>
  <div class='child-blue'></div>
</div></code>```

Code example: https://codepen.io/asad111/pen/jOPqpaj

All elements must be in this location but no horizontal scroll bar for the green element (of course this can't be just overflow-x hidden or a hack like that)

I can't take the overflow: auto from the parent, otherwise it will not scroll for elements in the flow. For example the blue box needs to force the parent to scroll.

Note: I really need the child to go out the parent bounds I'm doing an animation of things moving on the screen and needs to go edge to edge.

So the question is, why position absolute element, that is not supposed to take space... well, takes space? And how can I fix it?

One solution is to wrap again:

https://codepen.io/asad111/pen/jOPqvYV

.parent {
  width: 300px;
  height: 300px;
  background: red;
  position: relative;
  overflow: auto;
}

.child-wrapper {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.child-green {
  position: absolute;
  top: 10px;
  left: 250px;
  width: 100px;
  height: 100px;
  background: green;
}

.child-blue {
  background: blue;
  margin: 5px;
  width: 100px;
  height: 500px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='parent'>
  <div class='child-wrapper'>
    <div class='child-green'></div>
  </div>
  <div class='child-blue'></div>
</div></code>```

Any other ideas?

答:
the child element has left 250px + width 100px, so together there is 350px in parent which is 300px wide, that's why it shows the scrollbar.
Make it left 200px, then the scrollbar will dissapear.</p>

ContentLicense: CC BY-SA 4.0

Body:
.parent {
  width: 300px;
  height: 300px;
  background: red;
  position: relative;

}

.child-green {
  position: absolute;
  top: 10px;
  left: 250px;
  width: 100px;
  height: 100px;
  background: green;
}

.child-blue {
  background: blue;
  margin: 5px;
  width: 100px;
  height: 500px;
}

Code example: https://codepen.io/asad111/pen/jOPqpaj

All elements must be in this location but no horizontal scroll bar for the green element (of course this can't be just overflow-x hidden or a hack like that)

I can't take the overflow: auto from the parent, otherwise it will not scroll for elements in the flow. For example the blue box needs to force the parent to scroll.

Note: I really need the child to go out the parent bounds I'm doing an animation of things moving on the screen and needs to go edge to edge.

So the question is, why position absolute element, that is not supposed to take space... well, takes space? And how can I fix it?

One solution is to wrap again:

https://codepen.io/asad111/pen/jOPqvYV

.parent {
  width: 300px;
  height: 300px;
  background: red;
  position: relative;
  overflow: auto;
}

.child-wrapper {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.child-green {
  position: absolute;
  top: 10px;
  left: 250px;
  width: 100px;
  height: 100px;
  background: green;
}

.child-blue {
  background: blue;
  margin: 5px;
  width: 100px;
  height: 500px;
}

Any other ideas?


问:
Merge indexes using pandas
I have a dataframe that looks like this

```<code>>>> df
          item  count
id  month
12  1     1351  19
          585   11
    2     1350  2
          140   1
</code>```

and another that has something like

```<code>>>> usermap
   id   age   gender
0  2    25    m
1  12   40    f
</code>```

end result should be:

```<code>>>> df_merged
id  age  gender month  item  count
12  40   f       1     1351  19
                       585   11
                 2     1350  2
                       140   1
</code>```

I'm thinking I could do:

```<code>df1 = df.reset_index()
df_merged = pd.merge(df1, usermap, on='id', how='left')
df_merged = df_merged.set_index(['id','age','gender','month'])
</code>```

but is there any better solution, especially for large dataframes?

答:
One idea with DataFrame.join, DataFrame.set_index and DataFrame.reorder_levels:

```<code>df = (df.join(usermap.set_index('id'))
        .set_index(['age','gender'], append=True)
        .reorder_levels(['id','age','gender','month']))
print (df)
                     item  count
id age gender month
12 40  f      1      1351     19
              1       585     11
              2      1350      2
              2       140      1
</code>```

Title: Merge indexes using pandas

Body:
I have a dataframe that looks like this

>>> df
          item  count
id  month
12  1     1351  19
          585   11
    2     1350  2
          140   1

and another that has something like

>>> usermap
   id   age   gender
0  2    25    m
1  12   40    f

end result should be:

>>> df_merged
id  age  gender month  item  count
12  40   f       1     1351  19
                       585   11
                 2     1350  2
                       140   1

I'm thinking I could do:

df1 = df.reset_index()
df_merged = pd.merge(df1, usermap, on='id', how='left')
df_merged = df_merged.set_index(['id','age','gender','month'])

but is there any better solution, especially for large dataframes?

Body:
One idea with DataFrame.join, DataFrame.set_index and DataFrame.reorder_levels:

df = (df.join(usermap.set_index('id'))
        .set_index(['age','gender'], append=True)
        .reorder_levels(['id','age','gender','month']))
print (df)
                     item  count
id age gender month
12 40  f      1      1351     19
              1       585     11
              2      1350      2
              2       140      1


问:
Why OAuth2 is not allowing to contain fragment identifier in redirect URI?
According to the OAuth2.0 spec, the redirect URI should not contain a fragment identifier.

The redirection endpoint URI MUST be an absolute URI as defined by
[RFC3986] Section 4.3. The endpoint URI MAY include an
"application/x-www-form-urlencoded" formatted (per Appendix B) query
component ([RFC3986] Section 3.4), which MUST be retained when adding
additional query parameters. The endpoint URI MUST NOT include a
fragment component.

Are there any specific reasons for why the spec has made such limitations?

Thanks in advance!

答: I think the reason against the fragment part is its use in the Implicit flow. Since the syntax of the URL fragment part is not standardized, the OAuth2 server would not know how to add its information (access_token and such) to the existing fragment value of the redirect URL.</p>


问:
Trouble With Rhyming Algorithm Scala
I want to make a method that takes two List of strings representing the sounds(phonemes & vowels) of two words as parameters. The function of this method is to determine whether or not the words rhyme based on the two sounds.

Definition of a rhyme: The words rhymes if the last vowel(inclusive) and after are the same. Words will rhyme even if the last vowel sounds have different stress. Only vowels will have stress levels(numbers)

My approach so far is to reverse the list so that the sounds are in reverse order and then add everything from the start of the line to the first vowel(inclusive). Then compare the two list to see if they equal. Please apply basic code, Im only at elementary level of scala. Just finished learning program execution.

Ex1: two words GEE and NEE will rhyme because GEE sound (“JH”,”IY1”) becomes (”IY1”,”JH”) and NEE sound (“N”,”IY1) becomes (”IY1”, “N”) since they have the same vowel everything else after should not be considered any more.

Ex2: two words GEE and JEEP will not rhyme because GEE sound (“JH”,”IY1”) becomes (”IY1”,”JH”) and JEEP sound (“JH”,”IY1”,”P”) becomes (”P”,”IY1”,”JH”) since the first sound in GEE is a vowel it’s being compared to “P” and “IY1” in JEEP.

Ex3: two words HALF and GRAPH will rhyme because HALF sound(“HH”,”AE1”,”F”) becomes (“F”,”AE1”,”HH”) and GRAPH sound (“G”,”R”,”AE2”,”F”) become (“F”,”AE2”,”R”,”G”) in this case although the first vowel have different stress(numbers) we ignore the stress since the vowels are the same.

```<code>
def isRhymeSounds(soundList1: List[String], soundList2: List[String]): Boolean={
    val revSound1 = soundList1.reverse
    val revSound2 = soundList2.reverse
    var revSoundList1:List[String] = List()
    var revSoundList2:List[String] = List()
    for(sound1 <- revSound1) {
      if(sound1.length >= 3) {
        val editVowel1 = sound1.substring(0,2)
        revSoundList1 = revSoundList1 :+ editVowel1
      }
      else {
        revSoundList1 = revSoundList1 :+ sound1
      }
    }
    for(sound2 <- revSound2) {
      if(sound2.length >= 3) {
        val editVowel2 = sound2.substring(0, 2)
        revSoundList2 = revSoundList2 :+ editVowel2
      }
      else {
        revSoundList2 = revSoundList2 :+ sound2
      }
    }
    if(revSoundList1 == revSoundList2){
      true
    }
    else{
      false
    }
  }
</code>```

答:
I don't think reversing is necessary.

```<code>def isRhyme(sndA :List[String], sndB :List[String]) :Boolean = {
  val vowel = "[AEIOUY]+".r
  sndA.foldLeft(""){case (res, s) => vowel.findPrefixOf(s).getOrElse(res+s)} ==
    sndB.foldLeft(""){case (res, s) => vowel.findPrefixOf(s).getOrElse(res+s)}
}
</code>```

explanation

"[AEIOUY]+".r - This is a Regular Expression (that's the .r part) that means "a String of one or more of these characters." In other words, any combination of capital letter vowels.

findPrefixOf() - This returns the first part of the test string that matches the regular expression. So vowel.findPrefixOf("AY2") returns Some("AY") because the first two letters match the regular expression. And vowel.findPrefixOf("OFF") returns Some("O") because only the first letter matches the regular expression. But vowel.findPrefixOf("BAY") returns None because the string does not start with any of the specified characters.

getOrElse() - This unwraps an Option. So Some("AY").getOrElse("X") returns "AY", and Some("O").getOrElse("X") returns "O", but None.getOrElse("X") returns "X" because there's nothing inside a None value so we go with the OrElse default return value.

foldLeft()() - This takes a collection of elements and, starting from the "left", it "folds" them in on each other until a final result is obtained.

So, consider how List("HH", "AE1", "F", "JH", "IY1", "P") would be processed.

```<code>res    s     result
===    ===   ======
""     HH    ""+HH   //s doesn't match the RE so default res+s
HH     AE1   AE      //s does match the RE, use only the matching part
AE     F     AE+F    //res+s
AEF    JH    AEF+JH  //res+s
AEFJH  IY1   IY      //only the matching part
IY     P     IY+P    //res+s

final result: "IYP"
</code>```

Title: Trouble With Rhyming Algorithm Scala

Body:
I want to make a method that takes two List of strings representing the sounds(phonemes & vowels) of two words as parameters. The function of this method is to determine whether or not the words rhyme based on the two sounds.

Definition of a rhyme: The words rhymes if the last vowel(inclusive) and after are the same. Words will rhyme even if the last vowel sounds have different stress. Only vowels will have stress levels(numbers)

My approach so far is to reverse the list so that the sounds are in reverse order and then add everything from the start of the line to the first vowel(inclusive). Then compare the two list to see if they equal. Please apply basic code, Im only at elementary level of scala. Just finished learning program execution.

Ex1: two words GEE and NEE will rhyme because GEE sound (“JH”,”IY1”) becomes (”IY1”,”JH”) and NEE sound (“N”,”IY1) becomes (”IY1”, “N”) since they have the same vowel everything else after should not be considered any more.

Ex2: two words GEE and JEEP will not rhyme because GEE sound (“JH”,”IY1”) becomes (”IY1”,”JH”) and JEEP sound (“JH”,”IY1”,”P”) becomes (”P”,”IY1”,”JH”) since the first sound in GEE is a vowel it’s being compared to “P” and “IY1” in JEEP.

Ex3: two words HALF and GRAPH will rhyme because HALF sound(“HH”,”AE1”,”F”) becomes (“F”,”AE1”,”HH”) and GRAPH sound (“G”,”R”,”AE2”,”F”) become (“F”,”AE2”,”R”,”G”) in this case although the first vowel have different stress(numbers) we ignore the stress since the vowels are the same.

def isRhymeSounds(soundList1: List[String], soundList2: List[String]): Boolean={
    val revSound1 = soundList1.reverse
    val revSound2 = soundList2.reverse
    var revSoundList1:List[String] = List()
    var revSoundList2:List[String] = List()
    for(sound1 <- revSound1) {
      if(sound1.length >= 3) {
        val editVowel1 = sound1.substring(0,2)
        revSoundList1 = revSoundList1 :+ editVowel1
      }
      else {
        revSoundList1 = revSoundList1 :+ sound1
      }
    }
    for(sound2 <- revSound2) {
      if(sound2.length >= 3) {
        val editVowel2 = sound2.substring(0, 2)
        revSoundList2 = revSoundList2 :+ editVowel2
      }
      else {
        revSoundList2 = revSoundList2 :+ sound2
      }
    }
    if(revSoundList1 == revSoundList2){
      true
    }
    else{
      false
    }
  }

Body:
I don't think reversing is necessary.

def isRhyme(sndA :List[String], sndB :List[String]) :Boolean = {
  val vowel = "[AEIOUY]+".r
  sndA.foldLeft(""){case (res, s) => vowel.findPrefixOf(s).getOrElse(res+s)} ==
    sndB.foldLeft(""){case (res, s) => vowel.findPrefixOf(s).getOrElse(res+s)}
}

explanation

"[AEIOUY]+".r - This is a Regular Expression (that's the .r part) that means "a String of one or more of these characters." In other words, any combination of capital letter vowels.

findPrefixOf() - This returns the first part of the test string that matches the regular expression. So vowel.findPrefixOf("AY2") returns Some("AY") because the first two letters match the regular expression. And vowel.findPrefixOf("OFF") returns Some("O") because only the first letter matches the regular expression. But vowel.findPrefixOf("BAY") returns None because the string does not start with any of the specified characters.

getOrElse() - This unwraps an Option. So Some("AY").getOrElse("X") returns "AY", and Some("O").getOrElse("X") returns "O", but None.getOrElse("X") returns "X" because there's nothing inside a None value so we go with the OrElse default return value.

foldLeft()() - This takes a collection of elements and, starting from the "left", it "folds" them in on each other until a final result is obtained.

So, consider how List("HH", "AE1", "F", "JH", "IY1", "P") would be processed.

res    s     result
===    ===   ======
""     HH    ""+HH   //s doesn't match the RE so default res+s
HH     AE1   AE      //s does match the RE, use only the matching part
AE     F     AE+F    //res+s
AEF    JH    AEF+JH  //res+s
AEFJH  IY1   IY      //only the matching part
IY     P     IY+P    //res+s

final result: "IYP"


问:
Cannot include boost.asio
I am trying to include boost.asio library, but whenever I do that I get this error message:

```<code> undefined reference to `boost::system::generic_category()'
</code>```

I can include any other boost library, but not this one.

I tried to link boost.System like this:

```<code>icpc -lboost_system main.cpp -o out.o
</code>```

It gave me this message

```<code>ld: cannot find -lboost_system
</code>```

答: As eluded to by @Space_C0wb0y, you need to either build Boost.System or use its correct name for linking (e.g. -lboost_system-mt).</p>

ContentLicense: CC BY-SA 3.0

Title: Cannot include boost.asio

Body:
I am trying to include boost.asio library, but whenever I do that I get this error message:

 undefined reference to `boost::system::generic_category()'

I can include any other boost library, but not this one.

I tried to link boost.System like this:

icpc -lboost_system main.cpp -o out.o

It gave me this message

ld: cannot find -lboost_system


问:
Divide 2 columns into 4 based on odd and even
I want to divide 2 columns into 4 based on odd and even. I have a table

```<code>INSERT INTO @tab
VALUES ('test', 'desc'), ('test1', 'desc1'), ('test2', 'desc2'),
       ('test3', 'desc3'), ('test4', 'desc4')
</code>```

I tried the following query:-

```<code>SELECT
    CASE
       WHEN A.RNK  % 2 = 1
          THEN Heading
    END AS Headingodds,
    CASE
       WHEN A.RNK  % 2 = 0
          THEN Heading
    END AS Headingeven,
    CASE
       WHEN A.RNK  % 2 = 1
          THEN A.[Description]
    END AS Descriptionodds,
    CASE
       WHEN A.RNK  % 2 = 0
          THEN A.[Description]
    END AS Descriptioneven
FROM
    (SELECT
         Id, Heading, [Description],
         ROW_NUMBER() OVER (ORDER BY Id) AS RNK
     FROM
         @tab) A
</code>```

Results I am getting from the query is:-

But I want the result in following format:-

```<code>DECLARE @tab1 TABLE(Headingodd VARCHAR(100), Headingeven VARCHAR(100), Descriptionodd VARCHAR(100), Descriptioneven VARCHAR(100))

INSERT INTO @tab1
VALUES ('test', 'test1', 'desc', 'desc1'),
       ('test2', 'test3', 'desc2', 'desc3'),
       ('test4', null, 'desc4', null)

SELECT * FROM @tab1
</code>```

答:
You need to generate the odd and even headings and descriptions separately and then you can JOIN them together on matching row numbers:

```<code>WITH A AS (
  SELECT Id, Heading, [Description],
         ROW_NUMBER() OVER (ORDER BY Id) AS RNK
  FROM tab
),
ODD AS (
  SELECT Heading, [Description],
         (RNK - 1) / 2 AS RN
  FROM A
  WHERE RNK % 2 = 1
),
EVEN AS (
  SELECT Heading, [Description],
         (RNK - 1) / 2 AS RN
  FROM A
  WHERE RNK % 2 = 0
)
SELECT o.Heading AS Headingodds,
       e.Heading AS Headingeven,
       o.Description AS Descriptionodds,
       e.Description AS Descriptioneven
FROM ODD o
LEFT JOIN EVEN e ON e.RN = o.RN
ORDER BY o.RN
</code>```

Output:

```<code>Headingodds     Headingeven     Descriptionodds     Descriptioneven
test            test1           desc                desc1
test2           test3           desc2               desc3
test4                           desc4
</code>```

Demo on dbfiddle

Body:
I want to divide 2 columns into 4 based on odd and even. I have a table

INSERT INTO @tab
VALUES ('test', 'desc'), ('test1', 'desc1'), ('test2', 'desc2'),
       ('test3', 'desc3'), ('test4', 'desc4')

I tried the following query:-

SELECT
    CASE
       WHEN A.RNK  % 2 = 1
          THEN Heading
    END AS Headingodds,
    CASE
       WHEN A.RNK  % 2 = 0
          THEN Heading
    END AS Headingeven,
    CASE
       WHEN A.RNK  % 2 = 1
          THEN A.[Description]
    END AS Descriptionodds,
    CASE
       WHEN A.RNK  % 2 = 0
          THEN A.[Description]
    END AS Descriptioneven
FROM
    (SELECT
         Id, Heading, [Description],
         ROW_NUMBER() OVER (ORDER BY Id) AS RNK
     FROM
         @tab) A

Results I am getting from the query is:-

But I want the result in following format:-

DECLARE @tab1 TABLE(Headingodd VARCHAR(100), Headingeven VARCHAR(100), Descriptionodd VARCHAR(100), Descriptioneven VARCHAR(100))

INSERT INTO @tab1
VALUES ('test', 'test1', 'desc', 'desc1'),
       ('test2', 'test3', 'desc2', 'desc3'),
       ('test4', null, 'desc4', null)

SELECT * FROM @tab1

Body:
You need to generate the odd and even headings and descriptions separately and then you can JOIN them together on matching row numbers:

WITH A AS (
  SELECT Id, Heading, [Description],
         ROW_NUMBER() OVER (ORDER BY Id) AS RNK
  FROM tab
),
ODD AS (
  SELECT Heading, [Description],
         (RNK - 1) / 2 AS RN
  FROM A
  WHERE RNK % 2 = 1
),
EVEN AS (
  SELECT Heading, [Description],
         (RNK - 1) / 2 AS RN
  FROM A
  WHERE RNK % 2 = 0
)
SELECT o.Heading AS Headingodds,
       e.Heading AS Headingeven,
       o.Description AS Descriptionodds,
       e.Description AS Descriptioneven
FROM ODD o
LEFT JOIN EVEN e ON e.RN = o.RN
ORDER BY o.RN

Output:

Headingodds     Headingeven     Descriptionodds     Descriptioneven
test            test1           desc                desc1
test2           test3           desc2               desc3
test4                           desc4

Demo on dbfiddle


答:
Try this code

.child {
  position: absolute;
  top: 10px;
  left: 0;
  width: 100px;
  height: 100px;
  background: green;
}
```

Title: How to make absolute positioned element to don't show scrollbars in the parent?


问:
Why am I getting a segmention fault?
For my class, we are using two compilers, xcode and codeboard, where codeboard is the more rigorous of the two and has a list of preset asserts to test your code. In my code for function a, I have nested loops, where I want i to always be one ahead of k. It works fine in xcode, but gives me a segmentation fault on codeboard.

```<code>for (int k = 0; k <= n-2; k++) {
    for (int i = k+1; i <= n-1; i++) {
        if (array[k] == array[i])
</code>```

What's strange is if I use k++ or ++k instead of k+1, it won't result in a segmentation fault, but my code won't pass all the asserts. I thought they were supposed to be the same thing?

What's even more strange is if I use k+1 in function b, it doesn't result in an error in codeboard.

```<code>for (int k = 0; k <= n-1; k++) {
    for (int i = k+1; i <= n-1; i++) {
        if (array[k] > array[i])
</code>```

Basically, what is happening here?

Edit: So, what I'm getting from everyone is that when I use i = k+1 in the inner loop, it increases the k value in the outer loop. Like, if k=1, i=2, then when it goes back to the outer loop, k=3. If that's the case, how would I get i from staying ahead of k?

Edit: Please ignore the k++ and k+1 part of my question, that was not really my main issue, just a side thing that kind of confused me, but I get the difference now. I'd delete that part from my post, but I'm pretty sure that's not allowed. My main question is how to keep my i value 1 greater than my k value.

In the following code, the goal is if any of the array values are the same, it should cout true at some point. In regards to reproducible results:

```<code>string a[3] = {"aaa", "bbbb", "cccc"};
int n = 3;
for (int k = 0; k <= n-2; k++) {
    int b = 0;
    for (int i = k+1; i <= n-1; i++) {
        if (a[k] == a[i])
            b++;
    }
    if (b != 0) {
        cout << "true" << endl;
        break;
    }
    else
        cout << "false" << endl;
}
</code>```

答:
k++ and k+1 are not the same.

If you use k++ instead of k+1 inside the loop in the code you have shown, you are actually performing two increments on the variable k, which is usually not what you want in the control variable of a loop.

K+1 does not alter the value of k.

k++ increments k after using its value.

++k increments k before using its value.

So basically what is happening is that every time you start the inner loop, k gets incremented. But in the last round of the external loop, when k is equal to n-1, you perform another increment, which sets k to n, and this is most certainly not what you wanted.

Title: Why am I getting a segmention fault?

Body:
For my class, we are using two compilers, xcode and codeboard, where codeboard is the more rigorous of the two and has a list of preset asserts to test your code. In my code for function a, I have nested loops, where I want i to always be one ahead of k. It works fine in xcode, but gives me a segmentation fault on codeboard.

for (int k = 0; k <= n-2; k++) {
    for (int i = k+1; i <= n-1; i++) {
        if (array[k] == array[i])

What's strange is if I use k++ or ++k instead of k+1, it won't result in a segmentation fault, but my code won't pass all the asserts. I thought they were supposed to be the same thing?

What's even more strange is if I use k+1 in function b, it doesn't result in an error in codeboard.

for (int k = 0; k <= n-1; k++) {
    for (int i = k+1; i <= n-1; i++) {
        if (array[k] > array[i])

Basically, what is happening here?

Edit: So, what I'm getting from everyone is that when I use i = k+1 in the inner loop, it increases the k value in the outer loop. Like, if k=1, i=2, then when it goes back to the outer loop, k=3. If that's the case, how would I get i from staying ahead of k?

Edit: Please ignore the k++ and k+1 part of my question, that was not really my main issue, just a side thing that kind of confused me, but I get the difference now. I'd delete that part from my post, but I'm pretty sure that's not allowed. My main question is how to keep my i value 1 greater than my k value.

In the following code, the goal is if any of the array values are the same, it should cout true at some point. In regards to reproducible results:

string a[3] = {"aaa", "bbbb", "cccc"};
int n = 3;
for (int k = 0; k <= n-2; k++) {
    int b = 0;
    for (int i = k+1; i <= n-1; i++) {
        if (a[k] == a[i])
            b++;
    }
    if (b != 0) {
        cout << "true" << endl;
        break;
    }
    else
        cout << "false" << endl;
}


问:
Possible to access SocketCan using dotnet core Socket in Linux?
I'm using dotnet core on a Linux platform and would like to set up communication with a CAN device. SocketCan is available on the Linux platform, but is there a way to use the  UnixDomainSocketEndPoint and Socket classes in dotnet core to access SocketCan directly?

When trying to create an instance of Socket with this test program on Linux (Debian9) environment:

using System;
using System.Net.Sockets;

namespace SocketScan
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Scan for available ProtocolType values");

            ScanForProtocolTypes(SocketType.Stream);
            ScanForProtocolTypes(SocketType.Raw);
        }

        private static void ScanForProtocolTypes(SocketType socketType)
        {
            for (var i = 0; i < 1000000; i++)
            {
                try
                {
                    var socket = new Socket(AddressFamily.Unix, socketType, (ProtocolType)i);
                    Console.WriteLine($"Succeeded creating socket with SocketType={socketType} ProtocolType={((ProtocolType)i)}");
                }
                catch (SocketException)
                { }
            }
        }
    }
}
```

<p>The output is:</p>

```$ dotnet run SocketTest.csproj
Scan for available ProtocolType values
Succeeded creating socket with SocketType=Stream ProtocolType=Unspecified
Succeeded creating socket with SocketType=Stream ProtocolType=Icmp
Succeeded creating socket with SocketType=Raw ProtocolType=Unspecified
Succeeded creating socket with SocketType=Raw ProtocolType=Icmp
```

What values for the enums AdressFamily, SocketType and ProtocolType will match a SocketCan socket?

答:
On .NET Core 3.0+ there are AddressFamily.ControllerAreaNetwork and ProtocolFamily.ControllerAreaNetwork, and SocketCAN needs a SocketType.Raw to work.
See the associated Pull Request at https://github.com/dotnet/corefx/pull/37315

Body:
I'm using dotnet core on a Linux platform and would like to set up communication with a CAN device. SocketCan is available on the Linux platform, but is there a way to use the  UnixDomainSocketEndPoint and Socket classes in dotnet core to access SocketCan directly?

When trying to create an instance of Socket with this test program on Linux (Debian9) environment:

using System;
using System.Net.Sockets;

namespace SocketScan
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Scan for available ProtocolType values");

            ScanForProtocolTypes(SocketType.Stream);
            ScanForProtocolTypes(SocketType.Raw);
        }

        private static void ScanForProtocolTypes(SocketType socketType)
        {
            for (var i = 0; i < 1000000; i++)
            {
                try
                {
                    var socket = new Socket(AddressFamily.Unix, socketType, (ProtocolType)i);
                    Console.WriteLine($"Succeeded creating socket with SocketType={socketType} ProtocolType={((ProtocolType)i)}");
                }
                catch (SocketException)
                { }
            }
        }
    }
}

The output is:

$ dotnet run SocketTest.csproj
Scan for available ProtocolType values
Succeeded creating socket with SocketType=Stream ProtocolType=Unspecified
Succeeded creating socket with SocketType=Stream ProtocolType=Icmp
Succeeded creating socket with SocketType=Raw ProtocolType=Unspecified
Succeeded creating socket with SocketType=Raw ProtocolType=Icmp

What values for the enums AdressFamily, SocketType and ProtocolType will match a SocketCan socket?


问:
how to text align center for the text with space and line break
I have the following example below:

.wrapper {
  text-align: center;
  border: 1px solid red;
  background-color: white;
  color: black;
  width: 240px;
  height: 200px;
  font-size: 36px;
  line-height: 43px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea class="wrapper" autosize>THE GREAT BANGKOK SALE</textarea></code>```

https://jsfiddle.net/ngoctuan001/cgLvh62o/2/

As you can see, I want to text-align the text in the textarea tag. Because the text area got a fixed width, it will try to break to next line when there is a space. However, when that happen, that row is slightly not center in human eyes due to the space.

As you can see in the screen shot above, the red line in the right hand side is always slightly longer than the red line in the left hand side, this is because the computer treats the space (highlighted) as 1 more character. But in human eyes, this is not considered as center aligned

Is there anyway to fix this ?
Thanks

答:
Unfortunately there is no concrete CSS solution at the time of writing
  to achieve the desired result

Alternative: use contenteditable

.container {
  width: 100px;
  height: 150px;
  background: #eee;
  display:flex;
  align-items: center;
  justify-content: center;
}

.text {
  text-align: center;
  word-break: break-all;
  margin: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="text" contenteditable=true>click here and edit</div>
</div></code>```

Body:
I have the following example below:

.wrapper {
  text-align: center;
  border: 1px solid red;
  background-color: white;
  color: black;
  width: 240px;
  height: 200px;
  font-size: 36px;
  line-height: 43px;
}

<textarea class="wrapper" autosize>THE GREAT BANGKOK SALE</textarea>

https://jsfiddle.net/ngoctuan001/cgLvh62o/2/

As you can see, I want to text-align the text in the textarea tag. Because the text area got a fixed width, it will try to break to next line when there is a space. However, when that happen, that row is slightly not center in human eyes due to the space.

As you can see in the screen shot above, the red line in the right hand side is always slightly longer than the red line in the left hand side, this is because the computer treats the space (highlighted) as 1 more character. But in human eyes, this is not considered as center aligned

Is there anyway to fix this ?
Thanks

Body:
Unfortunately there is no concrete CSS solution at the time of writing
  to achieve the desired result

Alternative: use contenteditable

.container {
  width: 100px;
  height: 150px;
  background: #eee;
  display:flex;
  align-items: center;
  justify-content: center;
}

.text {
  text-align: center;
  word-break: break-all;
  margin: 10px;
}

<div class="container">
  <div class="text" contenteditable=true>click here and edit</div>
</div>


问:
Using SwiftUI, how do I animate pie progress bar
I've created the code for displaying the pie progress bar. I need to add an animation to this progress bar. I tried linear animation but it didn't help. I'm stuck and don't know how to get it to animate. Can someone help? Here's the code.</p>

```<code>import SwiftUI

struct PieProgress: View {
    @State var progress: Float

    var body: some View {
        GeometryReader { geometry in
            VStack(spacing:20) {
                HStack{
                    Text("0%")
                    Slider(value: self.$progress)
                    Text("100%")
                }.padding()
                Circle()
                    .stroke(Color.gray, lineWidth: 1)
                    .frame(width: geometry.size.width, height: geometry.size.width, alignment: .center)
                    .padding()
                    .overlay(
                        PieShape(progress: Double(self.progress))
                            .frame(width: geometry.size.width - 10, height: geometry.size.width - 10 , alignment: .center)
                            .foregroundColor(.blue)
                    )
            }
        }
    }
}

struct PieShape: Shape {
    var progress: Double = 0.0
    private let startAngle: Double = (Double.pi) * 1.5
    private var endAngle: Double {
        get {
            return self.startAngle + Double.pi * 2 * self.progress
        }
    }

    func path(in rect: CGRect) -> Path {
        var path = Path()
        let arcCenter =  CGPoint(x: rect.size.width / 2, y: rect.size.width / 2)
        let radius = rect.size.width / 2
        path.move(to: arcCenter)
        path.addArc(center: arcCenter, radius: radius, startAngle: Angle(radians: startAngle), endAngle: Angle(radians: endAngle), clockwise: false)
        path.closeSubpath()
        return path
    }
}
</code>```

答:
Xcode 13.4 / iOS 15.5

With updated deprecated methods and now w/o hard-codes

```<code>Circle()
    .stroke(Color.gray, lineWidth: 1)
    .overlay(
        PieShape(progress: Double(self.progress))
            .padding(4)
            .foregroundColor(.blue)
    )
    .frame(maxWidth: .infinity)
    .animation(Animation.linear, value: progress) // << here !!
    .aspectRatio(contentMode: .fit)
</code>```

Test code is here

Original

Here is possible approach (tested & works with Xcode 11.2 / iOS 13.2):

You need to specify animatableData for your shape as below

struct PieShape: Shape {
var progress: Double = 0.0

```<code> var animatableData: Double {
     get {
         self.progress
     }
     set {
         self.progress = newValue
     }
 }
 ...
</code>```

then add animation to Circle

Circle()
.stroke(Color.gray, lineWidth: 1)
.frame(width: geometry.size.width, height: geometry.size.width, alignment: .center)
.padding()
.overlay(
PieShape(progress: Double(self.progress))
.frame(width: geometry.size.width - 10, height: geometry.size.width - 10 , alignment: .center)
.foregroundColor(.blue)
)
.animation(Animation.linear) // << here !!

and that's it. For testing (only!) you can add the following in PieProgress

```<code>.onAppear {
    DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
        self.progress = 0.72
    }
}
</code>```

Note: to use PieProgress as reused component it would be reasonable to make progress as @Binding, just in case.

Body:
I've created the code for displaying the pie progress bar. I need to add an animation to this progress bar. I tried linear animation but it didn't help. I'm stuck and don't know how to get it to animate. Can someone help? Here's the code.

import SwiftUI

struct PieProgress: View {
    @State var progress: Float

    var body: some View {
        GeometryReader { geometry in
            VStack(spacing:20) {
                HStack{
                    Text("0%")
                    Slider(value: self.$progress)
                    Text("100%")
                }.padding()
                Circle()
                    .stroke(Color.gray, lineWidth: 1)
                    .frame(width: geometry.size.width, height: geometry.size.width, alignment: .center)
                    .padding()
                    .overlay(
                        PieShape(progress: Double(self.progress))
                            .frame(width: geometry.size.width - 10, height: geometry.size.width - 10 , alignment: .center)
                            .foregroundColor(.blue)
                    )
            }
        }
    }
}

struct PieShape: Shape {
    var progress: Double = 0.0
    private let startAngle: Double = (Double.pi) * 1.5
    private var endAngle: Double {
        get {
            return self.startAngle + Double.pi * 2 * self.progress
        }
    }

    func path(in rect: CGRect) -> Path {
        var path = Path()
        let arcCenter =  CGPoint(x: rect.size.width / 2, y: rect.size.width / 2)
        let radius = rect.size.width / 2
        path.move(to: arcCenter)
        path.addArc(center: arcCenter, radius: radius, startAngle: Angle(radians: startAngle), endAngle: Angle(radians: endAngle), clockwise: false)
        path.closeSubpath()
        return path
    }
}

Body:
Xcode 13.4 / iOS 15.5

With updated deprecated methods and now w/o hard-codes

Circle()
    .stroke(Color.gray, lineWidth: 1)
    .overlay(
        PieShape(progress: Double(self.progress))
            .padding(4)
            .foregroundColor(.blue)
    )
    .frame(maxWidth: .infinity)
    .animation(Animation.linear, value: progress) // << here !!
    .aspectRatio(contentMode: .fit)

Test code is here

Original

Here is possible approach (tested & works with Xcode 11.2 / iOS 13.2):

You need to specify animatableData for your shape as below

struct PieShape: Shape {
var progress: Double = 0.0

 var animatableData: Double {
     get {
         self.progress
     }
     set {
         self.progress = newValue
     }
 }
 ...

then add animation to Circle

Circle()
.stroke(Color.gray, lineWidth: 1)
.frame(width: geometry.size.width, height: geometry.size.width, alignment: .center)
.padding()
.overlay(
PieShape(progress: Double(self.progress))
.frame(width: geometry.size.width - 10, height: geometry.size.width - 10 , alignment: .center)
.foregroundColor(.blue)
)
.animation(Animation.linear) // << here !!

and that's it. For testing (only!) you can add the following in PieProgress

.onAppear {
    DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
        self.progress = 0.72
    }
}

Note: to use PieProgress as reused component it would be reasonable to make progress as @Binding, just in case.


问:
Rendering component with property coming from fetch in componentDidMount React
I am trying to render a component that needs props passed to it. These props require data that can only come from an api fetch. The issue is that I'm fetching from the api in componentDidMount but the render method gets mounted before the componentDidMount method so it says that it cannot read property of undefined because it tries to render the component before the data gets to be fetched. heroImage is an object that gets stored into the state during the fetch call but it does not exist in the state before the fetch call.

```<code>class Home extends React.Component{
    constructor(){
        super();
        this.state={
            searchTerm: '',
            movies: [],
            error: false,
            loading: false,
        };
    }

    componentDidMount(){
        const fetchMovies = async endpoint => {

            const isLoadMore = endpoint.search('page');
            try{
                const result = await (await fetch(endpoint)).json();
                this.setState(prev => ({
                    ...prev,
                    movies: isLoadMore !== -1 ? [...prev.movies, ...result.results] : [...result.results],
                    heroImage: prev.heroImage || result.results[0],
                    currentPage: result.page,
                    totalPages: result.total_pages
                }));
            } catch(error){
                alert(error);
            }
        }
        console.log('...fetching');
        fetchMovies(POPULAR_BASE_URL);
        console.log('done fetching...');
    }

    render(){
        const {heroImage} = this.state;
        return(
            <React.Fragment>
                <HeroImage
                    image={`${IMAGE_BASE_URL}${BACKDROP_SIZE}${heroImage.backdrop_path}`}
                    title={heroImage.original_title}
                    text={heroImage.overview}
                />
            </React.Fragment>
        );
    }
};
</code>```

The app has trouble reading the image prop that's getting passed to the HeroImage component. This is because it requires the heroImage object that only comes from the fetch call to exist so that it can select the backdrop_path property from it. Since render method mounts first, the object is never stored in the state. This is the issue I need help solving. Thanks.

答:
Just add an iternary check like this. So it only renders when there is data in heroImage</p>

```<code>   render(){
        const {heroImage} = this.state;
        return(
            <React.Fragment>
                heroImage && <HeroImage
                    image={`${IMAGE_BASE_URL}${BACKDROP_SIZE}${heroImage.backdrop_path}`}
                    title={heroImage.original_title}
                    text={heroImage.overview}
                />
            </React.Fragment>
        );
    }
</code>```

Body:
I am trying to render a component that needs props passed to it. These props require data that can only come from an api fetch. The issue is that I'm fetching from the api in componentDidMount but the render method gets mounted before the componentDidMount method so it says that it cannot read property of undefined because it tries to render the component before the data gets to be fetched. heroImage is an object that gets stored into the state during the fetch call but it does not exist in the state before the fetch call.

class Home extends React.Component{
    constructor(){
        super();
        this.state={
            searchTerm: '',
            movies: [],
            error: false,
            loading: false,
        };
    }

    componentDidMount(){
        const fetchMovies = async endpoint => {

            const isLoadMore = endpoint.search('page');
            try{
                const result = await (await fetch(endpoint)).json();
                this.setState(prev => ({
                    ...prev,
                    movies: isLoadMore !== -1 ? [...prev.movies, ...result.results] : [...result.results],
                    heroImage: prev.heroImage || result.results[0],
                    currentPage: result.page,
                    totalPages: result.total_pages
                }));
            } catch(error){
                alert(error);
            }
        }
        console.log('...fetching');
        fetchMovies(POPULAR_BASE_URL);
        console.log('done fetching...');
    }

    render(){
        const {heroImage} = this.state;
        return(
            <React.Fragment>
                <HeroImage
                    image={`${IMAGE_BASE_URL}${BACKDROP_SIZE}${heroImage.backdrop_path}`}
                    title={heroImage.original_title}
                    text={heroImage.overview}
                />
            </React.Fragment>
        );
    }
};

The app has trouble reading the image prop that's getting passed to the HeroImage component. This is because it requires the heroImage object that only comes from the fetch call to exist so that it can select the backdrop_path property from it. Since render method mounts first, the object is never stored in the state. This is the issue I need help solving. Thanks.

Body:
Just add an iternary check like this. So it only renders when there is data in heroImage

   render(){
        const {heroImage} = this.state;
        return(
            <React.Fragment>
                heroImage && <HeroImage
                    image={`${IMAGE_BASE_URL}${BACKDROP_SIZE}${heroImage.backdrop_path}`}
                    title={heroImage.original_title}
                    text={heroImage.overview}
                />
            </React.Fragment>
        );
    }


问:
How to plot 3D multiple Linear Regression with 2 features using matplotlib?
I need to plot a 3D plot with multiple Linear Regression with 2 features in matplotlib. How can I do that?

this is my code:

```<code>import pandas
from sklearn import linear_model

df = pandas.read_csv("cars.csv")

X = df[['Weight', 'Volume']]
y = df['CO2']

regr = linear_model.LinearRegression()

predictedCO2 = regr.predict([scaled[0]])
print(predictedCO2)
</code>```

答:
So you want to plot a 3d plot of your regression model's outcome. In your 3d plot, for each point you have (x, y, z) = (Weight, Volume, PredictedCO2).

Now you can plot it with:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import random

# dummy variables for demonstration
x = [random.random()*100 for _ in range(100)]
y = [random.random()*100 for _ in range(100)]
z = [random.random()*100 or _ in range(100)]

# build the figure instance
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, c='blue', marker='o')

# set your labels
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()
```

This will give you a plot like this:

Body:
I need to plot a 3D plot with multiple Linear Regression with 2 features in matplotlib. How can I do that?

this is my code:

import pandas
from sklearn import linear_model

df = pandas.read_csv("cars.csv")

X = df[['Weight', 'Volume']]
y = df['CO2']

regr = linear_model.LinearRegression()

predictedCO2 = regr.predict([scaled[0]])
print(predictedCO2)

Body:
So you want to plot a 3d plot of your regression model's outcome. In your 3d plot, for each point you have (x, y, z) = (Weight, Volume, PredictedCO2).

Now you can plot it with:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import random

# dummy variables for demonstration
x = [random.random()*100 for _ in range(100)]
y = [random.random()*100 for _ in range(100)]
z = [random.random()*100 or _ in range(100)]

# build the figure instance
fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, c='blue', marker='o')

# set your labels
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

This will give you a plot like this:


问:
Execute javascript from inside update panel on every refresh
I have an aspx page which is made of 3 user controls (ascx). I have an update panel wrapping the 3 user controls like this:

```<code><asp:UpdatePanel ID="UpdatePanelWrapper" runat="server">
    <ContentTemplate>
         <uc1:UserControl1 ID="UserControl1" runat="server" />
         <uc2:UserControl2 ID="UserControl2" runat="server"/>
         <uc2:UserControl3 ID="UserControl3" runat="server"/>
    </ContentTemplate>
</asp:UpdatePanel>
</code>```

I show each user control by separate, so when "UserControl1" is displayed, the other 2 user controls are hidden.

Inside "UserControl1" I have some asp controls and some javascript functions. My problem is that these javascript functions are never called when "UpdatePanelWrapper" is refreshed.

I have tried this solution http://blog.dreamlabsolutions.com/post/2009/02/24/jQuery-document-ready-and-ASP-NET-Ajax-asynchronous-postback.aspx, by adding that javascript call inside the "UserControl1", though it's not working. I made it work only if I add that javascript call in the aspx page, but not inside the "UserControl1".

Any help would be appreciated, Thank you.

答:
you can use

Sys.Application.add_load(WireEvents); // fix wiring for .NET ajax updatepanel

like

```<code><script language="javascript" type="text/javascript">
// <![CDATA[
    Sys.Application.add_load(WireEvents); // fix wiring for .NET ajax updatepanel
    $(WireEvents); // handle page load wiring using jquery. This will fire on page load

    function WireEvents() {
               //do stuff here
    };
// ]]>
</script>
</code>```

oh and one more thing. do be careful with the funciton names. otherwise it'll be a mess.
try something like this

```<code><script language="javascript" type="text/javascript">
// <![CDATA[
    Sys.Application.add_load(WireEvents_<%=this.ID%>); // fix wiring for .NET ajax updatepanel
    $(WireEvents_<%=this.ID%>); // handle page load wiring

    function WireEvents_<%=this.ID%>() {

    };// end WireEvents_

// ]]>
</script>
</code>```

so basically adding _<%=this.ID%> to the funciton name ensures that each instance of the control is calling it's own function. assuming you can have multiple instances of the control. If not at least it prevents the confusion when calling wireevents for different controls

Body:
I have an aspx page which is made of 3 user controls (ascx). I have an update panel wrapping the 3 user controls like this:

<asp:UpdatePanel ID="UpdatePanelWrapper" runat="server">
    <ContentTemplate>
         <uc1:UserControl1 ID="UserControl1" runat="server" />
         <uc2:UserControl2 ID="UserControl2" runat="server"/>
         <uc2:UserControl3 ID="UserControl3" runat="server"/>
    </ContentTemplate>
</asp:UpdatePanel>

I show each user control by separate, so when "UserControl1" is displayed, the other 2 user controls are hidden.

Inside "UserControl1" I have some asp controls and some javascript functions. My problem is that these javascript functions are never called when "UpdatePanelWrapper" is refreshed.

I have tried this solution http://blog.dreamlabsolutions.com/post/2009/02/24/jQuery-document-ready-and-ASP-NET-Ajax-asynchronous-postback.aspx, by adding that javascript call inside the "UserControl1", though it's not working. I made it work only if I add that javascript call in the aspx page, but not inside the "UserControl1".

Any help would be appreciated, Thank you.

Body:
you can use

Sys.Application.add_load(WireEvents); // fix wiring for .NET ajax updatepanel

like

<script language="javascript" type="text/javascript">
// <![CDATA[
    Sys.Application.add_load(WireEvents); // fix wiring for .NET ajax updatepanel
    $(WireEvents); // handle page load wiring using jquery. This will fire on page load

    function WireEvents() {
               //do stuff here
    };
// ]]>
</script>

oh and one more thing. do be careful with the funciton names. otherwise it'll be a mess.
try something like this

<script language="javascript" type="text/javascript">
// <![CDATA[
    Sys.Application.add_load(WireEvents_<%=this.ID%>); // fix wiring for .NET ajax updatepanel
    $(WireEvents_<%=this.ID%>); // handle page load wiring

    function WireEvents_<%=this.ID%>() {

    };// end WireEvents_

// ]]>
</script>

so basically adding _<%=this.ID%> to the funciton name ensures that each instance of the control is calling it's own function. assuming you can have multiple instances of the control. If not at least it prevents the confusion when calling wireevents for different controls


问:
How to build docker image and push to azure container registry
I am using Azure Pipelines and have successfully built a pipeline to build and deploy a docker image to azure app services.

Now I am trying to figure out how to build a docker image in a pipeline and then publish it to the artifact staging directory so I can push it to the azure container registry instead. I have looked all over google to see how this is done with no luck, this is going to be a three part question.

I am successfully building a dockerfile in my pipeline with the exception that I can not figure out how to delete a temporary file (keep getting access denied)

```<code>Removing intermediate container 543fb86650c4
 ---> 3ccb8c3a555e
Step 10/28 : RUN del -f "./NuGet.Config"
 ---> Running in c2ba7a3266a4
C:\src\NuGet.Config
Access is denied.
</code>```

The image build continues from there and succeeds but I am trying to publish an artifact, I want to take the built image and pass it to the release pipeline to be pushed to azure container registry. The publish artifact fails because it cant find the image, and I am really not sure how to find it?

```<code>##[warning]Directory 'd:\a\1\a' is empty. Nothing will be added to build artifact 'Email'.
</code>```

Maybe I am going about this all wrong? If so, please suggest an alternative, just remember I want to push my docker image to the azure container registry instead of the azure app service.

Question 1: How can I delete the file within the container in the pipeline task?

Question 2: How do I push a docker image to the Azure container registry instead of the Azure app service?

I am using the UI to configure my pipeline and do not have a full yaml file to share but here is the yaml from the view option:

```<code>pool:
  name: Azure Pipelines
variables:
  Parameters.ArtifactName: 'Email'

steps:
- task: Docker@2
  displayName: 'Build an image'
  inputs:
    containerRegistry: 'Azure Container'
    repository: email
    command: build
    Dockerfile: Services/Email/Email/Dockerfile
    buildContext: Services/Email
    tags: latest
    arguments: '-o $(build.artifactstagingdirectory)'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact'
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)'
    ArtifactName: '$(Parameters.ArtifactName)'
</code>```

Question 3: Once I get the file to publish to the artifact staging directory how would I access it to push the image to the container registry?

UPDATE TO INCLUDE DOCKERFILE

```<code>FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-nanoserver-1809 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-nanoserver-1809 AS build
WORKDIR /src
COPY ["Email/Email.csproj", "Email/"]
COPY ./NuGet.Config ./
RUN dotnet restore "Email/Email.csproj" --configfile ./NuGet.Config
RUN del "./NuGet.Config"
COPY . .
WORKDIR "/src/Email"
RUN dotnet build "Email.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Email.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Email.dll"]
</code>```

答:
How can I delete the file within the pipeline task?

You can use Delete Files task to delete files or folders from the agent working directory. For below example.

```<code> - task: DeleteFiles@1
   displayName: 'Delete files'
   inputs:
     SourceFolder: '$(Build.SourcesDirectory)'
     Contents: NuGet.Config
</code>```

The commands in dockerfile are executed in the containers, delete files command cannot delete the files on local drive. For deleting files within the container you can check the methods discussed in this thread.

Update:

2,How do I push the docker image build over to the release pipeline?

You can run all docker commands in a powershell task. So you can build your docker image in the powershell task and use docker image save command to save it to a place. Then publish it to use PublishBuildArtifacts task. In this way you donot need to use docker tasks

Please check below example:

```<code>- powershell: |
   docker build . -t python/test:tag1
   docker image save python/test:tag1 -o $(Build.ArtifactStagingDirectory)/imagetest.tar

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact'
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)'
</code>```

In above powershell task. I first used docker build command to build the image and tag it python/test:tag1, then i used docker image save to save the image to
$(Build.ArtifactStagingDirectory)/imagetest.tar. Then i can publish it use PublishBuildArtifacts task.

Update:

How can I delete the file within the container in the pipeline task.

You can specify the Administrator to del the files inside a container to fix the access denied error. Add USER Administrator in your dockerfile before RUN del command.  Check below example:

```<code>USER Administrator
RUN del remove.txt
</code>```

Hope above helps!

Body:
I am using Azure Pipelines and have successfully built a pipeline to build and deploy a docker image to azure app services.

Now I am trying to figure out how to build a docker image in a pipeline and then publish it to the artifact staging directory so I can push it to the azure container registry instead. I have looked all over google to see how this is done with no luck, this is going to be a three part question.

I am successfully building a dockerfile in my pipeline with the exception that I can not figure out how to delete a temporary file (keep getting access denied)

Removing intermediate container 543fb86650c4
 ---> 3ccb8c3a555e
Step 10/28 : RUN del -f "./NuGet.Config"
 ---> Running in c2ba7a3266a4
C:\src\NuGet.Config
Access is denied.

The image build continues from there and succeeds but I am trying to publish an artifact, I want to take the built image and pass it to the release pipeline to be pushed to azure container registry. The publish artifact fails because it cant find the image, and I am really not sure how to find it?

##[warning]Directory 'd:\a\1\a' is empty. Nothing will be added to build artifact 'Email'.

Maybe I am going about this all wrong? If so, please suggest an alternative, just remember I want to push my docker image to the azure container registry instead of the azure app service.

Question 1: How can I delete the file within the container in the pipeline task?

Question 2: How do I push a docker image to the Azure container registry instead of the Azure app service?

I am using the UI to configure my pipeline and do not have a full yaml file to share but here is the yaml from the view option:

pool:
  name: Azure Pipelines
variables:
  Parameters.ArtifactName: 'Email'

steps:
- task: Docker@2
  displayName: 'Build an image'
  inputs:
    containerRegistry: 'Azure Container'
    repository: email
    command: build
    Dockerfile: Services/Email/Email/Dockerfile
    buildContext: Services/Email
    tags: latest
    arguments: '-o $(build.artifactstagingdirectory)'

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact'
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)'
    ArtifactName: '$(Parameters.ArtifactName)'

Question 3: Once I get the file to publish to the artifact staging directory how would I access it to push the image to the container registry?

UPDATE TO INCLUDE DOCKERFILE

FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-nanoserver-1809 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1-nanoserver-1809 AS build
WORKDIR /src
COPY ["Email/Email.csproj", "Email/"]
COPY ./NuGet.Config ./
RUN dotnet restore "Email/Email.csproj" --configfile ./NuGet.Config
RUN del "./NuGet.Config"
COPY . .
WORKDIR "/src/Email"
RUN dotnet build "Email.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Email.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Email.dll"]

Body:
How can I delete the file within the pipeline task?

You can use Delete Files task to delete files or folders from the agent working directory. For below example.

 - task: DeleteFiles@1
   displayName: 'Delete files'
   inputs:
     SourceFolder: '$(Build.SourcesDirectory)'
     Contents: NuGet.Config

The commands in dockerfile are executed in the containers, delete files command cannot delete the files on local drive. For deleting files within the container you can check the methods discussed in this thread.

Update:

2,How do I push the docker image build over to the release pipeline?

You can run all docker commands in a powershell task. So you can build your docker image in the powershell task and use docker image save command to save it to a place. Then publish it to use PublishBuildArtifacts task. In this way you donot need to use docker tasks

Please check below example:

- powershell: |
   docker build . -t python/test:tag1
   docker image save python/test:tag1 -o $(Build.ArtifactStagingDirectory)/imagetest.tar

- task: PublishBuildArtifacts@1
  displayName: 'Publish Artifact'
  inputs:
    PathtoPublish: '$(build.artifactstagingdirectory)'

In above powershell task. I first used docker build command to build the image and tag it python/test:tag1, then i used docker image save to save the image to
$(Build.ArtifactStagingDirectory)/imagetest.tar. Then i can publish it use PublishBuildArtifacts task.

Update:

How can I delete the file within the container in the pipeline task.

You can specify the Administrator to del the files inside a container to fix the access denied error. Add USER Administrator in your dockerfile before RUN del command.  Check below example:

USER Administrator
RUN del remove.txt

Hope above helps!


问:
Loop through result set of mysql in Bash - routines
I want to make specific .sql file for each of my routines.

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

 routine_names=$(mysql mydb  --execute="SELECT
    *
FROM
    information_schema.routines
WHERE
    routine_type = 'PROCEDURE' OR routine_type ='FUNCTION'
        AND routine_schema = 'mydb';"|cut -f1)

for routine in "$routine_names"
do
    if [ -e "${routine}.sql" ]
     then
    echo "ok"
    else
     content_procedure=$(mysql mydb--execute="SHOW CREATE PROCEDURE $routine;")
     echo "$content_procedure" >> masoud.txt
   fi
done
</code>```

my routine_names variable is a list of my procedures. like this:

```<code>SP_ONE
SP_TWO
SP_THREE
</code>```

I want to loop of these result. but I think the result is not an array. because routine variable has all content.

答:
wrap your mysql mydb ... command with ()

```<code> routine_names=($(mysql mydb  --execute="SELECT
    *
FROM
    information_schema.routines
WHERE
    routine_type = 'PROCEDURE' OR routine_type ='FUNCTION'
        AND routine_schema = 'mydb';"|cut -f1))
</code>```

I was curious and got the idea from here.

Body:
I want to make specific .sql file for each of my routines.

#!/bin/bash

 routine_names=$(mysql mydb  --execute="SELECT
    *
FROM
    information_schema.routines
WHERE
    routine_type = 'PROCEDURE' OR routine_type ='FUNCTION'
        AND routine_schema = 'mydb';"|cut -f1)

for routine in "$routine_names"
do
    if [ -e "${routine}.sql" ]
     then
    echo "ok"
    else
     content_procedure=$(mysql mydb--execute="SHOW CREATE PROCEDURE $routine;")
     echo "$content_procedure" >> masoud.txt
   fi
done

my routine_names variable is a list of my procedures. like this:

SP_ONE
SP_TWO
SP_THREE

I want to loop of these result. but I think the result is not an array. because routine variable has all content.

Body:
wrap your mysql mydb ... command with ()

 routine_names=($(mysql mydb  --execute="SELECT
    *
FROM
    information_schema.routines
WHERE
    routine_type = 'PROCEDURE' OR routine_type ='FUNCTION'
        AND routine_schema = 'mydb';"|cut -f1))

I was curious and got the idea from here.


问:
Prevent users from changing amount charged on payment page
I am trying to integrate payment gateway on my website.  There are three courses each having different prices. I am passing the value of the amount and package to form.php and i have made the input fields to readonly but the user can still change the amount in inspect element and make it 0 and pass on the value and get the course for free. How can i stop user from changing the value? or is there any other way to pass the value? or encrypt it and then decrypt it again?

here is my code index.php

```<code><div id="outer">
        <div class="box">
            <h4>Rs. 9,900/-</h4>
            <ul>
                <li>2-Days Classroom Training</li>
                <li>E-Learning Course</li>
            </ul>
            <form action="form.php" method="post">
                <input type="hidden" name="amount" value="9900" readonly="readonly">
                <input type="hidden" name="package" value="basic" readonly="readonly">
                <input type="submit" name="BUY NOW" value="BUY NOW">
            </form>
        </div>
        <div class="box">
            <h4>Rs. 11,900/-</h4>
            <ul>
                <li>4-Days Classroom Training</li>
                <li>E-Learning Course</li>
            </ul>
            <form action="form.php" method="post">
                <input type="hidden" name="amount" value="11900" readonly="readonly">
                <input type="hidden" name="package" value="standard" readonly="readonly">
                <input type="submit" name="BUY NOW" value="BUY NOW">
            </form>
        </div>
        <div class="box">
            <h4>Rs. 14,900/-</h4>
            <ul>
                <li>4-Days Classroom Training</li>
                <li>E-Learning Course</li>
                <li>5 Hours Personal Session With The Trainer</li>
            </ul>
            <form action="form.php" method="post">
                <input type="hidden" name="amount" value="14900" readonly="readonly">
                <input type="hidden" name="package" value="pro" readonly="readonly">
                <input type="submit" name="BUY NOW" value="BUY NOW">
            </form>
        </div>
    </div>
</code>```

form.php

```<code><body>
    <?php
        if (isset($_POST['amount']) && isset($_POST['package'])) {
            $amount = $_POST['amount'];
            $package = $_POST['package'];
        }
    ?>

<div>
<table>
    <form name="postForm" action="form_process.php" method="POST" >
    <tr><td>txnid</td><td><input type="text" name="txnid" readonly="readonly" value="<?php echo $txnid=time().rand(1000,99999); ?>" /></td></tr>
    <tr><td>amount</td><td><input type="text" name="amount" readonly="readonly" value="<?php echo $amount; ?>" /></td></tr>
    <tr><td>firstname</td><td><input type="text" name="firstname" value="" /></td></tr>
    <tr><td>email</td><td><input type="text" name="email" value="" /></td></tr>
    <tr><td>phone</td><td><input type="text" name="phone" value="" /></td></tr>
    <tr><td>Package</td><td><input type="text" name="productinfo" readonly="readonly" value="<?php echo $package; ?>"/></td></tr>
    <tr><td colspan="3"><input type="hidden" name="service_provider" value="payu_paisa" size="64" /></td></tr>
    <tr><td><input type="hidden" name="surl" value="http://localhost/payment/success.php" size="64" readonly="readonly" /></td></tr>
    <tr><td><input type="hidden" name="furl" value="http://localhost/payment/failure.php" size="64" readonly="readonly" /></td></tr>
    <tr><td><input type="submit" /></td><td><input type="reset" /></td></tr>
    </form>
</table>
</div>
</body>
</code>```

form_process.php

```<code><script>
    function submitForm() {
      var postForm = document.forms.postForm;
      postForm.submit();
    }
</script>
</head>
<?php
if(!isset($_POST['firstname'])){header("location: form.php");}
// Change the Merchant key here as provided by Payumoney
$MERCHANT_KEY = "*******";

// Change the Merchant Salt as provided by Payumoney
$SALT = "********";

    $firstname =$_POST['firstname'];
    $email =$_POST['email'];
    $phone =$_POST['phone'];
    $productinfo =$_POST['productinfo'];
    $service_provider =$_POST['service_provider'];
    $amount =$_POST['amount'];
    $txnid =$_POST['txnid'];
    $productinfo =$_POST['productinfo'];
    $surl =$_POST['surl'];
    $furl =$_POST['furl'];

    //$ =$_POST[''];

    $hashseq=$MERCHANT_KEY.'|'.$txnid.'|'.$amount.'|'.$productinfo.'|'.$firstname.'|'.$email.'|||||||||||'.$SALT;
    $hash =strtolower(hash("sha512", $hashseq));

?>

<body onload="submitForm();">

<div>
<h2>Payment Gateway Testing Sample</h2>
<table>
<tr><td>Transaction Id</td><td><strong><?php echo $_POST['txnid']; ?></strong></td><td>Amount: </td><td><strong>Rs. <?php echo $_POST['amount']; ?></strong></td>
</table>
<div >
<p>In this page we will genrate hash and send it to payumoney.</p>
<br>
<p>Please be patient. this process might take some time,<br />please do not hit refresh or browser back button or close this window</p>
</div>
</div>

<div>
    <form name="postForm" action="https://sandboxsecure.payu.in/_payment" method="POST" >
        <input type="hidden" name="key" value="<?php echo $MERCHANT_KEY; ?>" />
        <input type="hidden" name="hash" value="<?php echo $hash;  ?>"/>
        <input type="hidden" name="txnid" value="<?php echo $_POST['txnid'];  ?>" />
        <input type="hidden" name="amount" value="<?php echo $_POST['amount'];  ?>" />
        <input type="hidden" name="firstname" value="<?php echo $_POST['firstname'];  ?>" />
        <input type="hidden" name="email" value="<?php echo $_POST['email'];  ?>" />
        <input type="hidden" name="phone" value="<?php echo $_POST['phone'];  ?>" />
        <input type="hidden" name="productinfo" value="<?php echo $_POST['productinfo'];  ?>" />
        <input type="hidden" name="service_provider" value="payu_paisa" size="64" />
        <input type="hidden" name="surl" value="<?php echo $_POST['surl'];  ?>" />
        <input type="hidden" name="furl" value="<?php echo $_POST['furl'];  ?>" />
    </form>
</div>
</body>
</code>```

success.php

```<code><body>
    <script>var time = 5;
setInterval(function() {
  var seconds = time % 60;
  var minutes = (time - seconds) / 60;
  if (seconds.toString().length == 1) {
    seconds = "0" + seconds;
  }
  if (minutes.toString().length == 1) {
    minutes = "0" + minutes;
  }
  document.getElementById("time").innerHTML = minutes + ":" + seconds;
  time--;
  if (time == 0) {
    window.location.href = "index.php";
  }
}, 1000);
</script>

    <div>
        <h2>Payment Success</h2>
    </div>

    <div>
        <?php
            if(isset($_POST['status'])){
                if($_POST['status']=="success"){
                    echo "<p>Payment Done Successfully.<br>Details Are Below.</p>";
                    echo "<p>Txn Id: ".$_POST['txnid']."</p>";
                    echo "<p>Name: ".$_POST['firstname']."</p>";
                    echo "<p>Email: ".$_POST['email']."</p>";
                    echo "<p>Amount: ".$_POST['amount']."</p>";
                    echo "<p>Phone No: ".$_POST['phone']."</p>";
                    echo "<p>Product Info: ".$_POST['productinfo']."</p>";
                    echo "<p>encryptedPaymentId: ".$_POST['encryptedPaymentId']."</p>";
                }
            }

            ?>
    </div>
    <div>Redirecting to home page in <span id="time"></span></div>
</code>```

答:
Check the value of the field, if its zero, just kill the execution of the code, send the user back to the form and print a warning...

Or you could use JavaScript to validate the amount onClick and double check after submission.

It's a jungle out there!!!

Body:
I am trying to integrate payment gateway on my website.  There are three courses each having different prices. I am passing the value of the amount and package to form.php and i have made the input fields to readonly but the user can still change the amount in inspect element and make it 0 and pass on the value and get the course for free. How can i stop user from changing the value? or is there any other way to pass the value? or encrypt it and then decrypt it again?

here is my code index.php

Rs. 9,900/-

2-Days Classroom Training

E-Learning Course

            <form action="form.php" method="post">
                <input type="hidden" name="amount" value="9900" readonly="readonly">
                <input type="hidden" name="package" value="basic" readonly="readonly">
                <input type="submit" name="BUY NOW" value="BUY NOW">
            </form>

Rs. 11,900/-

4-Days Classroom Training

E-Learning Course

            <form action="form.php" method="post">
                <input type="hidden" name="amount" value="11900" readonly="readonly">
                <input type="hidden" name="package" value="standard" readonly="readonly">
                <input type="submit" name="BUY NOW" value="BUY NOW">
            </form>

Rs. 14,900/-

4-Days Classroom Training

E-Learning Course

5 Hours Personal Session With The Trainer

            <form action="form.php" method="post">
                <input type="hidden" name="amount" value="14900" readonly="readonly">
                <input type="hidden" name="package" value="pro" readonly="readonly">
                <input type="submit" name="BUY NOW" value="BUY NOW">
            </form>

form.php

    <?php
        if (isset($_POST['amount']) && isset($_POST['package'])) {
            $amount = $_POST['amount'];
            $package = $_POST['package'];
        }
    ?>

    <form name="postForm" action="form_process.php" method="POST" >

txnid	<input type="text" name="txnid" readonly="readonly" value="<?php echo $txnid=time().rand(1000,99999); ?>" />

amount	<input type="text" name="amount" readonly="readonly" value="<?php echo $amount; ?>" />

firstname	<input type="text" name="firstname" value="" />

email	<input type="text" name="email" value="" />

phone	<input type="text" name="phone" value="" />

Package	<input type="text" name="productinfo" readonly="readonly" value="<?php echo $package; ?>"/>

<input type="hidden" name="service_provider" value="payu_paisa" size="64" />

<input type="hidden" name="surl" value="http://localhost/payment/success.php" size="64" readonly="readonly" />

<input type="hidden" name="furl" value="http://localhost/payment/failure.php" size="64" readonly="readonly" />

<input type="submit" />	<input type="reset" />

    </form>

form_process.php

<?php
if(!isset($_POST['firstname'])){header("location: form.php");}
// Change the Merchant key here as provided by Payumoney
$MERCHANT_KEY = "*******";

// Change the Merchant Salt as provided by Payumoney
$SALT = "********";

    $firstname =$_POST['firstname'];
    $email =$_POST['email'];
    $phone =$_POST['phone'];
    $productinfo =$_POST['productinfo'];
    $service_provider =$_POST['service_provider'];
    $amount =$_POST['amount'];
    $txnid =$_POST['txnid'];
    $productinfo =$_POST['productinfo'];
    $surl =$_POST['surl'];
    $furl =$_POST['furl'];

    //$ =$_POST[''];

    $hashseq=$MERCHANT_KEY.'|'.$txnid.'|'.$amount.'|'.$productinfo.'|'.$firstname.'|'.$email.'|||||||||||'.$SALT;
    $hash =strtolower(hash("sha512", $hashseq));

?>

Payment Gateway Testing Sample

Transaction Id	<?php echo $_POST['txnid']; ?>	Amount: 	Rs. <?php echo $_POST['amount']; ?>

In this page we will genrate hash and send it to payumoney.

Please be patient. this process might take some time,
please do not hit refresh or browser back button or close this window

    <form name="postForm" action="https://sandboxsecure.payu.in/_payment" method="POST" >
        <input type="hidden" name="key" value="<?php echo $MERCHANT_KEY; ?>" />
        <input type="hidden" name="hash" value="<?php echo $hash;  ?>"/>
        <input type="hidden" name="txnid" value="<?php echo $_POST['txnid'];  ?>" />
        <input type="hidden" name="amount" value="<?php echo $_POST['amount'];  ?>" />
        <input type="hidden" name="firstname" value="<?php echo $_POST['firstname'];  ?>" />
        <input type="hidden" name="email" value="<?php echo $_POST['email'];  ?>" />
        <input type="hidden" name="phone" value="<?php echo $_POST['phone'];  ?>" />
        <input type="hidden" name="productinfo" value="<?php echo $_POST['productinfo'];  ?>" />
        <input type="hidden" name="service_provider" value="payu_paisa" size="64" />
        <input type="hidden" name="surl" value="<?php echo $_POST['surl'];  ?>" />
        <input type="hidden" name="furl" value="<?php echo $_POST['furl'];  ?>" />
    </form>

success.php

Payment Success

        <?php
            if(isset($_POST['status'])){
                if($_POST['status']=="success"){
                    echo "
Payment Done Successfully.
Details Are Below.
";
                    echo "
Txn Id: ".$_POST['txnid']."
";
                    echo "
Name: ".$_POST['firstname']."
";
                    echo "
Email: ".$_POST['email']."
";
                    echo "
Amount: ".$_POST['amount']."
";
                    echo "
Phone No: ".$_POST['phone']."
";
                    echo "
Product Info: ".$_POST['productinfo']."
";
                    echo "
encryptedPaymentId: ".$_POST['encryptedPaymentId']."
";
                }
            }

            ?>

Redirecting to home page in


问:
HTTP Error 429 Too Many Requests - delete cookies
I am using module google search for webscraping, but I got this error 429. I tried uninstall and install module again, but it didn't help. So my next idea is delete cookies, but I don't know how. Can you help me, please?</p>
```<code>query = 'site:https://stackoverflow.com urllib.error.HTTPError: HTTP Error 429: Too Many Requests'
search_query = search(query=query, stop=10)
for url in search_query:
print(url)
</code>```

答:
There is resolution of my problem: https://support.google.com/gsa/answer/4411411#requests

How to disable cookie handling with the Python requests library?

Body:
I am using module google search for webscraping, but I got this error 429. I tried uninstall and install module again, but it didn't help. So my next idea is delete cookies, but I don't know how. Can you help me, please?

query = 'site:https://stackoverflow.com urllib.error.HTTPError: HTTP Error 429: Too Many Requests'
search_query = search(query=query, stop=10)
for url in search_query:
print(url)


问:
Creating a new NSURLConnection inside of connectionDidFinishLoading
I have a NSURLConnection that gets data from a JSON web service, and everything works fine. I'm using it to post something to the server and get a success response.

After that call I want to initiate another NSURLConnection to refresh the data, so I'm doing so inside the connectionDidFinishLoading method, however this second connection isn't calling connectionDidFinishLoading when it is done loading.

Can I not initiate a NSURLConnection from inside the connectionDidFinishLoading method?

EDIT: Below is the code. I subclassed NSURLConnection to include a Tag NSString, calling the new class NSURLConnectionHelper. I'm using this to differentiate which connection has called the connectionDidFinishLoading.

```<code>- (void)connectionDidFinishLoading:(NSURLConnectionHelper *)connection
{

        if([connection.Tag isEqual:@"NewMessage"]){

            NSString *jsonString = [[NSString alloc] initWithData:receivedNewMessageData encoding:NSASCIIStringEncoding];

            NSDictionary *results = [jsonString JSONValue];

            [jsonString release];

            [connection release];

            if ([[results objectForKey:@"MessageAdded"] isEqual:@"True"]) {

                User *newUser = [[User alloc] init];
                [newUser retrieveFromUserDefaults];

                if([newUser IsLoggedIn]){
                Message *message = (Message *)[messages objectAtIndex: 0];

                        NSString *urlAsString = // url for webservice goes here

                        NSURL *url = [NSURL URLWithString:urlAsString];
                        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
                        NSURLConnectionHelper *connection1 = [[NSURLConnectionHelper alloc] initWithRequest:request delegate:self];
                        connection1.Tag = @"GetLatestMessages";

                        [request release];

                        if (connection1) {
                                receivedLatestMessagesData = [[NSMutableData data] retain];
                        } else {
                                // Inform the user that the connection failed.
                        }
                }
            }
      }else if([connection.Tag isEqual:@"GetLatestMessages"]){
    //do some other stuff but this code is never reached
  }
}
</code>```

答: I'm not familiar with NSURLConnectionHelper but it looks like you're never starting the connection.

Body:
I have a NSURLConnection that gets data from a JSON web service, and everything works fine. I'm using it to post something to the server and get a success response.

After that call I want to initiate another NSURLConnection to refresh the data, so I'm doing so inside the connectionDidFinishLoading method, however this second connection isn't calling connectionDidFinishLoading when it is done loading.

Can I not initiate a NSURLConnection from inside the connectionDidFinishLoading method?

EDIT: Below is the code. I subclassed NSURLConnection to include a Tag NSString, calling the new class NSURLConnectionHelper. I'm using this to differentiate which connection has called the connectionDidFinishLoading.

- (void)connectionDidFinishLoading:(NSURLConnectionHelper *)connection
{

        if([connection.Tag isEqual:@"NewMessage"]){

            NSString *jsonString = [[NSString alloc] initWithData:receivedNewMessageData encoding:NSASCIIStringEncoding];

            NSDictionary *results = [jsonString JSONValue];

            [jsonString release];

            [connection release];

            if ([[results objectForKey:@"MessageAdded"] isEqual:@"True"]) {

                User *newUser = [[User alloc] init];
                [newUser retrieveFromUserDefaults];

                if([newUser IsLoggedIn]){
                Message *message = (Message *)[messages objectAtIndex: 0];

                        NSString *urlAsString = // url for webservice goes here

                        NSURL *url = [NSURL URLWithString:urlAsString];
                        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
                        NSURLConnectionHelper *connection1 = [[NSURLConnectionHelper alloc] initWithRequest:request delegate:self];
                        connection1.Tag = @"GetLatestMessages";

                        [request release];

                        if (connection1) {
                                receivedLatestMessagesData = [[NSMutableData data] retain];
                        } else {
                                // Inform the user that the connection failed.
                        }
                }
            }
      }else if([connection.Tag isEqual:@"GetLatestMessages"]){
    //do some other stuff but this code is never reached
  }
}


问:
trying to implement a side navigation with a toggle button in <mat-toolbar>?
I am having a side navigation panel with some details.
In the header component I am having a button which should toggle the side navigation.
I have implemented a toolbar using .My requirement is that when i click on  that button, the side navigation should toggle in and out.
How to implement it ?

My navigation.component.html:

```<code><mat-toolbar>
      </mat-toolbar>
<mat-sidenav-container>

    <mat-list>
    <mat-list-item>Accounts</mat-list-item>
    <mat-list-item>UserProfile</mat-list-item>
    <mat-list-item>Contact me</mat-list-item>
    <mat-list-item>Gspeed</mat-list-item>

  </mat-list>

 </mat-sidenav-container>
</code>```

header.component.html

```<code><body [ngClass]="selectedStyle" ><div >

    <select [(ngModel)]="selectedStyle" >
       <option *ngFor="let s of styles" [ngValue]="s">{{s}}</option>
    </select>
    <button mat-icon-button (click)="toggleSidenav()">
      <mat-icon >Details</mat-icon></button>

    </div>
   </body>
</code>```

app.component.ts

```<code>import { Component, OnInit,Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  styles: string[] = [];
  selectedStyle: string;
  open: false;
   toggleSidenav(){
     open: !this.open;
   }

  constructor() {

  }

  ngOnInit(){

    this.styles = ['red','green','blue','none'];
    }

}
</code>```

答:
Edit: this is answering the question based on a complex component hierarchy. I didn't realise your header and sidebar components were both in app component. In which case it's a trivial solution.

The two common ways of doing this are

bubble events from event source to interested components. In your case this would mean bubbling through the common path between header component and sidebar component.

By this, I mean you have a series of child -> parent event handling relationships like this:

```<code><child (event)="handleEvent($event)">
</child>
</code>```

Where event is some event emitter emitting events of T: @Output() event: EventEmitter<T> = new EventEmitter<T>();

And then when you have bubbled up to the common ancestor, you have a series of parent -> child relationships like this:

```<code><child [childEventResult]="eventResult">
</child>
</code>```

Where eventResult is some property of type T and childEventResult is some input property of type T: @Input() eventResult: T;.

This is a tedious approach if you have a complex component hierarchy, or want to change the hierarchy.

Pass the data between a common service.

Inject the common service into both components. Set up a subject on the service. The interested component (sidebar) would subscribe to the subject, and the event source component (header) would send new values to the subject when an event happens.

```<code>export class MyService {
  private sidebarChange$: Subject<boolean> = new Subject<boolean>();

  // header updates the subject via this method
  updateSidebar(visible: boolean): void {
    this.sidebarChange$.next(visible);
  }

  // Sidebar subscribes to this. Needs a more suitable name
  sidebarChange(): Observable<boolean> {
    return this.sidebarChange$.asObservable();
  }
}
</code>```

This approach is better if you have a complex component structure, but I feel a bit unsure about leaking pure UI concerns into my services.

Body:
I am having a side navigation panel with some details.
In the header component I am having a button which should toggle the side navigation.
I have implemented a toolbar using .My requirement is that when i click on  that button, the side navigation should toggle in and out.
How to implement it ?

My navigation.component.html:

<mat-toolbar>
      </mat-toolbar>
<mat-sidenav-container>

    <mat-list>
    <mat-list-item>Accounts</mat-list-item>
    <mat-list-item>UserProfile</mat-list-item>
    <mat-list-item>Contact me</mat-list-item>
    <mat-list-item>Gspeed</mat-list-item>

  </mat-list>

 </mat-sidenav-container>

header.component.html

    <select [(ngModel)]="selectedStyle" >
       <option *ngFor="let s of styles" [ngValue]="s">{{s}}</option>
    </select>
    <button mat-icon-button (click)="toggleSidenav()">
      <mat-icon >Details</mat-icon></button>

app.component.ts

import { Component, OnInit,Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  styles: string[] = [];
  selectedStyle: string;
  open: false;
   toggleSidenav(){
     open: !this.open;
   }

  constructor() {

  }

  ngOnInit(){

    this.styles = ['red','green','blue','none'];
    }

}

Body:
Edit: this is answering the question based on a complex component hierarchy. I didn't realise your header and sidebar components were both in app component. In which case it's a trivial solution.

The two common ways of doing this are

bubble events from event source to interested components. In your case this would mean bubbling through the common path between header component and sidebar component.

By this, I mean you have a series of child -> parent event handling relationships like this:

<child (event)="handleEvent($event)">
</child>

Where event is some event emitter emitting events of T: @Output() event: EventEmitter<T> = new EventEmitter<T>();

And then when you have bubbled up to the common ancestor, you have a series of parent -> child relationships like this:

<child [childEventResult]="eventResult">
</child>

Where eventResult is some property of type T and childEventResult is some input property of type T: @Input() eventResult: T;.

This is a tedious approach if you have a complex component hierarchy, or want to change the hierarchy.

Pass the data between a common service.

Inject the common service into both components. Set up a subject on the service. The interested component (sidebar) would subscribe to the subject, and the event source component (header) would send new values to the subject when an event happens.

export class MyService {
  private sidebarChange$: Subject<boolean> = new Subject<boolean>();

  // header updates the subject via this method
  updateSidebar(visible: boolean): void {
    this.sidebarChange$.next(visible);
  }

  // Sidebar subscribes to this. Needs a more suitable name
  sidebarChange(): Observable<boolean> {
    return this.sidebarChange$.asObservable();
  }
}

This approach is better if you have a complex component structure, but I feel a bit unsure about leaking pure UI concerns into my services.


问:
Remote Service in gwt is executed twice
I'm making a call to a service with GWT.

In the client side I made only one call to the method, but in the server-side, the method in the service is called twice.

I debugged the client side with GWT-Tools in Firefox; and when I call once the method, there are two executions in the server. The same data in the parameters, but in two different threads.

I have more calls in the same applications, but the problem is only with that one.

答:
I got the same problem, and in my case, I found the component I want to add listener to have been register twice, and these two listeners did the same thing -- to call the same RPC method.

So that's why it calls the RPC method once when I debug the client side code, but twice in server side, cause the other call is from the other listener.

Title: Remote Service in gwt is executed twice


问:
Media Queries: How to target all landscape devices below 1024 using css media query
How to target all landscape devices below 1024 using css media query this should work only for mobile devices not desktop browsers</p>

答:
In below Media Query CSS will be affected to devices where maximum width is 1024px. That means devices where screen width is less than 1024px will be affected from this.</p>

```<code> @media screen and ( max-width :1024px) and (min-device-pixel-ratio : 2.0)
     and (orientation: landscape){
       .your_CSS_Class{

          //your styles

      }
    }
</code>```

Body:
In below Media Query CSS will be affected to devices where maximum width is 1024px. That means devices where screen width is less than 1024px will be affected from this.

 @media screen and ( max-width :1024px) and (min-device-pixel-ratio : 2.0)
     and (orientation: landscape){
       .your_CSS_Class{

          //your styles

      }
    }