问:
How to obtain a random sample from a categorical distribution using Matlab's rand()?
I want to generate samples according to a simple categorical probability distribution, e.g.

```<code>p(A) = 0.1
p(B) = 0.5
p(C) = 0.25
p(D) = 0.15
</code>```

Using rand(), which uniformly generates samples in (0,1] what is the best way to achieve this?

答:
You could just check if the random number is less than the probability of each category, in order of increasing probability:

```<code>value = rand()
if value < p(A)
    return A
if value < p(A)+p(B)
    return B
if value < p(A)+p(B)+P(C)
    return C
else
    return D
</code>```

I can't really tell you the best way to get them in order without knowing more about your code. If you have only a small number of cases that won't be changing, it might be easiest just to hard-code it once by hand as I've done above.

Edit: now that I think about it, since we're accumulating the probabilities, it doesn't really matter what order they're in. I've adjusted my code accordingly.

Edit edit: I think this is essentially how randsample works.

Body:
I want to generate samples according to a simple categorical probability distribution, e.g.

p(A) = 0.1
p(B) = 0.5
p(C) = 0.25
p(D) = 0.15

Using rand(), which uniformly generates samples in (0,1] what is the best way to achieve this?

Body:
You could just check if the random number is less than the probability of each category, in order of increasing probability:

value = rand()
if value < p(A)
    return A
if value < p(A)+p(B)
    return B
if value < p(A)+p(B)+P(C)
    return C
else
    return D

I can't really tell you the best way to get them in order without knowing more about your code. If you have only a small number of cases that won't be changing, it might be easiest just to hard-code it once by hand as I've done above.

Edit: now that I think about it, since we're accumulating the probabilities, it doesn't really matter what order they're in. I've adjusted my code accordingly.

Edit edit: I think this is essentially how randsample works.


来源: stackexchange

问:
Set headers on sandbox with srcdoc?
I'm trying to set some CSP policies on my sandboxed iframe with allow scripts. Naturally meta tags wouldn't do the trick if the iframe itself has scripts enabled and can just remove the meta tags right? Is there a way to create the iframe with srcdoc and still set the CSP or do I have to load it from a server?</p>

答:
The csp attribute does apply to srcdoc iframes. Being a local scheme, no response headers are needed. Just writing  will enforce that CSP on the iframe and I guess do more or less what you would like. This is specified here.

Keep in mind that the csp attribute is currently only implemented in chromium. Also notice that the behaviour for srcdoc was just fixed in M90. Prior to that, I believe chromium was incorrectly discarding the csp attribute for srcdoc iframes.

ContentLicense: CC BY-SA 4.0

Title: Set headers on sandbox with srcdoc?

Body:
The csp attribute does apply to srcdoc iframes. Being a local scheme, no response headers are needed. Just writing <iframe csp="defaul-src 'none'" srcdoc="something"> will enforce that CSP on the iframe and I guess do more or less what you would like. This is specified here.

Keep in mind that the csp attribute is currently only implemented in chromium. Also notice that the behaviour for srcdoc was just fixed in M90. Prior to that, I believe chromium was incorrectly discarding the csp attribute for srcdoc iframes.


问:
Data Format is returning nil for this format "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
Well, I have this specific raw string returning from backend which is a date string "2020-05-27T23:59:59.000+02:00"

I am trying to format the string using the following code:-

```<code> let passExpiresAtString =  "2020-05-27T23:59:59.000+02:00"
 let df = DateFormatter()
 df.locale = Locale(identifier: "en_US_POSIX")
 df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
 session.passExpiresAt = df.date(from: passExpiresAtString)
</code>```

So, I will be glad if anyone can pin me, what I am doing wrong with the date format settings.

Thanks for your help.

答:
Alternatively set the calendar of the formatter to an ISO8601 calendar

```<code>let passExpiresAtString =  "2020-05-27T23:59:59.000+02:00"
let df = DateFormatter()
df.calendar = Calendar(identifier: .iso8601)
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
session.passExpiresAt = df.date(from: passExpiresAtString)
</code>```

or – still more reliable – use ISO8601DateFormatter

```<code>let passExpiresAtString =  "2020-05-27T23:59:59.000+02:00"
let df = ISO8601DateFormatter()
df.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
session.passExpiresAt = df.date(from: passExpiresAtString)
</code>```

Body:
Well, I have this specific raw string returning from backend which is a date string "2020-05-27T23:59:59.000+02:00"

I am trying to format the string using the following code:-

 let passExpiresAtString =  "2020-05-27T23:59:59.000+02:00"
 let df = DateFormatter()
 df.locale = Locale(identifier: "en_US_POSIX")
 df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
 session.passExpiresAt = df.date(from: passExpiresAtString)

So, I will be glad if anyone can pin me, what I am doing wrong with the date format settings.

Thanks for your help.

Body:
Alternatively set the calendar of the formatter to an ISO8601 calendar

let passExpiresAtString =  "2020-05-27T23:59:59.000+02:00"
let df = DateFormatter()
df.calendar = Calendar(identifier: .iso8601)
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
session.passExpiresAt = df.date(from: passExpiresAtString)

or – still more reliable – use ISO8601DateFormatter

let passExpiresAtString =  "2020-05-27T23:59:59.000+02:00"
let df = ISO8601DateFormatter()
df.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
session.passExpiresAt = df.date(from: passExpiresAtString)


问:
jQuery index on each function
I am curious why I need this index

```<code>$(document).ready(function() {
        $(".divToggle").each(function(index){
            var buttonId = $(this)[0].attributes["id"].value.toString();
            var idParts = buttonId.split('_');
            var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";
            $(this).click(function() {
                 $("#" + uniquePart).toggle("slow");
            });
        });
    });
</code>```

Why do I need the "[0]" in "var buttonId = $(this)[0]…"  Without it, I get an attributes["id"] is null error..

答:
Technically you don't need it with a little modification of your code. What happens with jQuery selectors is they are simply a bunch of element references in an array.  so instead of

```<code><div id ="myelement"></div>
</code>```

you get

```<code>[<div id ="myelement"></div>]
</code>```

using $(this) puts this in an array and allows it to be used with jQuery functions. If you aren't using jQuery functions just use this.  So your code would become

```<code>var buttonId = this.attributes["id"].value.toString();
</code>```

ContentLicense: CC BY-SA 3.0

Title: jQuery index on each function

Body:
I am curious why I need this index

$(document).ready(function() {
        $(".divToggle").each(function(index){
            var buttonId = $(this)[0].attributes["id"].value.toString();
            var idParts = buttonId.split('_');
            var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";
            $(this).click(function() {
                 $("#" + uniquePart).toggle("slow");
            });
        });
    });

Why do I need the "[0]" in "var buttonId = $(this)[0]…"  Without it, I get an attributes["id"] is null error..

Body:
Technically you don't need it with a little modification of your code. What happens with jQuery selectors is they are simply a bunch of element references in an array.  so instead of

<div id ="myelement"></div>

you get

[<div id ="myelement"></div>]

using $(this) puts this in an array and allows it to be used with jQuery functions. If you aren't using jQuery functions just use this.  So your code would become

var buttonId = this.attributes["id"].value.toString();


问:
Why map or reduce keeps running without any condition given?
```<code>const array = [7, 2, 4, 1, 10, 6, 5, 11]

const max = array.reduce((acc, val) => {
    console.log(val, acc)

    return val > acc ? val : acc
}, 0)

console.log(max)
</code>```

I was looking at this code of reduce array method, one thing I couldn't understand at all is, How the reducer function is going to the next iteration? There is no condition that forces the reducer function to go to the next element in the array. In the first iteration, the val is 7, the first element of the array, and acc is 0, the reducer function returns 7 as per the condition written.
My question is how the number 7 as being the new accumulator is going to be called on the reducer function. I thought the normal procedure is you have to meet some kind of condition to iterate over again and again. Is there something written in the reduce method itself? Can you explain me please?

答:
As per the docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

The reduce() method executes a user-supplied “reducer” callback function on each element of the array,

Body:
const array = [7, 2, 4, 1, 10, 6, 5, 11]

const max = array.reduce((acc, val) => {
    console.log(val, acc)

    return val > acc ? val : acc
}, 0)

console.log(max)

I was looking at this code of reduce array method, one thing I couldn't understand at all is, How the reducer function is going to the next iteration? There is no condition that forces the reducer function to go to the next element in the array. In the first iteration, the val is 7, the first element of the array, and acc is 0, the reducer function returns 7 as per the condition written.
My question is how the number 7 as being the new accumulator is going to be called on the reducer function. I thought the normal procedure is you have to meet some kind of condition to iterate over again and again. Is there something written in the reduce method itself? Can you explain me please?


问:
Selenium WebDriver - Not able to access or click elements using PageObjectModel
I have defined Web Elements using Page Object model in Selenium. From test method, when ever I try to access or perform any action on those web elements my test completely skips it and completes, with no error.

```<code>public class HomePage extends Base{

@FindBy(xpath="//button[@id='sparkButton']")
    public WebElement menuDropDown;

public HomePage(){
        PageFactory.initElements(driver, this);
    }

public void clickHomepagemenuDropDown() {
        menuDropDown.click();
        System.out.println("Print HELLO");
   }
}

public class Test1 extends Base{

  HomePage homepage = new HomePage() ;
  @Test(priority=1)
  public void homePage() throws Exception {
    try {
      //do something
        homepage.clickHomepagemenuDropDown();
      //print something
       }catch (Exception e) {
               System.out.println (e);
                  return;
       }

}
</code>```

If I replace homepage.clickHomepagemenuDropDown();
with below lines, my program will run fine.

```<code>WebElement mdd = driver.findElement(By.xpath("//button[@id='sparkButton']"));
mdd.click();
</code>```

Is there some set up that I'm missing?

Update after correcting catch message--
I get following null exception
Cannot invoke "org.openqa.selenium.SearchContext.findElement(org.openqa.selenium.By)" because "this.searchContext" is null

答: In the test class, try creating a method with beforetest/beforemethod annotation and place the object for the homepage within these methods</p>

Body:
I have defined Web Elements using Page Object model in Selenium. From test method, when ever I try to access or perform any action on those web elements my test completely skips it and completes, with no error.

public class HomePage extends Base{

@FindBy(xpath="//button[@id='sparkButton']")
    public WebElement menuDropDown;

public HomePage(){
        PageFactory.initElements(driver, this);
    }

public void clickHomepagemenuDropDown() {
        menuDropDown.click();
        System.out.println("Print HELLO");
   }
}

public class Test1 extends Base{

  HomePage homepage = new HomePage() ;
  @Test(priority=1)
  public void homePage() throws Exception {
    try {
      //do something
        homepage.clickHomepagemenuDropDown();
      //print something
       }catch (Exception e) {
               System.out.println (e);
                  return;
       }

}

If I replace homepage.clickHomepagemenuDropDown();
with below lines, my program will run fine.

WebElement mdd = driver.findElement(By.xpath("//button[@id='sparkButton']"));
mdd.click();

Is there some set up that I'm missing?

Update after correcting catch message--
I get following null exception
Cannot invoke "org.openqa.selenium.SearchContext.findElement(org.openqa.selenium.By)" because "this.searchContext" is null


问:
Prefer static libraries but fallback to shared if not found
GCC (or the linker) prefers dynamic libraries over static ones by default. That means if I have

```<code>libfoo.so
libfoo.a
libbar.a
</code>```

and if I am building another library libmylib.so as follows:

```<code>gcc -shared -o mylib.so ... -lfoo -lbar
</code>```

the linker will link to libfoo.so (by preference) and libbar.a since that is the only one available.

One can force linking of static libraries by specifying -static (or -Wl,-Bstatic) instead.

```<code>gcc -shared -o mylib.so ... -static -lfoo -lbar
</code>```

This all works fine and will link to static versions of both libs.

However if I do not have the static libs it will not fallback to the shared libs. That is if I only have

```<code>libfoo.so
libbar.a
</code>```

the linking will fail because of missing libfoo.a instead of falling back to libfoo.so since it is the only one available.

Is there anyway to force this behavior where static libs are preferred but shared libs are picked if there is no static one that matches? (without having to explicitly specify -Wl,-Bdynamic manually for every such case)

答:
Is there anyway to force this behavior where static libs are preferred but shared libs are picked if there is no static one that matches?

Not that I know of.

This is quite an unusual requirement. Usually you want to link everything dynamically, except a few libraries (which you know in advance) which you want to link in statically.

For a solution to that problem, see this answer.

Body:
GCC (or the linker) prefers dynamic libraries over static ones by default. That means if I have

libfoo.so
libfoo.a
libbar.a

and if I am building another library libmylib.so as follows:

gcc -shared -o mylib.so ... -lfoo -lbar

the linker will link to libfoo.so (by preference) and libbar.a since that is the only one available.

One can force linking of static libraries by specifying -static (or -Wl,-Bstatic) instead.

gcc -shared -o mylib.so ... -static -lfoo -lbar

This all works fine and will link to static versions of both libs.

However if I do not have the static libs it will not fallback to the shared libs. That is if I only have

libfoo.so
libbar.a

the linking will fail because of missing libfoo.a instead of falling back to libfoo.so since it is the only one available.

Is there anyway to force this behavior where static libs are preferred but shared libs are picked if there is no static one that matches? (without having to explicitly specify -Wl,-Bdynamic manually for every such case)


问:
Reasons and benefits for using a literal in asp over html
I am fairly new to asp.net so this may seem like a stupid question, but:

I am attempting to modify a pre-exsiting help menu in a web-app.

In this menu the previous developer, just used three literals seperated by paragraphs and a button linking to a 100 page manual. (i know doesn't seem to be much help, hence why i was planning to update and fix this)

What i had in mind was setting something up like a menu that would link to the different section of the page when the title is clicked.

So something along these lines:

```<code><h1>Menu Contents</h1>
<ol>
<li>section1</li>
<li>section2</li>
<li>etc</li>
 </ol>
</code>```

After the contents section i would have the first section with it's details.

What i am wondering is why would i use asp-literals over just sticking to html?
So basically i would like to know what are the benefits or reasons for using asp literals and i guess when is it that i should use them?

I've attempted to find the solution to this on my own, but the only related matters i have been able to find have to deal with people arguing whether literals or labels are the best option so it's not entirely helpful.

Any help or suggestions are greatly appreciated.
Thanks.

答:
You generally use literals if you want to be able to control the text you display programmatically. Say your page has a way to edit the section titles of your manual, for instance. Or say your manual is in multiple languages and you want the user to be able to set her language and see the section titles displayed in that language.
In your case, by what you're saying, I infer none of this applies and your manual is quite static. In that case I would stick to simple HTML.</p>

Body:
I am fairly new to asp.net so this may seem like a stupid question, but:

I am attempting to modify a pre-exsiting help menu in a web-app.

In this menu the previous developer, just used three literals seperated by paragraphs and a button linking to a 100 page manual. (i know doesn't seem to be much help, hence why i was planning to update and fix this)

What i had in mind was setting something up like a menu that would link to the different section of the page when the title is clicked.

So something along these lines:

Menu Contents

section1

section2

etc

After the contents section i would have the first section with it's details.

What i am wondering is why would i use asp-literals over just sticking to html?
So basically i would like to know what are the benefits or reasons for using asp literals and i guess when is it that i should use them?

I've attempted to find the solution to this on my own, but the only related matters i have been able to find have to deal with people arguing whether literals or labels are the best option so it's not entirely helpful.

Any help or suggestions are greatly appreciated.
Thanks.


问:
MongoDB Node.js TypeError: Cannot read property 'db' of null
I'm making a DB for my project, but in this code:

```<code>function getallvideos(callback) {
  MongoClient.connect(url, function(err, client) {
    const db = client.db("cathub")
    db.collection("videos", function(err, collection) {
      collection.find().toArray(function(err, res) {
        callback(res)
      })
    })
    db.close()
  })
}
</code>```

I get this error:

TypeError: Cannot read property 'db' of null

答:
I figured out, in newer versions of MongoDB (3 and higher) they have essentially changed the way of connecting node server to the database. To establish a reusable connection (So that we can access the connected database from any other file), I created an async function in my db.js file where the connection is established and then exported it. In the end of the file, I have called the function. The code is as follows:

```<code>const {MongoClient} = require('mongodb')

const client = new MongoClient('mongodb+srv://todoAppUser:<password>@cluster0.6lvjr.mongodb.net/myDatabase?retryWrites=true&w=majority')

async function start(){
  await client.connect()
  console.log("Connected")
  module.exports = client.db()
  const app = require('./app')
  app.listen(3000)
}

  start()
</code>```

and while calling it from another file:

```<code>const productCollection = require('./db').collection("product");
</code>```

This code gives me no error and works perfectly fine. With the help of the above code, one can use this conveniently while following the MVC (Model-View-Controller) framework.

OwnerDisplayName: anon

LastEditorDisplayName: anon

Body:
I'm making a DB for my project, but in this code:

function getallvideos(callback) {
  MongoClient.connect(url, function(err, client) {
    const db = client.db("cathub")
    db.collection("videos", function(err, collection) {
      collection.find().toArray(function(err, res) {
        callback(res)
      })
    })
    db.close()
  })
}

I get this error:

TypeError: Cannot read property 'db' of null

Body:
I figured out, in newer versions of MongoDB (3 and higher) they have essentially changed the way of connecting node server to the database. To establish a reusable connection (So that we can access the connected database from any other file), I created an async function in my db.js file where the connection is established and then exported it. In the end of the file, I have called the function. The code is as follows:

const {MongoClient} = require('mongodb')

const client = new MongoClient('mongodb+srv://todoAppUser:<password>@cluster0.6lvjr.mongodb.net/myDatabase?retryWrites=true&w=majority')

async function start(){
  await client.connect()
  console.log("Connected")
  module.exports = client.db()
  const app = require('./app')
  app.listen(3000)
}

  start()

and while calling it from another file:

const productCollection = require('./db').collection("product");

This code gives me no error and works perfectly fine. With the help of the above code, one can use this conveniently while following the MVC (Model-View-Controller) framework.


问:
Iterate elements and toggle using classList in javascript
Conditions:

Please use javascript and classList property to invert which elements have .highlight class.

Basically iterate over all the
 elements and toggle the class of .highlight.
on each one.

You should not alter anything in HTML and CSS.

Your result should be like this!

/* app.js */
let list =  document.querySelector('li');

list.classList.add('');```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* index.css */
/*No need to touch anything in this file:*/
li {
  background-color: #B10DC9;
}

.highlight {
  background-color: #7FDBFF;
}</code>```

<!DOCTYPE html>

    <title>ClasList</title>

<link rel="stylesheet" type="text/css" href="index.css">

Hello

Hello

Hello

Hello

Hello

Hello

```

答:
The following solution removes the .highlight class style from the
 if the .highlight class style is applied to the
. If the .highlight class style is not applied to the
 element, the .highlight class style is added to the
 element.

Method-1

/* The querySelectorAll() method is used to select all
 elements. */
let list = document.querySelectorAll('li');
var listArray = [...list];

/* Each
 element is checked using the forEach() method. */
listArray.forEach(element => {
  /* Is the ".highlight" class style applied to the
 element? */
  if(element.classList.contains("highlight")) {
    /* Remove the ".highlight" class style from the
 element. */
    element.classList.remove("highlight");
  }
  else {
    /* Add the class style ".highlight" to the
 element. */
    element.classList.add("highlight");
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li {
  background-color: #B10DC9;
}

.highlight {
  background-color: #7FDBFF;
}</code>```

<!DOCTYPE html>

  <title>ClasList</title>
  <link rel="stylesheet" type="text/css" href="index.css">

Hello

Hello

Hello

Hello

Hello

Hello

```
</div>
</div>
</p>
<h5>Method-2</h5>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/* The querySelectorAll() method is used to select all <li> elements. */
let list = document.querySelectorAll('li');

window.addEventListener('load', (event) => {
  for(let i = 0 ; i < list.length ; ++i) {
    if(list[i].classList.contains("highlight"))
      list[i].classList.remove("highlight");
    else
      list[i].classList.add("highlight");
  }
});</code>```

li {
  background-color: #B10DC9;
}

.highlight {
  background-color: #7FDBFF;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<head>
  <title>ClasList</title>
  <link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
  <ul>
      <li>Hello</li>
      <li class="highlight">Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li class="highlight">Hello</li>
      <li>Hello</li>
  </ul>
  <script src="app.js"></script>
</body>
</html></code>```

Body:
Conditions:

Please use javascript and classList property to invert which elements have .highlight class.

Basically iterate over all the
 elements and toggle the class of .highlight.
on each one.

You should not alter anything in HTML and CSS.

Your result should be like this!

/* app.js */
let list =  document.querySelector('li');

list.classList.add('');

/* index.css */
/*No need to touch anything in this file:*/
li {
  background-color: #B10DC9;
}

.highlight {
  background-color: #7FDBFF;
}

<!DOCTYPE html>

    <title>ClasList</title>

<link rel="stylesheet" type="text/css" href="index.css">

Hello

Hello

Hello

Hello

Hello

Hello

Body:
The following solution removes the .highlight class style from the <li> if the .highlight class style is applied to the <li>. If the .highlight class style is not applied to the <li> element, the .highlight class style is added to the <li> element.

Method-1

/* The querySelectorAll() method is used to select all <li> elements. */
let list = document.querySelectorAll('li');
var listArray = [...list];

/* Each <li> element is checked using the forEach() method. */
listArray.forEach(element => {
  /* Is the ".highlight" class style applied to the <li> element? */
  if(element.classList.contains("highlight")) {
    /* Remove the ".highlight" class style from the <li> element. */
    element.classList.remove("highlight");
  }
  else {
    /* Add the class style ".highlight" to the <li> element. */
    element.classList.add("highlight");
  }
});

li {
  background-color: #B10DC9;
}

.highlight {
  background-color: #7FDBFF;
}

<!DOCTYPE html>
<head>
  <title>ClasList</title>
  <link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
  <ul>
      <li>Hello</li>
      <li class="highlight">Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li class="highlight">Hello</li>
      <li>Hello</li>
  </ul>
  <script src="app.js"></script>
</body>
</html>

Method-2

/* The querySelectorAll() method is used to select all <li> elements. */
let list = document.querySelectorAll('li');

window.addEventListener('load', (event) => {
  for(let i = 0 ; i < list.length ; ++i) {
    if(list[i].classList.contains("highlight"))
      list[i].classList.remove("highlight");
    else
      list[i].classList.add("highlight");
  }
});

li {
  background-color: #B10DC9;
}

.highlight {
  background-color: #7FDBFF;
}

<!DOCTYPE html>
<head>
  <title>ClasList</title>
  <link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
  <ul>
      <li>Hello</li>
      <li class="highlight">Hello</li>
      <li>Hello</li>
      <li>Hello</li>
      <li class="highlight">Hello</li>
      <li>Hello</li>
  </ul>
  <script src="app.js"></script>
</body>
</html>


问:
Could not resolve dependency: peer react@"^16.13.1 || ^17.0.0" from @ckeditor/ckeditor5-react@3.0.3 node_modules/@ckeditor/ckeditor5-react
enter image description here

Could not resolve dependency:
npm ERR! peer react@"^16.13.1 || ^17.0.0" from @ckeditor/ckeditor5-react@3.0.3
npm ERR! node_modules/@ckeditor/ckeditor5-react
npm ERR!   @ckeditor/ckeditor5-react@"^3.0.3" from the root project

答:
This is dute to npm not working for new versions in your project.
You have to force install the npm and node.
Try the commands:

npm insatll -f@ version that exists

npm install -f


问:
Is there any difference between bag= bag + n - i +1 and bag += n - i + 1
Is there any difference between bag= bag + n - i +1  and bag += n - i + 1 bcs is shows differnt while running a program below:

var n = 5
for (i = 1; i <= n; i++) {
  var bag = ""

  for (j = 1; j <= n - i + 1; j++) {
    bag += n - j + 1
  }
  console.log(bag)
}
// 2nd way
var n = 5; //
for (let i = 1; i <= n; i++) {
  var string = "";
  for (let j = 1; j <= n - i + 1; j++) {
    string = string + n - j + 1;
  }
  console.log(string);
}```

Replit link

答:
bag = bag + n - i + 1 and bag += n - i + 1 are not the same.

In the former, bag is coerced into a number

In the latter, the result is being coered into a string

The coercision occurs at the subtraction operator:

console.log('' + 1);
//=> '1'

console.log('' - 1);
//=> -1```

Body:
Is there any difference between bag= bag + n - i +1  and bag += n - i + 1 bcs is shows differnt while running a program below:

var n = 5
for (i = 1; i <= n; i++) {
  var bag = ""

  for (j = 1; j <= n - i + 1; j++) {
    bag += n - j + 1
  }
  console.log(bag)
}
// 2nd way
var n = 5; //
for (let i = 1; i <= n; i++) {
  var string = "";
  for (let j = 1; j <= n - i + 1; j++) {
    string = string + n - j + 1;
  }
  console.log(string);
}

Replit link


问:
How I can get current active users from Firebase with Flutter?
I am making an application using flutter and firebase. I need to get active users from firebase.
I am trying by creating a boolean field in firebase collection with name isActive = false and initiate a function with name _checkInternetConnectivity(); in this function I set when the internet connection is available update value of isActive = true in firebase and when there is no internet connection update value isActive = false so far my code is working perfectly but problem is that when internet connection is available it set the value of isActive = true but when there is no internet connection it unable to update the value isActive = false.

code is here:

```<code>void initState() {
    super.initState();
    _checkInternetConnectivity();
}

_checkInternetConnectivity() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      FirebaseFirestore.instance.collection('Profile').doc(user.uid).update({
        'isActive': true,
      });
      print('done mobile');
    } else if (connectivityResult == ConnectivityResult.wifi) {
      _addData.doc(user.uid).update({
        'isActive': true,
      });
      print('done wifi');
    } else if (connectivityResult == ConnectivityResult.none) {
      FirebaseFirestore.instance.collection('Profile').doc(user.uid).update({
        'isActive': false,
      });
      print('done none');
    }
  }
}
</code>```

so, how I can improve this code or any other way by which I can get active users from firebase with flutter.

 Regards

答: You can create a field like lastActiveTimestamp and update it every time an user opens the app. Then you can filter users by the last time they use the app.

Body:
I am making an application using flutter and firebase. I need to get active users from firebase.
I am trying by creating a boolean field in firebase collection with name isActive = false and initiate a function with name _checkInternetConnectivity(); in this function I set when the internet connection is available update value of isActive = true in firebase and when there is no internet connection update value isActive = false so far my code is working perfectly but problem is that when internet connection is available it set the value of isActive = true but when there is no internet connection it unable to update the value isActive = false.

code is here:

void initState() {
    super.initState();
    _checkInternetConnectivity();
}

_checkInternetConnectivity() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      FirebaseFirestore.instance.collection('Profile').doc(user.uid).update({
        'isActive': true,
      });
      print('done mobile');
    } else if (connectivityResult == ConnectivityResult.wifi) {
      _addData.doc(user.uid).update({
        'isActive': true,
      });
      print('done wifi');
    } else if (connectivityResult == ConnectivityResult.none) {
      FirebaseFirestore.instance.collection('Profile').doc(user.uid).update({
        'isActive': false,
      });
      print('done none');
    }
  }
}

so, how I can improve this code or any other way by which I can get active users from firebase with flutter.

 Regards


问:
#line keyword in C
I am trying to understand some code and I've come across a keyword that I've never seen before. I tried to google it, but haven't found anything regarding it as well.

```<code>char *valtext;
#line 1 "Values.l"
#define INITIAL 0
#line 2 "Values.l"
int reserve(char *s);
#line 388 "lex.val.c"
</code>```

I've included the entire block hoping that perhaps someone can help me understand this chunk of code. I can't find any files on my system named "Values.l" and this chunk of code is located in the "lex.val.c" file.

Thanks in advance.

答:
A #line directive sets the compiler's setting for the current file name and line number.  This affects the __FILE__ and __LINE__ symbols, the output generated by a failing assert(), and diagnostic messages (errors and warnings).  It's typically used by the preprocessor so that error and warning messages can refer to the original source code, not to the output of the preprocessor (which is typically discarded by the time you see any messages).

It's also used by other tools that generate C source code, such as lex/flex and yacc/bison, so that error messages can refer to the input file rather than the (temporary) generated C code.

The definitive reference is the C standard (pdf), section 6.10.4.

A line of the form

```<code>#line number
</code>```

sets the current line number.  A line of the form

```<code>#line number "file-name"
</code>```

sets both the line number and the file name.  You can also generate one of these two forms via macro expansion; for example:

```<code>#define LINE 42
#define FILE "foo.c"
#line LINE FILE
</code>```

Title: #line keyword in C

Body:
I am trying to understand some code and I've come across a keyword that I've never seen before. I tried to google it, but haven't found anything regarding it as well.

char *valtext;
#line 1 "Values.l"
#define INITIAL 0
#line 2 "Values.l"
int reserve(char *s);
#line 388 "lex.val.c"

I've included the entire block hoping that perhaps someone can help me understand this chunk of code. I can't find any files on my system named "Values.l" and this chunk of code is located in the "lex.val.c" file.

Thanks in advance.

Body:
A #line directive sets the compiler's setting for the current file name and line number.  This affects the __FILE__ and __LINE__ symbols, the output generated by a failing assert(), and diagnostic messages (errors and warnings).  It's typically used by the preprocessor so that error and warning messages can refer to the original source code, not to the output of the preprocessor (which is typically discarded by the time you see any messages).

It's also used by other tools that generate C source code, such as lex/flex and yacc/bison, so that error messages can refer to the input file rather than the (temporary) generated C code.

The definitive reference is the C standard (pdf), section 6.10.4.

A line of the form

#line number

sets the current line number.  A line of the form

#line number "file-name"

sets both the line number and the file name.  You can also generate one of these two forms via macro expansion; for example:

#define LINE 42
#define FILE "foo.c"
#line LINE FILE


答:
Note that array.reduce:

reduce
calls the callback, as a function, once for each element after the
first element present in the array, in ascending order.

You could understand the reduce as a array.map but the goal of it is to change the array to a singe output.

It will loop over the whole array same with the forEach/map/...

Check below example, even though you don't do anything, like return or anything else to array.reduce, it will still work and iterate the array

You could check here for more

But of course if you don't use return for array.reduce, there will be no benefit for you to use array.reduce

const array = [7, 2, 4, 1, 10, 6, 5, 11]

const max = array.reduce((acc, val) => {
  console.log(val)
}, 0)

console.log(max)```

Title: Why map or reduce keeps running without any condition given?


问:
Component not re-rendering when updating state within map function
I don't know why the component isn't re-rendering automatically when I click on the button that runs the function update.  I see that the after click on the button, the state updates but the list does not automatically re-render.  Isn't the component supposed to re-render when setFoobar is called?

```<code>import React, { useEffect, useState } from "react";

const SomeList = () => {
  const [foobar, setFoobar] = useState([
    {
      description: "description1",
      date: "date1",
    },
    {
      description: "description2",
      date: "date2",
    },
  ]);
  const update = () => {
    const newFoobar = foobar;
    newFoobar.push({
      description: "This new item should render in view",
      date: "asdf",
    });
    setFoobar(newFoobar);
  };
  const generateList = foobar((each, idx) => {
    return (
      <div key={idx}>
        <div>{each.description}</div>
        <div>{each.date}</div>
        <div>
          <button onClick={update}>Click</button>
        </div>
      </div>
    );
  });
  return <div>{generateList}</div>;
};

export default SomeList;
</code>```

答:
Your code is not working because const newFoobar = foobar;, the previous state and new state is same object so the component will not re-render. So you have to create a new object and update it

```<code>const update = () => {
    const newFoobar = [...foobar];
    newFoobar.push({
      description: "This new item should render in view",
      date: "asdf",
    });
    setFoobar(footer);
  };
</code>```

Body:
I don't know why the component isn't re-rendering automatically when I click on the button that runs the function update.  I see that the after click on the button, the state updates but the list does not automatically re-render.  Isn't the component supposed to re-render when setFoobar is called?

import React, { useEffect, useState } from "react";

const SomeList = () => {
  const [foobar, setFoobar] = useState([
    {
      description: "description1",
      date: "date1",
    },
    {
      description: "description2",
      date: "date2",
    },
  ]);
  const update = () => {
    const newFoobar = foobar;
    newFoobar.push({
      description: "This new item should render in view",
      date: "asdf",
    });
    setFoobar(newFoobar);
  };
  const generateList = foobar((each, idx) => {
    return (

{each.description}

{each.date}

          <button onClick={update}>Click</button>

    );
  });
  return
{generateList}
;
};

export default SomeList;

Body:
Your code is not working because const newFoobar = foobar;, the previous state and new state is same object so the component will not re-render. So you have to create a new object and update it

const update = () => {
    const newFoobar = [...foobar];
    newFoobar.push({
      description: "This new item should render in view",
      date: "asdf",
    });
    setFoobar(footer);
  };


问:
Selecting A Dynamic range in Excel using Python - Openpyxl
I have an Excel file with data in column A. I want to loop through each cell and select the row that that i first come across that has a formula.

This is my code:

```<code>import openpyxl
wb=openpyxl.load_workbook(path1)
sheet = wb['Sheet1']

names=sheet['A']

for cellObj in names:
    val = str(cellObj.value)
    if val[0] == "=":
        #select the row from column A to Z and make it's values equal to itself (like doing a copy/pasteSpecial values in excel to remove the formula)
</code>```

I guess i can append the row in an empty list then make it equal to the row again, but how do i even do that?

Thanks!

答:
Basically, you just wanted to remove the formula and leave the actual data itself? If you want this for the whole file then add data_only=True. I also suggest saving the workbook in a different filename or create a copy of original excel file.</p>
```<code>import openpyxl
wb = openpyxl.load_workbook(path1, data_only=True)
wb.save(save_path)
wb.close()
</code>```

Body:
I have an Excel file with data in column A. I want to loop through each cell and select the row that that i first come across that has a formula.

This is my code:

import openpyxl
wb=openpyxl.load_workbook(path1)
sheet = wb['Sheet1']

names=sheet['A']

for cellObj in names:
    val = str(cellObj.value)
    if val[0] == "=":
        #select the row from column A to Z and make it's values equal to itself (like doing a copy/pasteSpecial values in excel to remove the formula)

I guess i can append the row in an empty list then make it equal to the row again, but how do i even do that?

Thanks!

Body:
Basically, you just wanted to remove the formula and leave the actual data itself? If you want this for the whole file then add data_only=True. I also suggest saving the workbook in a different filename or create a copy of original excel file.

import openpyxl
wb = openpyxl.load_workbook(path1, data_only=True)
wb.save(save_path)
wb.close()


问:
How to detect when webview url changes in flutter?
I have been looking around for a webview plugin in flutter that can detect when the url changes, but didn't find a match? The reason I am trying to detect a url change is because I want to change a bool variable to true when changed, which will then change the color of a appbar, is this possible?Are there any simple/easy examples out there that can achieve what i'm looking for? Thanks for any help in advance!</p>

答:
In Webview you have optional navigationDelegate parameter

```<code>WebView(
      // initialUrl: 'https://flutter.dev',
      onWebViewCreated: (WebViewController webViewController) {
        _controller = webViewController;
        _loadHtmlFromAssets();
      },
      navigationDelegate: (NavigationRequest request) {
        setState(() {
      widget.appBarcolor = Colors.black87;
    });
        //Any other URL works
        return NavigationDecision.navigate;
      },
    );
  }
</code>```

Sample:

```<code>class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  Color appBarcolor = Colors.blue;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  WebViewController? _controller;

  @override
  void initState() {
    super.initState();
    // Enable virtual display.
    if (Platform.isAndroid) WebView.platform = AndroidWebView();
  }

  void _incrementCounter() {
    _controller!.goBack();
    setState(() {
      widget.appBarcolor = Colors.blue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: widget.appBarcolor,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: controller(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.arrow_back),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  _loadHtmlFromAssets() async {
    // String fileText = await rootBundle.loadString('assets/help.html');
    var fileText =
        "<!DOCTYPE html> <html> <head> <title>HTML, CSS and JavaScript demo</title> <style> .rotate { transform: rotate(1700deg) ; } .rotate2 { transform: rotate(90deg) ; } .bg { background: url(https://picsum.photos/2000/1000?image=1069) center/cover; height: 50vh; width: 50vh; } body { margin:0; overflow:hidden; } </style> </head> "
        "<!-- Start your code here --> <ul> <li> <a href ='http://duckduckgo.com/' /><p> duckduckgo.com</a> </li>  <li> <a href='http://www.google.com'>google.com </a> </li>    <li> <a href='http://www.yahoo.com/'> yahoo.com </a> </li></ul> </html>";
    _controller?.loadUrl(Uri.dataFromString(fileText,
            mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
        .toString());
  }

  WebView controller() {
    return WebView(
      // initialUrl: 'https://flutter.dev',
      onWebViewCreated: (WebViewController webViewController) {
        _controller = webViewController;
        _loadHtmlFromAssets();
      },
      navigationDelegate: (NavigationRequest request) {
        setState(() {
          widget.appBarcolor = Colors.black87;
        });

        //Any other url works
        return NavigationDecision.navigate;
      },
    );
  }
}
</code>```

While Debug navigation request value:

Body:
In Webview you have optional navigationDelegate parameter

WebView(
      // initialUrl: 'https://flutter.dev',
      onWebViewCreated: (WebViewController webViewController) {
        _controller = webViewController;
        _loadHtmlFromAssets();
      },
      navigationDelegate: (NavigationRequest request) {
        setState(() {
      widget.appBarcolor = Colors.black87;
    });
        //Any other URL works
        return NavigationDecision.navigate;
      },
    );
  }

Sample:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;
  Color appBarcolor = Colors.blue;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  WebViewController? _controller;

  @override
  void initState() {
    super.initState();
    // Enable virtual display.
    if (Platform.isAndroid) WebView.platform = AndroidWebView();
  }

  void _incrementCounter() {
    _controller!.goBack();
    setState(() {
      widget.appBarcolor = Colors.blue;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: widget.appBarcolor,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: controller(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.arrow_back),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  _loadHtmlFromAssets() async {
    // String fileText = await rootBundle.loadString('assets/help.html');
    var fileText =
        "<!DOCTYPE html> <html> <head> <title>HTML, CSS and JavaScript demo</title> <style> .rotate { transform: rotate(1700deg) ; } .rotate2 { transform: rotate(90deg) ; } .bg { background: url(https://picsum.photos/2000/1000?image=1069) center/cover; height: 50vh; width: 50vh; } body { margin:0; overflow:hidden; } </style> </head> "
        "<!-- Start your code here --> <ul> <li> <a href ='http://duckduckgo.com/' /><p> duckduckgo.com</a> </li>  <li> <a href='http://www.google.com'>google.com </a> </li>    <li> <a href='http://www.yahoo.com/'> yahoo.com </a> </li></ul> </html>";
    _controller?.loadUrl(Uri.dataFromString(fileText,
            mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
        .toString());
  }

  WebView controller() {
    return WebView(
      // initialUrl: 'https://flutter.dev',
      onWebViewCreated: (WebViewController webViewController) {
        _controller = webViewController;
        _loadHtmlFromAssets();
      },
      navigationDelegate: (NavigationRequest request) {
        setState(() {
          widget.appBarcolor = Colors.black87;
        });

        //Any other url works
        return NavigationDecision.navigate;
      },
    );
  }
}

While Debug navigation request value:


问:
Error when I try to execute 'sanity start' after success with 'sanity init'
I am trying to install the Sanity studio and I followed these steps:

npm install --global @sanity/cli

sanity install

sanity init

After the init step, I try to run the next step:

sanity start

but it says:

```<code>Run the command again within a Sanity project directory, where "@sanity/core"
is installed as a dependency.
    at D.runCommand (F:/All Node and related projects/node_modules/@sanity/cli/b
in/sanity-cli.js:3254:1345)
    at t.exports (F:/All Node and related projects/node_modules/@sanity/cli/bin/sanity-cli.js:1794:2419)
</code>```

But when I try to cd into my sanity project directory, it is not even able to recognize sanity, it says:

```<code>'sanity' is not recognized as an internal or external command,
operable program or batch file.
</code>```

Is my dependencies directory structure incorrect?
What conditions should be met before you can call  sanity start?

THANKS!

答:
The reason why sanity start not working is your command prompt location not same as you installed all sanity packages.

Go back to commend prompt go to the location where sanity is installed and give the commend sanity start it will work .

Body:
I am trying to install the Sanity studio and I followed these steps:

npm install --global @sanity/cli

sanity install

sanity init

After the init step, I try to run the next step:

sanity start

but it says:

Run the command again within a Sanity project directory, where "@sanity/core"
is installed as a dependency.
    at D.runCommand (F:/All Node and related projects/node_modules/@sanity/cli/b
in/sanity-cli.js:3254:1345)
    at t.exports (F:/All Node and related projects/node_modules/@sanity/cli/bin/sanity-cli.js:1794:2419)

But when I try to cd into my sanity project directory, it is not even able to recognize sanity, it says:

'sanity' is not recognized as an internal or external command,
operable program or batch file.

Is my dependencies directory structure incorrect?
What conditions should be met before you can call  sanity start?

THANKS!


问:
What type should I use for a const object in JSONSchemaType in AJV?
I'm writing a validator using AJV and have defined the schema as follows:

```<code>const ajv = new Ajv({ allErrors: true, $data: true });

export interface UpdateTaskRequest {
  pathParameters: {
    listId: string;
    taskId: string;
  };
  body: {
    id: string;
    name: string;
    isCompleted?: boolean;
    desc?: string;
    dueDate?: string;
  };
}

export const updateTaskRequestSchema: JSONSchemaType<UpdateTaskRequest> = {
  $schema: "http://json-schema.org/draft-07/schema#",
  type: "object",
  properties: {
    pathParameters: {
      type: "object",
      properties: {
        listId: {
          type: "string",
        },
        taskId: {
          type: "string",
        },
      },
      required: ["listId", "taskId"],
    },
    body: {
      type: "object",
      properties: {
        id: {
          const: { $data: "/pathParameters/taskId" },
        },
        name: {
          type: "string",
          maxLength: 200,
        },
        isCompleted: {
          type: "boolean",
          nullable: true,
        },
        desc: {
          type: "string",
          nullable: true,
          maxLength: 400,
        },
        dueDate: {
          type: "string",
          nullable: true,
          format: "date-time",
        },
      },
      required: ["id", "name"],
    },
  },
  required: ["pathParameters", "body"],
};
</code>```

I want to validate that body.id is equal to pathParameters.taskId so I used the const keyword in conjunction with the $data reference as explained here.

```<code>id: {
  const: { $data: "/pathParameters/taskId" },
},
</code>```

The problem is I'm getting the following error:

The types of 'properties.id' are incompatible between these types.
Type '{ const: { $data: string; }; }' is not assignable to type '{ $ref: string; } | (UncheckedJSONSchemaType<string, false> & { const?: string | undefined; enum?: readonly string[] | undefined; default?: string | undefined; })'.
Types of property 'const' are incompatible.
Type '{ $data: string; }' is not assignable to type 'string'.ts(2322)

How do I tell the TypeScript compiler that { $data: string; } will eventually resolve to string so as to resolve the above error? I tried the following but it did not work:

```<code>id: {
  type: "string",
  const: { $data: "/pathParameters/taskId" },
},
</code>```

答:
I found a workaround by defining the $data reference in an if/then expression:</p>
```<code>export const updateTaskRequestSchema: JSONSchemaType<UpdateTaskRequest> = {
  $schema: "http://json-schema.org/draft-07/schema#",
  type: "object",
  properties: {
    pathParameters: {
      type: "object",
      properties: {
        listId: {
          type: "string",
        },
        taskId: {
          type: "string",
        },
      },
      required: ["listId", "taskId"],
    },
    body: {
      type: "object",
      properties: {
        id: {
          type: "string",
        },
        name: {
          type: "string",
          maxLength: 200,
        },
        isCompleted: {
          type: "boolean",
          nullable: true,
        },
        desc: {
          type: "string",
          nullable: true,
          maxLength: 400,
        },
        dueDate: {
          type: "string",
          nullable: true,
          format: "date-time",
        },
      },
      required: ["id", "name"],
    },
  },
  required: ["pathParameters", "body"],
  if: {
    properties: {
      pathParameters: {
        type: "object",
        properties: {
          taskId: {
            type: "string",
          },
        },
      },
    },
  },
  then: {
    properties: {
      body: {
        type: "object",
        properties: {
          id: {
            const: { $data: "/pathParameters/taskId" },
          },
        },
      },
    },
  },
};
</code>```

Body:
I'm writing a validator using AJV and have defined the schema as follows:

const ajv = new Ajv({ allErrors: true, $data: true });

export interface UpdateTaskRequest {
  pathParameters: {
    listId: string;
    taskId: string;
  };
  body: {
    id: string;
    name: string;
    isCompleted?: boolean;
    desc?: string;
    dueDate?: string;
  };
}

export const updateTaskRequestSchema: JSONSchemaType<UpdateTaskRequest> = {
  $schema: "http://json-schema.org/draft-07/schema#",
  type: "object",
  properties: {
    pathParameters: {
      type: "object",
      properties: {
        listId: {
          type: "string",
        },
        taskId: {
          type: "string",
        },
      },
      required: ["listId", "taskId"],
    },
    body: {
      type: "object",
      properties: {
        id: {
          const: { $data: "/pathParameters/taskId" },
        },
        name: {
          type: "string",
          maxLength: 200,
        },
        isCompleted: {
          type: "boolean",
          nullable: true,
        },
        desc: {
          type: "string",
          nullable: true,
          maxLength: 400,
        },
        dueDate: {
          type: "string",
          nullable: true,
          format: "date-time",
        },
      },
      required: ["id", "name"],
    },
  },
  required: ["pathParameters", "body"],
};

I want to validate that body.id is equal to pathParameters.taskId so I used the const keyword in conjunction with the $data reference as explained here.

id: {
  const: { $data: "/pathParameters/taskId" },
},

The problem is I'm getting the following error:

The types of 'properties.id' are incompatible between these types.
Type '{ const: { $data: string; }; }' is not assignable to type '{ $ref: string; } | (UncheckedJSONSchemaType<string, false> & { const?: string | undefined; enum?: readonly string[] | undefined; default?: string | undefined; })'.
Types of property 'const' are incompatible.
Type '{ $data: string; }' is not assignable to type 'string'.ts(2322)

How do I tell the TypeScript compiler that { $data: string; } will eventually resolve to string so as to resolve the above error? I tried the following but it did not work:

id: {
  type: "string",
  const: { $data: "/pathParameters/taskId" },
},

Body:
I found a workaround by defining the $data reference in an if/then expression:

export const updateTaskRequestSchema: JSONSchemaType<UpdateTaskRequest> = {
  $schema: "http://json-schema.org/draft-07/schema#",
  type: "object",
  properties: {
    pathParameters: {
      type: "object",
      properties: {
        listId: {
          type: "string",
        },
        taskId: {
          type: "string",
        },
      },
      required: ["listId", "taskId"],
    },
    body: {
      type: "object",
      properties: {
        id: {
          type: "string",
        },
        name: {
          type: "string",
          maxLength: 200,
        },
        isCompleted: {
          type: "boolean",
          nullable: true,
        },
        desc: {
          type: "string",
          nullable: true,
          maxLength: 400,
        },
        dueDate: {
          type: "string",
          nullable: true,
          format: "date-time",
        },
      },
      required: ["id", "name"],
    },
  },
  required: ["pathParameters", "body"],
  if: {
    properties: {
      pathParameters: {
        type: "object",
        properties: {
          taskId: {
            type: "string",
          },
        },
      },
    },
  },
  then: {
    properties: {
      body: {
        type: "object",
        properties: {
          id: {
            const: { $data: "/pathParameters/taskId" },
          },
        },
      },
    },
  },
};


问:
XML for Web Service: inline attachment
I have to invoke a web service with a single parameter, a String in XML format.
I'm building this via an XSLT transformation. So far so good.

The problem is with this XSD fragment:

```<code><xs:complexType name="Document">
    <xs:sequence>
        <xs:element name="title" type="xs:string" minOccurs="1"/>
        <xs:element name="content" type="xs:base64Binary" minOccurs="1"/>
    </xs:sequence>
</xs:complexType>
</code>```

which translates (for example) into this XML:

```<code><attachment>
    <title>test title</title>
    <content>
    PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Inllc
    yI/Pg0KPG1zZ3ByYXRpY2E+DQogICAgPHByYXRpY2E+DQogICAgICAgIDxwcm9jZXNzbz
    4NCiAgICAgICAgICAgIDxjb2RQcm9jZXNzbz4xPC9jb2RQcm9jZXNzbz4NCiAgICAgICA
    gICAgIDxjb2RJc3RhbnphUHJvY2Vzc28MzwvY29kSXN0YW56YVByb2Nlc3NvPg0KICAgI
    CAgICAgICAgPGNvZFN0YXRvPjYwPC9jb2RTdGF0bz4NCiAgICAgICAgPC9wcm9jZXNzbz
    4NCiAgICA8L3ByYXRpY2E+DQo8L21zZ3ByYXRpY2E+
    </content>
</attachment>
</code>```

Yes, you got it right: I have to insert a file content into the XML document in base 64 binary format.

I thought about inserting a placeholder with XSLT and then processing the XML document to replace it with the actual file content, but I'm wondering if there are any best practices for these occasions, maybe some fancy XSTL trick well beyond my knowledge or some Java tools which may come in handy.

How would you do that?

NOTE: I can't use SOAP with attachment, and I'm well aware that the aforementioned approach is prone to failure in case of huge attachments, but at the moment our counterpart will not budge.

答:
This is not exactly the answer you are looking for, but XML processors like Woodstox link text support efficient reading and writing of inline Base64-encoded content.
With Woodstox 4.0 it's done using so-called Typed Access API, part of Stax2 extension API (under package "org.codehaus.stax2.typed.*", TypedXMLStreamReader, TypedXMLStreamWriter).

This allows for streaming reading/writing of element and attribute values, given binary data.

The trick would then be to hook this up with XSLT. Another possibly simpler way is to figure out if client APIs Soap stacks (like CXF aka XFire) can give you access to content via XMLStreamReader/Writer. Most new ones are based on Stax, and usually embed Woodstox.

OwnerDisplayName: Manrico Corazzi

ContentLicense: CC BY-SA 2.5

Title: XML for Web Service: inline attachment

Body:
I have to invoke a web service with a single parameter, a String in XML format.
I'm building this via an XSLT transformation. So far so good.

The problem is with this XSD fragment:

<xs:complexType name="Document">
    <xs:sequence>
        <xs:element name="title" type="xs:string" minOccurs="1"/>
        <xs:element name="content" type="xs:base64Binary" minOccurs="1"/>
    </xs:sequence>
</xs:complexType>

which translates (for example) into this XML:

<attachment>
    <title>test title</title>
    <content>
    PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Inllc
    yI/Pg0KPG1zZ3ByYXRpY2E+DQogICAgPHByYXRpY2E+DQogICAgICAgIDxwcm9jZXNzbz
    4NCiAgICAgICAgICAgIDxjb2RQcm9jZXNzbz4xPC9jb2RQcm9jZXNzbz4NCiAgICAgICA
    gICAgIDxjb2RJc3RhbnphUHJvY2Vzc28MzwvY29kSXN0YW56YVByb2Nlc3NvPg0KICAgI
    CAgICAgICAgPGNvZFN0YXRvPjYwPC9jb2RTdGF0bz4NCiAgICAgICAgPC9wcm9jZXNzbz
    4NCiAgICA8L3ByYXRpY2E+DQo8L21zZ3ByYXRpY2E+
    </content>
</attachment>

Yes, you got it right: I have to insert a file content into the XML document in base 64 binary format.

I thought about inserting a placeholder with XSLT and then processing the XML document to replace it with the actual file content, but I'm wondering if there are any best practices for these occasions, maybe some fancy XSTL trick well beyond my knowledge or some Java tools which may come in handy.

How would you do that?

NOTE: I can't use SOAP with attachment, and I'm well aware that the aforementioned approach is prone to failure in case of huge attachments, but at the moment our counterpart will not budge.

OwnerDisplayName: StaxMan


问:
Why bother with an API for google's CDN
http://code.google.com/apis/libraries/devguide.html states that you need to sign up for an API to use the CDN. But why? You can clearly use it without.

Doesn't linking to google.com/blah/jquery.js?myAPIcode mean that a new version of jquery.js would be downloaded, rather than using a cached version? So using an API would slow down my website, and not using one would speed it up? Is there any advantage of using an API? Or is it just so Google can "contact you directly if we detect an issue with your site" AKA track you?

答: Given the http://html5boilerplate.com/ guys don't use an API, I think it's best not to. No one seems to know of a good reason. And Google tracking your site isn't a good reason (you probably use google analytics anyway!).</p>

Title: Why bother with an API for google's CDN


问:
How can I pass a function to the child component?
I have this component with a modal for confirmation when deleting an item. How can I pass the function to the child component so that once I click the button Agree, it will trigger this function for delete.

The function to delete an item:

```<code> const deleteProduct = async (id) => {
    const productDoc = doc(db, "products", id);
    await deleteDoc(productDoc);
  };
</code>```

The Dialog:

```<code> <Modal
        title="Confirmation"
        subtitle={sample}
        isOpen={isOpen}
        handleClose={handleClose}
      />
</code>```

The Reusable component:

```<code>import {
  Dialog,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  Button,
  DialogActions,
} from "@mui/material";

const Modal = ({ title, subtitle, children, isOpen, handleClose }) => {
  const handleConfirm = () => {
    alert("You Agreed!");
    handleClose();
  };
  return (
    <Dialog open={isOpen} onClose={handleClose}>
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{subtitle}</DialogContentText>
        <Divider />
        {children}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          Cancel
        </Button>
        <Button onClick={handleConfirm} color="primary">
          Agree
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default Modal;
</code>```

答:
You can pass the deleteProduct function and the id as props to the Modal Components like bellow:

The Dialog:

```<code><Modal
   title="Confirmation"
   subtitle={sample}
   isOpen={isOpen}
   id={id}
   handleClose={handleClose}
   deleteProduct={deleteProduct}
 />
</code>```

The Reusable component:

```<code>import {
  Dialog,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  Button,
  DialogActions,
} from "@mui/material";

const Modal = ({ title, subtitle, children, isOpen, id, handleClose, deleteProduct }) => {
  const handleConfirm = () => {
    alert("You Agreed!");
    handleClose();
    deleteProduct(id)
  };
  return (
    <Dialog open={isOpen} onClose={handleClose}>
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{subtitle}</DialogContentText>
        <Divider />
        {children}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          Cancel
        </Button>
        <Button onClick={handleConfirm} color="primary">
          Agree
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default Modal;
</code>```

Body:
I have this component with a modal for confirmation when deleting an item. How can I pass the function to the child component so that once I click the button Agree, it will trigger this function for delete.

The function to delete an item:

 const deleteProduct = async (id) => {
    const productDoc = doc(db, "products", id);
    await deleteDoc(productDoc);
  };

The Dialog:

 <Modal
        title="Confirmation"
        subtitle={sample}
        isOpen={isOpen}
        handleClose={handleClose}
      />

The Reusable component:

import {
  Dialog,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  Button,
  DialogActions,
} from "@mui/material";

const Modal = ({ title, subtitle, children, isOpen, handleClose }) => {
  const handleConfirm = () => {
    alert("You Agreed!");
    handleClose();
  };
  return (
    <Dialog open={isOpen} onClose={handleClose}>
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{subtitle}</DialogContentText>
        <Divider />
        {children}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          Cancel
        </Button>
        <Button onClick={handleConfirm} color="primary">
          Agree
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default Modal;

Body:
You can pass the deleteProduct function and the id as props to the Modal Components like bellow:

The Dialog:

<Modal
   title="Confirmation"
   subtitle={sample}
   isOpen={isOpen}
   id={id}
   handleClose={handleClose}
   deleteProduct={deleteProduct}
 />

The Reusable component:

import {
  Dialog,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  Button,
  DialogActions,
} from "@mui/material";

const Modal = ({ title, subtitle, children, isOpen, id, handleClose, deleteProduct }) => {
  const handleConfirm = () => {
    alert("You Agreed!");
    handleClose();
    deleteProduct(id)
  };
  return (
    <Dialog open={isOpen} onClose={handleClose}>
      <DialogTitle>{title}</DialogTitle>
      <DialogContent>
        <DialogContentText>{subtitle}</DialogContentText>
        <Divider />
        {children}
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color="error">
          Cancel
        </Button>
        <Button onClick={handleConfirm} color="primary">
          Agree
        </Button>
      </DialogActions>
    </Dialog>
  );
};

export default Modal;


问:
Firebase node.js application opens someone else's profile
I have a node.js application which I deployed as Firebase function. The issue that I am having is, if user1 is logged it from a window and user2 open the url in a seperate device+browser, User2 is automatically logged in as user1. I am not sure why this is happening.

Some things I have tried

Setting the Auth persistence to None.

Changing my session config in index.js which looks like

```<code>app.use(session({
    name: '__session',
    secret: 'random',
    resave: true,
    saveUninitialized: true,
    cookie: {
        maxAge: 5 * 24 * 60 * 60 * 1000, // 5 days
        secure: false,
        httpOnly: true
    }
}));

app.use(flash());

app.use(async(req, res, next) => {
    res.locals.success = req.flash('success');
    res.locals.error = req.flash('error')
    res.locals.currentUser = firebase.auth().currentUser;
    next();
});
</code>```

Anyone faced similar issue? Any idea how to fix this?

Thanks a lot in advance!

答: Session data is not saved in the cookie itself, just the session ID. Session data is stored server-side.

Body:
I have a node.js application which I deployed as Firebase function. The issue that I am having is, if user1 is logged it from a window and user2 open the url in a seperate device+browser, User2 is automatically logged in as user1. I am not sure why this is happening.

Some things I have tried

Setting the Auth persistence to None.

Changing my session config in index.js which looks like

app.use(session({
    name: '__session',
    secret: 'random',
    resave: true,
    saveUninitialized: true,
    cookie: {
        maxAge: 5 * 24 * 60 * 60 * 1000, // 5 days
        secure: false,
        httpOnly: true
    }
}));

app.use(flash());

app.use(async(req, res, next) => {
    res.locals.success = req.flash('success');
    res.locals.error = req.flash('error')
    res.locals.currentUser = firebase.auth().currentUser;
    next();
});

Anyone faced similar issue? Any idea how to fix this?

Thanks a lot in advance!


问:
Cypress : The submit button is disabled even after all the text fields have filled
I was trying to automate a text submit form using cypress. The 'Create student'  button is disabled even after all the fields have been filled

Please see the cypress error

code :

it('should be able to add a new student and update the details, remove from the class and delete the account', function () {
        cy.visit(
            'https://readingeggs.blake-staging.com/district_ui#/reading/manage-schools/students/195286/new'
        )
        cy.findByLabelText('First Name').type('ark')
        cy.get('#first-name').should('have.value', 'ark')
        cy.findByLabelText('Last Name').type('last')
        cy.get('#last-name').should('have.value', 'last')
        cy.get('[data-test-select-grade]').select('1')
        cy.get('#grade-dropdown').should('have.value', '1')
        cy.get('[data-test-select-teacher]').select('Lehner, Abbey')
        cy.get('#teacher-dropdown').should('have.value', '3068134')

        cy.get('[data-test-submit-new-student]').click()
        cy.get('#main')
            .findByRole('alert')
            .should('include.text', `Successfully created a student`)
    })
})
```

答:
One option would be to use {force: true} with click().

it('should be able to add a new student and update the details, remove from the class and delete the account', function () {
  cy.visit(
    'https://readingeggs.blake-staging.com/district_ui#/reading/manage-schools/students/195286/new'
  )
  cy.findByLabelText('First Name').type('ark')
  cy.get('#first-name').should('have.value', 'ark')
  cy.findByLabelText('Last Name').type('last')
  cy.get('#last-name').should('have.value', 'last')
  cy.get('[data-test-select-grade]').select('1')
  cy.get('#grade-dropdown').should('have.value', '1')
  cy.get('[data-test-select-teacher]').select('Lehner, Abbey')
  cy.get('#teacher-dropdown').should('have.value', '3068134')
  cy.get('[data-test-submit-new-student]').click({force: true})
  cy.get('#main')
    .findByRole('alert')
    .should('include.text', 'Successfully created a student')
})
```


问:
GitLab CI/CD Could I get artifacts real path in runner then send files with scp?
I'm learning GitLab CI/CD, I want to when finished build send files in artifacts, the idea is possible?</p>
```<code>image: maven:3.8.1-jdk-11

stages:
  - build
  - deploy

build:
  stage: build
  script:
    - mvn clean install
  artifacts:
    paths:
      - "*/target/*.jar"

deploy:
  stage: deploy
  script:
    - scp -r <artifacts_path> root@test.com:~/Deploy
</code>```

答:
Could I get artifacts real path in runner then send files with scp?

Generally speaking, no. You must rely on artifact restoration process. Keep in mind that (1) artifacts are generally not stored on the runner and (2) docker runners execute jobs inside of a docker container and typically would not have access to files on the runner host, even if artifacts were stored there.

When jobs start, artifacts from previous stages are restored into the workspace.

So, as an alternative solution, you can simply start with an empty workspace (don't checkout the repo), then upload all files in the workspace, which should be only the restored artifacts, assuming there are no file-based variables.

deploy:
  variables:  # prevent checkout of repository
    GIT_STRATEGY: none
  stage: deploy
  script:
    - ls -laht  # list files, which should be just restored artifacts
    - scp -r ./ root@test.com:~/Deploy
```
<p>Another way might be to just use the same glob pattern used in the <code>artifacts:paths:</code> to find the files and upload them.</p>
<pre class="lang-yaml prettyprint-override"><code>variables:
  ARTIFACTS_PATTERN: "*/target/*.jar"

build:
  # ...
  artifacts:
    paths:
      - $ARTIFACTS_PATTERN

deploy:
  script: # something like this. Not sure if scp supports glob patterns
    - rsync -a -m --include="$ARTIFACTS_PATTERN" user@remote:~/Deploy
</code>```

Body:
I'm learning GitLab CI/CD, I want to when finished build send files in artifacts, the idea is possible?

image: maven:3.8.1-jdk-11

stages:
  - build
  - deploy

build:
  stage: build
  script:
    - mvn clean install
  artifacts:
    paths:
      - "*/target/*.jar"

deploy:
  stage: deploy
  script:
    - scp -r <artifacts_path> root@test.com:~/Deploy

Body:
Could I get artifacts real path in runner then send files with scp?

Generally speaking, no. You must rely on artifact restoration process. Keep in mind that (1) artifacts are generally not stored on the runner and (2) docker runners execute jobs inside of a docker container and typically would not have access to files on the runner host, even if artifacts were stored there.

When jobs start, artifacts from previous stages are restored into the workspace.

So, as an alternative solution, you can simply start with an empty workspace (don't checkout the repo), then upload all files in the workspace, which should be only the restored artifacts, assuming there are no file-based variables.

deploy:
  variables:  # prevent checkout of repository
    GIT_STRATEGY: none
  stage: deploy
  script:
    - ls -laht  # list files, which should be just restored artifacts
    - scp -r ./ root@test.com:~/Deploy

Another way might be to just use the same glob pattern used in the artifacts:paths: to find the files and upload them.

variables:
  ARTIFACTS_PATTERN: "*/target/*.jar"

build:
  # ...
  artifacts:
    paths:
      - $ARTIFACTS_PATTERN

deploy:
  script: # something like this. Not sure if scp supports glob patterns
    - rsync -a -m --include="$ARTIFACTS_PATTERN" user@remote:~/Deploy


问:
How can I convert FutureBuilder code to StreamBuilder?
I am trying to get data from Firestore and pass that data to screen using stream. I have done this using FutureBuilder, this solution works as followed, but I need to use StreamBuilder Can anyone help me find the problem?

```<code>Future<List<Business>> list(FirebaseFirestore _firesore) async {
    CollectionReference _col = _firesore.collection('Buisiness');
    var _result = await _col.get();
    var _docs =  _result.docs;
    return List.generate(_docs.length, (index) {
      var satir = _docs[index].data();
      return Business.fromMap(satir as Map<String, dynamic>);
    });
  }
</code>```

This Code works in FutureBuilder but not StreamBuilder

```<code> StreamBuilder<List<Business>>(
          stream: _firestorelist.list(_firestore), // Error Here
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              List<Business>? data = snapshot.data;
              return ListView.builder(
                itemCount: data!.length,
                itemBuilder: (context, index) {
                  var result = data[index];
                  return ListTile(
                    title: Text(result.nereden),
                    subtitle: Text(result.nereye),
                    trailing: Text(result.fiyat),
                  );
                },
              );
            } else {
              return CircularProgressIndicator();
            }
          },
        )```
```

答:
The current method is a One-time Read method, You can get snapshots from the specific collection.

You can change the method like this and Then use it as stream in streamBuilder:

list(FirebaseFirestore _firesore) async {
    CollectionReference _col = _firesore.collection('Buisiness');
    var _result = await _col.snapshots();
    return _result;
  }
```

Body:
I am trying to get data from Firestore and pass that data to screen using stream. I have done this using FutureBuilder, this solution works as followed, but I need to use StreamBuilder Can anyone help me find the problem?

Future<List<Business>> list(FirebaseFirestore _firesore) async {
    CollectionReference _col = _firesore.collection('Buisiness');
    var _result = await _col.get();
    var _docs =  _result.docs;
    return List.generate(_docs.length, (index) {
      var satir = _docs[index].data();
      return Business.fromMap(satir as Map<String, dynamic>);
    });
  }

This Code works in FutureBuilder but not StreamBuilder

 StreamBuilder<List<Business>>(
          stream: _firestorelist.list(_firestore), // Error Here
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              List<Business>? data = snapshot.data;
              return ListView.builder(
                itemCount: data!.length,
                itemBuilder: (context, index) {
                  var result = data[index];
                  return ListTile(
                    title: Text(result.nereden),
                    subtitle: Text(result.nereye),
                    trailing: Text(result.fiyat),
                  );
                },
              );
            } else {
              return CircularProgressIndicator();
            }
          },
        )```


问:
GKE AppArmor profile is unconfined eventhough the node has it defined and working
I am trying to load an apparmor profile I created using GKE and some of the following instructions.

To apply the created app armor profile I followed this instructions:

https://cloud.google.com/container-optimized-os/docs/how-to/secure-apparmor#creating_a_custom_security_profile

which is just the apparmor parser applied to the node[s], and some follow up instructions to apply this same profile creation during restart of the node.
Basically is running the following line:

```<code>/sbin/apparmor_parser --replace --write-cache /etc/apparmor.d/no_raw_net
</code>```

and testing that a container with this profile is secured as expected.

As a second step I defined an environment variable with the apparmor profile name inside of an environment variable of the pod. As explained in here:

https://cloud.google.com/migrate/anthos/docs/troubleshooting/app-armor-profile

Basically is defining the pod in this way:

```<code>spec:
  containers:
  - image: gcr.io/my-project/my-container:v1.0.0
    name: my-container
    env:
    - name: HC_APPARMOR_PROFILE
      value: "apparmor-profile-name"
    securityContext:
      privileged: true
</code>```

Inside of the host the apparmor profile works as expected. But I cannot provide this profile.

Also tried removing the security context section of the pod that is defined as true in the documentation for gke.

Last but not least I tried with k8s pod annotation which is a feature of k8s to set a profile to a given container as explained here:

https://kubernetes.io/docs/tutorials/security/apparmor/

with this the pod looks like this:

```<code>apiVersion: v1
kind: Pod
metadata:
  name: hello-apparmor-2
  annotations:
    container.apparmor.security.beta.kubernetes.io/hello: localhost/k8s-apparmor-example-allow-write
spec:
  containers:
  - name: hello
    image: busybox
    command: [ "sh", "-c", "echo 'Hello AppArmor!' && sleep 1h" ]
</code>```

but also had no good luck to apply the given profile.

Also tried to apply user-data config as a custom metadata for the cloud-init of the node instance, so it can add also the profile I created to app armor, and double check that the creation matters is not an issue but the edition of the cluster matadata is disable post creation of the cluster, and the creation of a new cluster node with the user-data is not allowed due to the fact that user-data is reserved for the container optimized os user data that will be defined by google.

No matter what I do I always end up either having unconfined profile for the current container or "cri-containerd.apparmor.d (enforce)" depending if the security context is set to true or not...

Do you have any advice on how can I provide the given profile to a pod in GKE?

答:
As mentioned I missed the way I was naming things, but besides that I also would like to mention one more alternative: https://github.com/kubernetes-sigs/security-profiles-operator which is to work with some kubernetes CRDs that allows to integrate with apparmor, seccomp, and SELinux.

Some of the implementation like AppArmor looks like it is still in WIP at the moment of this writing and I hope this initiative moves forward.

Body:
I am trying to load an apparmor profile I created using GKE and some of the following instructions.

To apply the created app armor profile I followed this instructions:

https://cloud.google.com/container-optimized-os/docs/how-to/secure-apparmor#creating_a_custom_security_profile

which is just the apparmor parser applied to the node[s], and some follow up instructions to apply this same profile creation during restart of the node.
Basically is running the following line:

/sbin/apparmor_parser --replace --write-cache /etc/apparmor.d/no_raw_net

and testing that a container with this profile is secured as expected.

As a second step I defined an environment variable with the apparmor profile name inside of an environment variable of the pod. As explained in here:

https://cloud.google.com/migrate/anthos/docs/troubleshooting/app-armor-profile

Basically is defining the pod in this way:

spec:
  containers:
  - image: gcr.io/my-project/my-container:v1.0.0
    name: my-container
    env:
    - name: HC_APPARMOR_PROFILE
      value: "apparmor-profile-name"
    securityContext:
      privileged: true

Inside of the host the apparmor profile works as expected. But I cannot provide this profile.

Also tried removing the security context section of the pod that is defined as true in the documentation for gke.

Last but not least I tried with k8s pod annotation which is a feature of k8s to set a profile to a given container as explained here:

https://kubernetes.io/docs/tutorials/security/apparmor/

with this the pod looks like this:

apiVersion: v1
kind: Pod
metadata:
  name: hello-apparmor-2
  annotations:
    container.apparmor.security.beta.kubernetes.io/hello: localhost/k8s-apparmor-example-allow-write
spec:
  containers:
  - name: hello
    image: busybox
    command: [ "sh", "-c", "echo 'Hello AppArmor!' && sleep 1h" ]

but also had no good luck to apply the given profile.

Also tried to apply user-data config as a custom metadata for the cloud-init of the node instance, so it can add also the profile I created to app armor, and double check that the creation matters is not an issue but the edition of the cluster matadata is disable post creation of the cluster, and the creation of a new cluster node with the user-data is not allowed due to the fact that user-data is reserved for the container optimized os user data that will be defined by google.

No matter what I do I always end up either having unconfined profile for the current container or "cri-containerd.apparmor.d (enforce)" depending if the security context is set to true or not...

Do you have any advice on how can I provide the given profile to a pod in GKE?


答:
You can write your data source method as</p>
```<code>Stream<List<Business>> list(FirebaseFirestore _firesore) {
  CollectionReference _col = _firesore.collection('Buisiness');

  final _snap = _col.snapshots();

  return _snap.map((event) => event.docs
      .map<Business>((e) => Business.fromMap(e.data() as Map<String, dynamic>))
      .toList());
}
</code>```

Title: How can I convert FutureBuilder code to StreamBuilder?

Body:
You can write your data source method as

Stream<List<Business>> list(FirebaseFirestore _firesore) {
  CollectionReference _col = _firesore.collection('Buisiness');

  final _snap = _col.snapshots();

  return _snap.map((event) => event.docs
      .map<Business>((e) => Business.fromMap(e.data() as Map<String, dynamic>))
      .toList());
}


问:
Make array consecutive
i got stucked in a chalenge in codeFights.my code pass the simple test and fail in just 2 from five of hidden tests her is the chalenge instruction:

Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.

```<code>Example

For statues = [6, 2, 3, 8], the output should be
makeArrayConsecutive2(statues) = 3.

Ratiorg needs statues of sizes 4, 5 and 7.

Input/Output

[time limit] 4000ms (js)
[input] array.integer statues

An array of distinct non-negative integers.

Constraints:
1 ≤ statues.length ≤ 10,
0 ≤ statues[i] ≤ 20.

[output] integer
</code>```

The minimal number of statues that need to be added to existing statues such that it contains every integer size from an interval [L, R] (for some L, R) and no other sizes.

and here is my code :

```<code>function makeArrayConsecutive2(statues) {
 //range the table from min to max
 var rang=statues.sort();
 var some=0;
 //if the table is one element
 if(rang.length-1==0){
  return 0;

 }else{
  //if the table contain more then one element
  for(i=0;i<=rang.length-2;i++){
   //add the deference of two consecutive position -1
   //to find the number of missing numbers
   some+=(rang[i+1]-rang[i]-1);
 }
  return some;
 }
}
</code>```

答:
Solution in PHP</p>
```<code>function solution($statues) {
    return max($statues) - min($statues) - count($statues) + 1;
}
</code>```

Title: Make array consecutive

Body:
i got stucked in a chalenge in codeFights.my code pass the simple test and fail in just 2 from five of hidden tests her is the chalenge instruction:

Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.

Example

For statues = [6, 2, 3, 8], the output should be
makeArrayConsecutive2(statues) = 3.

Ratiorg needs statues of sizes 4, 5 and 7.

Input/Output

[time limit] 4000ms (js)
[input] array.integer statues

An array of distinct non-negative integers.

Constraints:
1 ≤ statues.length ≤ 10,
0 ≤ statues[i] ≤ 20.

[output] integer

The minimal number of statues that need to be added to existing statues such that it contains every integer size from an interval [L, R] (for some L, R) and no other sizes.

and here is my code :

function makeArrayConsecutive2(statues) {
 //range the table from min to max
 var rang=statues.sort();
 var some=0;
 //if the table is one element
 if(rang.length-1==0){
  return 0;

 }else{
  //if the table contain more then one element
  for(i=0;i<=rang.length-2;i++){
   //add the deference of two consecutive position -1
   //to find the number of missing numbers
   some+=(rang[i+1]-rang[i]-1);
 }
  return some;
 }
}

Body:
Solution in PHP

function solution($statues) {
    return max($statues) - min($statues) - count($statues) + 1;
}


问:
ImageMagick not letting me upload jpgs
I am running Paperclip 2.3.11 and ImageMagick 6.7.1-1.
I am uploading images to an Amazon S3 account.

If I upload a .png file it works fine, if I upload a .jpg it does not.

This is the error generated in my view when I try uploading a jpg:

```<code>3 errors prohibited this post from being saved:
  Photo /var/folders/k9/kw7hkdmx741cqrc1h6_qwc580000gp/T/stream20110817-6147-urdz8d-0.jpg is not recognized by the 'identify' command.
  Photo /var/folders/k9/kw7hkdmx741cqrc1h6_qwc580000gp/T/stream20110817-6147-urdz8d-0.jpg is not recognized by the 'identify' command.
  Photo /var/folders/k9/kw7hkdmx741cqrc1h6_qwc580000gp/T/stream20110817-6147-urdz8d-0.jpg is not recognized by the 'identify' command.
</code>```

And my log reads:

```<code>Started POST "/posts" for 127.0.0.1 at Wed Aug 17 20:35:12 -0400 2011
Processing by PostsController#create as HTML
Parameters: {"commit"=>"Create Post", "post"=>{"photo"=>#<ActionDispatch::Http::UploadedFile:0x10c64d900 @headers="Content-Disposition: form-data; name=\"post[photo]\"; filename=\"Stonehenge.jpg\"\r\nContent-Type: image/jpeg\r\n", @content_type="image/jpeg", @original_filename="Stonehenge.jpg", @tempfile=#<File:/var/folders/k9/kw7hkdmx741cqrc1h6_qwc580000gp/T/RackMultipart20110817-6147-1uad809-0>>, "title"=>"test", "description"=>"test"}, "authenticity_token"=>"V/EinZAi2NNYx7AokikTpQFkNtADNiauW5vcNGdhTug=", "utf8"=>"\342\234\223"}
[paperclip] identify -format %wx%h '/var/folders/k9/kw7hkdmx741cqrc1h6_qwc580000gp/T/stream20110817-6147-urdz8d-0.jpg[0]' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::NotIdentifiedByImageMagickError: /var/folders/k9/kw7hkdmx741cqrc1h6_qwc580000gp/T/stream20110817-6147-urdz8d-0.jpg is not recognized by the 'identify' command.>
</code>```

Has anyone encountered this before? Let me know if any other info would be helpful.

UPDATE:
Just noticed that .jpg files do upload fine on a different computer (both are Macs running 10.6/10.7 respectively). This leaves me even more lost. What could be misconfigured on my other machine?

答:
You should install JPG support for ImageMagick.

http://www.randycullom.com/chatterbox/archives/2006/12/installing_imag.html

Here is jpegsrc and other sources for ImageMagick:

http://www.imagemagick.org/download/delegates/

Title: ImageMagick not letting me upload jpgs

Body:
I am running Paperclip 2.3.11 and ImageMagick 6.7.1-1.
I am uploading images to an Amazon S3 account.

If I upload a .png file it works fine, if I upload a .jpg it does not.

This is the error generated in my view when I try uploading a jpg:

3 errors prohibited this post from being saved:
  Photo /var/folders/k9/kw7hkdmx741cqrc1h6_qwc580000gp/T/stream20110817-6147-urdz8d-0.jpg is not recognized by the 'identify' command.
  Photo /var/folders/k9/kw7hkdmx741cqrc1h6_qwc580000gp/T/stream20110817-6147-urdz8d-0.jpg is not recognized by the 'identify' command.
  Photo /var/folders/k9/kw7hkdmx741cqrc1h6_qwc580000gp/T/stream20110817-6147-urdz8d-0.jpg is not recognized by the 'identify' command.

And my log reads:

Started POST "/posts" for 127.0.0.1 at Wed Aug 17 20:35:12 -0400 2011
Processing by PostsController#create as HTML
Parameters: {"commit"=>"Create Post", "post"=>{"photo"=>#<ActionDispatch::Http::UploadedFile:0x10c64d900 @headers="Content-Disposition: form-data; name=\"post[photo]\"; filename=\"Stonehenge.jpg\"\r\nContent-Type: image/jpeg\r\n", @content_type="image/jpeg", @original_filename="Stonehenge.jpg", @tempfile=#<File:/var/folders/k9/kw7hkdmx741cqrc1h6_qwc580000gp/T/RackMultipart20110817-6147-1uad809-0>>, "title"=>"test", "description"=>"test"}, "authenticity_token"=>"V/EinZAi2NNYx7AokikTpQFkNtADNiauW5vcNGdhTug=", "utf8"=>"\342\234\223"}
[paperclip] identify -format %wx%h '/var/folders/k9/kw7hkdmx741cqrc1h6_qwc580000gp/T/stream20110817-6147-urdz8d-0.jpg[0]' 2>/dev/null
[paperclip] An error was received while processing: #<Paperclip::NotIdentifiedByImageMagickError: /var/folders/k9/kw7hkdmx741cqrc1h6_qwc580000gp/T/stream20110817-6147-urdz8d-0.jpg is not recognized by the 'identify' command.>

Has anyone encountered this before? Let me know if any other info would be helpful.

UPDATE:
Just noticed that .jpg files do upload fine on a different computer (both are Macs running 10.6/10.7 respectively). This leaves me even more lost. What could be misconfigured on my other machine?


问:
PJAX doesn't load script modules
I'm trying to incorporate javascript modules into a site that uses PJAX, e.g.:

I'm finding that when I navigate to these pages from another page in the site, the modules never load. They do load if I refresh the page. Is there a way to ensure that modules like this work with PJAX here?

答: If you use this file in one page only. call this file in the #pjax-container not outside the container. for more information check this.

Title: PJAX doesn't load script modules


问:
Slash commands only available in 1 guild ID
I've recently followed a slash command tutorial from discordjs guide. It all works, but the issue is that I am unable to have the slash commands in more than 1 server, as I have manually put the guild ID in, and cannot find a way to get the guild ID when the bot is ready. Here's the code:

const clientID = '942177936553959464';
const guildID = '936781831037157426';

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    commands.push(command.data.toJSON());
}

(async () => {
    try {
        console.log('Started refreshing application (/) commands.');

        await rest.put(
            Routes.applicationGuildCommands(clientID, guildID), // Error is at guildID, as it is not getting the actual guilds ID, just the one I set for testing.
            { body: commands },
        );

        console.log('Successfully reloaded application (/) commands.');
    } catch (error) {
        console.error(error);
    }
})();
```

答:
The way you register is a guild-specific way of registering slash commands. There are 2 routes you can take.
First - Have an array of guild IDs and loop over them and register it per guild. Something like this would work fine

const clientID = "942177936553959464";
const guilds = ["id1", "id2", "id3"];
guilds.forEach((guildID) => {
    // Register the slash commands here
});
```

Second - Register the slash commands globally(For all guilds).  Do note global commands take some time to be cached and made available by the discord API.

https://discordjs.guide/interactions/registering-slash-commands.html#global-commands

Note - The First approach should be followed while the bot is in the development stage and not in production

Body:
The way you register is a guild-specific way of registering slash commands. There are 2 routes you can take.
First - Have an array of guild IDs and loop over them and register it per guild. Something like this would work fine

const clientID = "942177936553959464";
const guilds = ["id1", "id2", "id3"];
guilds.forEach((guildID) => {
    // Register the slash commands here
});

Second - Register the slash commands globally(For all guilds).  Do note global commands take some time to be cached and made available by the discord API.

https://discordjs.guide/interactions/registering-slash-commands.html#global-commands

Note - The First approach should be followed while the bot is in the development stage and not in production


问:
Detect if there are items left to scroll in a flutter Listview
I have listview in a gridview in a flutter calendar app. I am trying to detect if a particular list view has half-visible or invisible items which need to be scrolled to be seen. If not, the user might not see that a day has an appointment/task unless they change resolution/view.

I'd like to add a little arrow, or overlay, just to warn the user there are extra items. Making the listview scrollable doesn't work well for me because then the gridview loses scrollability, unless I make the ListViews shrinkwrap, which causes its own problems.

Any help appreciated...

答:
you can use an Text to tell the user there is more contact and if the list is on end you remove that text
by using this inview_notifier_list package
and check if onListEndReached</p>


问:
Failed to register application "/". Error description: The process cannot access the file because it is being used by another process. (0x80070020)
If you are not able to run your application due to the following error:

Failed to register application "/". Error description: The process cannot access the file because it is being used by another process. (0x80070020)

答:
The error occurred because the port on which the application wants to run is currently being used by another application.
Right click on the sln file and open the file in notepad and then edit vmport and then reload the project.

below link can help you :

https://www.c-sharpcorner.com/blogs/the-process-cannot-access-the-file-because-it-is-being-used-by-another#:~:text=The%20main%20cause%20for%20this,being%20used%20by%20another%20process.