问:
Combinatorica`PlanarQ doesn't work
```<code> g1=Graph[{UndirectedEdge[a,b]}];
 GraphQ[g1]
 (*
   OUT: True
 *)
   (*Needs["Combinatorica`"]*)
 PlanarQ[g1]
 (*
    OUT: PlanarQ[.-.]
 *)
 Combinatorica`PlanarQ[g1]
 (*
   OUT: Combinatorica`PlanarQ[.-.]
 *)
</code>```

Why doesn't PlanarQ give back "True" or "False" ?

答:
You probably need:

```<code>Needs["GraphUtilities`"]
Needs["Combinatorica`"]

cg1 = ToCombinatoricaGraph[g1];

PlanarQ[cg1]
</code>```

I don't have v8 to check, however.

Title: Combinatorica`PlanarQ doesn't work

Body:
 g1=Graph[{UndirectedEdge[a,b]}];
 GraphQ[g1]
 (*
   OUT: True
 *)
   (*Needs["Combinatorica`"]*)
 PlanarQ[g1]
 (*
    OUT: PlanarQ[.-.]
 *)
 Combinatorica`PlanarQ[g1]
 (*
   OUT: Combinatorica`PlanarQ[.-.]
 *)

Why doesn't PlanarQ give back "True" or "False" ?

Body:
You probably need:

Needs["GraphUtilities`"]
Needs["Combinatorica`"]

cg1 = ToCombinatoricaGraph[g1];

PlanarQ[cg1]

I don't have v8 to check, however.


来源: stackexchange

问:
Embed audio stream from CDN
I am trying to embed a police radio stream from broadcastify into my web application. I have tried using the  tag with no success (code below). Any suggestions? </p>

```<code> <audio src="https://broadcastify.cdnstream1.com/28286">Davenport</audio>
</code>```

答:
If you want to display the audio element, you need to add the controls property.

```<code><audio src="https://broadcastify.cdnstream1.com/28286" controls>Davenport</audio>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Embed audio stream from CDN

Body:
I am trying to embed a police radio stream from broadcastify into my web application. I have tried using the  tag with no success (code below). Any suggestions?

 <audio src="https://broadcastify.cdnstream1.com/28286">Davenport</audio>

Body:
If you want to display the audio element, you need to add the controls property.

<audio src="https://broadcastify.cdnstream1.com/28286" controls>Davenport</audio>


问:
How to get "copy as cURL" in the script?
There is a feature called "Copy as cURL" from the browsers in Developer Mode with a network tab.
I can get that copy of cURL headers by clicking mouse.

Is it possible to get the result from the shell without GUI?

答: Just use curl from the command line.  curl -I <URL> should do the trick to only get the headers, or curl -i <URL> if you want the headers along with the payload.  For other options see man curl or curl --help from the command lien.


问:
Find the count of IDs that have the same value
I'd like to get a count of all of the Ids that have have the same value (Drops) as other Ids. For instance, the illustration below shows you that ID 1 and 3 have A drops so the query would count them. Similarly, ID 7 & 18 have B drops so that's another two IDs that the query would count totalling in 4 Ids that share the same values so that's what my query would return.

```<code>+------+-------+
| ID   | Drops |
+------+-------+
|  1   |   A   |
|  2   |   C   |
|  3   |   A   |
|  7   |   B   |
| 18   |   B   |
+------+-------+
</code>```

I've tried the several approaches but the following query was my last attempt.

```<code>With cte1 (Id1, D1) as
(
    select Id, Drops
    from Posts
),
cte2 (Id2, D2) as
(
    select Id, Drops
    from Posts
)
Select count(distinct c1.Id1) newcnt, c1.D1
from cte1 c1
left outer join cte2 c2 on c1.D1 = c2.D2
group by c1.D1
</code>```

The result if written out in full would be a single value output but the records that the query should be choosing should look as follows:

```<code>    +------+-------+
    | ID   | Drops |
    +------+-------+
    |  1   |   A   |
    |  3   |   A   |
    |  7   |   B   |
    | 18   |   B   |
    +------+-------+
</code>```

Any advice would be great. Thanks

答:
First group the count of the ids for your drops and then sum the values greater than 1.</p>

```<code>select sum(countdrops) as total from
(select drops , count(id) as countdrops from yourtable group by drops) as temp
where countdrops > 1;
</code>```

Body:
I'd like to get a count of all of the Ids that have have the same value (Drops) as other Ids. For instance, the illustration below shows you that ID 1 and 3 have A drops so the query would count them. Similarly, ID 7 & 18 have B drops so that's another two IDs that the query would count totalling in 4 Ids that share the same values so that's what my query would return.

+------+-------+
| ID   | Drops |
+------+-------+
|  1   |   A   |
|  2   |   C   |
|  3   |   A   |
|  7   |   B   |
| 18   |   B   |
+------+-------+

I've tried the several approaches but the following query was my last attempt.

With cte1 (Id1, D1) as
(
    select Id, Drops
    from Posts
),
cte2 (Id2, D2) as
(
    select Id, Drops
    from Posts
)
Select count(distinct c1.Id1) newcnt, c1.D1
from cte1 c1
left outer join cte2 c2 on c1.D1 = c2.D2
group by c1.D1

The result if written out in full would be a single value output but the records that the query should be choosing should look as follows:

    +------+-------+
    | ID   | Drops |
    +------+-------+
    |  1   |   A   |
    |  3   |   A   |
    |  7   |   B   |
    | 18   |   B   |
    +------+-------+

Any advice would be great. Thanks

Body:
First group the count of the ids for your drops and then sum the values greater than 1.

select sum(countdrops) as total from
(select drops , count(id) as countdrops from yourtable group by drops) as temp
where countdrops > 1;


Title: R: Reshape every 2 rows of data into 1 row based on factor of a single column

Body:
I have the below data:

              TimeStamp      Fab23.A   start.end
1   2020-03-02 20:44:00     27.54236       start
2   2020-03-02 20:50:00    186.08670         end
3   2020-03-03 18:12:00     37.33132       start
4   2020-03-03 18:16:00    189.78060         end
5   2020-03-04 17:48:00     33.78360       start
6   2020-03-04 17:52:00    190.08100         end
.
.
.

I'm trying to reshape them to the below format based on the last categorical value of last column:

        start.TimeStamp          end.TimeStamp    start.Fab23.A    start.Fab23.A
1   2020-03-02 20:44:00    2020-03-02 20:50:00         27.54236        186.08670
2   2020-03-03 18:12:00    2020-03-03 18:16:00         37.33132        189.78060
3   2020-03-04 17:48:00    2020-03-04 17:52:00         33.78360        190.08100
.
.
.

I have tried reshape and melt function but to no avail.
Will appreciate any advice.

Body:
You can use :

library(dplyr)

df %>%
  group_by(start.end) %>%
  mutate(row = row_number()) %>%
  tidyr::pivot_wider(names_from = start.end,
                    values_from = c(TimeStamp, Fab23.A)) %>%
  select(-row)

# A tibble: 3 x 4
#  TimeStamp_start    TimeStamp_end      Fab23.A_start Fab23.A_end
#  <chr>              <chr>                      <dbl>       <dbl>
#1 2020-03-0220:44:00 2020-03-0220:50:00          27.5        186.
#2 2020-03-0318:12:00 2020-03-0318:16:00          37.3        190.
#3 2020-03-0417:48:00 2020-03-0417:52:00          33.8        190.

Or using data.table :

library(data.table)
dcast(setDT(df), rowid(start.end)~start.end,value.var = c("TimeStamp", "Fab23.A"))

data

df <- structure(list(TimeStamp = c("2020-03-0220:44:00", "2020-03-0220:50:00",
"2020-03-0318:12:00", "2020-03-0318:16:00", "2020-03-0417:48:00",
"2020-03-0417:52:00"), Fab23.A = c(27.54236, 186.0867, 37.33132,
189.7806, 33.7836, 190.081), start.end = c("start", "end", "start",
"end", "start", "end")), class = "data.frame", row.names = c(NA, -6L))


问:
How can a trie be used in a search engine(not for autocomplete)?
I've come across this:

The core information stored by a search engine is a dictionary, called an inverted
  index or inverted file, storing key-value pairs (w,L), where w is a word and L is
  a collection of pages containing word w. The keys (words) in this dictionary are
  called index terms and should be a set of vocabulary entries and proper nouns as
  large as possible. The elements in this dictionary are called occurrence lists and
  should cover as many Web pages as possible.

We can efficiently implement an inverted index with a data structure consisting
  of the following:

An array storing the occurrence lists of the terms (in no particular order).

A compressed trie for the set of index terms, where each leaf stores the index
  of the occurrence list of the associated term.
  The reason for storing the occurrence lists outside the trie is to keep the size of the
  trie data structure sufficiently small to fit in internal memory. Instead, because of
  their large total size, the occurrence lists have to be stored on disk.

and I don't understand it. If a dictionary is used to store occurence lists, what's the purpose of the trie? If I'm going to have to search for the word in the dictionary anyway, why bother with the trie?

Edit: The quote is from Data Structures and Algorithms in Python by Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser

答: Putting each word w into a Trie data structure reduces the memory needed to store the words and speeds up a search for a specific word. At the end of each word in the Trie, you'll find a list of pointers to documents that contain the word for which you searched.</p>


问:
Print all subsets in an array that equal to a given sum recursively
I have to write a code with a two methods that takes an array (non-negative) and a value sum as parameters.
I have to use the methods:

```<code>public static void printSubsetSums(int[] arr, int sum) {

}

public static void printSubsetSums(int[] arr, int sum, int i, String acc)
{

}
</code>```

We are not allowed to add methods or any more parameters for the current methods.
I did something similar that just prints the number of subsets that are from a given array according to a sum. but i'm having a hard time to change it to do this task...
my array is limited to the length of 5.

ecxample:
"Enter 5 numbers to array"
input:1 2 3 4 5
"Enter a number into sum"
input:8
3

why 3? (3,5) , (1,3,4) , (1,2,5)

Thank you for your help!!!

答:
Here is a recursive approach for solving this problem:

    public static void printSubsetSums(int[] arr, int sum) {
        printSubsetSums(arr, sum, 0, "");
    }

    public static void printSubsetSums(int[] arr, int sum, int i, String acc)
    {
        if (sum == 0 && !"".equals(acc)) {
            System.out.println(acc);
            acc = "";
        }
        if (i == arr.length) {
            return;
        }
        printSubsetSums(arr, sum, i + 1, acc);
        printSubsetSums(arr, sum - arr[i], i + 1, acc+" "+arr[i]);
    }
```

<h1>Explanation:</h1>

<p>First, you input your integer array and desired sum into the <code>printSubsetSums(int[] arr, int sum)</code> method that calls the helper method (<code>printSubsetSums(int[] arr, int sum, int i, String acc)</code>), where <code>i</code> is <code>arr</code>'s index and <code>acc</code> is the
 output for how the sum was reached.</p>

<p><code>if (i == arr.length) { return; }</code> acts as the base case to exit out of the recursive method (<code>i</code> is out of bounds).</p>

<p>Notice that we have <strong>two</strong> recursive calls (<code>printSubsetSums(arr, sum, i + 1, acc)</code> and <code>printSubsetSums(arr, sum - arr[i], i + 1, acc+" "+arr[i])</code>). The first acts if the current number would not work in order to reach the sum and thus <code>i</code> is incremented to "try again" with the next number in <code>arr</code>. The second option is that the current number will work, and so you move on to the next index whilst accounting for the current number (subtracting it from <code>sum</code> in order to eventually reach 0 [when we know that the numbers selected did add up to 10] and adding it to <code>acc</code>).</p>

<p>Finally, we print <code>acc</code> when the <code>sum</code> is 0. We also set <code>acc = ""</code> and avoid printing when <code>"".equals(acc)</code> in order to avoid counting the same answer multiple times.</p>

<h1>Result:</h1>

<p><strong>Example Input:</strong></p>

<p><code>printSubsetSums(new int[]{1,2,3,4,5}, 8)</code></p>

<p><strong>Example Output:</strong></p>

``` 3 5
 1 3 4
 1 2 5
```

Body:
I have to write a code with a two methods that takes an array (non-negative) and a value sum as parameters.
I have to use the methods:

public static void printSubsetSums(int[] arr, int sum) {

}

public static void printSubsetSums(int[] arr, int sum, int i, String acc)
{

}

We are not allowed to add methods or any more parameters for the current methods.
I did something similar that just prints the number of subsets that are from a given array according to a sum. but i'm having a hard time to change it to do this task...
my array is limited to the length of 5.

ecxample:
"Enter 5 numbers to array"
input:1 2 3 4 5
"Enter a number into sum"
input:8
3

why 3? (3,5) , (1,3,4) , (1,2,5)

Thank you for your help!!!

Body:
Here is a recursive approach for solving this problem:

    public static void printSubsetSums(int[] arr, int sum) {
        printSubsetSums(arr, sum, 0, "");
    }

    public static void printSubsetSums(int[] arr, int sum, int i, String acc)
    {
        if (sum == 0 && !"".equals(acc)) {
            System.out.println(acc);
            acc = "";
        }
        if (i == arr.length) {
            return;
        }
        printSubsetSums(arr, sum, i + 1, acc);
        printSubsetSums(arr, sum - arr[i], i + 1, acc+" "+arr[i]);
    }

Explanation:

First, you input your integer array and desired sum into the printSubsetSums(int[] arr, int sum) method that calls the helper method (printSubsetSums(int[] arr, int sum, int i, String acc)), where i is arr's index and acc is the
 output for how the sum was reached.

if (i == arr.length) { return; } acts as the base case to exit out of the recursive method (i is out of bounds).

Notice that we have two recursive calls (printSubsetSums(arr, sum, i + 1, acc) and printSubsetSums(arr, sum - arr[i], i + 1, acc+" "+arr[i])). The first acts if the current number would not work in order to reach the sum and thus i is incremented to "try again" with the next number in arr. The second option is that the current number will work, and so you move on to the next index whilst accounting for the current number (subtracting it from sum in order to eventually reach 0 [when we know that the numbers selected did add up to 10] and adding it to acc).

Finally, we print acc when the sum is 0. We also set acc = "" and avoid printing when "".equals(acc) in order to avoid counting the same answer multiple times.

Result:

Example Input:

printSubsetSums(new int[]{1,2,3,4,5}, 8)

Example Output:

 3 5
 1 3 4
 1 2 5


问:
Javascript "Permission Denied" Error in IE.x
I did the mistake of creating my entire web application and not testing it on IE along the way. I only tested it on Firefox and Safari. The web app runs fine on both Safari and Firefox but it gives a Permission Denied error on IE.

I am using Google AuthSub authentication and so for authenticating using Google Account, it first redirects to allow the app access to Google Account. After authentication, IE changes 'http' to 'https'. This does not happen with either Firefox or Safari. They remain with the 'http' protocol.

IE then gives a Permission Denied error. Is the JavaScript conflicting with 'https' in any way?

The app is here -> http://ankitahuja.com/apps/proxycal

and the error-causing page is -> http://ankitahuja.com/apps/proxycal/proxycal.php

答:
When I open up the proxycal.php page in both IE and FF, an error is raised on this line in the Javascript (in function _run):

```<code>calendarService = new google.gdata.calendar.CalendarService('proxycal');
</code>```

Here, calendar is not a member of google.gdata.

I suggest you debug through the call stack to find out what is not being initialized.

OwnerDisplayName: ankit

ContentLicense: CC BY-SA 2.5

Body:
When I open up the proxycal.php page in both IE and FF, an error is raised on this line in the Javascript (in function _run):

calendarService = new google.gdata.calendar.CalendarService('proxycal');

Here, calendar is not a member of google.gdata.

I suggest you debug through the call stack to find out what is not being initialized.

OwnerDisplayName: Cerebrus


问:
Copy selected multiple values to the text box
I have drop down list as below.

```<code>     <select id="checkOwner" multiple="multiple" onchange="copyValue()">
       <option value="FIRSTNAME">First Name</option>
       <option value="LASTNAME">Last Name</option>
     </select>
</code>```

I used Below javascript to add checkbox

```<code>$(function() {
  $('#checkOwner').multiselect({
   });
});
</code>```

I used below javascript to copy selected value to text field.

```<code>function copyValue() {
  var dropboxvalue = document.getElementById('checkOwner').value;
  document.getElementById('mytextbox').value = dropboxvalue;
}
</code>```

But the problem is, this copy only one value. I want to copy all the selected values. How can I do this?

答:
my approach is loop on the options then check the condition if isSelected

html

```<code><select name="checkOwner" multiple="multiple" onchange="copyValue(this)">
</code>```

js

```<code>const copyValue = me => {
    let y = Array.from(document.querySelectorAll('select option')).map(x => x.selected ? x.value : '')
    document.getElementById('mytextbox').value = y.join(' ');
}
</code>```

Body:
I have drop down list as below.

     <select id="checkOwner" multiple="multiple" onchange="copyValue()">
       <option value="FIRSTNAME">First Name</option>
       <option value="LASTNAME">Last Name</option>
     </select>

I used Below javascript to add checkbox

$(function() {
  $('#checkOwner').multiselect({
   });
});

I used below javascript to copy selected value to text field.

function copyValue() {
  var dropboxvalue = document.getElementById('checkOwner').value;
  document.getElementById('mytextbox').value = dropboxvalue;
}

But the problem is, this copy only one value. I want to copy all the selected values. How can I do this?

Body:
my approach is loop on the options then check the condition if isSelected

html

<select name="checkOwner" multiple="multiple" onchange="copyValue(this)">

js

const copyValue = me => {
    let y = Array.from(document.querySelectorAll('select option')).map(x => x.selected ? x.value : '')
    document.getElementById('mytextbox').value = y.join(' ');
}


问:
IE automation VBA - How to access a span button without any text
I am trying to do IE automation using VBA and facing a problem in clicking a span element.

I want to click on the below element.

```<code><span class="x-btn-icon-el x-btn-icon-el-default-toolbar-small de-icon-export_item " id="KEY_TOOLTIP_Export-btnIconEl" role="presentation" data-ref="btnIconEl" unselectable="on"> </span>
</code>```

Below is the code for the HTML Page. Since it is an intranet page, can't post the link for the same.

```<code><a tabindex="-1" class="x-btn x-unselectable x-box-item x-toolbar-item x-btn-default-toolbar-small x-btn-over" id="KEY_TOOLTIP_Export" style="margin: 0px; left: 32px; top: 2px; right: auto;" hidefocus="on" unselectable="on" componentId="KEY_TOOLTIP_Export" data-qtip="Export">
  <span class="x-btn-wrap x-btn-wrap-default-toolbar-small " id="KEY_TOOLTIP_Export-btnWrap" role="presentation" data-ref="btnWrap" unselectable="on">
    <span class="x-btn-button x-btn-button-default-toolbar-small  x-btn-no-text x-btn-icon x-btn-icon-left x-btn-button-center " id="KEY_TOOLTIP_Export-btnEl" role="presentation" data-ref="btnEl" unselectable="on">
      <span class="x-btn-icon-el x-btn-icon-el-default-toolbar-small de-icon-export_item " id="KEY_TOOLTIP_Export-btnIconEl" role="presentation" data-ref="btnIconEl" unselectable="on"> </span>
        <span class="x-btn-inner x-btn-inner-default-toolbar-small" id="KEY_TOOLTIP_Export-btnInnerEl" data-ref="btnInnerEl" unselectable="on"> </span>
</span>
</span>
</a>
</code>```

Below are the options I have tried using other reference posts.
Find the Span element by ID and then find the parent for it, which seems to be the  tag.

```<code>doc.getElementById("KEY_TOOLTIP_Export-btnIconEl").ParentNode.Click
</code>```

Tried with class name as well.

```<code>doc.getElementsByClassName("x-btn-icon-el x-btn-icon-el-default-toolbar-small de-icon-export_item").Item(0).ParentNode.Click
</code>```

I am able to find the element in the parent frame using the debugging option, so that should rule out the iFrame, isn't it?

I am very new to HTML, JavaScript so not understanding what else to check.

答:
If the provide code not inside the Iframe tag, you could use the following code to find the element.

```<code>Sub Test()
    Dim IE As Object
    Dim selectItem As Object

    Set IE = CreateObject("InternetExplorer.Application")
    With IE
        .Visible = True
        .Navigate "<website url>"

        While IE.ReadyState <> 4
            DoEvents
        Wend
        'Find element by ID property.
       'Set selectItem = IE.document.getElementById("KEY_TOOLTIP_Export-btnIconEl")
       'Debug.Print SelectItem.innerText
       'selectItem.Click

       'Find element by Class Name
       Set selectItem = IE.document.getElementsByClassName("x-btn-icon-el x-btn-icon-el-default-toolbar-small de-icon-export_item")(0)

       Debug.Print selectItem.innerText
       selectItem.Click

    End With
    Set IE = Nothing
End Sub
</code>```

Note: please remember to change the website url to your owns.

In order to see the effect more clearly, I have added the onclick event in the span tag and a tag. The Html resource as below:

```<code> <a tabindex="-1" onclick="alert('a click');" class="x-btn x-unselectable x-box-item x-toolbar-item x-btn-default-toolbar-small x-btn-over" id="KEY_TOOLTIP_Export" style="margin: 0px; left: 32px; top: 2px; right: auto;" hidefocus="on" unselectable="on" componentId="KEY_TOOLTIP_Export" data-qtip="Export">
    <span class="x-btn-wrap x-btn-wrap-default-toolbar-small " id="KEY_TOOLTIP_Export-btnWrap" role="presentation" data-ref="btnWrap" unselectable="on">
        <span class="x-btn-button x-btn-button-default-toolbar-small  x-btn-no-text x-btn-icon x-btn-icon-left x-btn-button-center " id="KEY_TOOLTIP_Export-btnEl" role="presentation" data-ref="btnEl" unselectable="on">
            <span class="x-btn-icon-el x-btn-icon-el-default-toolbar-small de-icon-export_item " id="KEY_TOOLTIP_Export-btnIconEl" role="presentation" data-ref="btnIconEl" onclick="alert('hi');" unselectable="on"> </span>
            <span class="x-btn-inner x-btn-inner-default-toolbar-small" id="KEY_TOOLTIP_Export-btnInnerEl" data-ref="btnInnerEl" unselectable="on"> </span>
        </span>
    </span>
</a>
</code>```

The screenshot:

If the elements inside the iframe tag, Html resource like this:

You could use the following code to find the iframe element first, and then, access the span element.

```<code>   Set selectItem = IE.document.getElementsByTagName("iframe")(0).contentDocument.getElementById("KEY_TOOLTIP_Export-btnIconEl")
   'Debug.Print selectItem.innerText 'debug, check the inner text.
   selectItem.Click
</code>```

Body:
I am trying to do IE automation using VBA and facing a problem in clicking a span element.

I want to click on the below element.

Below is the code for the HTML Page. Since it is an intranet page, can't post the link for the same.

Below are the options I have tried using other reference posts.
Find the Span element by ID and then find the parent for it, which seems to be the  tag.

doc.getElementById("KEY_TOOLTIP_Export-btnIconEl").ParentNode.Click

Tried with class name as well.

doc.getElementsByClassName("x-btn-icon-el x-btn-icon-el-default-toolbar-small de-icon-export_item").Item(0).ParentNode.Click

I am able to find the element in the parent frame using the debugging option, so that should rule out the iFrame, isn't it?

I am very new to HTML, JavaScript so not understanding what else to check.

Body:
If the provide code not inside the Iframe tag, you could use the following code to find the element.

Sub Test()
    Dim IE As Object
    Dim selectItem As Object

    Set IE = CreateObject("InternetExplorer.Application")
    With IE
        .Visible = True
        .Navigate "<website url>"

        While IE.ReadyState <> 4
            DoEvents
        Wend
        'Find element by ID property.
       'Set selectItem = IE.document.getElementById("KEY_TOOLTIP_Export-btnIconEl")
       'Debug.Print SelectItem.innerText
       'selectItem.Click

       'Find element by Class Name
       Set selectItem = IE.document.getElementsByClassName("x-btn-icon-el x-btn-icon-el-default-toolbar-small de-icon-export_item")(0)

       Debug.Print selectItem.innerText
       selectItem.Click

    End With
    Set IE = Nothing
End Sub

Note: please remember to change the website url to your owns.

In order to see the effect more clearly, I have added the onclick event in the span tag and a tag. The Html resource as below:

 <a tabindex="-1" onclick="alert('a click');" class="x-btn x-unselectable x-box-item x-toolbar-item x-btn-default-toolbar-small x-btn-over" id="KEY_TOOLTIP_Export" style="margin: 0px; left: 32px; top: 2px; right: auto;" hidefocus="on" unselectable="on" componentId="KEY_TOOLTIP_Export" data-qtip="Export">
    <span class="x-btn-wrap x-btn-wrap-default-toolbar-small " id="KEY_TOOLTIP_Export-btnWrap" role="presentation" data-ref="btnWrap" unselectable="on">
        <span class="x-btn-button x-btn-button-default-toolbar-small  x-btn-no-text x-btn-icon x-btn-icon-left x-btn-button-center " id="KEY_TOOLTIP_Export-btnEl" role="presentation" data-ref="btnEl" unselectable="on">
            <span class="x-btn-icon-el x-btn-icon-el-default-toolbar-small de-icon-export_item " id="KEY_TOOLTIP_Export-btnIconEl" role="presentation" data-ref="btnIconEl" onclick="alert('hi');" unselectable="on">&nbsp;</span>
            <span class="x-btn-inner x-btn-inner-default-toolbar-small" id="KEY_TOOLTIP_Export-btnInnerEl" data-ref="btnInnerEl" unselectable="on">&nbsp;</span>
        </span>
    </span>
</a>

The screenshot:

If the elements inside the iframe tag, Html resource like this:

You could use the following code to find the iframe element first, and then, access the span element.

   Set selectItem = IE.document.getElementsByTagName("iframe")(0).contentDocument.getElementById("KEY_TOOLTIP_Export-btnIconEl")
   'Debug.Print selectItem.innerText 'debug, check the inner text.
   selectItem.Click


问:
disable default zoom in feature on input controls in webview
when user clicks on input controls like input text of text area, the webview zooms in by default,

Can we control this feature.

答:
Yes use it.You can set zoom on webview according to your requirement.</p>
```<code>WebView webView=(WebView)this.findViewById(R.id.link4_view);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.setInitialScale(50);
    webView.loadUrl("http://www.racquetime.com/terms");
            webView.zoomIn();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Yes use it.You can set zoom on webview according to your requirement.

WebView webView=(WebView)this.findViewById(R.id.link4_view);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.setInitialScale(50);
    webView.loadUrl("http://www.racquetime.com/terms");
            webView.zoomIn();


问:
Point-In-time-recovery in Greenplum Database
We have recently setup greenplum. Now the major concern is to setup strategy for PITR. Postgres provides PITR capability but I am a little confused as how will it work in greenplum as each segment will have it's own log directory and config file</p>

答:
We recently introduced the concept of named restore point to serve as a building block for PITR for greenplum. In order to use this you will need to use the catalog function gp_create_restore_point() which internally creates a cluster wide consistency point across all the segments. This function returns all the restore point location () for each segment and the master. Using these recovery points you will be able to configure the recover.conf in your PITR cluster

To demonstrate how Greenplum named restore points work, a new test
directory src/test/gpdb_pitr has been added. The test showcases WAL
Archiving in conjunction with the named restore points to do
Point-In-Time Recovery.

In case you are most interested in the details, please refer to the following two commits that discusses this functionality in detail https://github.com/greenplum-db/gpdb/commit/47896cc89b4935199aa7d97043f2b7572a71042b

https://github.com/greenplum-db/gpdb/commit/40e0fd9ce6c7da3921f0b12e55118320204f0f6d


问:
Check if file exists in HDFS path?
How can I check if a file exists given a certain base path. I am providing the method a file list for example:
file1.snappy, file2,snappy,...

I need to check if file exists in either of the given paths for example: hdfs://a/b/c/source/file1.snappy or if file exists in hdfs://a/b/c/target/file1.snappy. How can I update/modify the method below to accept /a/b/c/target/ or /a/b/c/source/ as a basepath and check if file exists? If it exists in source add to a sourceList and if it is in destination add to a destination list.

```<code>  val fs = FileSystem.get(sprk.sparkContext.hadoopConfiguration)

  def fileExists(fileList:Array[String]) : Boolean = {
    var fileNotFound = 0
    fileList.foreach{
      file => {
        if(!fs.exists(new Path(file)))  fileNotFound+=1
        print("fileList",file)
      }
    }
    if(fileNotFound > 0) {
      println(fileNotFound + ": number of files not found probably moved")
      false
    }
    else
      true
  }
</code>```

答:
I have a source dir and target are like this below example

try this way for recursive lookup

URI.create(... ) is very imp when you are dealing with s3 objects (will also works with hdfs / local fs)

```<code>import java.net.URI

import org.apache.hadoop.fs.{FileSystem, LocatedFileStatus, Path, RemoteIterator}
import org.apache.log4j.{Level, Logger}
import org.apache.spark.SparkContext
import org.apache.spark.sql.SparkSession
/**
    * getAllFiles - get all files recursively from the sub folders.
    *
    * @param path String
    * @param sc SparkContext
    * @return Seq[String]
    */
  def getAllFiles(path: String, sc: SparkContext): Seq[String] = {
    val conf = sc.hadoopConfiguration
    val fs = FileSystem.get(URI.create(path), conf)
    val files: RemoteIterator[LocatedFileStatus] = fs.listFiles(new Path(path), true) // true for recursive lookup
    val buf = new ArrayBuffer[String]
    while (files.hasNext()) {
      val fileStatus = files.next();
      buf.append(fileStatus.getPath().toString)
    }
    buf.toSeq
  }
</code>```

Example usage  :

```<code> val spark: SparkSession = SparkSession.builder.appName(getClass.getName)
    .master("local[*]").getOrCreate

  val sc = spark.sparkContext

  val myfiles: Seq[String] = getAllFiles("data/test_table", sc)
  myfiles.foreach(println)
  println(myfiles.contains("/data/test_table/source/part-00000-19b67f0c-3fb0-4718-8a31-ac770e2dc0ba-c000.snappy.parquet"))
</code>```

Result :

```<code>/data/test_table/target/part-00000-9205704a-cb0c-4933-87d4-c21313e76297-c000.snappy.parquet
/data/test_table/target/part-00000-19b67f0c-3fb0-4718-8a31-ac770e2dc0ba-c000.snappy1111.parquet
/data/test_table/target/part-00000-9205704a-cb0c-4933-87d4-c21313e76297-c000.snappy11.parquet
/data/test_table/source/part-00000-19b67f0c-3fb0-4718-8a31-ac770e2dc0ba-c000.snappy1.parquet
/data/test_table/source/part-00000-19b67f0c-3fb0-4718-8a31-ac770e2dc0ba-c000.snappy111.parquet
/data/test_table/source/part-00000-19b67f0c-3fb0-4718-8a31-ac770e2dc0ba-c000.snappy.parquet

true
</code>```

Title: Check if file exists in HDFS path?

Body:
How can I check if a file exists given a certain base path. I am providing the method a file list for example:
file1.snappy, file2,snappy,...

I need to check if file exists in either of the given paths for example: hdfs://a/b/c/source/file1.snappy or if file exists in hdfs://a/b/c/target/file1.snappy. How can I update/modify the method below to accept /a/b/c/target/ or /a/b/c/source/ as a basepath and check if file exists? If it exists in source add to a sourceList and if it is in destination add to a destination list.

  val fs = FileSystem.get(sprk.sparkContext.hadoopConfiguration)

  def fileExists(fileList:Array[String]) : Boolean = {
    var fileNotFound = 0
    fileList.foreach{
      file => {
        if(!fs.exists(new Path(file)))  fileNotFound+=1
        print("fileList",file)
      }
    }
    if(fileNotFound > 0) {
      println(fileNotFound + ": number of files not found probably moved")
      false
    }
    else
      true
  }

Body:
I have a source dir and target are like this below example

try this way for recursive lookup

URI.create(... ) is very imp when you are dealing with s3 objects (will also works with hdfs / local fs)

import java.net.URI

import org.apache.hadoop.fs.{FileSystem, LocatedFileStatus, Path, RemoteIterator}
import org.apache.log4j.{Level, Logger}
import org.apache.spark.SparkContext
import org.apache.spark.sql.SparkSession
/**
    * getAllFiles - get all files recursively from the sub folders.
    *
    * @param path String
    * @param sc SparkContext
    * @return Seq[String]
    */
  def getAllFiles(path: String, sc: SparkContext): Seq[String] = {
    val conf = sc.hadoopConfiguration
    val fs = FileSystem.get(URI.create(path), conf)
    val files: RemoteIterator[LocatedFileStatus] = fs.listFiles(new Path(path), true) // true for recursive lookup
    val buf = new ArrayBuffer[String]
    while (files.hasNext()) {
      val fileStatus = files.next();
      buf.append(fileStatus.getPath().toString)
    }
    buf.toSeq
  }

Example usage  :

 val spark: SparkSession = SparkSession.builder.appName(getClass.getName)
    .master("local[*]").getOrCreate

  val sc = spark.sparkContext

  val myfiles: Seq[String] = getAllFiles("data/test_table", sc)
  myfiles.foreach(println)
  println(myfiles.contains("/data/test_table/source/part-00000-19b67f0c-3fb0-4718-8a31-ac770e2dc0ba-c000.snappy.parquet"))

Result :

/data/test_table/target/part-00000-9205704a-cb0c-4933-87d4-c21313e76297-c000.snappy.parquet
/data/test_table/target/part-00000-19b67f0c-3fb0-4718-8a31-ac770e2dc0ba-c000.snappy1111.parquet
/data/test_table/target/part-00000-9205704a-cb0c-4933-87d4-c21313e76297-c000.snappy11.parquet
/data/test_table/source/part-00000-19b67f0c-3fb0-4718-8a31-ac770e2dc0ba-c000.snappy1.parquet
/data/test_table/source/part-00000-19b67f0c-3fb0-4718-8a31-ac770e2dc0ba-c000.snappy111.parquet
/data/test_table/source/part-00000-19b67f0c-3fb0-4718-8a31-ac770e2dc0ba-c000.snappy.parquet

true


问:
Conditional commands in discord.py
I want a user to be able to find out about something by, for example, saying something like !ask [___]. I would have a certain list of things that it could ask. Specifically, what notes are in a certain musical scale. So they would ask !scale Cmajor and get a response of "the notes in C major are C,D,E,F,G,A,B." I'm an absolute beginner and have no idea how to do this. I've made one bot before, but that's all my python experience.</p>

答:
You can view how to do such a task from the discord.py documentation

Specifically something like this could work, assuming you're using the latest version of discord.py, and following the appropriate setup:

```<code># This is assuming your prefix is already defined, and you have a general bot setup
@bot.command()
async def scale(ctx, arg): # assuming the prefix is !, the command will be !scale argument
    if arg.lower() == "cmajor":
        await ctx.send("The notes in C major are C,D,E,F,G,A,B.")
    else:
        await ctx.send("Invalid scale.") # add more scales as needed
</code>```

Title: Conditional commands in discord.py

Body:
You can view how to do such a task from the discord.py documentation

Specifically something like this could work, assuming you're using the latest version of discord.py, and following the appropriate setup:

# This is assuming your prefix is already defined, and you have a general bot setup
@bot.command()
async def scale(ctx, arg): # assuming the prefix is !, the command will be !scale argument
    if arg.lower() == "cmajor":
        await ctx.send("The notes in C major are C,D,E,F,G,A,B.")
    else:
        await ctx.send("Invalid scale.") # add more scales as needed


问:
concatenating columns in a dataframe pyspark with null values
```<code>Data:
Name1            Name2            Name3(Expected)
RR Industries    null            RR Industries
RR Industries    RR Industries   RR IndustriesRR Industries
</code>```

Code:

```<code>.withColumn("Name3",F.concat(F.trim(Name1), F.trim(Name2)))
</code>```

Actual result:
The columns with null values are deleted.
I want the output to be as seen in Name3(Expected Columnt)

I think, the issue occurs after the joining the tables
The name column is available in df2 and df3.
before joining they do not contain null values.

Issue:
After joining; since pyspark doesnt delete the common columns, we have two name1 columns from 2 tables
I tried replcaing it with empty string;it didnt work and throws error

How do I replace null values with empty string after joining tables

```<code>df = df1\
.join(df2,"code",how = 'left') \
.join(df3,"id",how = 'left')\
.join(df4,"id",how = 'left')\
.withColumn('name1',F.when(df2('name1').isNull(),'').otherwise(df2('name1')))\
.withColumn('name1',F.when(df3('name1').isNull(),'').otherwise(df3('name1')))\
.withColumn("Name1",F.concat(F.trim(df2.name1), F.trim(df3.name1)))
</code>```

答:
you can try this approach in pyspark</p>

```<code>from pyspark.sql import SparkSession
from pyspark.sql import functions as F

spark = SparkSession.builder \
.appName('practice')\
.getOrCreate()

sc= spark.sparkContext

df = sc.parallelize([
("RR Industries",None), ("RR Industries", "RR Industries")]).toDF(["Name1",
  "Name2"])

 df.withColumn("Name3", F.concat_ws("", F.col("Name1"),
 F.col("Name2"))).show(truncate=False)

+-------------+-------------+--------------------------+
|Name1        |Name2        |Name3                     |
+-------------+-------------+--------------------------+
|RR Industries|null         |RR Industries             |
|RR Industries|RR Industries|RR IndustriesRR Industries|
+-------------+-------------+--------------------------+
</code>```

Body:
Data:
Name1            Name2            Name3(Expected)
RR Industries    null            RR Industries
RR Industries    RR Industries   RR IndustriesRR Industries

Code:

.withColumn("Name3",F.concat(F.trim(Name1), F.trim(Name2)))

Actual result:
The columns with null values are deleted.
I want the output to be as seen in Name3(Expected Columnt)

I think, the issue occurs after the joining the tables
The name column is available in df2 and df3.
before joining they do not contain null values.

Issue:
After joining; since pyspark doesnt delete the common columns, we have two name1 columns from 2 tables
I tried replcaing it with empty string;it didnt work and throws error

How do I replace null values with empty string after joining tables

df = df1\
.join(df2,"code",how = 'left') \
.join(df3,"id",how = 'left')\
.join(df4,"id",how = 'left')\
.withColumn('name1',F.when(df2('name1').isNull(),'').otherwise(df2('name1')))\
.withColumn('name1',F.when(df3('name1').isNull(),'').otherwise(df3('name1')))\
.withColumn("Name1",F.concat(F.trim(df2.name1), F.trim(df3.name1)))

Body:
you can try this approach in pyspark

from pyspark.sql import SparkSession
from pyspark.sql import functions as F

spark = SparkSession.builder \
.appName('practice')\
.getOrCreate()

sc= spark.sparkContext

df = sc.parallelize([
("RR Industries",None), ("RR Industries", "RR Industries")]).toDF(["Name1",
  "Name2"])

 df.withColumn("Name3", F.concat_ws("", F.col("Name1"),
 F.col("Name2"))).show(truncate=False)

+-------------+-------------+--------------------------+
|Name1        |Name2        |Name3                     |
+-------------+-------------+--------------------------+
|RR Industries|null         |RR Industries             |
|RR Industries|RR Industries|RR IndustriesRR Industries|
+-------------+-------------+--------------------------+


问:
Can I change the image file of an existing Evas_Object?

I am developing a watch face with Tizen Native using the EFL libraries. After creating many objects with:

Evas_Object *view_create_parts(Evas_Object *parent, const char *image_path,
    int position_x, int position_y, int size_w, int size_h) {
    Evas_Object *parts = NULL;

    parts = elm_image_add(parent);

    elm_image_file_set(parts, image_path, NULL);

    evas_object_move(parts, position_x, position_y);
    evas_object_resize(parts, size_w, size_h);

    evas_object_show(parts);

    return parts;
}
```

I would like to change the image of some of the existing objects later on as needed. Is this possible? I know that I could also load all possible variants as individual objects and show/hide the objects accordingly. But I find it way simpler and elegant to just change the image of an existing object. Plus, this probably uses less resources too.

I tried to do this:

elm_image_file_set(<part_I_want_to_change_its_image>, "images/newimage.png", NULL));

But instead of changing to the correct image, the object just disappears. Any ideas?

答:
I finally found out what I was doing wrong. I was not aware of how the image path has to be formed. Nonworking method:

```<code>elm_image_file_set(s_info.hand_hour, "images/new_image.png", NULL);
</code>```

Working method:

```<code>char image_path[PATH_MAX] = { 0, };
data_get_resource_path("images/new_image.png", image_path, sizeof(image_path));
elm_image_file_set(s_info.hand_hour, image_path, NULL);
</code>```

Body:
I am developing a watch face with Tizen Native using the EFL libraries. After creating many objects with:

Evas_Object *view_create_parts(Evas_Object *parent, const char *image_path,
    int position_x, int position_y, int size_w, int size_h) {
    Evas_Object *parts = NULL;

    parts = elm_image_add(parent);

    elm_image_file_set(parts, image_path, NULL);

    evas_object_move(parts, position_x, position_y);
    evas_object_resize(parts, size_w, size_h);

    evas_object_show(parts);

    return parts;
}

I would like to change the image of some of the existing objects later on as needed. Is this possible? I know that I could also load all possible variants as individual objects and show/hide the objects accordingly. But I find it way simpler and elegant to just change the image of an existing object. Plus, this probably uses less resources too.

I tried to do this:

elm_image_file_set(<part_I_want_to_change_its_image>, "images/newimage.png", NULL));

But instead of changing to the correct image, the object just disappears. Any ideas?

Body:
I finally found out what I was doing wrong. I was not aware of how the image path has to be formed. Nonworking method:

elm_image_file_set(s_info.hand_hour, "images/new_image.png", NULL);

Working method:

char image_path[PATH_MAX] = { 0, };
data_get_resource_path("images/new_image.png", image_path, sizeof(image_path));
elm_image_file_set(s_info.hand_hour, image_path, NULL);


问:
Search text file that created today by partial name and copy over to another folder in powershell
I just wandering how can I search a text file that created today by partial name and copy over to another folder in power shell.

Example:
I have the following files:

```<code>LS_TA__Importing__123.TXT (created today)
LS_TA__Importing__145.TXT (created yesterday)
LS_TA__Importing__287.TXT (created yesterday)
LS_TA__Importing__687.TXT (created day after yesterday)
</code>```

How could I use power shell to search for the text file that created today by partial name (example LS_TA__Importing__*.TXT) and copy over to another folder?

答:
You can use Get-ChildItem and select only files that were created today

```<code>Get-ChildItem 'LS_TA__Importing__*.TXT' | where {$_.CreationTime -gt (Get-Date).Date}
</code>```

and pipe the results to Move-Item

```<code>Get-ChildItem 'LS_TA__Importing__*.TXT' | where {$_.CreationTime -gt (Get-Date).Date} | Move-Item -Destination .\OtherFolder
</code>```

Body:
I just wandering how can I search a text file that created today by partial name and copy over to another folder in power shell.

Example:
I have the following files:

LS_TA__Importing__123.TXT (created today)
LS_TA__Importing__145.TXT (created yesterday)
LS_TA__Importing__287.TXT (created yesterday)
LS_TA__Importing__687.TXT (created day after yesterday)

How could I use power shell to search for the text file that created today by partial name (example LS_TA__Importing__*.TXT) and copy over to another folder?

Body:
You can use Get-ChildItem and select only files that were created today

Get-ChildItem 'LS_TA__Importing__*.TXT' | where {$_.CreationTime -gt (Get-Date).Date}

and pipe the results to Move-Item

Get-ChildItem 'LS_TA__Importing__*.TXT' | where {$_.CreationTime -gt (Get-Date).Date} | Move-Item -Destination .\OtherFolder


问:
(Django, Python) How do I fix json.decoder.JSONDecodeError?
I have been trying to make an order/cart app for a sandwich shop. While I am testing I keep getting the error that has to do with decoding the JSON data front-end engineers send me.

Below is the POST request that the server receives.

```<code>{
    "default_ingredients": [
        {
            "id": 1,
            "name": "이탈리안 화이트 (top)",
            "image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/Options/o_BreadItalian_customizer_large.png",
            "price": "0.00",
            "ingredient_category_id": 1
        },
        {
            "id": 23,
            "name": "토마토",
            "image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/OptionsIds/10133_customizer_large.png",
            "price": "0.00",
            "ingredient_category_id": 3
        },
    ],
    "added_ingredients": [
        {
            "id": 18,
            "name": "살라미",
            "image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/Options/o_TurkeyBasedHamSalamiBologna_customizer_large.png",
            "price": "0.00",
            "ingredient_category_id": 2
        },
        {
            "id": 19,
            "name": "페퍼로니",
            "image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/Options/o_Pepperoni_customizer_large.png",
            "price": "1800.00",
            "ingredient_category_id": 2
        },
    ],
    "product_name": "이탈리안 비엠티",
}
</code>```

And below is my views.py for the order app

```<code>import json
import ast
import jwt
import bcrypt

from django.views               import View
from django.http                import JsonResponse

from .models        import (
    Order,
    Cart,
    CartIngredient,
    DestinationLocation,
    OrderStatus
)
from product.models import (
    Product,
    Category,
    SubCategory,
    Nutrition,
    Ingredient,
    ProductIngredient
)
from store.models           import Store
from account.models         import Customer
from codesandwich.settings  import SECRET_KEY

def login_required(func):
        def wrapper(self, request, *args, **kwargs):

            header_token    = request.META.get('HTTP_AUTHORIZATION')
            decoded_token   = jwt.decode(header_token, SECRET_KEY, algorithm='HS256')['email']

            try:
                if Customer.objects.filter(email=decoded_token).exists():
                    return func(self, request, *args, **kwargs)
                else:
                    return JsonResponse({"message": "customer does not exist"})
            except jwt.DecodeError:
                return JsonResponse({"message": "WRONG_TOKEN!"}, status=403)
            except KeyError:
                return JsonResponse({"message": "Key Error"}, status=405)
            except Customer.objects.filter(email=decoded_token).DoesNotExist:
                return JsonResponse({"message": "User Not Found"}, status=406)
        return wrapper

class CartView(View):

    @login_required
    def post(self, request):
        #import pdb; pdb.set_trace()
######### PART THAT NEEDS TO BE FIXED ################################
        body = json.loads(request.body).decode('utf-8')             #
######################################################################
        ## must receive user info
        ## decoded_token -> email -> filter(email=email) -> retrieve id
        header_token    = request.META.get('HTTP_AUTHORIZATION', '')
        decoded_token   = jwt.decode(header_token,SECRET_KEY, algorithm='HS256')['email']
        customer_id = Customer.objects.get(email=decoded_token).id
        a = Customer.objects.get(id=customer_id)
         ## below is when the customer's order is still active
        if Order.objects.filter(customer_id = customer_id).last().order_status.id == 2:

            ## update the order by just adding carts
            order_id = Order.objects.filter(customer = a).last().id
            order = Order.objects.get(id = order_id)
            if body['product']:
                product_id = body['product']['id']
                product = Product.objects.get(id = product_id)
                #this extracts the price
                price = body['product']['default_price']
                price = float(price)
                ## make a new cart for default_item
                Cart.objects.create(order = order, price = price, amount = 1, product = product)
                order.total_price += price
                order.save()

</code>```

The part in question is right below 'class CartView(View)'

And this is the error message:

```<code>> /Users/woohyunan/projects/Wecode/code-sandwich/code-sandwich-backend/code-sandwich-backend/order/views.py(52)post()->None
-> body = json.loads(request.body).decode('utf-8')
(Pdb) next
json.decoder.JSONDecodeError: Expecting value: line 17 column 2 (char 636)
> /Users/woohyunan/projects/Wecode/code-sandwich/code-sandwich-backend/code-sandwich-backend/order/views.py(36)wrapper()
-> return func(self, request, *args, **kwargs)
</code>```

What should I do to avoid this error? I have tried ast as well but it still didn't work for me.

答:
I found the answer. The answer was in decoding with 'utf-8' BEFORE using the ast evaluation.</p>

```<code>body = ast.literal_eval(request.body.decode('utf-8'))
</code>```

Body:
I have been trying to make an order/cart app for a sandwich shop. While I am testing I keep getting the error that has to do with decoding the JSON data front-end engineers send me.

Below is the POST request that the server receives.

{
    "default_ingredients": [
        {
            "id": 1,
            "name": "이탈리안 화이트 (top)",
            "image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/Options/o_BreadItalian_customizer_large.png",
            "price": "0.00",
            "ingredient_category_id": 1
        },
        {
            "id": 23,
            "name": "토마토",
            "image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/OptionsIds/10133_customizer_large.png",
            "price": "0.00",
            "ingredient_category_id": 3
        },
    ],
    "added_ingredients": [
        {
            "id": 18,
            "name": "살라미",
            "image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/Options/o_TurkeyBasedHamSalamiBologna_customizer_large.png",
            "price": "0.00",
            "ingredient_category_id": 2
        },
        {
            "id": 19,
            "name": "페퍼로니",
            "image_url": "https://media.subway.com/digital/Account_Updates/Assets/App-Base/Web_Images/Subway/en-us/Options/o_Pepperoni_customizer_large.png",
            "price": "1800.00",
            "ingredient_category_id": 2
        },
    ],
    "product_name": "이탈리안 비엠티",
}

And below is my views.py for the order app

import json
import ast
import jwt
import bcrypt

from django.views               import View
from django.http                import JsonResponse

from .models        import (
    Order,
    Cart,
    CartIngredient,
    DestinationLocation,
    OrderStatus
)
from product.models import (
    Product,
    Category,
    SubCategory,
    Nutrition,
    Ingredient,
    ProductIngredient
)
from store.models           import Store
from account.models         import Customer
from codesandwich.settings  import SECRET_KEY

def login_required(func):
        def wrapper(self, request, *args, **kwargs):

            header_token    = request.META.get('HTTP_AUTHORIZATION')
            decoded_token   = jwt.decode(header_token, SECRET_KEY, algorithm='HS256')['email']

            try:
                if Customer.objects.filter(email=decoded_token).exists():
                    return func(self, request, *args, **kwargs)
                else:
                    return JsonResponse({"message": "customer does not exist"})
            except jwt.DecodeError:
                return JsonResponse({"message": "WRONG_TOKEN!"}, status=403)
            except KeyError:
                return JsonResponse({"message": "Key Error"}, status=405)
            except Customer.objects.filter(email=decoded_token).DoesNotExist:
                return JsonResponse({"message": "User Not Found"}, status=406)
        return wrapper

class CartView(View):

    @login_required
    def post(self, request):
        #import pdb; pdb.set_trace()
######### PART THAT NEEDS TO BE FIXED ################################
        body = json.loads(request.body).decode('utf-8')             #
######################################################################
        ## must receive user info
        ## decoded_token -> email -> filter(email=email) -> retrieve id
        header_token    = request.META.get('HTTP_AUTHORIZATION', '')
        decoded_token   = jwt.decode(header_token,SECRET_KEY, algorithm='HS256')['email']
        customer_id = Customer.objects.get(email=decoded_token).id
        a = Customer.objects.get(id=customer_id)
         ## below is when the customer's order is still active
        if Order.objects.filter(customer_id = customer_id).last().order_status.id == 2:

            ## update the order by just adding carts
            order_id = Order.objects.filter(customer = a).last().id
            order = Order.objects.get(id = order_id)
            if body['product']:
                product_id = body['product']['id']
                product = Product.objects.get(id = product_id)
                #this extracts the price
                price = body['product']['default_price']
                price = float(price)
                ## make a new cart for default_item
                Cart.objects.create(order = order, price = price, amount = 1, product = product)
                order.total_price += price
                order.save()

The part in question is right below 'class CartView(View)'

And this is the error message:

> /Users/woohyunan/projects/Wecode/code-sandwich/code-sandwich-backend/code-sandwich-backend/order/views.py(52)post()->None
-> body = json.loads(request.body).decode('utf-8')
(Pdb) next
json.decoder.JSONDecodeError: Expecting value: line 17 column 2 (char 636)
> /Users/woohyunan/projects/Wecode/code-sandwich/code-sandwich-backend/code-sandwich-backend/order/views.py(36)wrapper()
-> return func(self, request, *args, **kwargs)

What should I do to avoid this error? I have tried ast as well but it still didn't work for me.

Body:
I found the answer. The answer was in decoding with 'utf-8' BEFORE using the ast evaluation.

body = ast.literal_eval(request.body.decode('utf-8'))


问:
Is there any way to set up a .bin file in my cloud vm to restart my server every time it crashes?
Title explains everything. I am currently working on a minecraft server for my school in the cloud; however it crashes frequently and I don't have enough time to restart it every time it crashes. Is there any way that I can make a file to restart it every time it crashes or better yet make it so that it can restart every night at midnight?</p>

答:
One of the options is to use additional VM to schedule a job (crontab) with OCI CLI restart command
The job can run every day at midnight and run the below command:

```<code>oci compute instance action --instance-id ocid.xxx --action SOFTRESET
</code>```

or

```<code>oci compute instance action --instance-id ocid.xxx --action RESET
</code>```

For your info

Body:
One of the options is to use additional VM to schedule a job (crontab) with OCI CLI restart command
The job can run every day at midnight and run the below command:

oci compute instance action --instance-id ocid.xxx --action SOFTRESET

or

oci compute instance action --instance-id ocid.xxx --action RESET

For your info


问:
Exception when adding a record to an Access 2007 database in c#
I'm trying to add a record to an Access 2007 database using c# but I get an exception.

Here's my code, the database is called hms and the table is called login

```<code>DataSet ds = new DataSet();

System.Data.OleDb.OleDbConnection con;
DataRow dRow;
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" +  Application.StartupPath + "\\hms.mdb";
string sql = "select * from login";
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);

System.Data.OleDb.OleDbCommandBuilder cb;
cb = new System.Data.OleDb.OleDbCommandBuilder(da);

dRow = ds.Tables[1].NewRow(); //I get an error on this line

dRow[1] = "sakest";
ds.Tables["hms"].Rows.Add(dRow);
da.Fill(ds, "hms");
da.Update(ds, "hms");

MessageBox.Show("new enrtry ");
</code>```

答:
What error message are you getting exactly. At a guess I would say that you are requesting a table that does not exist, your query only returns 1 table so it's index would be 0

Try this:

```<code>dRow = ds.Tables[0].NewRow();
</code>```

Body:
I'm trying to add a record to an Access 2007 database using c# but I get an exception.

Here's my code, the database is called hms and the table is called login

DataSet ds = new DataSet();

System.Data.OleDb.OleDbConnection con;
DataRow dRow;
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=" +  Application.StartupPath + "\\hms.mdb";
string sql = "select * from login";
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);

System.Data.OleDb.OleDbCommandBuilder cb;
cb = new System.Data.OleDb.OleDbCommandBuilder(da);

dRow = ds.Tables[1].NewRow(); //I get an error on this line

dRow[1] = "sakest";
ds.Tables["hms"].Rows.Add(dRow);
da.Fill(ds, "hms");
da.Update(ds, "hms");

MessageBox.Show("new enrtry ");

Body:
What error message are you getting exactly. At a guess I would say that you are requesting a table that does not exist, your query only returns 1 table so it's index would be 0

Try this:

dRow = ds.Tables[0].NewRow();


问:
cant connect database mysql through tcp forwarding
i want to access database in google cloud server via TCP Forwarding, I have username = root password = my-password , server-name

i am doing:

Set TCP Forward in cloud server

gcloud compute start-iap-tunnel sg01dbcluster-node-2 3306
--local-host-port=localhost:3307
--zone=asia-southeast1-b

output :

```<code>Listening on port [3307].
</code>```

Then i connect to database server using mysql workbench
hostname localhost
port :3307
username : root
password : my-password

but i have error:

```<code>Failed to Connect to MySQL at localhost:3307 with user root
Lost connection to MySQL server at 'reading initial communication packet', system error: 0
</code>```

any idea what step that i missed ?

答:
i have done fixing the connecting problem, before that i am sounding that i have a instances-name , username root and password my-password  to connect database in cloud server (the database was sql) via TCP IP forwarding. cloud server was google cloud compute engine.  here are the step:

in local

gcloud config set (i am using config set project and zone, don't forget using alpha/beta if the code doesn't running)

TCP Other connection (check last section)

gcloud beta compute start-iap-tunnel my-instances-name 3306 --local-host-port=localhost:3309

wait a second until show:

```<code>Listening Port [3309]
</code>```

Open mysql workbench and put the hostname : localhost , port : 3309 , username : root , password : my-password

Body:
i want to access database in google cloud server via TCP Forwarding, I have username = root password = my-password , server-name

i am doing:

Set TCP Forward in cloud server

gcloud compute start-iap-tunnel sg01dbcluster-node-2 3306
--local-host-port=localhost:3307
--zone=asia-southeast1-b

output :

Listening on port [3307].

Then i connect to database server using mysql workbench
hostname localhost
port :3307
username : root
password : my-password

but i have error:

Failed to Connect to MySQL at localhost:3307 with user root
Lost connection to MySQL server at 'reading initial communication packet', system error: 0

any idea what step that i missed ?

Body:
i have done fixing the connecting problem, before that i am sounding that i have a instances-name , username root and password my-password  to connect database in cloud server (the database was sql) via TCP IP forwarding. cloud server was google cloud compute engine.  here are the step:

in local

gcloud config set (i am using config set project and zone, don't forget using alpha/beta if the code doesn't running)

TCP Other connection (check last section)

gcloud beta compute start-iap-tunnel my-instances-name 3306 --local-host-port=localhost:3309

wait a second until show:

Listening Port [3309]

Open mysql workbench and put the hostname : localhost , port : 3309 , username : root , password : my-password


问:
S3 vs DynamoDB for Static content
I have a requirement to display Terms and Condition for Order fulfillment to consumers purchasing products on my web portal. Since T&C is a Static content that rarely changes, I am planning to store this file in the AWS S3 bucket. I can pull the static content at runtime using Spring Rest API and display it in the user's web browser, or present it in some other format. I want to know your views about using S3 for this use case? Another option is to use DynamoDB.. but S3 seems to be simple to use.     </p>

答:
If your frontend is hosting on S3, I would suggest you upload your T&C to S3 as well.

But if you are rendering webpage from the application (e.g. Spring), then I suggest you put them on DynamoDB.

Title: S3 vs DynamoDB for Static content


问:
How to override Django AuthenticationForm inactive message
I am trying to display a custom error message when an account exists but is inactive. To do this I am overrriding the AuthenticationForm's error_messages.

forms.py:

```<code>class AuthForm(AuthenticationForm):
    error_messages = {
        'invalid_login': (
            "This custom message works"
        ),
        'inactive': (
            "This custom message does not."
        ),
    }
</code>```

urls.py:

```<code>path('login/', auth_views.LoginView.as_view(
        template_name='employees/login.html',
        authentication_form=AuthForm),
         name='login'),
</code>```

As you can see the inactive message does not work. Thoughts on why?

Edit: when inactive accounts try to login the invalid_login message shows and not the inactive, message.

答: This is a bug which exists in Django. There is also another SO thread which discusses this issue.</p>

Body:
I am trying to display a custom error message when an account exists but is inactive. To do this I am overrriding the AuthenticationForm's error_messages.

forms.py:

class AuthForm(AuthenticationForm):
    error_messages = {
        'invalid_login': (
            "This custom message works"
        ),
        'inactive': (
            "This custom message does not."
        ),
    }

urls.py:

path('login/', auth_views.LoginView.as_view(
        template_name='employees/login.html',
        authentication_form=AuthForm),
         name='login'),

As you can see the inactive message does not work. Thoughts on why?

Edit: when inactive accounts try to login the invalid_login message shows and not the inactive, message.


问:
How do I properly nest queries in cakephp with where clauses?
I'm trying to get an order from the orders table that contains a product url from the product table. I tried using this subquery but cakephp keeps reading the url value s20_ultra as :c0

```<code>$temp = $this->Orders->getAssociation('Product')->find()->where(['product.url' => 's20_ultra']);
$result = $this->Orders->find()->where(["productId IN" => $temp]);
echo $result;
</code>```

Appending firstOrFail() to the end of the first query temp and commenting out the second query result as a test works just fine but when I append it to both I get Cannot convert value of type %s to integer exception.
This would be the normal query of what I'm trying to accomplish:

```<code>select * from `order` where productId in (select product.id from product where url = 's20_ultra')
</code>```

答:
Based on what you've said, I think that the following should work. This assumes that the associations are correctly set up in both directions between Orders and Product. (Note, that's a non-standard naming scheme, it would normally be Products.)

```<code>$product = $this->Orders->getAssociation('Product')
    ->findByUrl('s20_ultra')
    ->contain(['Orders'])
    ->firstOrFail();
debug($product->orders);
</code>```

Body:
I'm trying to get an order from the orders table that contains a product url from the product table. I tried using this subquery but cakephp keeps reading the url value s20_ultra as :c0

$temp = $this->Orders->getAssociation('Product')->find()->where(['product.url' => 's20_ultra']);
$result = $this->Orders->find()->where(["productId IN" => $temp]);
echo $result;

Appending firstOrFail() to the end of the first query temp and commenting out the second query result as a test works just fine but when I append it to both I get Cannot convert value of type %s to integer exception.
This would be the normal query of what I'm trying to accomplish:

select * from `order` where productId in (select product.id from product where url = 's20_ultra')

Body:
Based on what you've said, I think that the following should work. This assumes that the associations are correctly set up in both directions between Orders and Product. (Note, that's a non-standard naming scheme, it would normally be Products.)

$product = $this->Orders->getAssociation('Product')
    ->findByUrl('s20_ultra')
    ->contain(['Orders'])
    ->firstOrFail();
debug($product->orders);


问:
Using datepicker with dd/mm/yyyy format
I'm using the ng-bootstrap datepicker, and I'd like to know how can I set the model like dd/mm/yyyy? For default, when the user select one day, a date like mm/dd/yyyy is sent to the model. Any help will be very appreciated!</p>

答:
```<code>constructor(@Inject(FormBuilder) fb: FormBuilder, private datePipe: DatePipe) {}

...

this.datePipe.transform(createdDate, 'dd-MMM-yyyy')
</code>```

Title: Using datepicker with dd/mm/yyyy format


问:
WebDriver can't find element by xpath using Java
The following is the snippet of WebDriver code using Java:

```<code>        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.pl/");
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        WebElement element = driver.findElement(By.name("q"));
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
WebElement query = driver.findElement(By.xpath("//html/body/div[2]/span/center/form/table/tbody/tr/td[2]/div/div/input"));

query.sendKeys("asd");
</code>```

After execution of code I got the following exception:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//html/body/div[2]/span/center/form/table/tbody/tr/td[2]/div/div/input"}
  System info: os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.6.0_24'
  Driver info: driver.version: RemoteWebDriver
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
      at java.lang.reflect.Constructor.newInstance(Unknown Source)
      at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:131)
      at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:105)
      at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:409)
      at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:192)
      at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:265)
      at org.openqa.selenium.By$6.findElement(By.java:205)
      at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:184)
      at test.main(test.java:24)

What's the wrong in my code?

答:
If you want to find elements by XPath. Then do the following:

```<code>WebDriver driver = new FirefoxDriver();
String baseUrl = "http://www.google.com";
Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);
selenium.open("http://www.google.com");
selenium.isElementPresent(XPath Variable);
</code>```

Also find more help on this site

Body:
The following is the snippet of WebDriver code using Java:

        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.pl/");
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        WebElement element = driver.findElement(By.name("q"));
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
WebElement query = driver.findElement(By.xpath("//html/body/div[2]/span/center/form/table/tbody/tr/td[2]/div/div/input"));

query.sendKeys("asd");

After execution of code I got the following exception:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//html/body/div[2]/span/center/form/table/tbody/tr/td[2]/div/div/input"}
  System info: os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.6.0_24'
  Driver info: driver.version: RemoteWebDriver
      at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
      at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
      at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
      at java.lang.reflect.Constructor.newInstance(Unknown Source)
      at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:131)
      at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:105)
      at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:409)
      at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:192)
      at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:265)
      at org.openqa.selenium.By$6.findElement(By.java:205)
      at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:184)
      at test.main(test.java:24)

What's the wrong in my code?

Body:
If you want to find elements by XPath. Then do the following:

WebDriver driver = new FirefoxDriver();
String baseUrl = "http://www.google.com";
Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);
selenium.open("http://www.google.com");
selenium.isElementPresent(XPath Variable);

Also find more help on this site


问:
Display Labels with Charts.JS
I created a radar chart with chart.js, however, I am having issues displaying the real data of my data points. I used the chart.js label plugin but it is displaying the point where the data point has plotted. How would I get it so my real data along with the label be displayed instead of the point where it is plotted. Many thanks!

<!doctype html>

  <meta charset="utf-8">
  <title>Apples</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/main.css">

  <meta name="theme-color" content="#fafafa">

Apple Values

<canvas id="Apple"></canvas>

```

答:
you can either use plugins to change the chart after it is drawn or controllers to change how the chart is drawn since there is no direct way to manipulate rendering of charts. These are the links:

https://www.chartjs.org/docs/latest/developers/plugins.html
https://www.chartjs.org/docs/latest/developers/charts.html#extending-existing-chart-types

For your particular example, here is the code for using plugins, the easier of the two;

```<code><!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Apples</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/main.css">

  <meta name="theme-color" content="#fafafa">
  <script src="js/vendor/modernizr-3.8.0.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
  <script>window.jQuery || document.write('<script src="js/vendor/jquery-3.4.1.min.js"><\/script>')</script>
  <script src="js/plugins.js"></script>
  <script src="js/main.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>
</head>

<body>
  <center><h3>Apple Values</h3></center>
<canvas id="Apple"></canvas>
  <script>

  var ctx = document.getElementById('Apple');

  var real_data = [
      ['133', '425', '222', '621', '151'],

];

  var data = {
      labels: ['X', 'Y','Z','N','A'],
      datasets: [{
          label: 'Apples',
          data: [.41, .5, .33, .72, .64],
          backgroundColor: 'rgba(101,81,255,0.2)',
          borderColor: 'rgba(101,81,255,0.5)',
          borderWidth: 1,
          pointBackgroundColor: 'rgba(0, 0, 0, 0.4)'
      }]
  };

  var options = {
      tooltips: {
          callbacks: {
              title: function(t, d) {
                  let title = d.datasets[t[0].datasetIndex].label;
                  return title;
              },
              label: function(t, d) {
                  let title = d.datasets[t.datasetIndex].label;
                  let label = d.labels[t.index];
                  let value = (title != 'Average') ? real_data[t.datasetIndex][t.index] : d.datasets[t.datasetIndex].data[t.index];
                  return label + ': ' + value;
              }
          }
      }
  };

  var plugins = [{
   afterDatasetsDraw: function(chart) {
    var real_data = ['133', '425', '222', '621', '151'];
      var ctx = chart.ctx;
      chart.data.datasets.forEach(function(dataset, index) {
         var datasetMeta = chart.getDatasetMeta(index);
         if (datasetMeta.hidden) return;
         datasetMeta.data.forEach(function(point, index) {
            var value = real_data[index],
                x = point.getCenterPoint().x,
                y = point.getCenterPoint().y,
                radius = point._model.radius,
                fontSize = 14,
                fontFamily = 'Verdana',
                fontColor = 'black',
                fontStyle = 'normal';
            ctx.save();
            ctx.textBaseline = 'middle';
            ctx.textAlign = 'center';
            ctx.font = fontStyle + ' ' + fontSize + 'px' + ' ' + fontFamily;
            ctx.fillStyle = fontColor;
            ctx.fillText(value, x, y - radius - fontSize);
            ctx.restore();
         });
      });
   }
}]
  var chart = new Chart(ctx, {
      type: 'radar',
      data: data,
      options: options,
      plugins: plugins

  });

  </script>

</body>

</html>
</code>```

Title: Display Labels with Charts.JS

Body:
you can either use plugins to change the chart after it is drawn or controllers to change how the chart is drawn since there is no direct way to manipulate rendering of charts. These are the links:

https://www.chartjs.org/docs/latest/developers/plugins.html
https://www.chartjs.org/docs/latest/developers/charts.html#extending-existing-chart-types

For your particular example, here is the code for using plugins, the easier of the two;

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Apples</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="css/normalize.css">
  <link rel="stylesheet" href="css/main.css">

  <meta name="theme-color" content="#fafafa">
  <script src="js/vendor/modernizr-3.8.0.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
  <script>window.jQuery || document.write('<script src="js/vendor/jquery-3.4.1.min.js"><\/script>')</script>
  <script src="js/plugins.js"></script>
  <script src="js/main.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>
</head>

<body>
  <center><h3>Apple Values</h3></center>
<canvas id="Apple"></canvas>
  <script>

  var ctx = document.getElementById('Apple');

  var real_data = [
      ['133', '425', '222', '621', '151'],

];

  var data = {
      labels: ['X', 'Y','Z','N','A'],
      datasets: [{
          label: 'Apples',
          data: [.41, .5, .33, .72, .64],
          backgroundColor: 'rgba(101,81,255,0.2)',
          borderColor: 'rgba(101,81,255,0.5)',
          borderWidth: 1,
          pointBackgroundColor: 'rgba(0, 0, 0, 0.4)'
      }]
  };

  var options = {
      tooltips: {
          callbacks: {
              title: function(t, d) {
                  let title = d.datasets[t[0].datasetIndex].label;
                  return title;
              },
              label: function(t, d) {
                  let title = d.datasets[t.datasetIndex].label;
                  let label = d.labels[t.index];
                  let value = (title != 'Average') ? real_data[t.datasetIndex][t.index] : d.datasets[t.datasetIndex].data[t.index];
                  return label + ': ' + value;
              }
          }
      }
  };

  var plugins = [{
   afterDatasetsDraw: function(chart) {
    var real_data = ['133', '425', '222', '621', '151'];
      var ctx = chart.ctx;
      chart.data.datasets.forEach(function(dataset, index) {
         var datasetMeta = chart.getDatasetMeta(index);
         if (datasetMeta.hidden) return;
         datasetMeta.data.forEach(function(point, index) {
            var value = real_data[index],
                x = point.getCenterPoint().x,
                y = point.getCenterPoint().y,
                radius = point._model.radius,
                fontSize = 14,
                fontFamily = 'Verdana',
                fontColor = 'black',
                fontStyle = 'normal';
            ctx.save();
            ctx.textBaseline = 'middle';
            ctx.textAlign = 'center';
            ctx.font = fontStyle + ' ' + fontSize + 'px' + ' ' + fontFamily;
            ctx.fillStyle = fontColor;
            ctx.fillText(value, x, y - radius - fontSize);
            ctx.restore();
         });
      });
   }
}]
  var chart = new Chart(ctx, {
      type: 'radar',
      data: data,
      options: options,
      plugins: plugins

  });

  </script>

</body>

</html>


问:
Webservice is not accessible publicly when using URL rewrite in IIS
I hosted webservice in private server. I then created URL rewrite rule in IIS which is there in public server(internet server).

Everytime I access the URL, It explicitly shows the private server's ip/ computer name in URL on browser rather than public url/IP. When I click on the URL for viewing script, it shows "Example.svc does not exist" error.

It also doesn't work when i try to add it as service reference in Visual studio by passing the URL in it. It throws the below error.

```<code>The request failed with HTTP status 400: Bad request
Metadata contains a reference that cannot be resolved: <SERVER URL>
The remote server turned an unexpected response: (405) Method not allowed.
</code>```

What should I do for accessing the URL publicly and also able to add it as reference in Visual studio.?

答:
It seems that you are deploying a WCF service in IIS. Is that correct? If the error “example.svc does not exists” occurred, please ensure that you have enabled certain Windows features in order to host WCF service in IIS.

The reason why we cannot add it as Service Reference in order to call the service is that we have not published the Metadata service endpoint. This depends on your WCF service type. Generally, we either add a Mex service endpoint or publish the service WSDL by adding Metadata service behavior.

```<code>  <services>
    <service name="WcfService1.Service1">
      <endpoint address="" binding="basicHttpBinding" bindingConfiguration="mybinding" contract="WcfService1.IService1">
      </endpoint>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
    </service>
  </services>
</code>```

```<code>  <behaviors>
        <serviceBehaviors>
          <behavior>
            <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
</code>```

Everytime I access the URL, It explicitly shows the private server's ip/ computer name in URL on browser rather than public url/IP.

In order to access the service by using the hostname/domain name URL, we should ensure that the domain name points to the public IP of the server. It is a network-related issue.

Feel free to let me know if the problem still exists.

Body:
I hosted webservice in private server. I then created URL rewrite rule in IIS which is there in public server(internet server).

Everytime I access the URL, It explicitly shows the private server's ip/ computer name in URL on browser rather than public url/IP. When I click on the URL for viewing script, it shows "Example.svc does not exist" error.

It also doesn't work when i try to add it as service reference in Visual studio by passing the URL in it. It throws the below error.

The request failed with HTTP status 400: Bad request
Metadata contains a reference that cannot be resolved: <SERVER URL>
The remote server turned an unexpected response: (405) Method not allowed.

What should I do for accessing the URL publicly and also able to add it as reference in Visual studio.?

Body:
It seems that you are deploying a WCF service in IIS. Is that correct? If the error “example.svc does not exists” occurred, please ensure that you have enabled certain Windows features in order to host WCF service in IIS.

The reason why we cannot add it as Service Reference in order to call the service is that we have not published the Metadata service endpoint. This depends on your WCF service type. Generally, we either add a Mex service endpoint or publish the service WSDL by adding Metadata service behavior.

  <services>
    <service name="WcfService1.Service1">
      <endpoint address="" binding="basicHttpBinding" bindingConfiguration="mybinding" contract="WcfService1.IService1">
      </endpoint>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
    </service>
  </services>

  <behaviors>
        <serviceBehaviors>
          <behavior>
            <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />

Everytime I access the URL, It explicitly shows the private server's ip/ computer name in URL on browser rather than public url/IP.

In order to access the service by using the hostname/domain name URL, we should ensure that the domain name points to the public IP of the server. It is a network-related issue.

Feel free to let me know if the problem still exists.


问:
Copy selected multiple values to the text box
I have drop down list as below.

```<code>     <select id="checkOwner" multiple="multiple" onchange="copyValue()">
       <option value="FIRSTNAME">First Name</option>
       <option value="LASTNAME">Last Name</option>
     </select>
</code>```

I used Below javascript to add checkbox

```<code>$(function() {
  $('#checkOwner').multiselect({
   });
});
</code>```

I used below javascript to copy selected value to text field.

```<code>function copyValue() {
  var dropboxvalue = document.getElementById('checkOwner').value;
  document.getElementById('mytextbox').value = dropboxvalue;
}
</code>```

But the problem is, this copy only one value. I want to copy all the selected values. How can I do this?

答:
Loop through the option and put selected values in a string and then output the string on the textbox</p>

```<code>function copyValue() {

  var str = "";
  for (var option of document.getElementById('checkOwner').options) {
    if (option.selected) {
      str+= option.value+" ";
    }

    document.getElementById('mytextbox').value = str;
  }
}
</code>```

Body:
I have drop down list as below.

     <select id="checkOwner" multiple="multiple" onchange="copyValue()">
       <option value="FIRSTNAME">First Name</option>
       <option value="LASTNAME">Last Name</option>
     </select>

I used Below javascript to add checkbox

$(function() {
  $('#checkOwner').multiselect({
   });
});

I used below javascript to copy selected value to text field.

function copyValue() {
  var dropboxvalue = document.getElementById('checkOwner').value;
  document.getElementById('mytextbox').value = dropboxvalue;
}

But the problem is, this copy only one value. I want to copy all the selected values. How can I do this?

Body:
Loop through the option and put selected values in a string and then output the string on the textbox

function copyValue() {

  var str = "";
  for (var option of document.getElementById('checkOwner').options) {
    if (option.selected) {
      str+= option.value+" ";
    }

    document.getElementById('mytextbox').value = str;
  }
}


问:
I've created a function in C++ to reverse a string recursively, but how can I make the funtion print a endl afterwards?
This is in C++ The original prompt was to create a recursive function that reverses a string. The function works, but I am not sure how to get endl IN the function after it reverses the string so it looks good in console. This works:

```<code>string reverse(string str) {
    if (str.size() == 1) {
        return str;
    }
    string str2 = reverse(str.substr(1));
    return str2 + str[0];
}
</code>```

答:
What about doing this:

```<code>string str="Hello";
cout << reverse(str) << endl;
</code>```

Here you will reverse the string, print it, and then start a new line.

You can place a newline inside by utilizing the last character index like this:

```<code>string reverse(string str, int length) {
    if (str.size() == 1) {
        return str;
    }
    string str2 = reverse(str.substr(1), length);
    // if are at the last character, we just insert a newline after it
    if(length == str2.length())
    {
        return str2 + str[0] + '\n';
    }
    return str2 + str[0];
}

int main()
{
    string str = "Hello";
    // we get position of last character
    cout << reverse(str, str.length() -1);

    return 0;
}
</code>```

Body:
This is in C++ The original prompt was to create a recursive function that reverses a string. The function works, but I am not sure how to get endl IN the function after it reverses the string so it looks good in console. This works:

string reverse(string str) {
    if (str.size() == 1) {
        return str;
    }
    string str2 = reverse(str.substr(1));
    return str2 + str[0];
}

Body:
What about doing this:

string str="Hello";
cout << reverse(str) << endl;

Here you will reverse the string, print it, and then start a new line.

You can place a newline inside by utilizing the last character index like this:

string reverse(string str, int length) {
    if (str.size() == 1) {
        return str;
    }
    string str2 = reverse(str.substr(1), length);
    // if are at the last character, we just insert a newline after it
    if(length == str2.length())
    {
        return str2 + str[0] + '\n';
    }
    return str2 + str[0];
}

int main()
{
    string str = "Hello";
    // we get position of last character
    cout << reverse(str, str.length() -1);

    return 0;
}


问:
The system cannot find the path specified. (os error 3)
I am using deno for the first time and The system cannot find the path specified. (os error 3) is the error I am getting. My code below:-

```<code>import { Application } from 'https://deno.land/x/oak/mod.ts'

const app = new Application();
const port = 3000;

app.use((ctx) => {
    ctx.response.body = "Hello World"
})

app.listen({ port })
console.log(`localhost:${port}`)
</code>```

I am using deno run --allow-net .\server.js on powershell to start deno. Any help would be appreciated.

EDIT: If I try to do a simple console.log and run the file with deno run server.js it runs fine which mean that the deno environment is setup correctly. As soon as I add the import statement at the top, the error starts happening.

答:
I got the same error. After some tries, I see that there is different betwwen nodejs and deno when use import. In node, we use this

```<code>import { Server } from './Server';
</code>```

But in deno we use

```<code>import { Server } from './Server/index.js
</code>```

It resolved my issue, hope is the same for you

Body:
I am using deno for the first time and The system cannot find the path specified. (os error 3) is the error I am getting. My code below:-

import { Application } from 'https://deno.land/x/oak/mod.ts'

const app = new Application();
const port = 3000;

app.use((ctx) => {
    ctx.response.body = "Hello World"
})

app.listen({ port })
console.log(`localhost:${port}`)

I am using deno run --allow-net .\server.js on powershell to start deno. Any help would be appreciated.

EDIT: If I try to do a simple console.log and run the file with deno run server.js it runs fine which mean that the deno environment is setup correctly. As soon as I add the import statement at the top, the error starts happening.

Body:
I got the same error. After some tries, I see that there is different betwwen nodejs and deno when use import. In node, we use this

import { Server } from './Server';

But in deno we use

import { Server } from './Server/index.js

It resolved my issue, hope is the same for you


问:
Hide Custom Header in specific screen with headerMode float
I have 3 screen in my app: "Home, Contacts, Profile". I created a custom header to show in Home and Contacts, but not in Profile screen. The problem is: my custom header don't hide in Profile Screen. If I remove my custm header to use the default header, it hides, but when I back to my custom header this doesn't happen.

App.js

```<code>       <NavigationContainer ref={navigationRef}>
            <Stack.Navigator
            headerMode="float"
            initialRouteName="Home"
            screenOptions={{
                header: props => <CustomHeader {...props} />
            }}>

                <Stack.Screen
                name="Home"
                component={Home}
                options={{
                    cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS
                }}/>

                <Stack.Screen name="Contacts" component={Contacts}
                options={{
                    cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS
                }}/>

                <Stack.Screen
                name="Profile"
                component={Profile}
                options={{
                    headerShown: false
                }} />

            </Stack.Navigator>
        </NavigationContainer>
</code>```

答:
You can provide screen wise header like.

```<code><NavigationContainer ref={navigationRef}>
  <Stack.Navigator
    headerMode="float"
    initialRouteName="Home">
    <Stack.Screen
      name="Home"
      component={Home}
      options={{
        cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
        header: (props) => <CustomHeader {...props} />
      }}
    />

    <Stack.Screen
      name="Contacts"
      component={Contacts}
      options={{
        cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
        header: (props) => <CustomHeader {...props} />
      }}
    />

    <Stack.Screen
      name="Profile"
      component={Profile}
      options={{
        headerShown: false,
        header: null,
      }}
    />
  </Stack.Navigator>
</NavigationContainer>;
</code>```

Or you can create custom function for all header

```<code>function getHeader(route, props) {
  const routeName = route.state
    ?
      route.state.routes[route.state.index].name
    : || 'Home';

  switch (routeName) {
    case 'Home':
    case 'Contacts':
      return <CustomHeader {...props} />
    case 'Profile':
      return null;
  }
}

and use it like

 <Stack.Screen
      name="Profile"
      component={Profile}
      options={({ route }) => ({
        header: (props)=> getHeader(route, props),
      })}
    />
</code>```

Source : https://reactnavigation.org/docs/screen-options-resolution

Body:
I have 3 screen in my app: "Home, Contacts, Profile". I created a custom header to show in Home and Contacts, but not in Profile screen. The problem is: my custom header don't hide in Profile Screen. If I remove my custm header to use the default header, it hides, but when I back to my custom header this doesn't happen.

App.js

       <NavigationContainer ref={navigationRef}>
            <Stack.Navigator
            headerMode="float"
            initialRouteName="Home"
            screenOptions={{
                header: props => <CustomHeader {...props} />
            }}>

                <Stack.Screen
                name="Home"
                component={Home}
                options={{
                    cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS
                }}/>

                <Stack.Screen name="Contacts" component={Contacts}
                options={{
                    cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS
                }}/>

                <Stack.Screen
                name="Profile"
                component={Profile}
                options={{
                    headerShown: false
                }} />

            </Stack.Navigator>
        </NavigationContainer>

Body:
You can provide screen wise header like.

<NavigationContainer ref={navigationRef}>
  <Stack.Navigator
    headerMode="float"
    initialRouteName="Home">
    <Stack.Screen
      name="Home"
      component={Home}
      options={{
        cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
        header: (props) => <CustomHeader {...props} />
      }}
    />

    <Stack.Screen
      name="Contacts"
      component={Contacts}
      options={{
        cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
        header: (props) => <CustomHeader {...props} />
      }}
    />

    <Stack.Screen
      name="Profile"
      component={Profile}
      options={{
        headerShown: false,
        header: null,
      }}
    />
  </Stack.Navigator>
</NavigationContainer>;

Or you can create custom function for all header

function getHeader(route, props) {
  const routeName = route.state
    ?
      route.state.routes[route.state.index].name
    : || 'Home';

  switch (routeName) {
    case 'Home':
    case 'Contacts':
      return <CustomHeader {...props} />
    case 'Profile':
      return null;
  }
}

and use it like

 <Stack.Screen
      name="Profile"
      component={Profile}
      options={({ route }) => ({
        header: (props)=> getHeader(route, props),
      })}
    />

Source : https://reactnavigation.org/docs/screen-options-resolution