问:
spreading the dataset on selected columns without any identifier
I would like to spread the dataset using few selected columns in which there are no unique identifiers to identify the rows. For this, I am using the publicly available iris dataset.

I have tried by removing the unwanted columns first and then creating the unique values without any duplicates. Later applying the spread on top of it.

```<code>iris %>% select(-c(Sepal.Width, Petal.Length, Petal.Width)) %>% unique() %>%
  spread(Species, Sepal.Length)
iris %>% select(-c(Sepal.Width, Petal.Length, Petal.Width)) %>% unique() %>%
  spread(key=Species, value=Sepal.Length)
</code>```

But it gives the below duplicate identifiers errors:

Error: Duplicate identifiers for rows (1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  11, 12, 13, 14, 15), (16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
  28, 29, 30, 31, 32, 33, 34, 35, 36), (37, 38, 39, 40, 41, 42, 43, 44,
  45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57)

using row_number(), have created a unique identifier so as to use while spreading the data and avoid error duplicate rows message.

```<code>iris %>% select(-c(Sepal.Width, Petal.Length, Petal.Width)) %>% unique() %>%
  mutate(row = row_number()) %>% spread(Species, Sepal.Length)
</code>```

which gives the below output:

```<code>#    row setosa versicolor virginica
# 1    1    5.1         NA        NA
# 2    2    4.9         NA        NA
# 3    3    4.7         NA        NA
# ...
# 16  16     NA        7.0        NA
# 17  17     NA        6.4        NA
# 18  18     NA        6.9        NA
# ...
# 37  37     NA         NA       6.3
# 38  38     NA         NA       5.8
# 39  39     NA         NA       7.1
</code>```

However, due to the row numbers, there are many NAs which is not expected. I tried to remove the row number so as to get the values as expected, but it did not materialize.

```<code>iris %>% select(-c(Sepal.Width, Petal.Length, Petal.Width)) %>% unique() %>%
  mutate(row = row_number()) %>%  spread(Species, Sepal.Length, -row)

iris %>% select(-c(Sepal.Width, Petal.Length, Petal.Width)) %>% unique() %>%
  mutate(row = row_number()) %>%  spread(Species, Sepal.Length, -one_of(row))
</code>```

Expected output:

```<code>tmp <- iris %>% select(-c(Sepal.Width, Petal.Length, Petal.Width)) %>% unique() %>%
  mutate(row = row_number()) %>% spread(Species, Sepal.Length)

cbind(setosa=unique(tmp$setosa), versicolor=unique(tmp$versicolor), virginica=unique(tmp$virginica))
#       setosa versicolor virginica
#  [1,]    5.1        7.0       6.3
#  [2,]    4.9        6.4       5.8
#  [3,]    4.7        6.9       7.1
#  [4,]    4.6        5.5       6.5
#  [5,]    5.0        6.5       7.6
#  [6,]    5.4        5.7       4.9
#  [7,]    4.4        6.3       7.3
#  [8,]    4.8        4.9       6.7
#  [9,]    4.3        6.6       7.2
# [10,]    5.8        5.2       6.4
# [11,]    5.7        5.0       6.8
# [12,]    5.2        5.9       5.7
# [13,]    5.5        6.0       7.7
# [14,]    4.5        6.1       6.0
# [15,]    5.3        5.6       6.9
# [16,]    5.1        6.7       5.6
# [17,]    4.9        5.8       6.2
# [18,]    4.7        6.2       6.1
# [19,]    4.6        6.8       7.4
# [20,]    5.0        5.4       7.9
# [21,]    5.4        5.1       5.9
</code>```

答:
```<code>library(dplyr)
library(tidyr)

tbl_df(iris) %>%
  select(Species, Sepal.Length) %>%       # select columns of interest
  group_by(Species) %>%                   # for each value
  mutate(id = row_number()) %>%           # create a row identifier
  spread(Species, Sepal.Length)           # reshape dataset

# # A tibble: 50 x 4
#       id setosa versicolor virginica
#  * <int>  <dbl>      <dbl>     <dbl>
# 1     1    5.1        7.0       6.3
# 2     2    4.9        6.4       5.8
# 3     3    4.7        6.9       7.1
# 4     4    4.6        5.5       6.3
# 5     5    5.0        6.5       6.5
# 6     6    5.4        5.7       7.6
# 7     7    4.6        6.3       4.9
# 8     8    5.0        4.9       7.3
# 9     9    4.4        6.6       6.7
# 10    10   4.9        5.2       7.2
# # ... with 40 more rows
</code>```

Be extra careful of how you create/use your row identifier. The code above just uses the order of the dataset. If you re-order it somehow, you're going to get different row combinations. Check the code below:

```<code>tbl_df(iris) %>%
  arrange(desc(Sepal.Length)) %>%         # order your values descending
  select(Species, Sepal.Length) %>%       # select columns of interest
  group_by(Species) %>%                   # for each value
  mutate(id = row_number()) %>%           # create a row identifier
  spread(Species, Sepal.Length)           # reshape dataset

# # A tibble: 50 x 4
#      id setosa versicolor virginica
# * <int>  <dbl>      <dbl>     <dbl>
# 1     1    5.8        7.0       7.9
# 2     2    5.7        6.9       7.7
# 3     3    5.7        6.8       7.7
# 4     4    5.5        6.7       7.7
# 5     5    5.5        6.7       7.7
# 6     6    5.4        6.7       7.6
# 7     7    5.4        6.6       7.4
# 8     8    5.4        6.6       7.3
# 9     9    5.4        6.5       7.2
# 10    10   5.4        6.4       7.2
# # ... with 40 more rows
</code>```

The arrange(desc.)), which is the difference from before, will make sure that you have the higher values on top rows (descending order).

Body:
I would like to spread the dataset using few selected columns in which there are no unique identifiers to identify the rows. For this, I am using the publicly available iris dataset.

I have tried by removing the unwanted columns first and then creating the unique values without any duplicates. Later applying the spread on top of it.

iris %>% select(-c(Sepal.Width, Petal.Length, Petal.Width)) %>% unique() %>%
  spread(Species, Sepal.Length)
iris %>% select(-c(Sepal.Width, Petal.Length, Petal.Width)) %>% unique() %>%
  spread(key=Species, value=Sepal.Length)

But it gives the below duplicate identifiers errors:

Error: Duplicate identifiers for rows (1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
  11, 12, 13, 14, 15), (16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
  28, 29, 30, 31, 32, 33, 34, 35, 36), (37, 38, 39, 40, 41, 42, 43, 44,
  45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57)

using row_number(), have created a unique identifier so as to use while spreading the data and avoid error duplicate rows message.

iris %>% select(-c(Sepal.Width, Petal.Length, Petal.Width)) %>% unique() %>%
  mutate(row = row_number()) %>% spread(Species, Sepal.Length)

which gives the below output:

#    row setosa versicolor virginica
# 1    1    5.1         NA        NA
# 2    2    4.9         NA        NA
# 3    3    4.7         NA        NA
# ...
# 16  16     NA        7.0        NA
# 17  17     NA        6.4        NA
# 18  18     NA        6.9        NA
# ...
# 37  37     NA         NA       6.3
# 38  38     NA         NA       5.8
# 39  39     NA         NA       7.1

However, due to the row numbers, there are many NAs which is not expected. I tried to remove the row number so as to get the values as expected, but it did not materialize.

iris %>% select(-c(Sepal.Width, Petal.Length, Petal.Width)) %>% unique() %>%
  mutate(row = row_number()) %>%  spread(Species, Sepal.Length, -row)

iris %>% select(-c(Sepal.Width, Petal.Length, Petal.Width)) %>% unique() %>%
  mutate(row = row_number()) %>%  spread(Species, Sepal.Length, -one_of(row))

Expected output:

tmp <- iris %>% select(-c(Sepal.Width, Petal.Length, Petal.Width)) %>% unique() %>%
  mutate(row = row_number()) %>% spread(Species, Sepal.Length)

cbind(setosa=unique(tmp$setosa), versicolor=unique(tmp$versicolor), virginica=unique(tmp$virginica))
#       setosa versicolor virginica
#  [1,]    5.1        7.0       6.3
#  [2,]    4.9        6.4       5.8
#  [3,]    4.7        6.9       7.1
#  [4,]    4.6        5.5       6.5
#  [5,]    5.0        6.5       7.6
#  [6,]    5.4        5.7       4.9
#  [7,]    4.4        6.3       7.3
#  [8,]    4.8        4.9       6.7
#  [9,]    4.3        6.6       7.2
# [10,]    5.8        5.2       6.4
# [11,]    5.7        5.0       6.8
# [12,]    5.2        5.9       5.7
# [13,]    5.5        6.0       7.7
# [14,]    4.5        6.1       6.0
# [15,]    5.3        5.6       6.9
# [16,]    5.1        6.7       5.6
# [17,]    4.9        5.8       6.2
# [18,]    4.7        6.2       6.1
# [19,]    4.6        6.8       7.4
# [20,]    5.0        5.4       7.9
# [21,]    5.4        5.1       5.9

Body:
library(dplyr)
library(tidyr)

tbl_df(iris) %>%
  select(Species, Sepal.Length) %>%       # select columns of interest
  group_by(Species) %>%                   # for each value
  mutate(id = row_number()) %>%           # create a row identifier
  spread(Species, Sepal.Length)           # reshape dataset

# # A tibble: 50 x 4
#       id setosa versicolor virginica
#  * <int>  <dbl>      <dbl>     <dbl>
# 1     1    5.1        7.0       6.3
# 2     2    4.9        6.4       5.8
# 3     3    4.7        6.9       7.1
# 4     4    4.6        5.5       6.3
# 5     5    5.0        6.5       6.5
# 6     6    5.4        5.7       7.6
# 7     7    4.6        6.3       4.9
# 8     8    5.0        4.9       7.3
# 9     9    4.4        6.6       6.7
# 10    10   4.9        5.2       7.2
# # ... with 40 more rows

Be extra careful of how you create/use your row identifier. The code above just uses the order of the dataset. If you re-order it somehow, you're going to get different row combinations. Check the code below:

tbl_df(iris) %>%
  arrange(desc(Sepal.Length)) %>%         # order your values descending
  select(Species, Sepal.Length) %>%       # select columns of interest
  group_by(Species) %>%                   # for each value
  mutate(id = row_number()) %>%           # create a row identifier
  spread(Species, Sepal.Length)           # reshape dataset

# # A tibble: 50 x 4
#      id setosa versicolor virginica
# * <int>  <dbl>      <dbl>     <dbl>
# 1     1    5.8        7.0       7.9
# 2     2    5.7        6.9       7.7
# 3     3    5.7        6.8       7.7
# 4     4    5.5        6.7       7.7
# 5     5    5.5        6.7       7.7
# 6     6    5.4        6.7       7.6
# 7     7    5.4        6.6       7.4
# 8     8    5.4        6.6       7.3
# 9     9    5.4        6.5       7.2
# 10    10   5.4        6.4       7.2
# # ... with 40 more rows

The arrange(desc.)), which is the difference from before, will make sure that you have the higher values on top rows (descending order).


来源: stackexchange

问:
Delete substrings started with 'vi-' within string
How can I go from 'mystr' to 'result'. I believe it can be done with regular expressions but I don't know how to do it.

mystr

```<code>var mystr = 'football vi-cnn-sel vi-sky test vi-axn red';
</code>```

result

```<code>var result = 'football test red';
</code>```

Regards,
Elio Fernandes

答:
You can use /( vi-\S+)/g regex and replace all found occurrences by an empty String.

var myStr = "football vi-cnn-sel vi-sky test vi-axn red";
var result = myStr.replace(/( vi-\S+)/gi, "");
console.log(result);```

S+ - matches all white-space characters

g - matches all occurrences (doesn't stop on the first found)

i - use case-insensitive matching (not sure if you need it). You can remove it if it's not necessary

ContentLicense: CC BY-SA 3.0

Body:
How can I go from 'mystr' to 'result'. I believe it can be done with regular expressions but I don't know how to do it.

mystr

var mystr = 'football vi-cnn-sel vi-sky test vi-axn red';

result

var result = 'football test red';

Regards,
Elio Fernandes

Body:
You can use /( vi-\S+)/g regex and replace all found occurrences by an empty String.

var myStr = "football vi-cnn-sel vi-sky test vi-axn red";
var result = myStr.replace(/( vi-\S+)/gi, "");
console.log(result);

S+ - matches all white-space characters

g - matches all occurrences (doesn't stop on the first found)

i - use case-insensitive matching (not sure if you need it). You can remove it if it's not necessary


问:
Excel-VBA Macro. Convert multiple .csv files with text to column and save the file to xlsx
Basically, i need to convert batch of .csv files with text to columns and the file should be converted to .xlsx on post "," delimiting.

Currently, i have sample code but am able to connect the dots to work with single click.

```<code>Option Explicit

Sub OpenCSV()

    Dim fd As FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = True
    fd.Show

    For Each fileItem In fd.SelectedItems

        Workbooks.OpenText Filename:= _
                           fileItem _
                           , Origin:=65001, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
                           xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
                           Comma:=False, Space:=False, Other:=False, TrailingMinusNumbers:=True

    Next

End Sub

Sub OpenCSVFolder()

    Dim fd As FileDialog

    Set fd = Application.FileDialog(msoFileDialogFolderPicker)

    fd.AllowMultiSelect = True
    fd.Show

    For Each folderItem In fd.SelectedItems

        fileItem = Dir(folderItem & "\" & "*.csv")

        While fileItem <> ""

            Workbooks.OpenText Filename:= _
                               folderItem & "\" & fileItem _
                               , Origin:=65001, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
                               xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
                               Comma:=False, Space:=False, Other:=False, TrailingMinusNumbers:=True
            fileItem = Dir

        Wend

    Next

End Sub

Sub CSVtoXLS()

    'UpdatebyExtendoffice20170814
    Dim xFd As FileDialog
    Dim xSPath As String
    Dim xCSVFile As String
    Dim xWsheet As String

    Application.DisplayAlerts = False
    Application.StatusBar = True

    xWsheet = ActiveWorkbook.Name

    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
    xFd.Title = "Select a folder:"

    If xFd.Show = -1 Then
        xSPath = xFd.SelectedItems(1)
    Else
        Exit Sub
    End If

    If Right(xSPath, 1) <> "\" Then xSPath = xSPath + "\"

    xCSVFile = Dir(xSPath & "*.csv")

    Do While xCSVFile <> ""

        Application.StatusBar = "Converting: " & xCSVFile
        Workbooks.Open Filename:=xSPath & xCSVFile
        ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xls", vbTextCompare), xlNormal
        ActiveWorkbook.Close
        Windows(xWsheet).Activate
        xCSVFile = Dir
    Loop

    Application.StatusBar = False
    Application.DisplayAlerts = True

End Sub
</code>```

答:
The second procedure is working for me. You could only change this line:

```<code>ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xlsx", vbTextCompare), FileFormat:=51
</code>```

You should have "," set as your delimiter in the system.
EDIT:

If, by chance, you had different default delimiter than in the .csv files, you could fill your loop with this code:

```<code>Dim qT As QueryTable
Dim newWb As Workbook
Dim sFileName As String

Do While xCSVFile <> ""

    Application.StatusBar = "Converting: " & xCSVFile
    Set newWb = Application.Workbooks.Add
    sFileName = Replace(xSPath & xCSVFile, ".csv", ".xlsx", vbTextCompare)
    Set qT = newWb.Worksheets(1).QueryTables.Add(Connection:="TEXT;" & _
        xSPath & xCSVFile, Destination:=newWb.Worksheets(1).Range("A1"))
    With qT
        .FieldNames = True
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileOtherDelimiter = "," 'set your delimiter here
        .Refresh
    End With
    newWb.SaveAs sFileName, FileFormat:=51
    newWb.Close
    xCSVFile = Dir
Loop
</code>```

I think this may be useful for google visitors

Body:
Basically, i need to convert batch of .csv files with text to columns and the file should be converted to .xlsx on post "," delimiting.

Currently, i have sample code but am able to connect the dots to work with single click.

Option Explicit

Sub OpenCSV()

    Dim fd As FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = True
    fd.Show

    For Each fileItem In fd.SelectedItems

        Workbooks.OpenText Filename:= _
                           fileItem _
                           , Origin:=65001, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
                           xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
                           Comma:=False, Space:=False, Other:=False, TrailingMinusNumbers:=True

    Next

End Sub

Sub OpenCSVFolder()

    Dim fd As FileDialog

    Set fd = Application.FileDialog(msoFileDialogFolderPicker)

    fd.AllowMultiSelect = True
    fd.Show

    For Each folderItem In fd.SelectedItems

        fileItem = Dir(folderItem & "\" & "*.csv")

        While fileItem <> ""

            Workbooks.OpenText Filename:= _
                               folderItem & "\" & fileItem _
                               , Origin:=65001, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
                               xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
                               Comma:=False, Space:=False, Other:=False, TrailingMinusNumbers:=True
            fileItem = Dir

        Wend

    Next

End Sub

Sub CSVtoXLS()

    'UpdatebyExtendoffice20170814
    Dim xFd As FileDialog
    Dim xSPath As String
    Dim xCSVFile As String
    Dim xWsheet As String

    Application.DisplayAlerts = False
    Application.StatusBar = True

    xWsheet = ActiveWorkbook.Name

    Set xFd = Application.FileDialog(msoFileDialogFolderPicker)
    xFd.Title = "Select a folder:"

    If xFd.Show = -1 Then
        xSPath = xFd.SelectedItems(1)
    Else
        Exit Sub
    End If

    If Right(xSPath, 1) <> "\" Then xSPath = xSPath + "\"

    xCSVFile = Dir(xSPath & "*.csv")

    Do While xCSVFile <> ""

        Application.StatusBar = "Converting: " & xCSVFile
        Workbooks.Open Filename:=xSPath & xCSVFile
        ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xls", vbTextCompare), xlNormal
        ActiveWorkbook.Close
        Windows(xWsheet).Activate
        xCSVFile = Dir
    Loop

    Application.StatusBar = False
    Application.DisplayAlerts = True

End Sub

Body:
The second procedure is working for me. You could only change this line:

ActiveWorkbook.SaveAs Replace(xSPath & xCSVFile, ".csv", ".xlsx", vbTextCompare), FileFormat:=51

You should have "," set as your delimiter in the system.
EDIT:

If, by chance, you had different default delimiter than in the .csv files, you could fill your loop with this code:

Dim qT As QueryTable
Dim newWb As Workbook
Dim sFileName As String

Do While xCSVFile <> ""

    Application.StatusBar = "Converting: " & xCSVFile
    Set newWb = Application.Workbooks.Add
    sFileName = Replace(xSPath & xCSVFile, ".csv", ".xlsx", vbTextCompare)
    Set qT = newWb.Worksheets(1).QueryTables.Add(Connection:="TEXT;" & _
        xSPath & xCSVFile, Destination:=newWb.Worksheets(1).Range("A1"))
    With qT
        .FieldNames = True
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileOtherDelimiter = "," 'set your delimiter here
        .Refresh
    End With
    newWb.SaveAs sFileName, FileFormat:=51
    newWb.Close
    xCSVFile = Dir
Loop

I think this may be useful for google visitors


问:
Detect click outside control
I display TestControl in grid when user clicks on the button:

```<code><Grid>
    <myControls:TestControl Panel.ZIndex="2" Visibility="Collapsed" Width="100" Height="100" />
    <Button "Open Test Control" Click="btnOpen_Click" />
</Grid>
</code>```

How can I hide TestControl when user clicks outside this control?

答: Haven't tried it, but LostFocus event may be a way to go, given that you set focus to your test control after showing it.</p>

Title: Detect click outside control

Body:
I display TestControl in grid when user clicks on the button:

<Grid>
    <myControls:TestControl Panel.ZIndex="2" Visibility="Collapsed" Width="100" Height="100" />
    <Button "Open Test Control" Click="btnOpen_Click" />
</Grid>

How can I hide TestControl when user clicks outside this control?


问:
php shopping cart session id remove
if have session cart items more than 1 its not work.. but its have only one its work. what happen for this

I put my all of codes in session. check what happen for this case...

here is my php code for this link ?action=remove&id=<value>

```<code>function checkCartForItem($addItem, $cartItems) {
     if (is_array($cartItems)){
          foreach($cartItems as $key => $item) {
              if($item['id'] === $addItem)
                  return $key;
          }
     }
     return false;
}

if (!empty($_GET['qty'])) {

    $qty = $_GET['qty'];
}

//Store it in a Array
$ITEM = array(
//Item name
'id' => $_POST['id']

);

$addItem = $_GET['id'];

//check
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
    case "add":
        if(!empty($_GET["qty"])) {

            $productByCode = $db_handle->runQuery("SELECT * FROM product WHERE id='" . $_GET["id"] . "'");
            $itemArray = array($productByCode[0]["id"]=>array('name'=>$productByCode[0]["product_name"], 'id'=>$productByCode[0]["id"], 'quantity'=>$qty, 'price'=>$productByCode[0]["new_price"]));

            $itemExists = checkCartForItem($addItem, $_SESSION['cart_item']);

            if ($itemExists !== false){
                $_SESSION['cart_item'][$itemExists]['quantity'] = $qty ;
            } else {

                if(!empty($_SESSION["cart_item"])) {

                    if(in_array($productByCode[0]["id"],$_SESSION["cart_item"])) {
                        foreach($_SESSION["cart_item"] as $k => $v) {
                                if($productByCode[0]["id"] == $k)
                                    $_SESSION["cart_item"][$k]["quantity"] = $qty;
                        }
                    } else {
                        $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
                    }
                } else {
                    $_SESSION["cart_item"] = $itemArray;
                }
            }
        }
    break;
    case "remove":
        if(!empty($_SESSION["cart_item"])) {
            foreach($_SESSION["cart_item"] as $k => $v) {
                    if($_GET["id"] == $k)
                        unset($_SESSION["cart_item"][$k]);
                    if(empty($_SESSION["cart_item"]))
                        unset($_SESSION["cart_item"]);
            }
        }

    break;
    case "empty":
        unset($_SESSION["cart_item"]);
    break;
}
}
</code>```

array (print_r($_SESSION["cart_item"]);)

```<code>Array ( [0] => Array ( [name] => Sadfsafsadf [id] => 11 [quantity] => 1 [price] => safsafsa ) [1] => Array ( [name] => TP-LINK 4 Port Wireless Dual Band N600 [id] => 13 [quantity] => 1 [price] => 15980 ) )
</code>```

答:
```<code> case "remove":
    if(!empty($_SESSION["cart_item"])) {
        foreach($_SESSION["cart_item"] as $k => $v) {
               if($_GET["id"] == $_SESSION["cart_item"][$k]['id'])//
                    unset($_SESSION["cart_item"][$k]);
                if(empty($_SESSION["cart_item"]))
                    unset($_SESSION["cart_item"]);
        }
    }
</code>```

it works!!

Title: php shopping cart session id remove

Body:
if have session cart items more than 1 its not work.. but its have only one its work. what happen for this

I put my all of codes in session. check what happen for this case...

here is my php code for this link ?action=remove&id=<value>

function checkCartForItem($addItem, $cartItems) {
     if (is_array($cartItems)){
          foreach($cartItems as $key => $item) {
              if($item['id'] === $addItem)
                  return $key;
          }
     }
     return false;
}

if (!empty($_GET['qty'])) {

    $qty = $_GET['qty'];
}

//Store it in a Array
$ITEM = array(
//Item name
'id' => $_POST['id']

);

$addItem = $_GET['id'];

//check
if(!empty($_GET["action"])) {
switch($_GET["action"]) {
    case "add":
        if(!empty($_GET["qty"])) {

            $productByCode = $db_handle->runQuery("SELECT * FROM product WHERE id='" . $_GET["id"] . "'");
            $itemArray = array($productByCode[0]["id"]=>array('name'=>$productByCode[0]["product_name"], 'id'=>$productByCode[0]["id"], 'quantity'=>$qty, 'price'=>$productByCode[0]["new_price"]));

            $itemExists = checkCartForItem($addItem, $_SESSION['cart_item']);

            if ($itemExists !== false){
                $_SESSION['cart_item'][$itemExists]['quantity'] = $qty ;
            } else {

                if(!empty($_SESSION["cart_item"])) {

                    if(in_array($productByCode[0]["id"],$_SESSION["cart_item"])) {
                        foreach($_SESSION["cart_item"] as $k => $v) {
                                if($productByCode[0]["id"] == $k)
                                    $_SESSION["cart_item"][$k]["quantity"] = $qty;
                        }
                    } else {
                        $_SESSION["cart_item"] = array_merge($_SESSION["cart_item"],$itemArray);
                    }
                } else {
                    $_SESSION["cart_item"] = $itemArray;
                }
            }
        }
    break;
    case "remove":
        if(!empty($_SESSION["cart_item"])) {
            foreach($_SESSION["cart_item"] as $k => $v) {
                    if($_GET["id"] == $k)
                        unset($_SESSION["cart_item"][$k]);
                    if(empty($_SESSION["cart_item"]))
                        unset($_SESSION["cart_item"]);
            }
        }

    break;
    case "empty":
        unset($_SESSION["cart_item"]);
    break;
}
}

array (print_r($_SESSION["cart_item"]);)

Array ( [0] => Array ( [name] => Sadfsafsadf [id] => 11 [quantity] => 1 [price] => safsafsa ) [1] => Array ( [name] => TP-LINK 4 Port Wireless Dual Band N600 [id] => 13 [quantity] => 1 [price] => 15980 ) )

Body:
 case "remove":
    if(!empty($_SESSION["cart_item"])) {
        foreach($_SESSION["cart_item"] as $k => $v) {
               if($_GET["id"] == $_SESSION["cart_item"][$k]['id'])//
                    unset($_SESSION["cart_item"][$k]);
                if(empty($_SESSION["cart_item"]))
                    unset($_SESSION["cart_item"]);
        }
    }

it works!!


问:
Datatype of escape sequences in c++
I am still a beginner.

Some of my teachers say that escape sequences are characters while others say they are "special" strings.

What are they exactly?

答:
An escape sequence is an alternative way to encode a character in the source code a character. Their most important role is to represent characters that cannot be used directly in the code.

There are two categories of such characters:

unprintable characters (ASCII codes 0..31), characters whose appearance used to depend on a code page (ASCII codes 128..255) and multi-byte characters;

characters that have a special meaning for the language and that meaning is related to the representation of strings inside the language.

The characters from the first category (except for the NUL character) can be represented by themselves in a C string but they might look strange or different on different computers; they are just an annoyance.

The most known characters from this group are the newline (\n), the tab character (\t) and the NUL character (\0).

The characters from the second category cannot be used because they have a special meaning. These characters are the quotes (") (its presence means the end of the string) and the apostrophe (') (used to enclose a character literal).

In order to have one of them into the language representation of a character or string they have to be escaped. This means, inside a string, \" represents the " character and the apostrophe character is encoded as '\''.

This way, the backslash character (\) also becomes special and it must be escaped (\\) to represent itself in a string or as a character.

Title: Datatype of escape sequences in c++


答:
You could split the string and filter out the words that match</p>

```<code>var mystr = 'football vi-cnn-sel vi-sky test vi-axn red';

mystr.split(' ').filter(function(v){
   if(!v.match("vi-")){
     return v;
   }
});
</code>```

Title: Delete substrings started with 'vi-' within string

Body:
You could split the string and filter out the words that match

var mystr = 'football vi-cnn-sel vi-sky test vi-axn red';

mystr.split(' ').filter(function(v){
   if(!v.match("vi-")){
     return v;
   }
});


问:
Global Search in Moodle 3.2
I am trying to setup global Solr search in moodle 3.2 on mac and using MAMP (locally). I have installed Solr 6.6.1, and can access its admin panel through http://127.0.0.1:8080/solr/ . But I am unable to link it with moodle through PECL Solr, the reasion is that I am unable to install PECL, I don't know where to place them, and how to link with moodle.

I am getting

and

答:
You need to follow these steps to get Solr working in Moodle.

Step:1 Delete core you have created in Solr.

Step:2 Create new core

Step:3 filled core name into Index name filed of Moodle Solr setting.

Step:4 sudo bin/solr stop -force

Step:5 sudo bin/solr start -force

If not working yet then need to reboot the system and restart Solr again.
Hope it is done!

Title: Global Search in Moodle 3.2


问:
Google Chrome Extension - Script Injections
I'm trying to get my Chrome Extension to inject some javascript with content_scripts, using this previous answer as a reference.

manifest.json

```<code>"name": "My Chrome Extension",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [{
    "matches": ["http://pagetoinject/script/into/*"],
    "js": ["contentscript.js"]
}]
</code>```

contenscript.js:

```<code>var s = document.createElement('script');
s.src = chrome.extension.getURL("script.js");
(document.head||document.documentElement).appendChild(s);
s.parentNode.removeChild(s);
</code>```

( also tried this method with no success. )

```<code>var s = document.createElement('script');
s.src = chrome.extension.getURL("script.js");
s.onload = function() {
    this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
</code>```

I keep getting this javascript error. Here's a screenshot.

    GET chrome-extension://invalid/
       (anonymous function)

答: In addition to the answers above I notice that in your contentscript.js you are just adding another script i.e script.js Why don't you directly add script.js through content_scripts in manifest.json.

Body:
I'm trying to get my Chrome Extension to inject some javascript with content_scripts, using this previous answer as a reference.

manifest.json

"name": "My Chrome Extension",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [{
    "matches": ["http://pagetoinject/script/into/*"],
    "js": ["contentscript.js"]
}]

contenscript.js:

var s = document.createElement('script');
s.src = chrome.extension.getURL("script.js");
(document.head||document.documentElement).appendChild(s);
s.parentNode.removeChild(s);

( also tried this method with no success. )

var s = document.createElement('script');
s.src = chrome.extension.getURL("script.js");
s.onload = function() {
    this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);

I keep getting this javascript error. Here's a screenshot.

    GET chrome-extension://invalid/
       (anonymous function)


问:
Responsive column for CSS not working
Why does the image not automatically go down if I reduce the width(mobile device)? Is there something wrong with my , @media or something else?

*I tried to make it responsive like bootstrap column. I divide it : twothird and third part, but the third part doesn't go down responsively, stuck on the right side even if I already adjust twothird and third only implemented in device with min-width:601px. Please help.

Thank you in advance.*

html {
   box-sizing : border-box;
}*,
*:before,
*:after {
   box-sizing : inherit;
}

html {
   -ms-text-size-adjust : 100%;
   -webkit-text-size-adjust : 100%;
   overflow-x : hidden;
   min-height: 100%;
   min-width: 100%;
}

html, body {
   font-family : Verdana, sans-serif;
   font-size : 15px;
   line-height : 1.5;
}

body {
   margin : 0;
}

a {
   background-color : transparent;
   -webkit-text-decoration-skip : objects;
   color : inherit;
}

a : active, a : hover {
   outline-width : 0;
}

h1 {
   font-size : 36px;
}

h2 {
   font-size : 30px;
}

h3 {
   font-size : 24px;
}

h4 {
   font-size : 20px;
}

h5 {
   font-size : 18px;
}

h5.italic {
   font-style : italic;
}

h6 {
   font-size : 16px;
}

p {
   color : #757575!important;
}

p.italic {
    font-style : italic;
}

@media (min-width : 993px) {
   .hide-large {
      display : none!important;
   }
}

@media (max-width : 992px) and (min-width : 601px) {
   .hide-medium {
      display : none!important;
   }
}

@media (max-width:600px){
   .hide-small {
      display:none!important;
   } .content-main {
      flex-direction: row;
   }
}

@media (min-width:601px){
   .quarter {
      width : 24.99999%;
   } .third {
      width : 33.33333%;
   } .twothird {
      width : 66.66666%;
   }
}

@media (max-width:992px){
   .content-main {
      margin-left : 0!important;
      margin-right : 0!important;
   }
}

img {
   border-style : none;
}

.theme {
   color : #fff!important;
   background-color : #000000!important;
}

.theme-l1 {
   color : #fff!important;
   background-color : #333333!important;
}

.top,.bottom {
   position : fixed;
   width : 100%;
   z-index : 1;
}

.top {
   top : 0;
}

.bottom {
   bottom : 0;
}

.bar {
   width : 100%;
   overflow : hidden;
}

.container, .panel {
   padding : 0.01em 16px;
   min-height: 50px;
   overflow: hidden;
}

.panel {
   margin-top : 16px;
   margin-bottom : 16px;
}

.bar .bar-item {
   padding : 8px 16px;
   float : left;
   width : auto;
   border : none;
   outline : none;
   display : block;
}

.bar .button {
   white-space : normal;
}

.bar-block .bar-item{
   width : 100%;
   display : block;
   padding : 8px 16px;
   text-align : left;
   border : none;
   outline : none;
   white-space : normal;
   float : none;
}

.button {
   -webkit-touch-callout : none;
   -webkit-user-select : none;
   -khtml-user-select : none;
   -moz-user-select : none;
   -ms-user-select : none;
   user-select : none;
   border : none;
   display : inline-block;
   outline : 0;
   padding : 8px 16px;
   vertical-align : middle;
   overflow : hidden;
   text-decoration : none;
   color : inherit;
   background-color : inherit;
   text-align : center;
   cursor : pointer;
   white-space : nowrap;
}

.button : hover {
   color : #000!important;
   background-color : #ccc!important;
}

.button : disabled{
   cursor : not-allowed;
   opacity : 0.3;
}

.teal {
   color : #fff!important;
   background-color : #009688!important;
}

.teal, .hover-teal : hover {
   color : #fff!important;
   background-color : #009688!important;
}

.white, .hover-white : hover {
   color : #000!important;
   background-color : #fff!important;
}

.margin-top {
   margin-top : 16px!important;
}

.margin-bottom {
   margin-bottom : 16px!important;
}

.margin-left {
   margin-left : 16px!important;
}

.margin-right {
   margin-right : 16px!important;
}

.right {
   float : right!important;
}

.display-container {
   position : relative;
}

.animate-opacity {
   animation : opac 0.8s;
} @keyframes opac {
   from {
      opacity : 0;
   } to {
      opacity : 1;
   }
}

.xlarge {
   font-size : 24px!important;
}

.xxlarge{
   font-size : 36px!important;
}

.left-align {
   text-align : left!important;
}

.center {
   text-align : center!important;
}

.padding-65 {
   padding-top : 65px!important;
   padding-bottom : 65px!important;
}

.padding-64 {
   padding-top : 64px!important;
   padding-bottom : 64px!important;
}

.light-grey, .hover-light-grey : hover {
   color : #000!important;
   background-color : #f1f1f1!important;
}

.bottombar {
   border-bottom : 6px solid #ccc!important;
}

.topbar {
   border-top : 6px solid #ccc!important;
}

.padding-16 {
   padding-top : 16px!important;
   padding-bottom : 16px!important;
}

.padding {
   padding : 8px 16px!important;
}
.quarter, .third,
.twothird {
   float : left;
   width : 100%;
}

.quarter {
   width : 24.99999%;
}

.third {
   width : 33.33333%;
}

.twothird {
   width : 66.66666%;
}

.row-padding,
.row-padding > .quarter,
.row-padding > .third,
.row-padding > .twothird {
   padding : 0 8px;
}

.content{
   max-width : 980px;
   margin : auto;
}

.hide{
   display : none!important;
}

.show {
   display : block!important;
}

.container : after, .container : before,
.panel : after, .panel : before,
.row-padding : after, .row-padding : before,
.bar : before, .bar : after {
   content : "";
   display : table;
   clear : both;
}

.circle {
   border-radius : 50%;
}

.content-main {
   max-width : 1020px;
   margin : auto;
   min-height: 50px;
   overflow: hidden;
}

.leftbar {
   border-left : 6px solid #ccc!important;
}

.serif {
   font-family : serif;
}

.karma {
   font-family :"Karma", sans-serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container row-padding padding-64" id="about">
  <div class="content">
   <div class="twothird">
   <h1 class="xlarge bottombar padding-16">About</h1>
   <h5 class="padding-32">Between art and craft, lies The Chino A Serie.</h5>

      <p class="padding-32">Discover brand new wave of chinoserie inside us, whether you just want an instagenic background for your dayout or appreciate a new beauty, history and art while you sip your Macadamia Coffee or chop the Feast Roasta Lamb. We present you "turn-back time" experience through walking corridor gallery with theme from contemporer to ancient baroque style. Oh, once more! Check out the fusion tile work in the floor of the cafe.</p>

      <h5 class="padding-32 italic">Entre art et artisanat, se trouve La  Chino A Série.</h5>

      <p class="padding-32 italic">Découvrez la toute nouvelle vague de chinoserie en nous, que vous souhaitiez simplement un arrière-plan instagène pour votre journée ou apprécier une nouvelle beauté, histoire et art pendant que vous sirotez votre Macadamia Coffee ou que vous coupez l'agneau Roasta Feast. Nous vous présentons l'expérience du temps de retour à travers la galerie de couloir à pied avec le thème du style contemporain à l'ancien style baroque. Oh, encore une fois! Découvrez le travail de carreaux de fusion dans le plancher du café.</p><br>
   </div><br><br>
   <div class="third center content padding-64">
    <img src="images/TealBird.jpg" alt="chinoiserie" style="width : 90%">
    <div class="panel">
     <p><i class="fa fa-quote-left xxlarge"></i><br>
      <i class="xlarge serif">White becomes teal, Birds free from the tale.
      </i><br>
      <i class="fa fa-quote-right xxlarge"></i>
     </p>
    </div>
   </div>
     </div>
 </div></code>```

答: Because the default width is 100% and the twothird has width of 66.66%, while third  has a width of 33.33%. The elements will fill up the empty spaces. What you could do is to set parent width to 66.66% or you give all three child elements a width of 100% (so it will automatically pushed everything beneath each other). </p>

Title: Responsive column for CSS not working

Body:
Why does the image not automatically go down if I reduce the width(mobile device)? Is there something wrong with my , @media or something else?

*I tried to make it responsive like bootstrap column. I divide it : twothird and third part, but the third part doesn't go down responsively, stuck on the right side even if I already adjust twothird and third only implemented in device with min-width:601px. Please help.

Thank you in advance.*

html {
   box-sizing : border-box;
}*,
*:before,
*:after {
   box-sizing : inherit;
}

html {
   -ms-text-size-adjust : 100%;
   -webkit-text-size-adjust : 100%;
   overflow-x : hidden;
   min-height: 100%;
   min-width: 100%;
}

html, body {
   font-family : Verdana, sans-serif;
   font-size : 15px;
   line-height : 1.5;
}

body {
   margin : 0;
}

a {
   background-color : transparent;
   -webkit-text-decoration-skip : objects;
   color : inherit;
}

a : active, a : hover {
   outline-width : 0;
}

h1 {
   font-size : 36px;
}

h2 {
   font-size : 30px;
}

h3 {
   font-size : 24px;
}

h4 {
   font-size : 20px;
}

h5 {
   font-size : 18px;
}

h5.italic {
   font-style : italic;
}

h6 {
   font-size : 16px;
}

p {
   color : #757575!important;
}

p.italic {
    font-style : italic;
}

@media (min-width : 993px) {
   .hide-large {
      display : none!important;
   }
}

@media (max-width : 992px) and (min-width : 601px) {
   .hide-medium {
      display : none!important;
   }
}

@media (max-width:600px){
   .hide-small {
      display:none!important;
   } .content-main {
      flex-direction: row;
   }
}

@media (min-width:601px){
   .quarter {
      width : 24.99999%;
   } .third {
      width : 33.33333%;
   } .twothird {
      width : 66.66666%;
   }
}

@media (max-width:992px){
   .content-main {
      margin-left : 0!important;
      margin-right : 0!important;
   }
}

img {
   border-style : none;
}

.theme {
   color : #fff!important;
   background-color : #000000!important;
}

.theme-l1 {
   color : #fff!important;
   background-color : #333333!important;
}

.top,.bottom {
   position : fixed;
   width : 100%;
   z-index : 1;
}

.top {
   top : 0;
}

.bottom {
   bottom : 0;
}

.bar {
   width : 100%;
   overflow : hidden;
}

.container, .panel {
   padding : 0.01em 16px;
   min-height: 50px;
   overflow: hidden;
}

.panel {
   margin-top : 16px;
   margin-bottom : 16px;
}

.bar .bar-item {
   padding : 8px 16px;
   float : left;
   width : auto;
   border : none;
   outline : none;
   display : block;
}

.bar .button {
   white-space : normal;
}

.bar-block .bar-item{
   width : 100%;
   display : block;
   padding : 8px 16px;
   text-align : left;
   border : none;
   outline : none;
   white-space : normal;
   float : none;
}

.button {
   -webkit-touch-callout : none;
   -webkit-user-select : none;
   -khtml-user-select : none;
   -moz-user-select : none;
   -ms-user-select : none;
   user-select : none;
   border : none;
   display : inline-block;
   outline : 0;
   padding : 8px 16px;
   vertical-align : middle;
   overflow : hidden;
   text-decoration : none;
   color : inherit;
   background-color : inherit;
   text-align : center;
   cursor : pointer;
   white-space : nowrap;
}

.button : hover {
   color : #000!important;
   background-color : #ccc!important;
}

.button : disabled{
   cursor : not-allowed;
   opacity : 0.3;
}

.teal {
   color : #fff!important;
   background-color : #009688!important;
}

.teal, .hover-teal : hover {
   color : #fff!important;
   background-color : #009688!important;
}

.white, .hover-white : hover {
   color : #000!important;
   background-color : #fff!important;
}

.margin-top {
   margin-top : 16px!important;
}

.margin-bottom {
   margin-bottom : 16px!important;
}

.margin-left {
   margin-left : 16px!important;
}

.margin-right {
   margin-right : 16px!important;
}

.right {
   float : right!important;
}

.display-container {
   position : relative;
}

.animate-opacity {
   animation : opac 0.8s;
} @keyframes opac {
   from {
      opacity : 0;
   } to {
      opacity : 1;
   }
}

.xlarge {
   font-size : 24px!important;
}

.xxlarge{
   font-size : 36px!important;
}

.left-align {
   text-align : left!important;
}

.center {
   text-align : center!important;
}

.padding-65 {
   padding-top : 65px!important;
   padding-bottom : 65px!important;
}

.padding-64 {
   padding-top : 64px!important;
   padding-bottom : 64px!important;
}

.light-grey, .hover-light-grey : hover {
   color : #000!important;
   background-color : #f1f1f1!important;
}

.bottombar {
   border-bottom : 6px solid #ccc!important;
}

.topbar {
   border-top : 6px solid #ccc!important;
}

.padding-16 {
   padding-top : 16px!important;
   padding-bottom : 16px!important;
}

.padding {
   padding : 8px 16px!important;
}
.quarter, .third,
.twothird {
   float : left;
   width : 100%;
}

.quarter {
   width : 24.99999%;
}

.third {
   width : 33.33333%;
}

.twothird {
   width : 66.66666%;
}

.row-padding,
.row-padding > .quarter,
.row-padding > .third,
.row-padding > .twothird {
   padding : 0 8px;
}

.content{
   max-width : 980px;
   margin : auto;
}

.hide{
   display : none!important;
}

.show {
   display : block!important;
}

.container : after, .container : before,
.panel : after, .panel : before,
.row-padding : after, .row-padding : before,
.bar : before, .bar : after {
   content : "";
   display : table;
   clear : both;
}

.circle {
   border-radius : 50%;
}

.content-main {
   max-width : 1020px;
   margin : auto;
   min-height: 50px;
   overflow: hidden;
}

.leftbar {
   border-left : 6px solid #ccc!important;
}

.serif {
   font-family : serif;
}

.karma {
   font-family :"Karma", sans-serif;
}

About

Between art and craft, lies The Chino A Serie.

Discover brand new wave of chinoserie inside us, whether you just want an instagenic background for your dayout or appreciate a new beauty, history and art while you sip your Macadamia Coffee or chop the Feast Roasta Lamb. We present you "turn-back time" experience through walking corridor gallery with theme from contemporer to ancient baroque style. Oh, once more! Check out the fusion tile work in the floor of the cafe.

Entre art et artisanat, se trouve La  Chino A Série.

Découvrez la toute nouvelle vague de chinoserie en nous, que vous souhaitiez simplement un arrière-plan instagène pour votre journée ou apprécier une nouvelle beauté, histoire et art pendant que vous sirotez votre Macadamia Coffee ou que vous coupez l'agneau Roasta Feast. Nous vous présentons l'expérience du temps de retour à travers la galerie de couloir à pied avec le thème du style contemporain à l'ancien style baroque. Oh, encore une fois! Découvrez le travail de carreaux de fusion dans le plancher du café.

      White becomes teal, Birds free from the tale.


问:
HTTP 500 Deploying Elixir/Phoenix to AWS Elastic Beanstalk
I'm having trouble with the elixir/phoenix config that I need for a deployment to AWS/Elastic Beanstalk. (Following the guide found here: https://thoughtbot.com/blog/deploying-elixir-to-aws-elastic-beanstalk-with-docker - my Dockerfile looks similar except for updated libraries).

I can run in eb local run, but am having trouble pushing to production.

However, when I try and deploy to EB, I get the following warning, and it crashes:

```<code>Environment health has transitioned from Degraded to Severe.
100.0 % of the requests are failing with HTTP 5xx.
Command failed on all instances.
Incorrect application version found on all instances. Expected version "app-8412-171116_115503" (deployment 5).
ELB processes are not healthy on all instances.
100.0 % of the requests to the ELB are erroring with HTTP 4xx.
Insufficient request rate (0.5 requests/min) to determine application health (5 minutes ago).
ELB health is failing or not available for all instances.
</code>```

I was wondering if someone could let me know if my configs look right.

I've been trying a bunch of things, but I think I've gotten confused, as I'm just guessing at this point.

config.exs

```<code>use Mix.Config

config :newsly,
  ecto_repos: [Newsly.Repo]

config :logger, :console,
  format: "$time $metadata[$level] $message\n",
  metadata: [:request_id]

import_config "#{Mix.env}.exs"
</code>```

prod.exs

```<code>use Mix.Config

config :logger, :console, format: "[$level] $message\n"

config :phoenix, :stacktrace_depth, 5

import_config "prod.secret.exs"
</code>```

prod.secret.exs

```<code>use Mix.Config

config :ex_aws,
  access_key_id: System.get_env("AWS_ACCESS_KEY_ID"),
  secret_access_key: System.get_env("AWS_SECRET_ACCESS_KEY"),
  bucket_name: System.get_env("BUCKET_NAME"),
  s3: [
   scheme: "https://",
   host: System.get_env("BUCKET_NAME"),
   region: "us-west-2"
  ]

config :newsly, Newsly.Repo,
  adapter: Ecto.Adapters.Postgres,
  username: System.get_env("USERNAME"),
  password: System.get_env("PASSWORD"),
  database: System.get_env("DATABASE"),
  hostname: System.get_env("DBHOST"),
  # sometimes hostname is db (like in the docker-compose method - play with this one)
  pool_size: 10

config :newsly, Newsly.Endpoint,
  http: [port: 4000],
  debug_errors: true,
  code_reloader: false,
  url: [scheme: "http", host: System.get_env("HOST"), port: 4000],
  secret_key_base: System.get_env("SECRET_KEY_BASE"),
  pubsub: [adapter: Phoenix.PubSub.PG2, pool_size: 5, name: Newsly.PubSub],
  check_origin: false,
  watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin",
                    cd: Path.expand("../", __DIR__)]]
</code>```

And in my Dockerfile I set my environment variables like the following;

```<code>ENV AWS_ACCESS_KEY_ID=nottelling
ENV AWS_SECRET_ACCESS_KEY=nottelling
ENV BUCKET_NAME=s3 storage bucket (not eb related)
ENV SECRET_KEY_BASE=nottelling
ENV HOST=host name of my eb instance im uploading to
ENV DBHOST=AWS rds host that holds postgres
ENV USERNAME=nottelling
ENV PASSWORD=nottelling
</code>```

My health report on the instance fails to red with the following warning:

```<code>Environment health has transitioned from Warning to Severe. 100.0 % of the requests are failing with HTTP 5xx. ELB processes are not healthy on all instances. ELB health is failing or not available for all instances.
</code>```

NGINX seems to be choking with the lines

```<code>2017/11/16 17:59:46 [error] 28815#0: *99 connect() failed (113: No route to host) while connecting to upstream, client: 172.31.20.108, server: , request: "GET / HTTP/1.1", upstream: "http://172.17.0.2:4000/", host: "172.31.38.244"
</code>```

in nginx logs.

If I look at eb-activity log I have

```<code>duplicate MIME type "text/html" in /etc/nginx/sites-enabled/elasticbeanstalk-nginx-docker-proxy.conf:11
</code>```

which seems to be killing nginx

```<code>[2017-11-16T18:02:33.927Z] INFO  [29355] - [Application update app-8412-171116_115503@5/AppDeployStage1/AppDeployEnactHook/01flip.sh] : Completed activity. Result:
  nginx: [warn] duplicate MIME type "text/html" in /etc/nginx/sites-enabled/elasticbeanstalk-nginx-docker-proxy.conf:11
  Stopping nginx: [  OK  ]
  Starting nginx: nginx: [warn] duplicate MIME type "text/html" in /etc/nginx/sites-enabled/elasticbeanstalk-nginx-docker-proxy.conf:11
  [  OK  ]
  iptables: Saving firewall rules to /etc/sysconfig/iptables: [  OK  ]
  Stopping current app container: e0161742ee69...
  Error response from daemon: No such image: aws_beanstalk/current-app:latest
  Making STAGING app container current...
  Untagged: aws_beanstalk/staging-app:latest
  eb-docker start/running, process 1398
  Docker container e25f2b562f4f is running aws_beanstalk/current-app.
</code>```

Does anyone have any ideas?

EDIT:

Digging through the logs for nginx I found

```<code>map $http_upgrade $connection_upgrade {
    default        "upgrade";
    ""            "";
}

server {
    listen 80;

    gzip on;
        gzip_comp_level 4;
        gzip_types text/html text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2})") {
        set $year $1;
        set $month $2;
        set $day $3;
        set $hour $4;
    }
    access_log /var/log/nginx/healthd/application.log.$year-$month-$day-$hour healthd;

    access_log    /var/log/nginx/access.log;

    location / {
        proxy_pass            http://docker;
        proxy_http_version    1.1;

        proxy_set_header    Connection            $connection_upgrade;
        proxy_set_header    Upgrade                $http_upgrade;
        proxy_set_header    Host                $host;
        proxy_set_header    X-Real-IP            $remote_addr;
        proxy_set_header    X-Forwarded-For        $proxy_add_x_forwarded_for;
    }
}
</code>```

So,

```<code>use Mix.Config

config :newsly,
  ecto_repos: [Newsly.Repo]

config :logger, :console,
  format: "$time $metadata[$level] $message\n",
  metadata: [:request_id]

import_config "#{Mix.env}.exs"
</code>```0

Seems to be referring to this line:

```<code>use Mix.Config

config :newsly,
  ecto_repos: [Newsly.Repo]

config :logger, :console,
  format: "$time $metadata[$level] $message\n",
  metadata: [:request_id]

import_config "#{Mix.env}.exs"
</code>```1

But at this point I would find it surprising if nginx was choking simply because it defines text/html twice. So now I'm not sure....

EDIT EDIT:
I should mention that my nginx/error.logs look like the following (the last lines repeat ad-infinum):

```<code>use Mix.Config

config :newsly,
  ecto_repos: [Newsly.Repo]

config :logger, :console,
  format: "$time $metadata[$level] $message\n",
  metadata: [:request_id]

import_config "#{Mix.env}.exs"
</code>```2

THIS IS THE HEART OF THE PROBLEM

NGINX fundamentally cant connect the entrypoint to the application and I don't know why!

UPDATE:

Using Kevin Johnson's advice I successfully pushed up to AWS ECR my Dockerfile and it compiled correctly when I eb deploy'ed my application with a good Dockerrun.aws.json. This is in fact a preferred way to do this. HOWEVER, I still get the same error! I do not know what is going on, but I think I can safely say that my Dockerfile successfully compiles.

I think there is something broken in AWS and I'm not sure what.

UPDATE

Problem is related to a NGINX routing issue. More information here in a clean question: How Do I modify NGINX routing on Elastic Beanstalk AWS?

答:
I highly suspect that the issue you are dealing with is either:

Your Dockerrun.aws.config file points to a non existing docker image on ECS Repository. This is indicated by the error message:
Error response from daemon: No such image: aws_beanstalk/current-app:latest
Making STAGING app container current...
When EB fails to replace the instance with the latest configuration, it will resort back to the old one, which could be the Hello World app of AWS that you may have leveraged in setting up EB. That container does not have a web service running on port 4000, whereas your Dockerrun.aws.config specifies port 4000.
(I would be surprised though that your Dockerrun.aws.config does not get replaced as well by EB to previous working version)
So check Dockerrun.aws.config and ensure that the image endpoint mentioned therein actually exists. Try pulling it locally and run it accordingly. First clean up your local environment of all images and running docker containers if need be.

Your application running within docker immediately crashes upon startup. Again, EB will detect this and replaces the crashed container with the previous container which again does not have port 4000 open.

ContentLicense: CC BY-SA 4.0

Body:
I'm having trouble with the elixir/phoenix config that I need for a deployment to AWS/Elastic Beanstalk. (Following the guide found here: https://thoughtbot.com/blog/deploying-elixir-to-aws-elastic-beanstalk-with-docker - my Dockerfile looks similar except for updated libraries).

I can run in eb local run, but am having trouble pushing to production.

However, when I try and deploy to EB, I get the following warning, and it crashes:

Environment health has transitioned from Degraded to Severe.
100.0 % of the requests are failing with HTTP 5xx.
Command failed on all instances.
Incorrect application version found on all instances. Expected version "app-8412-171116_115503" (deployment 5).
ELB processes are not healthy on all instances.
100.0 % of the requests to the ELB are erroring with HTTP 4xx.
Insufficient request rate (0.5 requests/min) to determine application health (5 minutes ago).
ELB health is failing or not available for all instances.

I was wondering if someone could let me know if my configs look right.

I've been trying a bunch of things, but I think I've gotten confused, as I'm just guessing at this point.

config.exs

use Mix.Config

config :newsly,
  ecto_repos: [Newsly.Repo]

config :logger, :console,
  format: "$time $metadata[$level] $message\n",
  metadata: [:request_id]

import_config "#{Mix.env}.exs"

prod.exs

use Mix.Config

config :logger, :console, format: "[$level] $message\n"

config :phoenix, :stacktrace_depth, 5

import_config "prod.secret.exs"

prod.secret.exs

use Mix.Config

config :ex_aws,
  access_key_id: System.get_env("AWS_ACCESS_KEY_ID"),
  secret_access_key: System.get_env("AWS_SECRET_ACCESS_KEY"),
  bucket_name: System.get_env("BUCKET_NAME"),
  s3: [
   scheme: "https://",
   host: System.get_env("BUCKET_NAME"),
   region: "us-west-2"
  ]

config :newsly, Newsly.Repo,
  adapter: Ecto.Adapters.Postgres,
  username: System.get_env("USERNAME"),
  password: System.get_env("PASSWORD"),
  database: System.get_env("DATABASE"),
  hostname: System.get_env("DBHOST"),
  # sometimes hostname is db (like in the docker-compose method - play with this one)
  pool_size: 10

config :newsly, Newsly.Endpoint,
  http: [port: 4000],
  debug_errors: true,
  code_reloader: false,
  url: [scheme: "http", host: System.get_env("HOST"), port: 4000],
  secret_key_base: System.get_env("SECRET_KEY_BASE"),
  pubsub: [adapter: Phoenix.PubSub.PG2, pool_size: 5, name: Newsly.PubSub],
  check_origin: false,
  watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin",
                    cd: Path.expand("../", __DIR__)]]

And in my Dockerfile I set my environment variables like the following;

ENV AWS_ACCESS_KEY_ID=nottelling
ENV AWS_SECRET_ACCESS_KEY=nottelling
ENV BUCKET_NAME=s3 storage bucket (not eb related)
ENV SECRET_KEY_BASE=nottelling
ENV HOST=host name of my eb instance im uploading to
ENV DBHOST=AWS rds host that holds postgres
ENV USERNAME=nottelling
ENV PASSWORD=nottelling

My health report on the instance fails to red with the following warning:

Environment health has transitioned from Warning to Severe. 100.0 % of the requests are failing with HTTP 5xx. ELB processes are not healthy on all instances. ELB health is failing or not available for all instances.

NGINX seems to be choking with the lines

2017/11/16 17:59:46 [error] 28815#0: *99 connect() failed (113: No route to host) while connecting to upstream, client: 172.31.20.108, server: , request: "GET / HTTP/1.1", upstream: "http://172.17.0.2:4000/", host: "172.31.38.244"

in nginx logs.

If I look at eb-activity log I have

duplicate MIME type "text/html" in /etc/nginx/sites-enabled/elasticbeanstalk-nginx-docker-proxy.conf:11

which seems to be killing nginx

[2017-11-16T18:02:33.927Z] INFO  [29355] - [Application update app-8412-171116_115503@5/AppDeployStage1/AppDeployEnactHook/01flip.sh] : Completed activity. Result:
  nginx: [warn] duplicate MIME type "text/html" in /etc/nginx/sites-enabled/elasticbeanstalk-nginx-docker-proxy.conf:11
  Stopping nginx: [  OK  ]
  Starting nginx: nginx: [warn] duplicate MIME type "text/html" in /etc/nginx/sites-enabled/elasticbeanstalk-nginx-docker-proxy.conf:11
  [  OK  ]
  iptables: Saving firewall rules to /etc/sysconfig/iptables: [  OK  ]
  Stopping current app container: e0161742ee69...
  Error response from daemon: No such image: aws_beanstalk/current-app:latest
  Making STAGING app container current...
  Untagged: aws_beanstalk/staging-app:latest
  eb-docker start/running, process 1398
  Docker container e25f2b562f4f is running aws_beanstalk/current-app.

Does anyone have any ideas?

EDIT:

Digging through the logs for nginx I found

map $http_upgrade $connection_upgrade {
    default        "upgrade";
    ""            "";
}

server {
    listen 80;

    gzip on;
        gzip_comp_level 4;
        gzip_types text/html text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

    if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2})") {
        set $year $1;
        set $month $2;
        set $day $3;
        set $hour $4;
    }
    access_log /var/log/nginx/healthd/application.log.$year-$month-$day-$hour healthd;

    access_log    /var/log/nginx/access.log;

    location / {
        proxy_pass            http://docker;
        proxy_http_version    1.1;

        proxy_set_header    Connection            $connection_upgrade;
        proxy_set_header    Upgrade                $http_upgrade;
        proxy_set_header    Host                $host;
        proxy_set_header    X-Real-IP            $remote_addr;
        proxy_set_header    X-Forwarded-For        $proxy_add_x_forwarded_for;
    }
}

So,

duplicate MIME type "text/html" in /etc/nginx/sites-enabled/elasticbeanstalk-nginx-docker-proxy.conf:11

Seems to be referring to this line:

gzip_types text/html text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;

But at this point I would find it surprising if nginx was choking simply because it defines text/html twice. So now I'm not sure....

EDIT EDIT:
I should mention that my nginx/error.logs look like the following (the last lines repeat ad-infinum):

2017/11/16 17:19:22 [warn] 18445#0: duplicate MIME type "text/html" in /etc/nginx/sites-enabled/elasticbeanstalk-nginx-docker-proxy.conf:11
2017/11/16 17:19:22 [warn] 18460#0: duplicate MIME type "text/html" in /etc/nginx/sites-enabled/elasticbeanstalk-nginx-docker-proxy.conf:11
2017/11/16 17:20:06 [error] 18467#0: *11 connect() failed (113: No route to host) while connecting to upstream, client: 172.31.32.139, server: , request: "GET / HTTP/1.1", upstream: "http://172.17.0.2:4000/", host: "172.31.38.244"
2017/11/16 17:20:15 [error] 18467#0: *13 connect() failed (113: No route to host) while connecting to upstream, client: 172.31.20.108, server: , request: "GET / HTTP/1.1", upstream: "http://172.17.0.2:4000/", host: "172.31.38.244"
2017/11/16 17:20:21 [error] 18467#0: *15 connect() failed (113: No route to host) while connecting to upstream, client: 172.31.32.139, server: , request: "GET / HTTP/1.1", upstream: "http://172.17.0.2:4000/", host: "172.31.38.244"
2017/11/16 17:20:30 [error] 18467#0: *17 connect() failed (113: No route to host) while connecting to upstream, client: 172.31.20.108, server: , request: "GET / HTTP/1.1", upstream:

THIS IS THE HEART OF THE PROBLEM

NGINX fundamentally cant connect the entrypoint to the application and I don't know why!

UPDATE:

Using Kevin Johnson's advice I successfully pushed up to AWS ECR my Dockerfile and it compiled correctly when I eb deploy'ed my application with a good Dockerrun.aws.json. This is in fact a preferred way to do this. HOWEVER, I still get the same error! I do not know what is going on, but I think I can safely say that my Dockerfile successfully compiles.

I think there is something broken in AWS and I'm not sure what.

UPDATE

Problem is related to a NGINX routing issue. More information here in a clean question: How Do I modify NGINX routing on Elastic Beanstalk AWS?


问:
How to set Password property of oledb connection in SSIS package
I am new to SSIS, here is the issue I am facing.
1) Created an OLEDB connection to connect to database. Storing the Connection String in SSIS variable and have added expression to Connection Manager to pick the connection string according to environment.
2) Have used Windows Authentication to connect to database, so that no need to provide user ID and Password. In development environment it worked perfectly fine. But when moved to testing environment, its failing with Error "SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER.  The AcquireConnection method call to the connection manager "REGEDB" failed with error code 0xC0202009"
3) Using SQL Server Configuration to deploy the package. But getting error Failed to load at least one of the configuration entries for the package. Check configuration entries for "CBPSSIS" and previous warnings to see descriptions of which configuration failed.
Below is the Connection String
Data Source=abcd\ISQLQ02;Initial Catalog=DRIP;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;
COuld you please let me know how to set Password property? I tired in Script file but its not working. Thank you

ConnectionManager OldedbConn;
 OldedbConn = Dts.Connections["QAREGE"];          Dts.Connections["QAREGE"].Properties["ServerName"].SetValue(OldedbConn, Dts.Variables["User::dbServerName"].Value);            Dts.Connections["QAREGE"].Properties["InitialCatalog"].SetValue(OldedbConn, Dts.Variables["User::dbCatalog"].Value);            Dts.Connections["QAREGE"].Properties["UserName"].SetValue(OldedbConn, Dts.Variables["User::dbUserID"].Value);            Dts.Connections["QAREGE"].Properties["Password"].SetValue(OldedbConn, Dts.Variables["User::dbPwd"].Value);

答: Since you are using ssis-2008 you can create a ssis configFile with .dtsConfig format with xml configuration file type. Include all your Database connection string in the config file. So when you moved your ssis package to another server you just need to edit the config file and set your connection based on your target server.


问:
run ruby-prof with a script that takes arguments
I know how to start ruby-prof with a script:

```<code> ruby-prof -p multi [SCRIPT_PATH]/my_script.rb
</code>```

but how can I run ruby-prof with a script that takes arguments ?

答:
Most commands that run another command will let you do this with the special double dash -- option, followed by the arguments you want to pass through. ruby-prof follows this norm.

If you have a Ruby file like this:

```<code># test.rb
puts "ARGV: #{ARGV.inspect}"
</code>```

You can run ruby-prof like this and get the args:

```<code>» ruby-prof test.rb -- arg1 arg2
ARGV: ["arg1", "arg2"]
</code>```

So in your specific case, you can do this:

```<code>» ruby-prof -p multi [SCRIPT_PATH]/my_script.rb -- arg1 arg2
</code>```

Body:
I know how to start ruby-prof with a script:

 ruby-prof -p multi [SCRIPT_PATH]/my_script.rb

but how can I run ruby-prof with a script that takes arguments ?

Body:
Most commands that run another command will let you do this with the special double dash -- option, followed by the arguments you want to pass through. ruby-prof follows this norm.

If you have a Ruby file like this:

# test.rb
puts "ARGV: #{ARGV.inspect}"

You can run ruby-prof like this and get the args:

» ruby-prof test.rb -- arg1 arg2
ARGV: ["arg1", "arg2"]

So in your specific case, you can do this:

» ruby-prof -p multi [SCRIPT_PATH]/my_script.rb -- arg1 arg2


问:
Make child having x% of parent's height set by min-height
My question isn't duplicate of this one, because in my case I use min-height attribute, which works slightly different than common height.

My issue is more advanced version of this one and concerns counterintuitive CSS behavior of min-height attribute. I'd like to set my child's height to 80% of parent's height set by min-height attribute. As shown below, we can set 100% of parent's height by inheriting min-height value, but I cannot do this for smaller percentage. Of course I don't like to set 100px for my child explicitly.

.parent {
  min-height: 100px;
  width: 100%;
  background-color: green;
}
.child {
  width: 30%;
  background-color: blue;
}
#c1 {
  min-height: inherit; /* =100% of parent's height*/
}
#c2 {
  min-height: 80%; /* doesn't work */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='parent'>
  <div id='c1' class='child'></div>
</div>
<br>
<div class='parent'>
  <div id='c2' class='child'></div>
</div></code>```

答:
you have to use position: relative to parent and position: absolute to child

.parent {
  min-height: 100px;
  width: 100%;
  background-color: green;
  position: relative;
}

.child {
  width: 30%;
  background-color: blue;
  position: absolute;
}

#c1 {
  min-height: inherit;
  /* =100% of parent's height*/
}

#c2 {
  min-height: 80%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='parent'>
  <div id='c1' class='child'></div>
</div>
<br>
<div class='parent'>
  <div id='c2' class='child'></div>
</div></code>```

Body:
you have to use position: relative to parent and position: absolute to child

.parent {
  min-height: 100px;
  width: 100%;
  background-color: green;
  position: relative;
}

.child {
  width: 30%;
  background-color: blue;
  position: absolute;
}

#c1 {
  min-height: inherit;
  /* =100% of parent's height*/
}

#c2 {
  min-height: 80%;
}

<div class='parent'>
  <div id='c1' class='child'></div>
</div>
<br>
<div class='parent'>
  <div id='c2' class='child'></div>
</div>


问:
How do i change my layout text dynamically?
i'm trying to change the Text on the BUTTON dynamically which is in the panel:

the initial text i've given is: var gost = "HPCL Jan 20 Put,40 cents ..";

```<code>    var bottomdetail = new Ext.Panel({
    flex:1,
    padding: 1,
    layout : {
                type: 'vbox',
                pack: 'center',
                align: 'stretch'
             },
    stretchX: true,
    items:[{
           xtype: 'button',
           flex: 1,
           baseCls: 'round',
           html: '<table border="0" height="100%" width="100%"><tr><td width="100%" style="color:#fff; padding-left:5px;" valign="middle">'+ gost + '</td><td valign="middle" align="right" style="padding-right:5px;"><img src="resources/Images/rightarrow.png"></img></td></tr></table>',
           handler: function(){window.location='DetailsPanel.html';}
           }]
});
</code>```

here is the piont where i use it to change the text :

```<code>    var shakepanel = new Ext.Panel({
                                layout : {
                                            type: 'hbox',
                                            pack: 'center',
                                            align: 'stretch'
                                         },
                                stretchX: true,
                                flex:1,
                                disable: true,
                                items: [{
                                        xtype: 'button',
                                        disable: true,
                                        layout: 'fit',
                                        ui: 'decline',
                                        text: 'SHAKE',
                                        flex:1,
                                        handler: function(){
                                            gost="ola i changed it";
                                            alert(bottomdetail.getText());
                                            }
                                     }]
                        });
</code>```

when i click on the button "SHAKE" the value of the "gost" is updated but how to apply the updated gost text to the bottomdetail panel which has the button in it.............

答:
What is not top off bottomdetail and shakepanel ? - should be PAPA ( newer talk to brother always to PAPA )....

In shakepanel -> button -> handler : fireEvent ( 'gostChanged', gost )

Tell PAPA to listen to it ( in listener or .on method )

When catched PAPA will change html on bottomdetail -> button ( it will be nice to have ref: there for easier access instead Ext.getComp or other search )

ContentLicense: CC BY-SA 2.5

Body:
i'm trying to change the Text on the BUTTON dynamically which is in the panel:

the initial text i've given is: var gost = "HPCL Jan 20 Put,40 cents ..";

    var bottomdetail = new Ext.Panel({
    flex:1,
    padding: 1,
    layout : {
                type: 'vbox',
                pack: 'center',
                align: 'stretch'
             },
    stretchX: true,
    items:[{
           xtype: 'button',
           flex: 1,
           baseCls: 'round',
           html: '

'+ gost + '

',
           handler: function(){window.location='DetailsPanel.html';}
           }]
});

here is the piont where i use it to change the text :

    var shakepanel = new Ext.Panel({
                                layout : {
                                            type: 'hbox',
                                            pack: 'center',
                                            align: 'stretch'
                                         },
                                stretchX: true,
                                flex:1,
                                disable: true,
                                items: [{
                                        xtype: 'button',
                                        disable: true,
                                        layout: 'fit',
                                        ui: 'decline',
                                        text: 'SHAKE',
                                        flex:1,
                                        handler: function(){
                                            gost="ola i changed it";
                                            alert(bottomdetail.getText());
                                            }
                                     }]
                        });

when i click on the button "SHAKE" the value of the "gost" is updated but how to apply the updated gost text to the bottomdetail panel which has the button in it.............


问:
Is console.log() a javascript built-in method?
I'm working with angular js. My project includes only the angular.min.js file, with no other references of js files like javascript etc.
The code which makes request to the server is as follows:

var app = angular
  .module("myModule", [])
  .controller("myController", function($scope, $http) {

    $http.get("WebService.asmx/GetAllEmployees")
      .then(function(response) {
        $scope.employees = response.data;
        console.log(response.data)
      }, function(reason) {
        $scope.error = reason.data;
      });
  });
```

<p>I'm wondering about the following line: </p>

```console.log(response.data)
```

I could not figure out who's property this function is?

Is this browser builtin function?

答:
console.log() is a feature for debugging purposes. It allows a script to log data to the JavaScript console.

If you want to display the message from console.log() in your browser, you need to access the browser's console.

Body:
I'm working with angular js. My project includes only the angular.min.js file, with no other references of js files like javascript etc.
The code which makes request to the server is as follows:

var app = angular
  .module("myModule", [])
  .controller("myController", function($scope, $http) {

    $http.get("WebService.asmx/GetAllEmployees")
      .then(function(response) {
        $scope.employees = response.data;
        console.log(response.data)
      }, function(reason) {
        $scope.error = reason.data;
      });
  });

I'm wondering about the following line:

console.log(response.data)

I could not figure out who's property this function is?

Is this browser builtin function?


问:
DOSGI Custom Provider Registration
I am trying to run DOSGI in Apache Felix.
I use CXF 3.2.0 bundles and DOSGI 2.3.0

I can successfully register services but I can not register global custom providers for my resources.

I have a Resource defined in interface:

```<code>@Path("")
public interface IToDoResource {

@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
List<ToDo> getAllToDos();

@GET
@Path("{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
ToDo getToDoById(@PathParam("id") Long id);
...
}
</code>```

Then implemented in:

```<code>@Component(//
    name = "My.ToDoRestService", //
    immediate = true, //
    property = //
    { //
        "service.exported.configs=org.apache.cxf.rs", //
        "service.exported.interfaces=*", //
         "org.apache.cxf.rs.address=/todos", //
    } //
)
public class ToDoResource implements IToDoResource {
....
}
</code>```

I try to register Global custom Providers for my classes.
I can make it working with "service.exported.intents" property on the resource and "IntentName" on the provider for one provider.
However for this resource I want to register 4 providers:

ToDo XML provider

ToDo Json provider

ArrayList XML provider

ArrayList Json provider

Alternatively I can also implement IntentsProvider on the resource and it also works.

However following does not work and I get no provider registered for this type error in the logs:

```<code>@Component(//
    name = "My.ToDoJsonProvider", //
    immediate = true, //
    service = MessageBodyWriter.class, //
    property = {
        "service.exported.configs=org.apache.cxf.rs", //
        "org.apache.cxf.rs.provider=true", //
    } //
)
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class ToDoJsonProvider implements MessageBodyWriter<ToDo> {
</code>```

GET on localhost:8080/cxf/todos/1 returns empty document and on logs:

JAXRSUtils:1834] No message body writer has been found for class my.todo.repository.api.ToDo, ContentType: application/xml

What do I miss here to register a custom provider globally?

答:
It seems like intents are only taken into account when they are directly named in the Resource properties.
"service.exported.intents" property must list all intents that can are required by the resource.

I could not find any documentation but the source code of the RsProvider and IntentManagerImpl classes helped to me.

RsProvider:
https://github.com/apache/cxf-dosgi/blob/master/provider-rs/src/main/java/org/apache/cxf/dosgi/dsw/handlers/rest/RsProvider.java

IntentManagerImpl:
https://github.com/apache/cxf-dosgi/blob/master/common/src/main/java/org/apache/cxf/dosgi/common/intent/impl/IntentManagerImpl.java

Title: DOSGI Custom Provider Registration

Body:
I am trying to run DOSGI in Apache Felix.
I use CXF 3.2.0 bundles and DOSGI 2.3.0

I can successfully register services but I can not register global custom providers for my resources.

I have a Resource defined in interface:

@Path("")
public interface IToDoResource {

@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
List<ToDo> getAllToDos();

@GET
@Path("{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
ToDo getToDoById(@PathParam("id") Long id);
...
}

Then implemented in:

@Component(//
    name = "My.ToDoRestService", //
    immediate = true, //
    property = //
    { //
        "service.exported.configs=org.apache.cxf.rs", //
        "service.exported.interfaces=*", //
         "org.apache.cxf.rs.address=/todos", //
    } //
)
public class ToDoResource implements IToDoResource {
....
}

I try to register Global custom Providers for my classes.
I can make it working with "service.exported.intents" property on the resource and "IntentName" on the provider for one provider.
However for this resource I want to register 4 providers:

ToDo XML provider

ToDo Json provider

ArrayList XML provider

ArrayList Json provider

Alternatively I can also implement IntentsProvider on the resource and it also works.

However following does not work and I get no provider registered for this type error in the logs:

@Component(//
    name = "My.ToDoJsonProvider", //
    immediate = true, //
    service = MessageBodyWriter.class, //
    property = {
        "service.exported.configs=org.apache.cxf.rs", //
        "org.apache.cxf.rs.provider=true", //
    } //
)
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class ToDoJsonProvider implements MessageBodyWriter<ToDo> {

GET on localhost:8080/cxf/todos/1 returns empty document and on logs:

JAXRSUtils:1834] No message body writer has been found for class my.todo.repository.api.ToDo, ContentType: application/xml

What do I miss here to register a custom provider globally?


问:
Dealing with Promises
I wanted to ask a question about the way I am using Promises, since I'm not sure if I have over complicated things.

Firstly I am trying to create some methods that I want to execute one after another as the rely on the outcome of each previous method.

My project structure is like so

```<code>my_project
csv
helpers
  FileDownload.js
scripts
  getCSVData.js
app.js
</code>```

Each file at the moment looks like

```<code>## FileDownload.js
const fetch = require('node-fetch');
const fs = require('fs');

module.exports = function(url, target) {
  return fetch(url)
  .then(function(res) {
    return new Promise((resolve, reject) => {
      var dest = fs.createWriteStream(target);
      res.body.pipe(dest)
      .on('finish', () => resolve()) // ** Resolve on success
      .on('error', reject);        // ** Reject on error
    });
  }).then(result => {
    console.log(`File saved at ${target}`)
    return result;
  });

}

## getCSVData.js

const file_download = require('../helpers/FileDownload')

function getPremierLeagueData() {
  file_download("http://www.football-data.co.uk/mmz4281/1718/E0.csv", "./csv/premier_league/premier_league.csv")
}

module.exports = {
  getPremierLeagueData: getPremierLeagueData
}

## app.js
const premier_league = require('./scripts/getCSVData')

premier_league.getPremierLeagueData()
  .then(function(result){ console.log(result)})
</code>```

When running node app.js i get the error TypeError: Cannot read property 'then' of undefined

If I go back to my FileDownload function and console.log(result) that is undefined.

My confusion here is that because resolve() is called I am thinking that the Promise is resolved? So that should carry through to the .then.

I am clearly misunderstanding something here.

答:
Need to return from getPremierLeagueData

```<code>function getPremierLeagueData() {
  return file_download("http://www.football-data.co.uk/mmz4281/1718/E0.csv", "./csv/premier_league/premier_league.csv")
}
</code>```

OR ( Use new ES6 syntax )

```<code>const getPremierLeagueData = () => file_download("http://www.football-data.co.uk/mmz4281/1718/E0.csv", "./csv/premier_league/premier_league.csv")
</code>```

Note :

you can also reduce this

```<code>module.exports = {
  getPremierLeagueData: getPremierLeagueData
}
</code>```

with

```<code>module.exports = { getPremierLeagueData }
</code>```

Title: Dealing with Promises

Body:
I wanted to ask a question about the way I am using Promises, since I'm not sure if I have over complicated things.

Firstly I am trying to create some methods that I want to execute one after another as the rely on the outcome of each previous method.

My project structure is like so

my_project
csv
helpers
  FileDownload.js
scripts
  getCSVData.js
app.js

Each file at the moment looks like

## FileDownload.js
const fetch = require('node-fetch');
const fs = require('fs');

module.exports = function(url, target) {
  return fetch(url)
  .then(function(res) {
    return new Promise((resolve, reject) => {
      var dest = fs.createWriteStream(target);
      res.body.pipe(dest)
      .on('finish', () => resolve()) // ** Resolve on success
      .on('error', reject);        // ** Reject on error
    });
  }).then(result => {
    console.log(`File saved at ${target}`)
    return result;
  });

}

## getCSVData.js

const file_download = require('../helpers/FileDownload')

function getPremierLeagueData() {
  file_download("http://www.football-data.co.uk/mmz4281/1718/E0.csv", "./csv/premier_league/premier_league.csv")
}

module.exports = {
  getPremierLeagueData: getPremierLeagueData
}

## app.js
const premier_league = require('./scripts/getCSVData')

premier_league.getPremierLeagueData()
  .then(function(result){ console.log(result)})

When running node app.js i get the error TypeError: Cannot read property 'then' of undefined

If I go back to my FileDownload function and console.log(result) that is undefined.

My confusion here is that because resolve() is called I am thinking that the Promise is resolved? So that should carry through to the .then.

I am clearly misunderstanding something here.

Body:
Need to return from getPremierLeagueData

function getPremierLeagueData() {
  return file_download("http://www.football-data.co.uk/mmz4281/1718/E0.csv", "./csv/premier_league/premier_league.csv")
}

OR ( Use new ES6 syntax )

const getPremierLeagueData = () => file_download("http://www.football-data.co.uk/mmz4281/1718/E0.csv", "./csv/premier_league/premier_league.csv")

Note :

you can also reduce this

module.exports = {
  getPremierLeagueData: getPremierLeagueData
}

with

module.exports = { getPremierLeagueData }


问:
Cannot post to a server in express
I have an express app that takes basic user input data. All of my get routes work fine but when submit a post request to the server I get a 404 on the url I'm posting to even though I have this page in my views folder.

app.js:

```<code>var express = require('express');
var path = require('path');
var consolidate = require('consolidate');
var bodyParser = require('body-parser');
var database = require('./database/database');
var Patient = require('./models/models').Patient;
var morgan = require('morgan');
var routes = require('./routes');
var app = express();

app.engine('html', consolidate.nunjucks);

app.set('view engine', 'html');
app.set('views', './views');

app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);

app.use(bodyParser.urlencoded({ extended: false }));

app.listen(3055);

module.exports = app;
</code>```

routes/index.js:

```<code>const express = require('express');
var bodyParser = require('body-parser');
var Patient = require('../models/models').Patient;
const router = express.Router();

router.get('/', function(req, res, next){
    res.render('index.html');
});

router.post('/addsubject', function(req, res, next){
    Patient.create(req.body).then(function(patient){
        res.redirect('/profile');
    }).catch(function(err){
        if(error.name === "SequelizeValidationError"){
       } else {
       return next(err);
       }
   }).catch(function(error){
      res.send(500, error);
   });
});

router.get('/profile', function(req, res, next){
    res.render('./profile.html');
});

router.get('/addsubject', function(req, res, next){
    // .... do something here ..
});

module.exports = router;
</code>```

I have the <form action="/addsubject" method="post"> in my index.html file.

index.html:

```<code><!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>dabl Demographic</title>
  <body>
    <h2>Add Subject</h2>
      <form action="/addsubject" method="post">
        <label for="fname">First Name: </label>
        <input type="text" name="fname" id="fname">
        <br>
        <label for="sname">Second Name: </label>
        <input type="text" name="sname" id="sname">
        <br>
        <label for="dob">dob: </label>
        <input type="text" name="dob" id="dob">
        <br>
        <label for="laterality">Laterality: </label>
        <input type="text" name="laterality" id="laterality">
        <br>
        <button>Submit</button>
      </form>
  </body>
</html>
</code>```

答:
Use body-parser middleware before app.router

```<code>...
app.use(bodyParser.urlencoded({ extended: false }));

app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
...
</code>```

Title: Cannot post to a server in express

Body:
I have an express app that takes basic user input data. All of my get routes work fine but when submit a post request to the server I get a 404 on the url I'm posting to even though I have this page in my views folder.

app.js:

var express = require('express');
var path = require('path');
var consolidate = require('consolidate');
var bodyParser = require('body-parser');
var database = require('./database/database');
var Patient = require('./models/models').Patient;
var morgan = require('morgan');
var routes = require('./routes');
var app = express();

app.engine('html', consolidate.nunjucks);

app.set('view engine', 'html');
app.set('views', './views');

app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);

app.use(bodyParser.urlencoded({ extended: false }));

app.listen(3055);

module.exports = app;

routes/index.js:

const express = require('express');
var bodyParser = require('body-parser');
var Patient = require('../models/models').Patient;
const router = express.Router();

router.get('/', function(req, res, next){
    res.render('index.html');
});

router.post('/addsubject', function(req, res, next){
    Patient.create(req.body).then(function(patient){
        res.redirect('/profile');
    }).catch(function(err){
        if(error.name === "SequelizeValidationError"){
       } else {
       return next(err);
       }
   }).catch(function(error){
      res.send(500, error);
   });
});

router.get('/profile', function(req, res, next){
    res.render('./profile.html');
});

router.get('/addsubject', function(req, res, next){
    // .... do something here ..
});

module.exports = router;

I have the <form action="/addsubject" method="post"> in my index.html file.

index.html:

<!doctype html>

    <meta charset="utf-8">
    <title>dabl Demographic</title>

Add Subject

      <form action="/addsubject" method="post">
        First Name:
        <input type="text" name="fname" id="fname">

        Second Name:
        <input type="text" name="sname" id="sname">

        dob:
        <input type="text" name="dob" id="dob">

        Laterality:
        <input type="text" name="laterality" id="laterality">

        <button>Submit</button>
      </form>

Body:
Use body-parser middleware before app.router

...
app.use(bodyParser.urlencoded({ extended: false }));

app.use(morgan('dev'));
//app.use(app.router);
app.use(routes);
...


问:
:host equivalent in component.ts
In component.css you can access <component> tag with :host selector.
Is there a direct way to access it in component.ts file?

I am aware of using ViewChild and parentElement, is there a more direct way of getting host DOM element?

答:
You can inject it</p>

```<code>class MyComponent {
  constructor(private elRef:ElementRef) {}

  ngAfterViewInit() {
    this.elRef.nativeElement...
  }
}
</code>```

Title: :host equivalent in component.ts

Body:
You can inject it

class MyComponent {
  constructor(private elRef:ElementRef) {}

  ngAfterViewInit() {
    this.elRef.nativeElement...
  }
}


问:
WordPress: Prevent get_query_var() from being cached
I have the below plugin code in PHP:

```<code>function getHotels() {
    if(get_query_var('htl_destination') !== null) {
        $url = "http://xmlfeed.laterooms.com/index.aspx?aid=100&rtype=4&kword=".get_query_var('htl_destination')."&sdate=".get_query_var('htl_start_date')."&nights=".get_query_var('htl_nights')."";
        $data = file_get_contents($url);

        $xml = simplexml_load_string($data) or die("Error cannot create object");
        foreach($xml->hotel as $hotel) {
            echo
            "<div class='panel'>
                <div>
                    <img class='img-left' src='{$hotel->images}'></img>
                    <div class='price'>
                        <p>Prices from</p>
                        <h1>£".str_replace(".0", "", $hotel->prices_from)."</h1>
                        <a href='#' class='view-now'>View now</a>
                    </div>
                    <div class='info'>
                        <h1>{$hotel->hotel_name}</h1>";
                        for($i=0; $hotel->hotel_star > $i; $i++) {
                            echo "<i>★</i>";
                        }
                        echo "
                        <p>{$hotel->hotel_address}</p>
                    </div>
                </div>
            </div>";
        }
    } else {
        echo "<p>No results</p>";
        print_r($_POST);
    }
}
</code>```

HTML:

```<code><form method="get" action="">
    <input style="margin-left: 0% width: 25%" class="form-control htl_filter" type="text" name="htl_destination" placeholder="Destination" required>
    <input style="margin-left: 0%" class="form-control htl_filter" type="date" name="htl_start_date" placeholder="Date" required>
    <div class="htl_filter" style="margin-left: 0%;">
        <select name="htl_nights" required>
            <option value="1">1 Night</option>
            <?php
                for ($i=2; $i < 29; $i++) {
                    echo "<option value={$i}>{$i} Nights</option>";
                }
            ?>
        </select>
    </div>
    <button style="width: 15%;" type="submit">Search</button>
</form>
</code>```

When the form is submitted to the following page the query variables are cached so the results go unchanged.

We have the siteground cache plugin installed on our site and the results do not change until I click "Purge SG Cache".

I have tried adding the url of the page which my plugin is on to the siteground cache plugin exclusion list with no success.

Is there a way to stop the variables from being cached?

答:
When I tried deactivating the SG cache plugin there was no difference possibly because the web page was being cached by the server. There is however a function which can be called to clear the cache so I've added this into my getHotels() function and the code now works.

The function is

```<code>if (function_exists('sg_cachepress_purge_cache')) {
    sg_cachepress_purge_cache();
}
</code>```

Body:
I have the below plugin code in PHP:

function getHotels() {
    if(get_query_var('htl_destination') !== null) {
        $url = "http://xmlfeed.laterooms.com/index.aspx?aid=100&rtype=4&kword=".get_query_var('htl_destination')."&sdate=".get_query_var('htl_start_date')."&nights=".get_query_var('htl_nights')."";
        $data = file_get_contents($url);

        $xml = simplexml_load_string($data) or die("Error cannot create object");
        foreach($xml->hotel as $hotel) {
            echo
            "

                    images}'>

Prices from

£".str_replace(".0", "", $hotel->prices_from)."

                        View now

{$hotel->hotel_name}
";
                        for($i=0; $hotel->hotel_star > $i; $i++) {
                            echo "★";
                        }
                        echo "

{$hotel->hotel_address}

";
        }
    } else {
        echo "
No results
";
        print_r($_POST);
    }
}

HTML:

<form method="get" action="">
    <input style="margin-left: 0% width: 25%" class="form-control htl_filter" type="text" name="htl_destination" placeholder="Destination" required>
    <input style="margin-left: 0%" class="form-control htl_filter" type="date" name="htl_start_date" placeholder="Date" required>

        <select name="htl_nights" required>
            <option value="1">1 Night</option>
            <?php
                for ($i=2; $i < 29; $i++) {
                    echo "<option value={$i}>{$i} Nights</option>";
                }
            ?>
        </select>

    <button style="width: 15%;" type="submit">Search</button>
</form>

When the form is submitted to the following page the query variables are cached so the results go unchanged.

We have the siteground cache plugin installed on our site and the results do not change until I click "Purge SG Cache".

I have tried adding the url of the page which my plugin is on to the siteground cache plugin exclusion list with no success.

Is there a way to stop the variables from being cached?

Body:
When I tried deactivating the SG cache plugin there was no difference possibly because the web page was being cached by the server. There is however a function which can be called to clear the cache so I've added this into my getHotels() function and the code now works.

The function is

if (function_exists('sg_cachepress_purge_cache')) {
    sg_cachepress_purge_cache();
}