问:
How can I send dynamic parameters to template in Azure Devops Yaml?
How can I add send several dynamic parameters to a template with azure devops yaml?

```<code>- pwsh: |
          $affected = npm run nx affected:apps -- --base=origin/master  --head=HEAD | grep -E '( - )(\w|-|\d|_)+'
          Write-Host "##vso[task.setvariable variable=affected;]$affected"
      - template: build.yml
          parameters:
            affected: $env:AFFECTED
</code>```

I think $affected is a list of string, here is the log when Write-Host "apps are ${affected}" :

Looks like affected: $env:AFFECTED``as parameters doesn't work. Here is the error :Mapping values are not allowed in this context`

Thanks

答:
Mapping values are not allowed in this context

The cause of this issue could be the YAML structure.

You could try to change the -template structure.

For example:

```<code>      - template: build.yml
        parameters:
          affected: $env:AFFECTED
</code>```

The parameter and affected field need to move forward two spaces(parameters and template are aligned).

Then this pipeline may work fine.

Here is a doc about the template sample.

Hope this helps.

Body:
How can I add send several dynamic parameters to a template with azure devops yaml?

- pwsh: |
          $affected = npm run nx affected:apps -- --base=origin/master  --head=HEAD | grep -E '( - )(\w|-|\d|_)+'
          Write-Host "##vso[task.setvariable variable=affected;]$affected"
      - template: build.yml
          parameters:
            affected: $env:AFFECTED

I think $affected is a list of string, here is the log when Write-Host "apps are ${affected}" :

Looks like affected: $env:AFFECTED``as parameters doesn't work. Here is the error :Mapping values are not allowed in this context`

Thanks

Body:
Mapping values are not allowed in this context

The cause of this issue could be the YAML structure.

You could try to change the -template structure.

For example:

      - template: build.yml
        parameters:
          affected: $env:AFFECTED

The parameter and affected field need to move forward two spaces(parameters and template are aligned).

Then this pipeline may work fine.

Here is a doc about the template sample.

Hope this helps.


来源: stackexchange

问:
Export Project into standalone .swf File
I am trying for quite some while now to find an answer on how to export a FlexProject into a standalone SWF file.
I have a FLV video which I put into the flvplayback Container and added the skin from Flash CS4.
So all it is ist just a simple Videoplayer.
We are working on a E-Learning Project and I want to put those Videos into the Main Application which was built with Flex 3.5, so to make things easier I need that standalone SWF Version of those Videos so my Teammates can just load them into the application with the flex swfloader.

I really hope I made myself clear, sorry English isnt my native language.

Here is the code from my project:

```<code>    public function init() {

    videoHolder1.addChild(debug);

    }

    ]]>
</fx:Script>
<fx:Declarations>
<video:FLVPlayback id="debug"
                   source="../Videos/Debug.flv"
                   scaleMode="maintainAspectRatio"
                   skin="../Skins/SkinUnderAllNoCaption.swf"
                   skinAutoHide="false"
                   width="960"
                   height="540"
                   skinBackgroundColor="#011293"

                   autoPlay="false"
                   />
</fx:Declarations>
<mx:UIComponent id="videoHolder1" />
</code>```

答:
for images you shoul do this. then image will be in swf. for videos i guess it similer. you need to try.</p>

```<code>[Embed(source="images/logo.gif")]
[Bindable]
public var imgCls:Class;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying for quite some while now to find an answer on how to export a FlexProject into a standalone SWF file.
I have a FLV video which I put into the flvplayback Container and added the skin from Flash CS4.
So all it is ist just a simple Videoplayer.
We are working on a E-Learning Project and I want to put those Videos into the Main Application which was built with Flex 3.5, so to make things easier I need that standalone SWF Version of those Videos so my Teammates can just load them into the application with the flex swfloader.

I really hope I made myself clear, sorry English isnt my native language.

Here is the code from my project:

    public function init() {

    videoHolder1.addChild(debug);

    }

    ]]>
</fx:Script>
<fx:Declarations>
<video:FLVPlayback id="debug"
                   source="../Videos/Debug.flv"
                   scaleMode="maintainAspectRatio"
                   skin="../Skins/SkinUnderAllNoCaption.swf"
                   skinAutoHide="false"
                   width="960"
                   height="540"
                   skinBackgroundColor="#011293"

                   autoPlay="false"
                   />
</fx:Declarations>
<mx:UIComponent id="videoHolder1" />

Body:
for images you shoul do this. then image will be in swf. for videos i guess it similer. you need to try.

[Embed(source="images/logo.gif")]
[Bindable]
public var imgCls:Class;


问:
How can data structures like Arrays in Java be of any type if they are objects themselves?
I might be getting a bit confused with OOP, just got into it, but if an array in java is an object, where it is calling the Array constructor from the Array class in java to make an instance of it, how is it possible for an Array in Java to be of primitive data type or any object type? Should not the type of the Array be Array type if that is what it is a class of? If I made a class called Car and then made an object called redCar of it, the type of the object is Car still. This does not just apply to Arrays but other data structures as well. Any easy explanations are welcome.</p>

答:
it is calling the Array constructor from the Array class in java to make an instance of it

Incorrect. Array types are not classes. As per JLS 10.8:

Although an array type is not a class, the Class object of every array acts as if...

Therefore, array types don't have constructors. Array objects are created using the newarray or anewarray bytecode instructions. Note that even though arrays are not instances of a class, they are still objects, because as per JLS 4.3.1:

An object is a class instance or an array.

Just from those two quotes you should realise that Java and the JVM gives arrays very special treatment.

how is it possible for an Array in Java to be of primitive data type or any object type?

You seem to think there is only one Array type. That's not true. You can turn any (non-parameterised) reference type, or a primitive type, into an array type. For example, Car[] is type of an array of Cars, int[] is the type of an array of ints. Car[] and int[] are both different types from Car and int.

Don't forget that you can add another [] to an array type to make it a 2D array, such as Car[][], which is also an array type.

ContentLicense: CC BY-SA 4.0


问:
How to line break a label object in ChartsJS (nested arrays won't work)
As answered here I'm using nested arrays to line break my labels on ChartsJS and it works fine but if I try to use nested arrays on my label (the object inside dataset) they won't line break.

For example in this graph:

I have 2 labels with new lines but if I try the same technique with my label (the legend above the graph) it won't line break.

Here is the code for this graph:

```<code>data: {  labels: [ 'Utensilios para escrita e artes','Faz de conta','Jogos',['Materiais não estruturado','/de largo alcançe/recicláveis'],['Repertório artístico-cultural e','científico de diferentes','origens étnico-raciais'],'Livros de história','Materiais para pesquisa',],

            datasets: [
                    { maxBarThickness: 70,label: 'Não há material presente',
                    backgroundColor: '#eb7071',

                    borderWidth: 1,
                    data: [ 2,41,24,51,78,33,62,]
                    },
                    { maxBarThickness: 70,label: ['Material presente,',' mas crianças não usaram'],
                    backgroundColor: '#f9ae60',

                    borderWidth: 1,
                    data: [ 24,38,48,39,15,48,30,]
                    },
                    { maxBarThickness: 70,label: 'Crianças usaram os materiais',
                    backgroundColor: '#73e599',

                    borderWidth: 1,
                    data: [ 73,21,28,10,7,20,7,]
                    },

                ]
            },
</code>```

I assumed the legend would not line break because in the code it was not a nested array so I changed my label to this:

```<code>label: [['Material presente,',' mas crianças não usaram']]
</code>```

But it still did not work.

Is there any way to line break these legends without having to generate them as a HTML script to manipulate them?

答:
There's no option that can be defined to easily achieve what you're looking for. An open feature request exists for such an option since 2016.

You'll have to generate custom HTML legend using legendCallback.

Inspired by this answer, I came up with the following code that illustrates how this can be done in your case. It shouldn't be too hard to further improve the styling of the legend labels and adapted them to your needs.

const chart = new Chart(document.getElementById("chart"), {
  type: "bar",
  data: {
    labels: [
      ['Utensilios para', 'escrita e artes'],
      ['Materiais não estruturado', 'de largo alcançe/recicláveis'],
      ['Repertório artístico-cultural e', 'científico de diferentes', 'origens étnico-raciais']
    ],
    datasets: [{
        label: "Não há material presente",
        data: [5, 8, 4],
        fill: false,
        backgroundColor: "rgba(255, 99, 132, 0.2)",
        borderColor: "rgb(255, 99, 132)",
        borderWidth: 1
      },
      {
        label: ["Material presente", "mas crianças não usaram"],
        data: [3, 5, 4],
        fill: false,
        backgroundColor: "rgba(255, 159, 64, 0.2)",
        borderColor: "rgb(255, 159, 64)",
        borderWidth: 1
      },
      {
        label: "Crianças usaram os materiais",
        data: [6, 5, 7],
        fill: false,
        backgroundColor: "rgba(255, 205, 86, 0.2)",
        borderColor: "rgb(255, 205, 86)",
        borderWidth: 1
      }
    ]
  },
  options: {
    legend: {
      display: false
    },
    tooltips: {
      callbacks: {
        title: (tooltipItems, data) => data.labels[tooltipItems[0].index],
        label: (tooltipItems, data) =>
          data.datasets[tooltipItems.datasetIndex].label + ': ' + tooltipItems.value + '%'
      }
    },
    legendCallback: chart => {
      let html = '
';
      chart.data.datasets.forEach((ds, i) => {
        html += '
';
        html += Array.isArray(ds.label) ? ds.label.join('
') : ds.label;
        html += '
';
      });
      return html + '
';
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

$("#legend").html(chart.generateLegend());

// Show/hide chart by click legend
updateDataset = (e, dsIndex) => {
  let hide = !chart.data.datasets[dsIndex].hidden;
  chart.data.datasets[dsIndex].hidden = hide;
  if (hide) {
    $('#' + e.path[0].id).css("text-decoration", "line-through");
  } else {
    $('#' + e.path[0].id).css("text-decoration", "");
  }
  chart.update();
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#legend>ul {
  padding: 0;
  text-align: center;
}

#legend li {
  cursor: pointer;
  margin: 10px 10px;
  display: inline-table;
}

#legend li span {
  position: relative;
  padding: 3px 5px;
  z-index: 2;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
}</code>```

  <canvas id="chart"></canvas>

```

UPDATE

Meanwhile I answered a similar question and invested some time to properly define the styling of the legend labels. Please have a look at this anwser.

Body:
As answered here I'm using nested arrays to line break my labels on ChartsJS and it works fine but if I try to use nested arrays on my label (the object inside dataset) they won't line break.

For example in this graph:

I have 2 labels with new lines but if I try the same technique with my label (the legend above the graph) it won't line break.

Here is the code for this graph:

data: {  labels: [ 'Utensilios para escrita e artes','Faz de conta','Jogos',['Materiais não estruturado','/de largo alcançe/recicláveis'],['Repertório artístico-cultural e','científico de diferentes','origens étnico-raciais'],'Livros de história','Materiais para pesquisa',],

            datasets: [
                    { maxBarThickness: 70,label: 'Não há material presente',
                    backgroundColor: '#eb7071',

                    borderWidth: 1,
                    data: [ 2,41,24,51,78,33,62,]
                    },
                    { maxBarThickness: 70,label: ['Material presente,',' mas crianças não usaram'],
                    backgroundColor: '#f9ae60',

                    borderWidth: 1,
                    data: [ 24,38,48,39,15,48,30,]
                    },
                    { maxBarThickness: 70,label: 'Crianças usaram os materiais',
                    backgroundColor: '#73e599',

                    borderWidth: 1,
                    data: [ 73,21,28,10,7,20,7,]
                    },

                ]
            },

I assumed the legend would not line break because in the code it was not a nested array so I changed my label to this:

label: [['Material presente,',' mas crianças não usaram']]

But it still did not work.

Is there any way to line break these legends without having to generate them as a HTML script to manipulate them?

Body:
There's no option that can be defined to easily achieve what you're looking for. An open feature request exists for such an option since 2016.

You'll have to generate custom HTML legend using legendCallback.

Inspired by this answer, I came up with the following code that illustrates how this can be done in your case. It shouldn't be too hard to further improve the styling of the legend labels and adapted them to your needs.

const chart = new Chart(document.getElementById("chart"), {
  type: "bar",
  data: {
    labels: [
      ['Utensilios para', 'escrita e artes'],
      ['Materiais não estruturado', 'de largo alcançe/recicláveis'],
      ['Repertório artístico-cultural e', 'científico de diferentes', 'origens étnico-raciais']
    ],
    datasets: [{
        label: "Não há material presente",
        data: [5, 8, 4],
        fill: false,
        backgroundColor: "rgba(255, 99, 132, 0.2)",
        borderColor: "rgb(255, 99, 132)",
        borderWidth: 1
      },
      {
        label: ["Material presente", "mas crianças não usaram"],
        data: [3, 5, 4],
        fill: false,
        backgroundColor: "rgba(255, 159, 64, 0.2)",
        borderColor: "rgb(255, 159, 64)",
        borderWidth: 1
      },
      {
        label: "Crianças usaram os materiais",
        data: [6, 5, 7],
        fill: false,
        backgroundColor: "rgba(255, 205, 86, 0.2)",
        borderColor: "rgb(255, 205, 86)",
        borderWidth: 1
      }
    ]
  },
  options: {
    legend: {
      display: false
    },
    tooltips: {
      callbacks: {
        title: (tooltipItems, data) => data.labels[tooltipItems[0].index],
        label: (tooltipItems, data) =>
          data.datasets[tooltipItems.datasetIndex].label + ': ' + tooltipItems.value + '%'
      }
    },
    legendCallback: chart => {
      let html = '<ul class="' + chart.id + '-legend">';
      chart.data.datasets.forEach((ds, i) => {
        html += '<li><span id="legend-' + i + '-item" style="background-color:' + ds.backgroundColor + '" onclick="updateDataset(event, \'' + i + '\')">';
        html += Array.isArray(ds.label) ? ds.label.join('<br />') : ds.label;
        html += '</span></li>';
      });
      return html + '</ul>';
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

$("#legend").html(chart.generateLegend());

// Show/hide chart by click legend
updateDataset = (e, dsIndex) => {
  let hide = !chart.data.datasets[dsIndex].hidden;
  chart.data.datasets[dsIndex].hidden = hide;
  if (hide) {
    $('#' + e.path[0].id).css("text-decoration", "line-through");
  } else {
    $('#' + e.path[0].id).css("text-decoration", "");
  }
  chart.update();
};

#legend>ul {
  padding: 0;
  text-align: center;
}

#legend li {
  cursor: pointer;
  margin: 10px 10px;
  display: inline-table;
}

#legend li span {
  position: relative;
  padding: 3px 5px;
  z-index: 2;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<div>
  <div id="legend"></div>
  <canvas id="chart"></canvas>
</div>

UPDATE

Meanwhile I answered a similar question and invested some time to properly define the styling of the legend labels. Please have a look at this anwser.


问:
How to return headers of columns that match a criteria for every row in a pandas dataframe?
I have a pandas dataframe df of the form :

```<code>     Col1      Col2      Col3      Col4

0    True      False     True      False
1    False     False     False     False
2    False     True      False     False
3    True      True      True      True
</code>```

Here True and False are boolean values.

I am trying to generate a new pandas dataframe new_df which should look like:

```<code>     Matched_Cols

0    [Col1, Col3]
1    []
2    [Col2]
3    [Col1, Col2, Col3, Col4]
</code>```

What is the most efficient way to achieve this?

答:
Unnecessarily long:</p>

```<code>df['Matched_Col'] = [np.compress(x,y) for x,y in zip(df.to_numpy(),np.tile(df.columns,(len(df),1)))]

Col1    Col2    Col3    Col4    Matched_Col
0   True    False   True    False   [Col1, Col3]
1   False   False   False   False   []
2   False   True    False   False   [Col2]
3   True    True    True    True    [Col1, Col2, Col3, Col4]
</code>```

Body:
I have a pandas dataframe df of the form :

     Col1      Col2      Col3      Col4

0    True      False     True      False
1    False     False     False     False
2    False     True      False     False
3    True      True      True      True

Here True and False are boolean values.

I am trying to generate a new pandas dataframe new_df which should look like:

     Matched_Cols

0    [Col1, Col3]
1    []
2    [Col2]
3    [Col1, Col2, Col3, Col4]

What is the most efficient way to achieve this?

Body:
Unnecessarily long:

df['Matched_Col'] = [np.compress(x,y) for x,y in zip(df.to_numpy(),np.tile(df.columns,(len(df),1)))]

Col1    Col2    Col3    Col4    Matched_Col
0   True    False   True    False   [Col1, Col3]
1   False   False   False   False   []
2   False   True    False   False   [Col2]
3   True    True    True    True    [Col1, Col2, Col3, Col4]


问:
Sorted a javascript array of objects by an object property
Hay, i have an array of objects and i need to sort them (either DESC or ASC) by a certain property of each object.

Here's the data

```<code>obj1 = new Object;
obj1.date = 1307010000;

obj2 = new Object;
obj2.date = 1306923600;

obj3 = new Object;
obj3.date = 1298974800;

obj4 = new Object;
obj4.date = 1306923600;

obj5 = new Object;
obj5.date = 1307096400;

data = [obj1,obj2,obj3,obj4,obj5];
</code>```

Now, i want to order the data array so that the objects are in order by date.

Can someone help me with this?

答:
Use the Array sort() method</p>

```<code>data.sort(function(a, b){
    return a.date - b.date;
});
</code>```

Body:
Hay, i have an array of objects and i need to sort them (either DESC or ASC) by a certain property of each object.

Here's the data

obj1 = new Object;
obj1.date = 1307010000;

obj2 = new Object;
obj2.date = 1306923600;

obj3 = new Object;
obj3.date = 1298974800;

obj4 = new Object;
obj4.date = 1306923600;

obj5 = new Object;
obj5.date = 1307096400;

data = [obj1,obj2,obj3,obj4,obj5];

Now, i want to order the data array so that the objects are in order by date.

Can someone help me with this?

Body:
Use the Array sort() method

data.sort(function(a, b){
    return a.date - b.date;
});


问:
Export more than one variable in ES6?
I'm trying to export more than one variable in ES6:

exports.js

```<code>var TestObject = Parse.Object.extend('TestObject')
var Post = Parse.Object.extend('Post')

export default TestObject
export Post
</code>```

main.js:

```<code>import TestObject from '../store'
import Post from '../store'

var testObject = new TestObject() // use Post in the same way
testObject.save(json).then(object => {
  console.log('yay! it worked', object)
})
</code>```

I understand that there's only one default value so I only used default in the first item.

However, I get this error message:

```<code>Module build failed: SyntaxError: /home/alex/node/my-project/src/store/index.js: Unexpected token (9:7)
   7 |
   8 | export default TestObject
>  9 | export Post
</code>```

Maybe I'm doing it the wrong way?

答:
In order to export multiple variables we have to take everything we want to export from a file  inside { } like this -

```<code>export { <var 1>, <var 2> , <var 3>, ... , <var n>};
</code>```

for default export we can separately write this-

```<code>export default <var name>;  // there can be only one default export;
</code>```

In you code you can make the following changes -

exports.js

```<code>export { Post };
</code>```

main.js

```<code>import { Post } from '<exports file>';
</code>```

example

Title: Export more than one variable in ES6?

Body:
I'm trying to export more than one variable in ES6:

exports.js

var TestObject = Parse.Object.extend('TestObject')
var Post = Parse.Object.extend('Post')

export default TestObject
export Post

main.js:

import TestObject from '../store'
import Post from '../store'

var testObject = new TestObject() // use Post in the same way
testObject.save(json).then(object => {
  console.log('yay! it worked', object)
})

I understand that there's only one default value so I only used default in the first item.

However, I get this error message:

Module build failed: SyntaxError: /home/alex/node/my-project/src/store/index.js: Unexpected token (9:7)
   7 |
   8 | export default TestObject
>  9 | export Post

Maybe I'm doing it the wrong way?

Body:
In order to export multiple variables we have to take everything we want to export from a file  inside { } like this -

export { <var 1>, <var 2> , <var 3>, ... , <var n>};

for default export we can separately write this-

export default <var name>;  // there can be only one default export;

In you code you can make the following changes -

exports.js

export { Post };

main.js

import { Post } from '<exports file>';

example


问:
Add text to specific line without removing the exist line in php
I'm trying to add only last name if first name is same

data.txt

```<code>Alice Sandy
Alice Nanami
James Watt
Alice Monica
Johann Gauss
</code>```

to result.txt

```<code>Alice Sandy Nanami Monica
James Watt
Johann Gauss
</code>```

I try with this code

$resultFile = "result.txt";
$search     = "Alice";
$lineNumber = false;
if ($handle = fopen($result, "r")) {
    $count = 0;
    while (($line = fgets($handle, 4096)) !== FALSE and !$lineNumber) {
        $count++;
        $lineNumber = (strpos($line, $search) !== FALSE) ? $count : $lineNumber;
        $isExist = (strpos($line, $search) !== FALSE) ? "yup" : "no";
    }
fclose($handle);
}
if($isExist=="yup"){
    $lines = file($resultFile);
    $lines[$lineNumber] = $lines[$lineNumber].' '.$lastName;
    file_put_contents($result, implode('', $lines));
}else{
    $fullName = $firstName.' '.$lastName;
    $fileOpen = fopen($result, "a");
    fwrite($fileOpen,$fullName);
    fclose($fileOpen);
    $addBreaker = "\n";
    $splResult = new SplFileObject($resultFile, 'a');
    $splResult->fwrite($addBreaker);
}
```

<p>But it give error offset (I'm using PHP 7) and the result is untidy</p>

```Alice Sandy Nanami
 Monica
James Watt

Johan Gauss
```

Thanks for help

答:
Use file() to collect the file contents as an array of lines. My snippet starts from there with $lines.

Iterate the array and makes each line modifiable by reference. (&)

Locate the first occurring needle match that not only exists in the line but matches the whole first word so that you don't get false-positive matching.

Then declare the first match as a reference variable (=&) and continue iterating the array.  Any subsequent matches will have the delimiting space and second word appended to the reference variable.  Then immediate unset the line to be purged from the document.

When done, re-implode the data and stuff the content into the result file.

This is clean, readable, and only needs one loop.

Code: (Demo)

```<code>// $lines = file('result.txt', FILE_IGNORE_NEW_LINES);
$lines = [
    'Alice Sandy',
    'Alice Nanami',
    'James Watt',
    'Alice Monica',
    'Johann Gauss',
    'Cooper Alice',
];

$needle = 'Alice';
foreach($lines as $index => &$line) {
    if ($needle === strstr($line, ' ', true)) { // check whole first word
        if (!isset($firstOccurrence)) {
            $firstOccurrence =& $line;
        } else {
            $firstOccurrence .= strstr($line, ' ');
            unset($lines[$index]);
        }
    }
}
var_export($lines);
// file_put_contents('result.txt', implode(PHP_EOL, $lines));
</code>```

Output:

```<code>array (
  0 => 'Alice Sandy Nanami Monica',
  2 => 'James Watt',
  4 => 'Johann Gauss',
  5 => 'Cooper Alice',
)
</code>```

P.s  if you want to know if any rows were changed you could check if the original array is === the new array after looping, or you could just use a boolean flag variable in the else condition.

Body:
I'm trying to add only last name if first name is same

data.txt

Alice Sandy
Alice Nanami
James Watt
Alice Monica
Johann Gauss

to result.txt

Alice Sandy Nanami Monica
James Watt
Johann Gauss

I try with this code

$resultFile = "result.txt";
$search     = "Alice";
$lineNumber = false;
if ($handle = fopen($result, "r")) {
    $count = 0;
    while (($line = fgets($handle, 4096)) !== FALSE and !$lineNumber) {
        $count++;
        $lineNumber = (strpos($line, $search) !== FALSE) ? $count : $lineNumber;
        $isExist = (strpos($line, $search) !== FALSE) ? "yup" : "no";
    }
fclose($handle);
}
if($isExist=="yup"){
    $lines = file($resultFile);
    $lines[$lineNumber] = $lines[$lineNumber].' '.$lastName;
    file_put_contents($result, implode('', $lines));
}else{
    $fullName = $firstName.' '.$lastName;
    $fileOpen = fopen($result, "a");
    fwrite($fileOpen,$fullName);
    fclose($fileOpen);
    $addBreaker = "\n";
    $splResult = new SplFileObject($resultFile, 'a');
    $splResult->fwrite($addBreaker);
}

But it give error offset (I'm using PHP 7) and the result is untidy

Alice Sandy Nanami
 Monica
James Watt

Johan Gauss

Thanks for help

Body:
Use file() to collect the file contents as an array of lines. My snippet starts from there with $lines.

Iterate the array and makes each line modifiable by reference. (&)

Locate the first occurring needle match that not only exists in the line but matches the whole first word so that you don't get false-positive matching.

Then declare the first match as a reference variable (=&) and continue iterating the array.  Any subsequent matches will have the delimiting space and second word appended to the reference variable.  Then immediate unset the line to be purged from the document.

When done, re-implode the data and stuff the content into the result file.

This is clean, readable, and only needs one loop.

Code: (Demo)

// $lines = file('result.txt', FILE_IGNORE_NEW_LINES);
$lines = [
    'Alice Sandy',
    'Alice Nanami',
    'James Watt',
    'Alice Monica',
    'Johann Gauss',
    'Cooper Alice',
];

$needle = 'Alice';
foreach($lines as $index => &$line) {
    if ($needle === strstr($line, ' ', true)) { // check whole first word
        if (!isset($firstOccurrence)) {
            $firstOccurrence =& $line;
        } else {
            $firstOccurrence .= strstr($line, ' ');
            unset($lines[$index]);
        }
    }
}
var_export($lines);
// file_put_contents('result.txt', implode(PHP_EOL, $lines));

Output:

array (
  0 => 'Alice Sandy Nanami Monica',
  2 => 'James Watt',
  4 => 'Johann Gauss',
  5 => 'Cooper Alice',
)

P.s  if you want to know if any rows were changed you could check if the original array is === the new array after looping, or you could just use a boolean flag variable in the else condition.


问:
React How to show individual data into popup
I am learning react I want to show movie data when clicking on particular div. currently, I called fancy box which is not right method to get the result

So I need help to show movie data once click on particular div.

```<code>class App extends React.Component {
  constructor() {
    super();
    this.state = {
      data: [],
      search: '',
    };
  }

  updateSearch(event) {
    this.setState({search: event.target.value.substr(0, 20)});
  }

  componentDidMount() {
    fetch('http://www.omdbapi.com/?apikey=MyKey&s=fast&plot=full')
      .then((Response) => Response.json())
      .then((findresponse) => {
        console.log(findresponse);
        this.setState({
          data: findresponse.Search,
        });
      });
  }
  render() {
    let filteredMovie = this.state.data.filter((dynamicData) => {
      return dynamicData.Title.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1;
    });
    return (
      <div className="container movies_list">
        <div className="row">
          <div className="col-md-12  p-4">
            <form>
              <input
                type="text"
                className="form-control"
                placeholder="Search"
                value={this.state.search}
                onChange={this.updateSearch.bind(this)}
              />
            </form>
          </div>

          {filteredMovie &&
            filteredMovie.map((dynamicData, key) => (
              <div className="col-md-3 mb-3" key={key}>
                <div className="card">
                  <img src={dynamicData.Poster} className="card-img-top" alt="..." />
                  <div className="card-body">
                    <h6 className="card-title">{dynamicData.Title} </h6>
                    <h6 className="card-title">Year: {dynamicData.Year} </h6>
                    <p className="card-text">{dynamicData.Plot} </p>
                    <a
                      data-fancybox
                      data-src="#hidden-content"
                      href="javascript:;"
                      className="btn btn-info"
                    >
                      View
                    </a>
                    <div id="hidden-content">
                      <img src={dynamicData.Poster} className="card-img-top" alt="..." />
                      <h2>{dynamicData.Title}</h2>
                      <p>{dynamicData.Year}</p>
                    </div>
                  </div>
                </div>
              </div>
            ))}
        </div>
      </div>
    );
  }
}
</code>```

答: I highly recommend Reakit for modal & popovers.</p>

Body:
I am learning react I want to show movie data when clicking on particular div. currently, I called fancy box which is not right method to get the result

So I need help to show movie data once click on particular div.

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      data: [],
      search: '',
    };
  }

  updateSearch(event) {
    this.setState({search: event.target.value.substr(0, 20)});
  }

  componentDidMount() {
    fetch('http://www.omdbapi.com/?apikey=MyKey&s=fast&plot=full')
      .then((Response) => Response.json())
      .then((findresponse) => {
        console.log(findresponse);
        this.setState({
          data: findresponse.Search,
        });
      });
  }
  render() {
    let filteredMovie = this.state.data.filter((dynamicData) => {
      return dynamicData.Title.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1;
    });
    return (

            <form>
              <input
                type="text"
                className="form-control"
                placeholder="Search"
                value={this.state.search}
                onChange={this.updateSearch.bind(this)}
              />
            </form>

          {filteredMovie &&
            filteredMovie.map((dynamicData, key) => (

{dynamicData.Title}

Year: {dynamicData.Year}

{dynamicData.Plot}

                      View

{dynamicData.Title}

{dynamicData.Year}

            ))}

    );
  }
}


问:
how to run node.js app from cmd with some predefined port in Windows
Is it some command exist to run my node.js code with directly specified port?
something like node server.js port=7777 ?

my server.js code looks like this

```<code>http.createServer(function (req, res) {
  if (mount(req, res)) return;
}).listen(process.env.PORT || 80);
</code>```

答:
On ubuntu I just do

```<code>PORT=7777 node .
</code>```

in commandline, no set or export needed.

Body:
Is it some command exist to run my node.js code with directly specified port?
something like node server.js port=7777 ?

my server.js code looks like this

http.createServer(function (req, res) {
  if (mount(req, res)) return;
}).listen(process.env.PORT || 80);

Body:
On ubuntu I just do

PORT=7777 node .

in commandline, no set or export needed.


问:
How to open maps App programmatically with coordinates in swift?
I have latitude and longitude that I want to open into my map application. I tried this code from HERE.

```<code>    func goToMap(){

    var lat1 : NSString = self.venueLat
    var lng1 : NSString = self.venueLng

    var latitude:CLLocationDegrees =  lat1.doubleValue
    var longitude:CLLocationDegrees =  lng1.doubleValue

    var coordinate = CLLocationCoordinate2DMake(latitude, longitude)

    var placemark : MKPlacemark = MKPlacemark(coordinate: coordinate, addressDictionary:nil)

    var mapItem:MKMapItem = MKMapItem(placemark: placemark)

    mapItem.name = "Target location"

    let launchOptions:NSDictionary = NSDictionary(object: MKLaunchOptionsDirectionsModeDriving, forKey: MKLaunchOptionsDirectionsModeKey)

    var currentLocationMapItem:MKMapItem = MKMapItem.mapItemForCurrentLocation()

    MKMapItem.openMapsWithItems([currentLocationMapItem, mapItem], launchOptions: launchOptions)

}
</code>```

This function successfully open maps but it doesn't show any pin. Also it shows user location which I don't want. I only want a pin on the map for the provided latitude and longitude.

答:
Update to the practical Daniel Saidi answer. This example is for telling only the destination coordinates. Maps will get as origin the user current position.  </p>

```<code>let url = URL(string: "http://maps.apple.com/maps?saddr=&daddr=\(lat),\(lon)")
UIApplication.shared.open(url!)

</code>```

Body:
I have latitude and longitude that I want to open into my map application. I tried this code from HERE.

    func goToMap(){

    var lat1 : NSString = self.venueLat
    var lng1 : NSString = self.venueLng

    var latitude:CLLocationDegrees =  lat1.doubleValue
    var longitude:CLLocationDegrees =  lng1.doubleValue

    var coordinate = CLLocationCoordinate2DMake(latitude, longitude)

    var placemark : MKPlacemark = MKPlacemark(coordinate: coordinate, addressDictionary:nil)

    var mapItem:MKMapItem = MKMapItem(placemark: placemark)

    mapItem.name = "Target location"

    let launchOptions:NSDictionary = NSDictionary(object: MKLaunchOptionsDirectionsModeDriving, forKey: MKLaunchOptionsDirectionsModeKey)

    var currentLocationMapItem:MKMapItem = MKMapItem.mapItemForCurrentLocation()

    MKMapItem.openMapsWithItems([currentLocationMapItem, mapItem], launchOptions: launchOptions)

}

This function successfully open maps but it doesn't show any pin. Also it shows user location which I don't want. I only want a pin on the map for the provided latitude and longitude.

Body:
Update to the practical Daniel Saidi answer. This example is for telling only the destination coordinates. Maps will get as origin the user current position.

let url = URL(string: "http://maps.apple.com/maps?saddr=&daddr=\(lat),\(lon)")
UIApplication.shared.open(url!)


问:
Nginx -- if referer, add (x-forwarded-for) ip to blacklist
I have written a basic http referer redirector that looks something like this:

```<code>if ($http_referer ~* (google|yahoo|bing|duckduckgo)) {  return 301 https://altavista.com; }
</code>```

My goal is something like this

```<code>if ($http_referer ~* (google|yahoo|bing|duckduckgo)) {
    add $x-forwarded-for bad_ips.txt; <-- this line is the question (x-forwarded-for because it's behind cloudflare)
    return 301 https://altavista.com;
}
if ($bad_ip) {
    return 301 https://altavista.com;
}
</code>```

Is there any way to do this?  The goal is essentially if you are referred from a website on the blacklist, I would like to add your ip to the redirect list.

Note: This does not need to be done purely in nginx; using other technologies in addition to nginx is fine so long as they are free.

Please note my site is utilizing cloudflare so rather than banning a simple IP it has to be using the x-forwarded-for address or I'm just banning cloudflare.

Thanks

答:
Until I remember there is no direct method to do this.

A paid option can be using Nginx Plus according to this blog.

Other than that there are 2 options that I can see now are:

Use OpenResty with LUA module. What you have to do is

on every request write IP to a file

on every request read from the file and if IP exists then 301 redirect.

If you do not want to use OpenResty then you can also build Nginx with LUA module.

[I am concerned about efficiency at this point. This method may add performance overhead as the file has to be parsed on every request.]

Use Fail2Ban with Nginx.

I wanted to add this in the comment but I don't have enough reputation to comment.

Body:
I have written a basic http referer redirector that looks something like this:

if ($http_referer ~* (google|yahoo|bing|duckduckgo)) {  return 301 https://altavista.com; }

My goal is something like this

if ($http_referer ~* (google|yahoo|bing|duckduckgo)) {
    add $x-forwarded-for bad_ips.txt; <-- this line is the question (x-forwarded-for because it's behind cloudflare)
    return 301 https://altavista.com;
}
if ($bad_ip) {
    return 301 https://altavista.com;
}

Is there any way to do this?  The goal is essentially if you are referred from a website on the blacklist, I would like to add your ip to the redirect list.

Note: This does not need to be done purely in nginx; using other technologies in addition to nginx is fine so long as they are free.

Please note my site is utilizing cloudflare so rather than banning a simple IP it has to be using the x-forwarded-for address or I'm just banning cloudflare.

Thanks


问:
How can I upload an inline picture from a chat message as a new bitmap file?
I'm trying to upload the content bytes of an inline picture from a Teams chat message as a new bitmap file. I'm getting the content bytes of the inline picture with this method GET https://graph.microsoft.com/beta/teams/{teamId}/channels/{channelId}/messages/{messageId}/hostedContents/{hostedContentId}/$value.

The response gives me content bytes which I try sending directly as the request body in this call PUT https://graph.microsoft.com/beta/drives/{channelDriveId}/items/{currentPhaseInBilderFolderId}:/picture_123.jpg:/content. To this request I have included "image/jpeg" as Content-Type in the header. The file gets created alright, but it's not created as an image. When trying to view the picture from the newly created file I'm prompted with this error: "This is not a valid bitmap file, or its format is not currently supported".

How can I grab an inline picture in a chat message and create a bitmap file out of it using Microsoft graph?

答:
The code is created with UiPath Studio (RPA tool). The request to get the content bytes looks like this:

The result of this GET is replace in the "getContentBytesResponse" variable as a string value. This is then used in the PUT method as such:

The reponse code from this call is 201 which indicates that the file was successfully created. And from the folder I see the file created, but not as an image. This picture is too large to be uploaded here. The limit is 2 MB and the file 2.4 MB.

I need to understand what is the proper approach to upload content bytes to be created as an image. Or does this upload method support text files solely?

EDITED:
Here is the response from the PUT method

```<code>{
    "@odata.context": "https://graph.microsoft.com/beta/$metadata#drives('{id}')/items/$entity",
    "@microsoft.graph.downloadUrl": "
    "createdDateTime": "2020-06-04T06:50:31Z",
    "eTag": "\"{AC1ABBB1-CE9A-4A02-93BE-6B27395A8FB7},1\"",
    "id": "01PJW2BXNRXMNKZGWOAJFJHPTLE44VVD5X",
    "lastModifiedDateTime": "2020-06-04T06:50:31Z",
    "name": "picture_04-06-2020-08-06-30-50.png",
    "webUrl": "https://{tenant}.sharepoint.com/sites/{sitepath}/picture_04-06-2020-08-06-30-50.png",
    "cTag": "\"c:{AC1ABBB1-CE9A-4A02-93BE-6B27395A8FB7},1\"",
    "size": 942463,
    "createdBy": {
        "application": {
            "id": "{id}",
            "displayName": "Dank Bot"
        },
        "user": {
            "email": "dankbot-cb7313ce1c@{tenant}.onmicrosoft.com",
            "id": "{id}",
            "displayName": "Dank Bot"
        }
    },
    "lastModifiedBy": {
        "application": {
            "id": "{id]",
            "displayName": "Dank Bot"
        },
        "user": {
            "email": "dankbot-cb7313ce1c@{tenant}.onmicrosoft.com",
            "id": "{id}",
            "displayName": "Dank Bot"
        }
    },
    "parentReference": {
        "driveId": "{id}",
        "driveType": "documentLibrary",
        "id": "{id}",
        "path": "/drives/{drivepath}"
    },
    "file": {
        "mimeType": "image/png",
        "hashes": {
            "quickXorHash": "zeZrJjSTjzjHtAn3QgXa5vgaxxA="
        }
    },
    "fileSystemInfo": {
        "createdDateTime": "2020-06-04T06:50:31Z",
        "lastModifiedDateTime": "2020-06-04T06:50:31Z"
    },
    "image": {}
}
</code>```

What is the correct way to upload image files?

Body:
The code is created with UiPath Studio (RPA tool). The request to get the content bytes looks like this:

The result of this GET is replace in the "getContentBytesResponse" variable as a string value. This is then used in the PUT method as such:

The reponse code from this call is 201 which indicates that the file was successfully created. And from the folder I see the file created, but not as an image. This picture is too large to be uploaded here. The limit is 2 MB and the file 2.4 MB.

I need to understand what is the proper approach to upload content bytes to be created as an image. Or does this upload method support text files solely?

EDITED:
Here is the response from the PUT method

{
    "@odata.context": "https://graph.microsoft.com/beta/$metadata#drives('{id}')/items/$entity",
    "@microsoft.graph.downloadUrl": "
    "createdDateTime": "2020-06-04T06:50:31Z",
    "eTag": "\"{AC1ABBB1-CE9A-4A02-93BE-6B27395A8FB7},1\"",
    "id": "01PJW2BXNRXMNKZGWOAJFJHPTLE44VVD5X",
    "lastModifiedDateTime": "2020-06-04T06:50:31Z",
    "name": "picture_04-06-2020-08-06-30-50.png",
    "webUrl": "https://{tenant}.sharepoint.com/sites/{sitepath}/picture_04-06-2020-08-06-30-50.png",
    "cTag": "\"c:{AC1ABBB1-CE9A-4A02-93BE-6B27395A8FB7},1\"",
    "size": 942463,
    "createdBy": {
        "application": {
            "id": "{id}",
            "displayName": "Dank Bot"
        },
        "user": {
            "email": "dankbot-cb7313ce1c@{tenant}.onmicrosoft.com",
            "id": "{id}",
            "displayName": "Dank Bot"
        }
    },
    "lastModifiedBy": {
        "application": {
            "id": "{id]",
            "displayName": "Dank Bot"
        },
        "user": {
            "email": "dankbot-cb7313ce1c@{tenant}.onmicrosoft.com",
            "id": "{id}",
            "displayName": "Dank Bot"
        }
    },
    "parentReference": {
        "driveId": "{id}",
        "driveType": "documentLibrary",
        "id": "{id}",
        "path": "/drives/{drivepath}"
    },
    "file": {
        "mimeType": "image/png",
        "hashes": {
            "quickXorHash": "zeZrJjSTjzjHtAn3QgXa5vgaxxA="
        }
    },
    "fileSystemInfo": {
        "createdDateTime": "2020-06-04T06:50:31Z",
        "lastModifiedDateTime": "2020-06-04T06:50:31Z"
    },
    "image": {}
}

What is the correct way to upload image files?


问:
Custom buttons in silverlight
How can I create buttons like this in silverlight. Do I need expression blend for this.

Since I need to use the modified buttons at many places in my application, should I do it as a user control?

答:
You don't need a UserControl for this, just a custom Button template as a style resource, which then you can reuse by setting the style on any Button instance.

While it's doable without Blend, I highly recommend you at least get the trial, it's a really really nice IDE for design / visual development!

Edit: As a little present here's a starting point :)

```<code><Style x:Key="ButtonStyle1" TargetType="Button">
    <Setter Property="Foreground" Value="#FFFFFFFF"/>
    <Setter Property="Padding" Value="3"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="BorderBrush" Value="#FF000000"/>
    <Setter Property="Template">
         <Setter.Value>
              <ControlTemplate TargetType="Button">
                    <Grid>
                          <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                      <VisualState x:Name="Normal"/>
                                      <VisualState x:Name="MouseOver"/>
                                      <VisualState x:Name="Pressed"/>
                                      <VisualState x:Name="Disabled">
                                           <Storyboard>
                                                <DoubleAnimation Duration="0" To="0.4" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="DisabledVisualElement"/>
                                           </Storyboard>
                                      </VisualState>
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="FocusStates">
                                        <VisualState x:Name="Focused">
                                                <Storyboard>
                                                    <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="FocusVisualElement"/>
                                                </Storyboard>
                                        </VisualState>
                                        <VisualState x:Name="Unfocused"/>
                                </VisualStateGroup>
                          </VisualStateManager.VisualStateGroups>
                          <Border x:Name="Background" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
                                  <Border.Background>
                                      <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                          <GradientStop Color="#FF707070" Offset="0"/>
                                          <GradientStop Color="#FF666666" Offset="0.49"/>
                                          <GradientStop Color="#FF5e5e5e" Offset="0.51"/>
                                          <GradientStop Color="#FF535353" Offset="1"/>
                                      </LinearGradientBrush>
                                  </Border.Background>
                          </Border>
                          <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
                                <ContentPresenter.Effect>
                                      <DropShadowEffect BlurRadius="3" ShadowDepth="2" Opacity="0.5"/>
                                </ContentPresenter.Effect>
                          </ContentPresenter>
                          <Rectangle x:Name="DisabledVisualElement" Fill="#FFFFFFFF" IsHitTestVisible="false" Opacity="0"/>
                          <Rectangle x:Name="FocusVisualElement" IsHitTestVisible="false" Margin="1" Opacity="0" Stroke="#FF6DBDD1" StrokeThickness="1"/>
                    </Grid>
              </ControlTemplate>
         </Setter.Value>
    </Setter>
</Style>
</code>```

Title: Custom buttons in silverlight

Body:
You don't need a UserControl for this, just a custom Button template as a style resource, which then you can reuse by setting the style on any Button instance.

While it's doable without Blend, I highly recommend you at least get the trial, it's a really really nice IDE for design / visual development!

Edit: As a little present here's a starting point :)

<Style x:Key="ButtonStyle1" TargetType="Button">
    <Setter Property="Foreground" Value="#FFFFFFFF"/>
    <Setter Property="Padding" Value="3"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="BorderBrush" Value="#FF000000"/>
    <Setter Property="Template">
         <Setter.Value>
              <ControlTemplate TargetType="Button">
                    <Grid>
                          <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup x:Name="CommonStates">
                                      <VisualState x:Name="Normal"/>
                                      <VisualState x:Name="MouseOver"/>
                                      <VisualState x:Name="Pressed"/>
                                      <VisualState x:Name="Disabled">
                                           <Storyboard>
                                                <DoubleAnimation Duration="0" To="0.4" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="DisabledVisualElement"/>
                                           </Storyboard>
                                      </VisualState>
                                </VisualStateGroup>
                                <VisualStateGroup x:Name="FocusStates">
                                        <VisualState x:Name="Focused">
                                                <Storyboard>
                                                    <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="FocusVisualElement"/>
                                                </Storyboard>
                                        </VisualState>
                                        <VisualState x:Name="Unfocused"/>
                                </VisualStateGroup>
                          </VisualStateManager.VisualStateGroups>
                          <Border x:Name="Background" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
                                  <Border.Background>
                                      <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                                          <GradientStop Color="#FF707070" Offset="0"/>
                                          <GradientStop Color="#FF666666" Offset="0.49"/>
                                          <GradientStop Color="#FF5e5e5e" Offset="0.51"/>
                                          <GradientStop Color="#FF535353" Offset="1"/>
                                      </LinearGradientBrush>
                                  </Border.Background>
                          </Border>
                          <ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
                                <ContentPresenter.Effect>
                                      <DropShadowEffect BlurRadius="3" ShadowDepth="2" Opacity="0.5"/>
                                </ContentPresenter.Effect>
                          </ContentPresenter>
                          <Rectangle x:Name="DisabledVisualElement" Fill="#FFFFFFFF" IsHitTestVisible="false" Opacity="0"/>
                          <Rectangle x:Name="FocusVisualElement" IsHitTestVisible="false" Margin="1" Opacity="0" Stroke="#FF6DBDD1" StrokeThickness="1"/>
                    </Grid>
              </ControlTemplate>
         </Setter.Value>
    </Setter>
</Style>


问:
ViewBag.Message not showing ASP.NET MVC c#
I have a view named Index.cshtml and controller named HomeController and I can't seem to show the ViewBag.Message and ViewBag.FileUrl to the view. The code is working I just can't show the ViewBag.message when the file is successfully uploaded.

Here's my code below

Index.cshtml

```<code>@{
ViewBag.Title = "Upload a file to S3 Bucket";
}

<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Message</h3>
<h3>@ViewBag.FileUrl</h3>

<p>Use this area to browse image and upload to S3 bucket.</p>
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
    @Html.TextBox("file", "", new { type = "file" }) <br />
    <input type="submit" value="Upload" />
    @ViewBag.FileUrl
    @ViewBag.Message
</div>
}
</code>```

HomeController.cs

```<code>[HttpGet]
public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    var s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion);
    var result = "";
    var keyName = file.FileName;
    var fileTransferUtility = new TransferUtility(s3Client);

    try
    {
        if (file.ContentLength > 0)
        {
            var filePath = Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileName(file.FileName));
            var fileTransferUtilityRequest = new TransferUtilityUploadRequest
            {
                BucketName = bucketName,
                FilePath = filePath,
                StorageClass = S3StorageClass.StandardInfrequentAccess,
                PartSize = 6291456, // 6 MB.
                Key = keyName,
                CannedACL = S3CannedACL.PublicRead
            };

            fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
            fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
            fileTransferUtility.Upload(fileTransferUtilityRequest);
            fileTransferUtility.Dispose();
        }
        result = string.Format("http://{0}.s3.amazonaws.com/{1}", bucketName, keyName);

        ViewBag.FileUrl = result;
        ViewBag.Message = "File Uploaded Successfully!!";
    }
    catch (AmazonS3Exception amazonS3Exception)
    {
        ViewBag.Message = "Error occurred: " + amazonS3Exception.Message;
    }

    return RedirectToAction("Index");
}
</code>```

答:
You assign ViewBag values, which are lost by the subsequent RedirectToAction().

Found the answer here, with detailed comparison of ViewData, ViewBag, and TempData. In your case, TempData should work.

Body:
I have a view named Index.cshtml and controller named HomeController and I can't seem to show the ViewBag.Message and ViewBag.FileUrl to the view. The code is working I just can't show the ViewBag.message when the file is successfully uploaded.

Here's my code below

Index.cshtml

@{
ViewBag.Title = "Upload a file to S3 Bucket";
}

@ViewBag.Title.

@ViewBag.Message

@ViewBag.FileUrl

Use this area to browse image and upload to S3 bucket.

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    @Html.TextBox("file", "", new { type = "file" })

    <input type="submit" value="Upload" />
    @ViewBag.FileUrl
    @ViewBag.Message

}

HomeController.cs

[HttpGet]
public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    var s3Client = new AmazonS3Client(accesskey, secretkey, bucketRegion);
    var result = "";
    var keyName = file.FileName;
    var fileTransferUtility = new TransferUtility(s3Client);

    try
    {
        if (file.ContentLength > 0)
        {
            var filePath = Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileName(file.FileName));
            var fileTransferUtilityRequest = new TransferUtilityUploadRequest
            {
                BucketName = bucketName,
                FilePath = filePath,
                StorageClass = S3StorageClass.StandardInfrequentAccess,
                PartSize = 6291456, // 6 MB.
                Key = keyName,
                CannedACL = S3CannedACL.PublicRead
            };

            fileTransferUtilityRequest.Metadata.Add("param1", "Value1");
            fileTransferUtilityRequest.Metadata.Add("param2", "Value2");
            fileTransferUtility.Upload(fileTransferUtilityRequest);
            fileTransferUtility.Dispose();
        }
        result = string.Format("http://{0}.s3.amazonaws.com/{1}", bucketName, keyName);

        ViewBag.FileUrl = result;
        ViewBag.Message = "File Uploaded Successfully!!";
    }
    catch (AmazonS3Exception amazonS3Exception)
    {
        ViewBag.Message = "Error occurred: " + amazonS3Exception.Message;
    }

    return RedirectToAction("Index");
}


问:
gRPC service endpoint is not accessible via Kong Gateway
gRPC services (developed in springboot) deployed as docker container on AWS linux (ec2). Started the docker image with port forwarding -p6565:6565.
Now when directly hit via BloomRPC on laptop, it worked : ec2.IP:6565 Package.Service.Method

Configured service & route in Kong:

```<code>{
            "host": "ec2.IP",
            "created_at": 1588403433,
            "connect_timeout": 60000,
            "id": "e657d8df-6247-458a-a8e8-bec00c41e03c",
            "protocol": "grpc",
            "name": "aws-grpc1",
            "read_timeout": 60000,
            "port": 6565,
            "path": null,
            "updated_at": 1588403433,
            "retries": 5,
            "write_timeout": 60000,
            "tags": null,
            "client_certificate": null
}

Route:
{
            "strip_path": false,
            "path_handling": "v0",
            "updated_at": 1588403452,
            "destinations": null,
            "headers": null,
            "protocols": [
                "grpc",
                "grpcs"
            ],
            "created_at": 1588403452,
            "snis": null,
            "service": {
                "id": "e657d8df-6247-458a-a8e8-bec00c41e03c"
            },
            "name": "aws-grpc1-route1",
            "methods": null,
            "preserve_host": false,
            "regex_priority": 0,
            "paths": [
                "/grpc2"
            ],
            "sources": null,
            "id": "5739297e-3be7-4a0d-8afb-cfa8ed01cec2",
            "https_redirect_status_code": 426,
            "hosts": null,
            "tags": null
        }
</code>```

Now hitting it via grpcurl -> its not working:

```<code>grpcurl -v -d "{}" -insecure ec2.ip:8443 package.service.pingMethod

Error invoking method "package.service.ping": target server does not expose service "package.service"
</code>```

Here is kong config which looks related:

```<code>"proxy_listen": [
            "0.0.0.0:8000 reuseport backlog=16384",
            "0.0.0.0:8443 **http2** ssl reuseport backlog=16384"
        ],
</code>```

So here are queries:
(1) can 8000 also be configured for https as insecure -> via passing a env KONG_PROXY_LISTEN variable at time of kong-container start by

```<code>    -e "KONG_PROXY_LISTEN=0.0.0.0:8000 http2, 0.0.0.0:8443 http2 ssl"
</code>```

Is this good to do?

(2) How to enable server side reflection? OR what is use of /grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo ?

答:
You need to expose HTTP2 Proxy Listener for Kong.
You can refer to this one: https://konghq.com/blog/manage-grpc-services-kong/

In short, you need to add env variable details for KONG_PROXY_LISTEN like so:

```<code>-e "KONG_PROXY_LISTEN=0.0.0.0:8000 http2, 0.0.0.0:8443 http2 ssl, 0.0.0.0:9080 http2, 0.0.0.0:9081 http2 ssl"
</code>```

Note: apparently Kong uses the ports 9080 for HTTP2 and 9081 for HTTP2 SSL. But I think this can be changed.

And also expose those 9080 and 9081 ports like so, this is example for docker run command:

```<code>-p 127.0.0.1:9080:9080 \
-p 127.0.0.1:9081:9081
</code>```

And use the 9080 port in grpcurl when you try to request, like so:

```<code>grpcurl -v -d '{"name": "Ken"}' -plaintext localhost:9080 facade.GreetingService/SayHello
</code>```

Body:
gRPC services (developed in springboot) deployed as docker container on AWS linux (ec2). Started the docker image with port forwarding -p6565:6565.
Now when directly hit via BloomRPC on laptop, it worked : ec2.IP:6565 Package.Service.Method

Configured service & route in Kong:

{
            "host": "ec2.IP",
            "created_at": 1588403433,
            "connect_timeout": 60000,
            "id": "e657d8df-6247-458a-a8e8-bec00c41e03c",
            "protocol": "grpc",
            "name": "aws-grpc1",
            "read_timeout": 60000,
            "port": 6565,
            "path": null,
            "updated_at": 1588403433,
            "retries": 5,
            "write_timeout": 60000,
            "tags": null,
            "client_certificate": null
}

Route:
{
            "strip_path": false,
            "path_handling": "v0",
            "updated_at": 1588403452,
            "destinations": null,
            "headers": null,
            "protocols": [
                "grpc",
                "grpcs"
            ],
            "created_at": 1588403452,
            "snis": null,
            "service": {
                "id": "e657d8df-6247-458a-a8e8-bec00c41e03c"
            },
            "name": "aws-grpc1-route1",
            "methods": null,
            "preserve_host": false,
            "regex_priority": 0,
            "paths": [
                "/grpc2"
            ],
            "sources": null,
            "id": "5739297e-3be7-4a0d-8afb-cfa8ed01cec2",
            "https_redirect_status_code": 426,
            "hosts": null,
            "tags": null
        }

Now hitting it via grpcurl -> its not working:

grpcurl -v -d "{}" -insecure ec2.ip:8443 package.service.pingMethod

Error invoking method "package.service.ping": target server does not expose service "package.service"

Here is kong config which looks related:

"proxy_listen": [
            "0.0.0.0:8000 reuseport backlog=16384",
            "0.0.0.0:8443 **http2** ssl reuseport backlog=16384"
        ],

So here are queries:
(1) can 8000 also be configured for https as insecure -> via passing a env KONG_PROXY_LISTEN variable at time of kong-container start by

    -e "KONG_PROXY_LISTEN=0.0.0.0:8000 http2, 0.0.0.0:8443 http2 ssl"

Is this good to do?

(2) How to enable server side reflection? OR what is use of /grpc.reflection.v1alpha.ServerReflection/ServerReflectionInfo ?

Body:
You need to expose HTTP2 Proxy Listener for Kong.
You can refer to this one: https://konghq.com/blog/manage-grpc-services-kong/

In short, you need to add env variable details for KONG_PROXY_LISTEN like so:

-e "KONG_PROXY_LISTEN=0.0.0.0:8000 http2, 0.0.0.0:8443 http2 ssl, 0.0.0.0:9080 http2, 0.0.0.0:9081 http2 ssl"

Note: apparently Kong uses the ports 9080 for HTTP2 and 9081 for HTTP2 SSL. But I think this can be changed.

And also expose those 9080 and 9081 ports like so, this is example for docker run command:

-p 127.0.0.1:9080:9080 \
-p 127.0.0.1:9081:9081

And use the 9080 port in grpcurl when you try to request, like so:

grpcurl -v -d '{"name": "Ken"}' -plaintext localhost:9080 facade.GreetingService/SayHello


问:
Why navbar components doesn't update after user logs in? (no Redux)
I want the Navbar to change state but I couldn't figure out how to pass state from Login to Navbar without using Redux. It only updates the state of the Navbar after I manually refresh the page. This is not good. It would be great if once I click on the Login button, then the Navbar also updates its state. How can I pass the state over?

App component:

```<code>const App = () => {
    return (
        <BrowserRouter>
            <div className="App">
                <Navbar />
                <Switch>
                    <Login exact path="/login" component={Login} />
                    <Signup exact path="/signup" component={Signup} />
                </Switch>
            </div>
        </BrowserRouter>
    );
};
</code>```

Navbar component:

```<code>class Navbar extends React.Component {
    constructor() {
        super();
        this.state = {
            modalOpen: false,
            isAuthenticated: false,
            name: '',
        };
}

componentDidMount() {
        if (localStorage.getItem('token')) {
            this.setState({ isAuthenticated: true });
        }
    }

render() {
        return (
            <div className="navbar">
                <div className="navbar-flex">
                    {this.state.isAuthenticated && <p>Hello {this.state.name}</p>}
                    <Button onClick={this.toggleModal}>Menu</Button>
                </div>
                {this.state.modalOpen && (
                    <div className="modal" ref={this.setWrapperRef}>
                        {!this.state.isAuthenticated ? (
                            <div>
                                <Link to="/">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Home</Button>
                                </Link>
                                <Link to="/login">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Login</Button>
                                </Link>
                                <Link to="/signup">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Signup</Button>
                                </Link>
                            </div>
                        ) : (
                            <div>
                                <Link to="/">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Home</Button>
                                </Link>
                                <Link to="/">
                                    <Button onClick={this.logout}>Logout</Button>
                                </Link>
                            </div>
                        )}
                    </div>
                )}
            </div>
        );
    }
</code>```

Login component submit method:

```<code>onSubmit = (e) => {
        e.preventDefault();

        this.setState({ loading: true });

        axios
            .post('/api/login', {
                email: this.state.email,
                password: this.state.password,
            })
            .then((res) => {
                if (res.data.token) {
                    localStorage.setItem('token', res.data.token);
                    this.setState({ loading: false });
                    this.props.history.push('/');
                } else if (res.data.status === 'fail') {
                    this.setState({ loading: false });
                }
            });
    };
</code>```

答:
Here is how i control my navbars to reflect on the current state (Authenticated or not).

you can create a method that checks the local storage for the token and returns false or true as a result, or you can perform anything you want to do to ensure authentication and return the value based on that.

```<code>const isAuthenticated = (token) => {
     localStorage.getItem(token) ? true:false;
}
</code>```

and then you can import it and on componentDidMount() you can call the method and store the result and do whatever you want to do with it.

Body:
I want the Navbar to change state but I couldn't figure out how to pass state from Login to Navbar without using Redux. It only updates the state of the Navbar after I manually refresh the page. This is not good. It would be great if once I click on the Login button, then the Navbar also updates its state. How can I pass the state over?

App component:

const App = () => {
    return (
        <BrowserRouter>

                <Navbar />
                <Switch>
                    <Login exact path="/login" component={Login} />
                    <Signup exact path="/signup" component={Signup} />
                </Switch>

        </BrowserRouter>
    );
};

Navbar component:

class Navbar extends React.Component {
    constructor() {
        super();
        this.state = {
            modalOpen: false,
            isAuthenticated: false,
            name: '',
        };
}

componentDidMount() {
        if (localStorage.getItem('token')) {
            this.setState({ isAuthenticated: true });
        }
    }

render() {
        return (

                    {this.state.isAuthenticated &&
Hello {this.state.name}
}
                    <Button onClick={this.toggleModal}>Menu</Button>

                {this.state.modalOpen && (

                        {!this.state.isAuthenticated ? (

                                <Link to="/">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Home</Button>
                                </Link>
                                <Link to="/login">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Login</Button>
                                </Link>
                                <Link to="/signup">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Signup</Button>
                                </Link>

                        ) : (

                                <Link to="/">
                                    <Button onClick={() => this.setState({ modalOpen: false })}>Home</Button>
                                </Link>
                                <Link to="/">
                                    <Button onClick={this.logout}>Logout</Button>
                                </Link>

                        )}

                )}

        );
    }

Login component submit method:

onSubmit = (e) => {
        e.preventDefault();

        this.setState({ loading: true });

        axios
            .post('/api/login', {
                email: this.state.email,
                password: this.state.password,
            })
            .then((res) => {
                if (res.data.token) {
                    localStorage.setItem('token', res.data.token);
                    this.setState({ loading: false });
                    this.props.history.push('/');
                } else if (res.data.status === 'fail') {
                    this.setState({ loading: false });
                }
            });
    };

Body:
Here is how i control my navbars to reflect on the current state (Authenticated or not).

you can create a method that checks the local storage for the token and returns false or true as a result, or you can perform anything you want to do to ensure authentication and return the value based on that.

const isAuthenticated = (token) => {
     localStorage.getItem(token) ? true:false;
}

and then you can import it and on componentDidMount() you can call the method and store the result and do whatever you want to do with it.


问:
How to add onload listener without XUL in Thunderbird Addon?
My goal is to access the current Text in the editor when composing a message with Thunderbird.

Before Thunderbird 68 my extension could access the text by

chrome.manifest:

overlay chrome://editor/content/editorOverlay.xul chrome://ext/content/extEditor.xul

extEditor.xul:

```<code><overlay id="x" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
     <script type="application/javascript" charset="UTF-8" src="chrome://ext/content/extEditor.js"/>
</overlay>
</code>```

extEditor.js:

```<code>document.getElementById("content-frame").addEventListener("keypress",
                                    function(e) {
                                        // do stuff;
                                    },
                                    false);
</code>```

As of now mozilla wants to get rid of XUL. I'm rewriting the extension to fit it into the new MailExtension system.

Does anyone know how to add an onload listener to the msgcomposeWindow like this without XUL? I guess I need a statement like this

```<code>document.getElementById("msgcomposeWindow").addEventListener("onload", function (e) {
    ///
});
</code>```

in the main messenger window but it gives me null return because obviously on starting thunderbird there is no msgcomposeWindow yet.

答:
xul: make an observer for windows. Test their windowtype. If it is the right one for the composewindow, add your listener. You can see the windowtype in debugger/inspector for the compose window.

For new webextensions, new access to compose has been added since: https://thunderbird-webextensions.readthedocs.io/en/latest/compose.html#onbeforesend-tab-details

see also the composeaction

Body:
My goal is to access the current Text in the editor when composing a message with Thunderbird.

Before Thunderbird 68 my extension could access the text by

chrome.manifest:

overlay chrome://editor/content/editorOverlay.xul chrome://ext/content/extEditor.xul

extEditor.xul:

<overlay id="x" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">


问:
How do you design a gradient for a layer in iOS?
I have to follow through my designer's gradient layer as shown below and I'm running into a wall trying to replicate her design (below).

I have the following code to try to replicate the same shadow but it is too solid compared to her gradient. How do I reduce my layer to have a gradient look and feel?

```<code>backgroundView.layer.shadowColor = UIColor.Custom.darkBlue.cgColor
backgroundView.layer.shadowOpacity = 1.0
backgroundView.layer.shadowRadius = 10
</code>```

EDIT:
I implemented what I needed using @Frankenstein's solution below.

```<code>backgroundView.backgroundColor = UIColor.Custom.darkBlue
let gradient: CAGradientLayer = CAGradientLayer()
gradient.colors = [UIColor.black.cgColor, UIColor.Custom.darkBlue.cgColor]
gradient.frame = CGRect(x: backgroundView.frame.origin.x, y: backgroundView.frame.origin.y - 39, width: view.bounds.width, height: 40)
view.layer.addSublayer(gradient)
</code>```

With the expected result below. Thank you!

答:
Here is how you can achieve that

```<code>  let gradient: CAGradientLayer = CAGradientLayer()

        gradient.colors = [UIColor.black.cgColor, UIColor.blue.cgColor]
        gradient.locations = [0.0 , 1.0]
        gradient.startPoint = CGPoint(x : 0.0, y : 0)
        gradient.endPoint = CGPoint(x :0.0, y: 0.15) // you need to play with 0.15 to adjust gradient vertically
        gradient.frame = view.bounds
        view.layer.addSublayer(gradient)
</code>```

With 0.15 to 0.5 you get

Body:
I have to follow through my designer's gradient layer as shown below and I'm running into a wall trying to replicate her design (below).

I have the following code to try to replicate the same shadow but it is too solid compared to her gradient. How do I reduce my layer to have a gradient look and feel?

backgroundView.layer.shadowColor = UIColor.Custom.darkBlue.cgColor
backgroundView.layer.shadowOpacity = 1.0
backgroundView.layer.shadowRadius = 10

EDIT:
I implemented what I needed using @Frankenstein's solution below.

backgroundView.backgroundColor = UIColor.Custom.darkBlue
let gradient: CAGradientLayer = CAGradientLayer()
gradient.colors = [UIColor.black.cgColor, UIColor.Custom.darkBlue.cgColor]
gradient.frame = CGRect(x: backgroundView.frame.origin.x, y: backgroundView.frame.origin.y - 39, width: view.bounds.width, height: 40)
view.layer.addSublayer(gradient)

With the expected result below. Thank you!

Body:
Here is how you can achieve that

  let gradient: CAGradientLayer = CAGradientLayer()

        gradient.colors = [UIColor.black.cgColor, UIColor.blue.cgColor]
        gradient.locations = [0.0 , 1.0]
        gradient.startPoint = CGPoint(x : 0.0, y : 0)
        gradient.endPoint = CGPoint(x :0.0, y: 0.15) // you need to play with 0.15 to adjust gradient vertically
        gradient.frame = view.bounds
        view.layer.addSublayer(gradient)

With 0.15 to 0.5 you get


问:
Java stream reduce to map
I got array list of strings, how could I reduce them to hash map

Input: [a, b, a, a, c, x]

Output: {(a: 3), (b: 1), (c: 1), (x: 1)}

PS. I searched for this. I need to do that with reduce not with frequency counting as in other questions, because my question is a simplified real task.

答:
Thanks @HadiJ for answer</p>

```<code>Map<String,Integer> result = Arrays.stream(str)
    .reduce(new HashMap<>(), (hashMap, e) -> {
        hashMap.merge(e, 1, Integer::sum);
        return hashMap;
    },
    (m, m2) -> {
        m.putAll(m2);
        return m;
    }
);
</code>```

Title: Java stream reduce to map

Body:
Thanks @HadiJ for answer

Map<String,Integer> result = Arrays.stream(str)
    .reduce(new HashMap<>(), (hashMap, e) -> {
        hashMap.merge(e, 1, Integer::sum);
        return hashMap;
    },
    (m, m2) -> {
        m.putAll(m2);
        return m;
    }
);


问:
Twilio Programmable Video not visible in ionic 4
I'm trying to implement a video call using Twilio video, Here the connect but gives Twilio access token.

I was got access token but the local room(local camera preview video not visible) and I was trying to connect remote video. the remote video also connected but it's not showing on the mobile screen.

HTML

```<code><ion-content  #scrollArea fullscreen>

<div id="video-container">

  <div id="local" #localVideo>
    <p>local video</p>
  </div>

  <div id="remote" #remoteVideo>
    <p>remote video</p>
  </div>
  <input type="text" [(ngModel)]="username" placeholder="username">

  <input type="text" [(ngModel)]="roomName" placeholder="room name">

  <input type="button" [disabled]="!username || !roomName ? true : false" value="connect" (click)="connect()">

  <input type="button" [disabled]="!twilioService.roomObj ? true : false" value="disconnect" (click)="disconnect()">

</div>

</ion-content>
</code>```

ts

```<code>import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { TwiliovideoService } from '../_service/twiliovideo.service';
import { ServiceProxy, ServiceRegistry } from '../_helpers/ServiceProxy';
import { IonContent } from '@ionic/angular';
import { async } from '@angular/core/testing';

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

  message1: string;
  accessToken: string;
  roomName: string;
  username: string;
  @ViewChild('scrollArea') content: IonContent;
  @ViewChild('localVideo') localVideo: ElementRef;
  @ViewChild('remoteVideo') remoteVideo: ElementRef;

  video_token: any;

  constructor(public twilioService: TwiliovideoService,public serviceProxy: ServiceProxy,) {

    this.twilioService.msgSubject.subscribe(r => {
      this.message1 = r;
    });

   }

  ngOnInit() {

    this.twilioService.localVideo = this.localVideo;
    this.twilioService.remoteVideo = this.remoteVideo;
    // this.connect();
  }

  //Video call

  log(message) {
    this.message1 = message;
  }

  disconnect() {
    if (this.twilioService.roomObj && this.twilioService.roomObj !== null) {
      this.twilioService.roomObj.disconnect();
      this.twilioService.roomObj = null;
    }
  }

  async connect() {
    let date = Date.now();
    let video_start = {
      userName: this.username,
      roomName: this.roomName
    }
    console.log(this.roomName)
    await this.serviceProxy.SingleRequest(ServiceRegistry.VIDEOCALL_SESSION,video_start).subscribe(async arg=>{
      this.video_token = arg.result
    });
    console.log(this.video_token)
    // localStorage.setItem('video_token', JSON.stringify({
    //   video_token: this.video_token,
    //   created_at: date
    // }));

    // let storage = JSON.parse(localStorage.getItem('video_token') || '{}');
    // if (!this.roomName || !this.username) { this.message1 = "enter username and room name."; return; }
    // if (storage['video_token'] && storage['created_at'] + 3600000 > date) {
      if(this.video_token){
      this.accessToken = this.video_token
      await this.twilioService.connectToRoom(this.accessToken, { name: this.roomName, audio: true, video: { width: 240 } })

      // return;

    }

    // if (this.video_token!= null)
    //   this.twilioService.connectToRoom(this.accessToken, { name: this.roomName, audio: true, video: { width: 240 } })
  }

  //

}
</code>```

Service.ts

```<code>import { Injectable, ElementRef } from '@angular/core';
import { connect, createLocalTracks, createLocalVideoTrack } from 'twilio-video';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class TwiliovideoService {
  msgSubject = new BehaviorSubject("");
  remoteVideo: ElementRef;
  localVideo: ElementRef;

  previewing: boolean;
  roomObj: any;

  constructor() { }

  connectToRoom(accessToken: string, options): void {

    connect(accessToken, options).then(room => {
      console.log(`Successfully joined a Room: ${room}`);
      if (!this.previewing && options['video']) {
        this.startLocalVideo();
        this.previewing = true;
      }

      // Attach the Participant's Media to a <div> element.
      room.on('participantConnected', participant => {
        console.log(`Participant "${participant.identity}" connected`);

        participant.tracks.forEach(publication => {
          if (publication.isSubscribed) {
            const track = publication.track;
            this.remoteVideo.nativeElement.appendChild(track.attach());
          }
        });

        participant.on('trackSubscribed', track => {
          this.remoteVideo.nativeElement.appendChild(track.attach());
        });
      });

      // Log your Client's LocalParticipant in the Room
      const localParticipant = room.localParticipant;
      console.log(`Connected to the Room as LocalParticipant "${localParticipant.identity}"`);

      // Log any Participants already connected to the Room
      room.participants.forEach(participant => {
        console.log(`Participant "${participant.identity}" is connected to the Room`);
        participant.on('trackSubscribed', track => {
          this.remoteVideo.nativeElement.appendChild(track.attach());
        });

      });

      // Log new Participants as they connect to the Room
      room.once('participantConnected', participant => {
        console.log(`Participant "${participant.identity}" has connected to the Room`);
      });

      // Log Participants as they disconnect from the Room
      room.once('participantDisconnected', participant => {
        console.log(`Participant "${participant.identity}" has disconnected from the Room`);
      });

    }, error => {
      console.error(`Unable to connect to Room: ${error.message}`);
    });

  }

  startLocalVideo(): void {
    createLocalVideoTrack().then(track => {
      this.localVideo.nativeElement.appendChild(track.attach());
    });
  }
}
</code>```

答:
you need to give audio and camera permissions inside config.xml and AndroidManifest.xml

install android permissions  (folllow ionic docs)

add these permissions in config.xml and AndroidManifest.xml

```<code>    <custom-config-file parent="/*" target="AndroidManifest.xml">
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-feature android:name="android.hardware.camera2.full" />
    <uses-feature android:name="android.hardware.camera2.autofocus" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.webkit.PermissionRequest" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
</custom-config-file>
</code>```

Body:
I'm trying to implement a video call using Twilio video, Here the connect but gives Twilio access token.

I was got access token but the local room(local camera preview video not visible) and I was trying to connect remote video. the remote video also connected but it's not showing on the mobile screen.

HTML

<ion-content  #scrollArea fullscreen>

local video

remote video

  <input type="text" [(ngModel)]="username" placeholder="username">

  <input type="text" [(ngModel)]="roomName" placeholder="room name">

  <input type="button" [disabled]="!username || !roomName ? true : false" value="connect" (click)="connect()">

  <input type="button" [disabled]="!twilioService.roomObj ? true : false" value="disconnect" (click)="disconnect()">

</ion-content>

ts

import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { TwiliovideoService } from '../_service/twiliovideo.service';
import { ServiceProxy, ServiceRegistry } from '../_helpers/ServiceProxy';
import { IonContent } from '@ionic/angular';
import { async } from '@angular/core/testing';

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

  message1: string;
  accessToken: string;
  roomName: string;
  username: string;
  @ViewChild('scrollArea') content: IonContent;
  @ViewChild('localVideo') localVideo: ElementRef;
  @ViewChild('remoteVideo') remoteVideo: ElementRef;

  video_token: any;

  constructor(public twilioService: TwiliovideoService,public serviceProxy: ServiceProxy,) {

    this.twilioService.msgSubject.subscribe(r => {
      this.message1 = r;
    });

   }

  ngOnInit() {

    this.twilioService.localVideo = this.localVideo;
    this.twilioService.remoteVideo = this.remoteVideo;
    // this.connect();
  }

  //Video call

  log(message) {
    this.message1 = message;
  }

  disconnect() {
    if (this.twilioService.roomObj && this.twilioService.roomObj !== null) {
      this.twilioService.roomObj.disconnect();
      this.twilioService.roomObj = null;
    }
  }

  async connect() {
    let date = Date.now();
    let video_start = {
      userName: this.username,
      roomName: this.roomName
    }
    console.log(this.roomName)
    await this.serviceProxy.SingleRequest(ServiceRegistry.VIDEOCALL_SESSION,video_start).subscribe(async arg=>{
      this.video_token = arg.result
    });
    console.log(this.video_token)
    // localStorage.setItem('video_token', JSON.stringify({
    //   video_token: this.video_token,
    //   created_at: date
    // }));

    // let storage = JSON.parse(localStorage.getItem('video_token') || '{}');
    // if (!this.roomName || !this.username) { this.message1 = "enter username and room name."; return; }
    // if (storage['video_token'] && storage['created_at'] + 3600000 > date) {
      if(this.video_token){
      this.accessToken = this.video_token
      await this.twilioService.connectToRoom(this.accessToken, { name: this.roomName, audio: true, video: { width: 240 } })

      // return;

    }

    // if (this.video_token!= null)
    //   this.twilioService.connectToRoom(this.accessToken, { name: this.roomName, audio: true, video: { width: 240 } })
  }

  //

}

Service.ts

import { Injectable, ElementRef } from '@angular/core';
import { connect, createLocalTracks, createLocalVideoTrack } from 'twilio-video';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class TwiliovideoService {
  msgSubject = new BehaviorSubject("");
  remoteVideo: ElementRef;
  localVideo: ElementRef;

  previewing: boolean;
  roomObj: any;

  constructor() { }

  connectToRoom(accessToken: string, options): void {

    connect(accessToken, options).then(room => {
      console.log(`Successfully joined a Room: ${room}`);
      if (!this.previewing && options['video']) {
        this.startLocalVideo();
        this.previewing = true;
      }

      // Attach the Participant's Media to a
 element.
      room.on('participantConnected', participant => {
        console.log(`Participant "${participant.identity}" connected`);

        participant.tracks.forEach(publication => {
          if (publication.isSubscribed) {
            const track = publication.track;
            this.remoteVideo.nativeElement.appendChild(track.attach());
          }
        });

        participant.on('trackSubscribed', track => {
          this.remoteVideo.nativeElement.appendChild(track.attach());
        });
      });

      // Log your Client's LocalParticipant in the Room
      const localParticipant = room.localParticipant;
      console.log(`Connected to the Room as LocalParticipant "${localParticipant.identity}"`);

      // Log any Participants already connected to the Room
      room.participants.forEach(participant => {
        console.log(`Participant "${participant.identity}" is connected to the Room`);
        participant.on('trackSubscribed', track => {
          this.remoteVideo.nativeElement.appendChild(track.attach());
        });

      });

      // Log new Participants as they connect to the Room
      room.once('participantConnected', participant => {
        console.log(`Participant "${participant.identity}" has connected to the Room`);
      });

      // Log Participants as they disconnect from the Room
      room.once('participantDisconnected', participant => {
        console.log(`Participant "${participant.identity}" has disconnected from the Room`);
      });

    }, error => {
      console.error(`Unable to connect to Room: ${error.message}`);
    });

  }

  startLocalVideo(): void {
    createLocalVideoTrack().then(track => {
      this.localVideo.nativeElement.appendChild(track.attach());
    });
  }
}

Body:
you need to give audio and camera permissions inside config.xml and AndroidManifest.xml

install android permissions  (folllow ionic docs)

add these permissions in config.xml and AndroidManifest.xml

    <custom-config-file parent="/*" target="AndroidManifest.xml">
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-feature android:name="android.hardware.camera2.full" />
    <uses-feature android:name="android.hardware.camera2.autofocus" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.webkit.PermissionRequest" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
</custom-config-file>


问:
How I get y_true and y_pred values for loss function?
How do I get the y_true and y_pred values for this loss function I wrote :

```<code>def kullback_leibler_divergence(y_true, y_pred):
    y_true = K.clip(y_true, K.epsilon(), 1)
    y_pred = K.clip(y_pred, K.epsilon(), 1)
    return K.sum(y_true * K.log(y_true / y_pred), axis=-1)
</code>```

答:
As I understood your question this might be useful.you can use from tensorflow.keras import backend as K to calculate anything using y_true, y_pred as the following example
when you compile, you should add the functions  **to the loss **. then it will provide y_true, y_pred values.

loss:String (name of objective function), objective function or tf.keras.losses.Loss instance. See tf.keras.losses. An objective function is any callable with the signature loss = fn(y_true, y_pred)

```<code># compile the model
model.compile(optimizer='adam', loss=kullback_leibler_divergence, metrics=['accuracy'])
</code>```

Body:
How do I get the y_true and y_pred values for this loss function I wrote :

def kullback_leibler_divergence(y_true, y_pred):
    y_true = K.clip(y_true, K.epsilon(), 1)
    y_pred = K.clip(y_pred, K.epsilon(), 1)
    return K.sum(y_true * K.log(y_true / y_pred), axis=-1)

Body:
As I understood your question this might be useful.you can use from tensorflow.keras import backend as K to calculate anything using y_true, y_pred as the following example
when you compile, you should add the functions  **to the loss **. then it will provide y_true, y_pred values.

loss:String (name of objective function), objective function or tf.keras.losses.Loss instance. See tf.keras.losses. An objective function is any callable with the signature loss = fn(y_true, y_pred)

# compile the model
model.compile(optimizer='adam', loss=kullback_leibler_divergence, metrics=['accuracy'])