问:
How to update GitHub authentification token on Rstudio to match the new policy?
While pushing a commit to GitHub yesterday, I received an email from the GitHub team:

Basic authentication using a password to Git is deprecated and will soon no longer work. Visit https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more information around suggested workarounds and removal dates.

Thanks,
The GitHub Team

I don't understand a word of the help page...
I did create a more secure access token a few months ago when they first announced the change in authentification, and entered it in the terminal of my mac. I thought that would be it. My question is: how to update an Rstudio session created when token weren't necessary to match the new access-token policy?

Thanks in advance for your help,

Rosalie

答:
The solutions above didn't work for me. I had to use:

credentials::set_github_pat("my_pat")
```

Then when prompted by the pop-up boxes I had to use my PAT as my password.

Body:
The solutions above didn't work for me. I had to use:

credentials::set_github_pat("my_pat")

Then when prompted by the pop-up boxes I had to use my PAT as my password.


来源: stackexchange

问:
pip is visible in system (C disk) but not for user
I installed pip and it is visible from C: disk. Command     C:\>pip -v shows version, etc.

But if I get error if I try to reach pip from one directory deeper (C:\Users):

```<code>C:\Users>pip -v
Traceback (most recent call last):
  File "C:\lib\runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Scripts\pip.exe\__main__.py", line 4, in <module>
ModuleNotFoundError: No module named 'pip'
</code>```

My environment variables (some of them):

Overall I want to be able to use pip in VS Code for packages installation.

答:
I solved it by running this command:

```<code>python -m ensurepip
</code>```

It ensured that python and its packages (therefore also pip) is included in PATH.

Now C:\Users>pip -v also works!

ContentLicense: CC BY-SA 4.0

Body:
I installed pip and it is visible from C: disk. Command     C:\>pip -v shows version, etc.

But if I get error if I try to reach pip from one directory deeper (C:\Users):

C:\Users>pip -v
Traceback (most recent call last):
  File "C:\lib\runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Scripts\pip.exe\__main__.py", line 4, in <module>
ModuleNotFoundError: No module named 'pip'

My environment variables (some of them):

Overall I want to be able to use pip in VS Code for packages installation.

Body:
I solved it by running this command:

python -m ensurepip

It ensured that python and its packages (therefore also pip) is included in PATH.

Now C:\Users>pip -v also works!


问:
Changing the request URL before request getting matched with the location or server
I'm using k8s cluster with nginx-ingress controller. I have a requirement to add a text to request URL before the request matches with server and location.

Ex: Request: abc.com/access/endpoint

I have an ingress that has host as abc.com and path as /access/(*.). So when the request is made the request matches with the ingress and directs the request to the service endpoint as expected.

But what I need is to change the request to abc.com/access/newtext/endpoint and then make it available for ingress. Is it possible to achieve this?

Thanks on advance

答:
I have not tried it, but would the rewrite annotation help you?

https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#rewrite

In some scenarios the exposed URL in the backend service differs from the specified path in the Ingress rule. Without a rewrite any request will return 404. Set the annotation nginx.ingress.kubernetes.io/rewrite-target to the path expected by the service.

If the Application Root is exposed in a different path and needs to be redirected, set the annotation nginx.ingress.kubernetes.io/app-root to redirect requests for /.


问:
R Code package markovchain doesn't properly recognize numbers as states
I have checked the documentation of the package and found an example of how they fitted a DTMC on data.frame objects using the following code:

```<code>library(holson)
data(holson)
singleMc<-markovchainFit(data=holson[,2:12],name="holson")
</code>```

The data I apply the code to is structured essentially in the same way as the holson data only that there are 10 states. Additionally, the numbers in my excel file are indeed integers and not class characters. These states are the numbers 1 to 10. When I run the code on my data it gives me a transition matrix where the states are listed as followed in (1,10,2,3,4,5,6,7,8,9). Thus in the matrix the state following 1 is 10.

It appears to me that R Studio thinks that the character 10 is between 1 and 2? (Like lexicographic sorting?) How can I fix this issue and have the package recognize 10 as the character following 9?

EDIT:
Here is an example

```<code>library(markovchain)
set.seed(12)
Test <- data.frame(entity = LETTERS[1:100],
                   Time1 = round(runif(n = 100, min = 1, max = 10)),
                   Time2 = round(runif(n = 100, min = 1, max = 10)),
                   Time3 = round(runif(n = 100, min = 1, max = 10)))
Test_Fit <- markovchainFit(data=Test[,2:4] , name="Test_FIT")
Est_Test_Fit <- Test_Fit$estimate
Est_Test_Fit@transitionMatrix
</code>```

答:
I am not familiar with the markovchain package.  I tend to use r4jags.

Reading the markovchain manual, it seems that a call to markovchainFit should be preceded by a call to createSequenceMatrix.  (See the example code on page 11 of the manual.)  The first parameter of createSequenceMatrix is "... a n x n matrix or a character vector or a list".  Thus, contrary to my comment above, it seems that markovchain expects the state labels to be character rather than numeric.  Given your question, it seems that your states are ordered rather than merely categorical, so the ordering '"1"', `"10", '"2"' is a problem for you.

The solution would be to convert your numeric state labels to character before calling markovChainFit/createSequenceMatrix.  Here are two possible ways of doing this:

```<code>charState <- LETTERS[state]
</code>```

which will give you state labels of "A" to "J".  or

```<code>charState <- sprintf("%02i", state)
</code>```

which produces "01", "02", ... , "10".

By the way, did you run your test code before adding it to your question?  Rows 27 to 100 of your Test dataframe have entity equal to NA, which I suspect is not what you intended.  In addition, I suspect your columns Time1 to Time3 are misnamed because I believe they contain states of the process rather than times at which the process(es) was/were in a given state.

Body:
I have checked the documentation of the package and found an example of how they fitted a DTMC on data.frame objects using the following code:

library(holson)
data(holson)
singleMc<-markovchainFit(data=holson[,2:12],name="holson")

The data I apply the code to is structured essentially in the same way as the holson data only that there are 10 states. Additionally, the numbers in my excel file are indeed integers and not class characters. These states are the numbers 1 to 10. When I run the code on my data it gives me a transition matrix where the states are listed as followed in (1,10,2,3,4,5,6,7,8,9). Thus in the matrix the state following 1 is 10.

It appears to me that R Studio thinks that the character 10 is between 1 and 2? (Like lexicographic sorting?) How can I fix this issue and have the package recognize 10 as the character following 9?

EDIT:
Here is an example

library(markovchain)
set.seed(12)
Test <- data.frame(entity = LETTERS[1:100],
                   Time1 = round(runif(n = 100, min = 1, max = 10)),
                   Time2 = round(runif(n = 100, min = 1, max = 10)),
                   Time3 = round(runif(n = 100, min = 1, max = 10)))
Test_Fit <- markovchainFit(data=Test[,2:4] , name="Test_FIT")
Est_Test_Fit <- Test_Fit$estimate
Est_Test_Fit@transitionMatrix

Body:
I am not familiar with the markovchain package.  I tend to use r4jags.

Reading the markovchain manual, it seems that a call to markovchainFit should be preceded by a call to createSequenceMatrix.  (See the example code on page 11 of the manual.)  The first parameter of createSequenceMatrix is "... a n x n matrix or a character vector or a list".  Thus, contrary to my comment above, it seems that markovchain expects the state labels to be character rather than numeric.  Given your question, it seems that your states are ordered rather than merely categorical, so the ordering '"1"', `"10", '"2"' is a problem for you.

The solution would be to convert your numeric state labels to character before calling markovChainFit/createSequenceMatrix.  Here are two possible ways of doing this:

charState <- LETTERS[state]

which will give you state labels of "A" to "J".  or

charState <- sprintf("%02i", state)

which produces "01", "02", ... , "10".

By the way, did you run your test code before adding it to your question?  Rows 27 to 100 of your Test dataframe have entity equal to NA, which I suspect is not what you intended.  In addition, I suspect your columns Time1 to Time3 are misnamed because I believe they contain states of the process rather than times at which the process(es) was/were in a given state.


问:
How to handle the cllocationmanager and google api?
Iam developing one applciation.In that i use the google places api for getting the information about any location.ANd i used the cllocation manager for finding the specific location latitude and longitude values.And i pass that updated latitude and longitude values to that google api url in the cllocationmanager delegate method..After getting that values directly establish the connection with that url in the same cllocationmanager delegate menthod.it called every time and remaining nsurlconnection methods didn't give the result.So i want to get the updated location values at the first time and establish the connection and stop the location updated values process.So please tell me how to correct this one.Or is this right way or not for getting the current location details.Is there any other way for getting the current location details.</p>

答:
Use this code</p>

```<code>[locationmanager stopUpdating];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use this code

[locationmanager stopUpdating];


问:
Clone a List, Map or Set in Dart
Coming from a Java background: what is the recommended way to "clone" a Dart List, Map and Set?

答:
Method-1: Recommended

For cloning a multi-dimensional (nested) List or Map, use the
json.decode() and json.encode()

```<code>List newList = json.decode(json.encode(oldList));
Map newMap = json.decode(json.encode(oldList));
</code>```

Method-2:

```<code>List newList = [...oldList];
Map newMap = {...oldMap}
</code>```

Method-3:

```<code>List newList = List.from(oldList);
Map newMap = Map.from(oldMap);
</code>```

Method-4:

```<code>List newList = List.of(oldList);
Map newMap = Map.of(oldMap);
</code>```

Method-5:

```<code>List newList = List.unmodifiable(oldList);
Map newMap = Map.unmodifiable(oldMap);
</code>```

For more References:

https://www.kindacode.com/article/how-to-clone-a-list-or-map-in-dart-and-flutter/
https://coflutter.com/dart-flutter-how-to-clone-copy-a-list/

Title: Clone a List, Map or Set in Dart

Body:
Method-1: Recommended

For cloning a multi-dimensional (nested) List or Map, use the
json.decode() and json.encode()

List newList = json.decode(json.encode(oldList));
Map newMap = json.decode(json.encode(oldList));

Method-2:

List newList = [...oldList];
Map newMap = {...oldMap}

Method-3:

List newList = List.from(oldList);
Map newMap = Map.from(oldMap);

Method-4:

List newList = List.of(oldList);
Map newMap = Map.of(oldMap);

Method-5:

List newList = List.unmodifiable(oldList);
Map newMap = Map.unmodifiable(oldMap);

For more References:

https://www.kindacode.com/article/how-to-clone-a-list-or-map-in-dart-and-flutter/
https://coflutter.com/dart-flutter-how-to-clone-copy-a-list/


问:
$lookup multi-level nesting array of objects in mongodb4.0
this is my local document
Class

```<code>{
    "_id":1,
    "array1": [{
        "name": "chenzhe",
        "_id": "1-1",
        "array1": [{
            "_id": "1-1-1",
            "name": "fbb",
            "nest_nest_array": [{
                "name": "ym",
                "_id": "1-1-1-1"
            },
            {
                "name": "ym",
                "_id": "1-1-1-2"
            }]
        }]
    },
    {
        "name": "gw",
        "_id": "1-2",
        "nestArray": [{
            "_id": "1-2-1",
            "name": "fbb",
            "nest_nest_array": [{
                "name": "ym",
                "_id": "1-2-1-1"
            }]
        }]
    }
]
}
</code>```

this is foreign collection documents
Person

```<code>{
  _id:"1",
  name:"chenzhe"
}
{
 _id:"2",
 name:"gw"
}
{
_id:"3",
name:"fbb"
},
{
 _id:"4",
 name:"ym"
}
</code>```

my document have multi-level nest array of objects . I want to $lookup pipeline another collection. The results are in their respective arrays

UPDATE:
What I do now is use $unwind first. then use $lookup pipeline.then use $addFields

```<code>{
  "array1.array1.array1.foreignarray":"$nest_nest_Array",
  "array1.array1.foreignarray":"$nest_Array",
  "array1.foreignarray":"$array"
}
</code>```

But I don't know how to assemble the documents back like

```<code>{
    "_id":1,
    "array1": [{
        "name": "chenzhe",
        "_id": "1-1",
        "foreignArray":[
            {
                "_id":"1",
                "name":"chenzhe"
            }
        ],
        "array1": [{
            "_id": "1-1-1",
            "name": "fbb",
            "foreignArray":[{
                "_id":"3",
                "name":"fbb"
            }],
            "array1": [{
                "name": "ym",
                "_id": "1-1-1-1",
                "foreignArray":[
                    {
                        "_id":"4",
                        "name":"ym"
                    }
                ]
            },
            {
                "name": "ym",
                "_id": "1-1-1-2",
                "foreignArray":[
                    {
                        "_id":"4",
                        "name":"ym"
                    }
                ]
            }]
        }]
    }
]
}
</code>```

答:
```<code>[{$unwind: {
  path: "$array1",
}}, {$unwind: {
  path: "$array1.nestArray",
}}, {$unwind: {
  path: "$array1.nestArray.nest_nest_array",
}}, {$lookup: {
  from: 'nestArray1',
  let:{array1Name:"$array1.nestArray.nest_nest_array.name"},
  pipeline:[
    {"$match":{
      "$expr":{
        "$eq":["$$array1Name","$name"]
      }
    }}
    ],
    as:"nest_nest_Array"
}}, {$lookup: {
  from: 'nestArray1',
  let:{array2Name:"$array1.nestArray.nestName"},
  pipeline:[{
    "$match":{
      "$expr":{
        "$eq":["$$array2Name","$name"]
      }
    }
  }],
  as:"nest_Array"
}}, {$lookup: {
  from: 'nestArray1',
  let:{array3Name:"$array1.name"},
  pipeline:[{
    "$match":{
      "$expr":{
        "$eq":["$$array3Name","$name"]
      }
    }
  }],
  as:"array"
}}, {$addFields: {
  "array1.nestArray.nest_nest_array.foreignarray":"$nest_nest_Array",
  "array1.nestArray.foreignarray":"$nest_Array",
  "array1.foreignarray":"$array"
}}, {$group: {
  _id: "$array1.nestArray._id",
  nest_Array:{$push:"$array1.nestArray.nest_nest_array"},
  root:{"$push":"$$ROOT"}
}}, {$addFields: {
  "root.array1.nestArray.nest_nest_array":"$nest_Array"
}}, {$replaceRoot: {
  newRoot: {$arrayElemAt:["$root",0]}
}}, {$group: {
  _id: "$array1._id",
  nest_Array:{$push:"$array1.nestArray"},
  root:{"$push":"$$ROOT"}
}}, {$addFields: {
  "root.array1.nestArray":"$nest_Array"
}}, {$replaceRoot: {
  newRoot: {$arrayElemAt:["$root",0]}
}}, {$group: {
  _id: "$_id",
  nest_Array:{$push:"$array1"},
  root:{"$push":"$$ROOT"}
}}, {$addFields: {
  "root.array1":"$nest_Array"
}}, {$replaceRoot: {
  newRoot: {$arrayElemAt:["$root",0]}
}}, {$project: {
  array:0,
  "nest_Array":0,
  "nest_nest_Array":0
}}]
</code>```

Body:
this is my local document
Class

{
    "_id":1,
    "array1": [{
        "name": "chenzhe",
        "_id": "1-1",
        "array1": [{
            "_id": "1-1-1",
            "name": "fbb",
            "nest_nest_array": [{
                "name": "ym",
                "_id": "1-1-1-1"
            },
            {
                "name": "ym",
                "_id": "1-1-1-2"
            }]
        }]
    },
    {
        "name": "gw",
        "_id": "1-2",
        "nestArray": [{
            "_id": "1-2-1",
            "name": "fbb",
            "nest_nest_array": [{
                "name": "ym",
                "_id": "1-2-1-1"
            }]
        }]
    }
]
}

this is foreign collection documents
Person

{
  _id:"1",
  name:"chenzhe"
}
{
 _id:"2",
 name:"gw"
}
{
_id:"3",
name:"fbb"
},
{
 _id:"4",
 name:"ym"
}

my document have multi-level nest array of objects . I want to $lookup pipeline another collection. The results are in their respective arrays

UPDATE:
What I do now is use $unwind first. then use $lookup pipeline.then use $addFields

{
  "array1.array1.array1.foreignarray":"$nest_nest_Array",
  "array1.array1.foreignarray":"$nest_Array",
  "array1.foreignarray":"$array"
}

But I don't know how to assemble the documents back like

{
    "_id":1,
    "array1": [{
        "name": "chenzhe",
        "_id": "1-1",
        "foreignArray":[
            {
                "_id":"1",
                "name":"chenzhe"
            }
        ],
        "array1": [{
            "_id": "1-1-1",
            "name": "fbb",
            "foreignArray":[{
                "_id":"3",
                "name":"fbb"
            }],
            "array1": [{
                "name": "ym",
                "_id": "1-1-1-1",
                "foreignArray":[
                    {
                        "_id":"4",
                        "name":"ym"
                    }
                ]
            },
            {
                "name": "ym",
                "_id": "1-1-1-2",
                "foreignArray":[
                    {
                        "_id":"4",
                        "name":"ym"
                    }
                ]
            }]
        }]
    }
]
}


问:
Import Email Addresses and Update the User's manager
I have a csv file that contains 2 columns. The first is the AD user's email and the second is that AD User's Manager's email.
I need a script that will read the csv file and update the User's Manager in AD based on the Manager's email in the csv.

Any help is greatly appreciated!

答:
So the first thing you want to do is list the steps you want to take.

Read and use the CSV

Get the AD User

Get the Manager

Set the Manager

Combine the scripts

Google for 'powershell csv'. You will find the Import-CSV command. Then you will have to test out what you can do with the CSV.

Google for 'Get AD User'. You will find the Get-ADUser command.

The manager must also be present in AD and will use the same command as in step 2.

Google for 'set manager AD'. You will find that it is possible with the Set-ADUser command.

Now you will have to combine and use some logic to put the pieces together

There are a lot of different ways to achieve it, but here is a simple example:

```<code>$csvFile = Import-CSV -Path "C:\Temp\ad_managers.csv" -Delimiter ";" # Check what delimiter you use comma or semicolon

foreach($user in $csvFile){
    $usersEmail = $user.userEmail # Note that userEmail is the column header name
    $managersEmail = $user.managerEmail # Note that managerEmail is the column header name
    if($usersEmail -and $managersEmail){
        $adUser = $false
        $adManager = $false
        try{
            $adUser = Get-ADUser -Filter {Emailaddress -eq $usersEmail} -Properties manager
            $adManager = Get-ADUser -Filter {Emailaddress -eq $managersEmail}
        }catch{
            Write-Host "Error while searching for user, error: $_" -ForegroundColor Red
            break
        }
        if($adUser -and $adManager){
            try{
                Write-Host "Setting manager: $($adManager.Name) for user: $($adManager.Name)"
                Set-ADUser -Identity $adUser.objectGUID.Guid -Manager $adManager.objectGuid.Guid -Confirm:$false -WhatIf # What if will show what it would do without actually doing it
            }catch{
                Write-Host "Error while setting manager: $($adManager.Name) for user: $($adManager.Name), error: $_" -ForegroundColor Red
                break
            }
        }else{
            Write-Host "Not all mandatory values found. User: $usersEmail. Manager: $managersEmail." -ForegroundColor Yellow
        }
    }
}
</code>```

Make sure to try and understand each part and Google for additional logic and explanation!

Body:
So the first thing you want to do is list the steps you want to take.

Read and use the CSV

Get the AD User

Get the Manager

Set the Manager

Combine the scripts

Google for 'powershell csv'. You will find the Import-CSV command. Then you will have to test out what you can do with the CSV.

Google for 'Get AD User'. You will find the Get-ADUser command.

The manager must also be present in AD and will use the same command as in step 2.

Google for 'set manager AD'. You will find that it is possible with the Set-ADUser command.

Now you will have to combine and use some logic to put the pieces together

There are a lot of different ways to achieve it, but here is a simple example:

$csvFile = Import-CSV -Path "C:\Temp\ad_managers.csv" -Delimiter ";" # Check what delimiter you use comma or semicolon

foreach($user in $csvFile){
    $usersEmail = $user.userEmail # Note that userEmail is the column header name
    $managersEmail = $user.managerEmail # Note that managerEmail is the column header name
    if($usersEmail -and $managersEmail){
        $adUser = $false
        $adManager = $false
        try{
            $adUser = Get-ADUser -Filter {Emailaddress -eq $usersEmail} -Properties manager
            $adManager = Get-ADUser -Filter {Emailaddress -eq $managersEmail}
        }catch{
            Write-Host "Error while searching for user, error: $_" -ForegroundColor Red
            break
        }
        if($adUser -and $adManager){
            try{
                Write-Host "Setting manager: $($adManager.Name) for user: $($adManager.Name)"
                Set-ADUser -Identity $adUser.objectGUID.Guid -Manager $adManager.objectGuid.Guid -Confirm:$false -WhatIf # What if will show what it would do without actually doing it
            }catch{
                Write-Host "Error while setting manager: $($adManager.Name) for user: $($adManager.Name), error: $_" -ForegroundColor Red
                break
            }
        }else{
            Write-Host "Not all mandatory values found. User: $usersEmail. Manager: $managersEmail." -ForegroundColor Yellow
        }
    }
}

Make sure to try and understand each part and Google for additional logic and explanation!


问:
Loop through each div of containers and compare the height on the base of index number
I am trying to loop through 2 main divs and their child divs too. Here is the code sample:

```<code><div class="containers">
    <div class="columns">Content 1</div>
    <div class="columns">Content 2</div>
    <div class="columns">Content 3</div>
</div>
<div class="containers">
    <div class="columns">Content 1</div>
    <div class="columns">Content 2</div>
    <div class="columns">Content 3</div>
</div>
</code>```

Applied the following jQuery code:

```<code>jQuery(".containers").each(function() {
    jQuery(this).find(".columns").each(function(index) {
       var colHeight = jQuery(this).outerHeight();
       console.log("Current index is " + index);
    });
});
</code>```

I'm getting index as per required: 0 1 2 0 1 2. How can I compare now the height of columns which are on index 0 and apply max height to both after compare? and same with next index 1, 2 and so on.

答:
I reverted into JavaScript for the most part. I find that having a composition of smaller functions to handle a few tasks easier to organize and debug. In the example below, all six .col are assigned a random height from 100px to 500px. Then each .box was separately iterated twice: once to get the heights of each .col and once to target each .col to set them to max height according to their shared index.

const ranRng = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

$('.col').each(function() {
  let h = ranRng(100, 500);
  $(this).height(h);
  $(this)[0].innerHTML += `<p>Original Height: ${h}px</p>`;
});

const getH = (node, n = true) => {
  if (n === true) {
    return [...node.children];
  }
  return [...node.children].map(n => $(n).height());
};

const AB = document.querySelectorAll('.box');

const maxH = (A, B) => {
  let a = getH(A, false);
  let b = getH(B, false);
  let c = a.map((h, i) => Math.max(h, b[i]));
  let d = getH(A);
  let e = getH(B);
  c.forEach((max, idx) => {
   $(d[idx]).height(max);
   $(e[idx]).height(max);
   d[idx].innerHTML += `<p>New Height: ${max}px</p>`;
   e[idx].innerHTML += `<p>New Height: ${max}px</p>`;
  });
};

maxH(AB[0], AB[1]);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box {display:flex;}
.col {border:1px solid #000}</code>```

Content 1

Content 2

Content 3

Content 1

Content 2

Content 3

```

Body:
I am trying to loop through 2 main divs and their child divs too. Here is the code sample:

Content 1

Content 2

Content 3

Content 1

Content 2

Content 3

Applied the following jQuery code:

jQuery(".containers").each(function() {
    jQuery(this).find(".columns").each(function(index) {
       var colHeight = jQuery(this).outerHeight();
       console.log("Current index is " + index);
    });
});

I'm getting index as per required: 0 1 2 0 1 2. How can I compare now the height of columns which are on index 0 and apply max height to both after compare? and same with next index 1, 2 and so on.

Body:
I reverted into JavaScript for the most part. I find that having a composition of smaller functions to handle a few tasks easier to organize and debug. In the example below, all six .col are assigned a random height from 100px to 500px. Then each .box was separately iterated twice: once to get the heights of each .col and once to target each .col to set them to max height according to their shared index.

const ranRng = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

$('.col').each(function() {
  let h = ranRng(100, 500);
  $(this).height(h);
  $(this)[0].innerHTML += `<p>Original Height: ${h}px</p>`;
});

const getH = (node, n = true) => {
  if (n === true) {
    return [...node.children];
  }
  return [...node.children].map(n => $(n).height());
};

const AB = document.querySelectorAll('.box');

const maxH = (A, B) => {
  let a = getH(A, false);
  let b = getH(B, false);
  let c = a.map((h, i) => Math.max(h, b[i]));
  let d = getH(A);
  let e = getH(B);
  c.forEach((max, idx) => {
   $(d[idx]).height(max);
   $(e[idx]).height(max);
   d[idx].innerHTML += `<p>New Height: ${max}px</p>`;
   e[idx].innerHTML += `<p>New Height: ${max}px</p>`;
  });
};

maxH(AB[0], AB[1]);

.box {display:flex;}
.col {border:1px solid #000}

<div class="box">
  <div class="col">Content 1</div>
  <div class="col">Content 2</div>
  <div class="col">Content 3</div>
</div>
<div class="box">
  <div class="col">Content 1</div>
  <div class="col">Content 2</div>
  <div class="col">Content 3</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
HTML tag inside JavaScript
I am trying to use some HTML tag inside JavaScript, but the HTML tag does not work. How can U use an HTML tag inside JavaScript? I wanted to use h1 but did not work.

if (document.getElementById('number1').checked) {

Hello member

}
```

答:
JavaScript is a scripting language, not a HTMLanguage type. It is mainly to do process at background and it needs document.write to display things on browser.
Also if your document.write exceeds one line, make sure to put concatenation + at the end of each line.

Example

```<code><script type="text/javascript">
if(document.getElementById('number1').checked) {
document.write("<h1>Hello" +
"member</h1>");
}
</script>
</code>```

Title: HTML tag inside JavaScript

Body:
JavaScript is a scripting language, not a HTMLanguage type. It is mainly to do process at background and it needs document.write to display things on browser.
Also if your document.write exceeds one line, make sure to put concatenation + at the end of each line.

Example

<script type="text/javascript">
if(document.getElementById('number1').checked) {
document.write("<h1>Hello" +
"member</h1>");
}
</script>


问:
Can not use bs4 even after installing bs4 in python
I install beautifulsoup and tried to use bs4 in VScode. I check the IDLE  where I can find the beautifulsoup but when I try to import in my vscode it is not running here is the picture

I am learning python and I am trying to solve this problem for the last 2 days. Please help me to solve this problem. I check this problem elsewhere and the solution over there did not work

答:
A general good thing to do is creating a virtual environment for managing python packages.

You can then use the virtual environment in VSCode as the python extension can auto-detect them/let you choose one:

Hope this can help you solve your dependency problem.

EDIT: as pointed out in a comment the content is links only here, I add the basics as to what you can do to manage venvs.

On unix-like systems in python3 (you may need to install an OS package to get the venv package, e.g. on Ubuntu sudo apt install python3-venv) you can use the following command to create a venv in the dir .venv:

```<code>python3 -m venv .venv
</code>```

Then you need to use the new venv, on Unix like OSes to activate the previously created .venv you use:

```<code>source .venv/bin/activate
</code>```

On windows you run the script:

```<code>./.venv/Scripts/activate
</code>```

Then you can install your dependencies in the venv, in the case of bs4:

```<code>pip install beautifulsoup4
</code>```

And then you can use the venv in VSCode. If you have the python extension VSCode will auto detect venvs in your current workdir. If it does not use ctrl + shift + P to open the command palette and then search for "Python: select interpreter", then give the path to the python binary in your venv e.g. ".venv/bin/python" or for Windows ".venv/Scripts/python.exe"

Body:
A general good thing to do is creating a virtual environment for managing python packages.

You can then use the virtual environment in VSCode as the python extension can auto-detect them/let you choose one:

Hope this can help you solve your dependency problem.

EDIT: as pointed out in a comment the content is links only here, I add the basics as to what you can do to manage venvs.

On unix-like systems in python3 (you may need to install an OS package to get the venv package, e.g. on Ubuntu sudo apt install python3-venv) you can use the following command to create a venv in the dir .venv:

python3 -m venv .venv

Then you need to use the new venv, on Unix like OSes to activate the previously created .venv you use:

source .venv/bin/activate

On windows you run the script:

./.venv/Scripts/activate

Then you can install your dependencies in the venv, in the case of bs4:

pip install beautifulsoup4

And then you can use the venv in VSCode. If you have the python extension VSCode will auto detect venvs in your current workdir. If it does not use ctrl + shift + P to open the command palette and then search for "Python: select interpreter", then give the path to the python binary in your venv e.g. ".venv/bin/python" or for Windows ".venv/Scripts/python.exe"


问:
java.lang.UnsatisfiedLinkError after changing minSdkVersion
After changing minSdkVersion from 21 to 24, i'm receiving exception:

```<code>java.lang.UnsatisfiedLinkError: dalvik.system.DexClassLoader[DexPathList[[dex file "/data/user/0/com.test.testprint/files/nepcore.dex"],nativeLibraryDirectories=[/data/app/com.test.testprint-2/lib/arm, /data/resource/lib, /vendor/lib, /system/lib]]] couldn't find "libDeviceConfig.so"
</code>```

After switching back to minSdk 21, everything back to work.

I also tried to add ndk filters, was not helpful :(

Can anybody help to understand how this exception connected with minSdkVersion?

答:
Was needed to add one line in manifest file, inside application section :)</p>
```<code><application
  ...
android:extractNativeLibs="true">
</code>```

Body:
After changing minSdkVersion from 21 to 24, i'm receiving exception:

java.lang.UnsatisfiedLinkError: dalvik.system.DexClassLoader[DexPathList[[dex file "/data/user/0/com.test.testprint/files/nepcore.dex"],nativeLibraryDirectories=[/data/app/com.test.testprint-2/lib/arm, /data/resource/lib, /vendor/lib, /system/lib]]] couldn't find "libDeviceConfig.so"

After switching back to minSdk 21, everything back to work.

I also tried to add ndk filters, was not helpful :(

Can anybody help to understand how this exception connected with minSdkVersion?

Body:
Was needed to add one line in manifest file, inside application section :)

<application
  ...
android:extractNativeLibs="true">


问:
MultiHeadAttention attention_mask [Keras, Tensorflow] example
I am struggling to mask my input for the MultiHeadAttention Layer. I am using the Transformer Block from Keras documentation with self-attention. I could not find any example code online so far and would appreciate if someone could give me a code snippet.

The transformer block from this page:

```<code>class TransformerBlock(layers.Layer):
    def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1):
        super(TransformerBlock, self).__init__()
        self.att = layers.MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim)
        self.ffn = keras.Sequential(
            [layers.Dense(ff_dim, activation="relu"), layers.Dense(embed_dim),]
        )
        self.layernorm1 = layers.LayerNormalization(epsilon=1e-6)
        self.layernorm2 = layers.LayerNormalization(epsilon=1e-6)
        self.dropout1 = layers.Dropout(rate)
        self.dropout2 = layers.Dropout(rate)

    def call(self, inputs, training):
        attn_output = self.att(inputs, inputs)
        attn_output = self.dropout1(attn_output, training=training)
        out1 = self.layernorm1(inputs + attn_output)
        ffn_output = self.ffn(out1)
        ffn_output = self.dropout2(ffn_output, training=training)
        return self.layernorm2(out1 + ffn_output)
</code>```

The documentation for masking one can find under this link:

attention_mask: a boolean mask of shape [B, T, S], that prevents
attention to certain positions. The boolean mask specifies which query
elements can attend to which key elements, 1 indicates attention and 0
indicates no attention. Broadcasting can happen for the missing batch
dimensions and the head dimension.

The only thing, I could get running is a mask created outside of the layer class as numpy array:

```<code>mask = np.ones((observations, sequence_length, sequence_length))
mask[X[:observations,:,0]==0]=0
</code>```

Then input while calling the layer, with the only change in the transformer block being:

```<code>def call(self, inputs, mask, training):
    attn_output = self.att(inputs, inputs, attention_mask=mask)
</code>```

However, this does of course not work when given a batch_size while fitting and does only work for 5 observations with my memory, so it doesn't make any sense.
Apart from that, I don't think this is masking the input properly - In general I am quite confused about how to mask, given the shape of the attention_mask (observations, sequence_length, sequence_length). The shape of my input is (observation, sequence_length, features). This input is being padded by zeros, however, when it comes to the transformer block, it has been already through an embedding layer and CNN.
I have tried various ways to write a function, which creates the mask while training with different Tensor or Keras objects. However I am running each time into errors.

I hope someone more fluent in Tensorflow/Keras will be able to provide an example.
Or somebody tells me that masking is useless given my architecture. The model is performing well. However, I hoped masking could help speed up the computing.
And it just buggs me that I cannot get my head around it.

答:
Maybe it is a little bit late, but for anyone who ends up on this post looking for a solution, this may help.

A typical scenario using a Transformer is in a NLP problem, where you have batches of sentences (let's assume that they are already tokenized for simplicity). Consider the following example:

```<code>sentences = [['Lorem', 'ipsum', 'dolor', 'sit', 'amet'], ['Integer', 'tincidunt', 'in', 'arcu', 'nec', 'fringilla', 'suscipit']]
</code>```

As you can see, we have two sentences of different lenght. In order to learn from them in a tensorflow model, we can pad the shortest one with a special token, let's say '[PAD]', and feed them into a Transformer model, as you proposed. Hence:

```<code>sentences = tf.constant([['Lorem', 'ipsum', 'dolor', 'sit', 'amet', '[PAD]', '[PAD]'], ['Integer', 'tincidunt', 'in', 'arcu', 'nec', 'fringilla', 'suscipit']])
</code>```

Also assuming that we already have a vocabulary of tokens extracted from some corpus, for example a vocabulary of 1000 tokens, we can define a StringLookup layer that converts our batch of sentences into their numerical proyections given the vocabulary. And we can specify which token is used for masking.

```<code>lookup = tf.keras.layers.StringLookup(vocabulary=vocabulary, mask_token='[PAD]')
x = lookup(sentences)
# x is a tf.Tensor([[2, 150, 19, 997, 9, 0, 0], [72, 14, 1, 1, 960, 58, 87]], shape=(2, 7), dtype=int64)
</code>```

where we can see that the [PAD] token maps to the 0 value in the vocabulary.

A typical next step is to feed this Tensor into an Embedding layer, something like this:

```<code>embedding = tf.keras.layers.Embedding(input_dim=lookup.vocabulary_size(), output_dim=64, mask_zero=True)
</code>```

The key here is the argument mask_zero. As per the documentation, this argument means:

Boolean, whether or not the input value 0 is a special "padding" value that should be masked out...

This allows the embedding layer to generate a mask for the subsequent layers to indicate which positions should be attended and which should not. This mask can be accessed via:

```<code>mask = embedding.compute_mask(sentences)
# mask is a tf.Tensor([[True, True, True, True, True, False, False], [True, True, True, True, True, True, True]], shape=(2, 7), dtype=bool)
</code>```

The tensor of the embeddings is of the form:

```<code>y = embedding(sentences)
# y is a tf.Tensor of shape=(2, 7, 64), dtype=float32)
</code>```

In order to use the mask into the MultiHeadAttention layer, the mask must be reshaped to accomplish with the shape requirements, which per the documentation is [B, T, S] where B means the batch size (2 in the example), T means the query size (7 in our example), and S means the key size (again 7 if we are using self attention). Also in a multihead attention layer we must take care of the number of heads H. The easiest way of creating a compatible mask with this input is via broadcasting:

```<code>mask = mask[:, tf.newaxis, tf.newaxis, :]
# mask is a tf.Tensor of shape=(2, 1, 1, 7), dtype=bool) -> [B, H, T, S]
</code>```

Then we can finally feed the MultiHeadAttention layer as follows:

```<code>mha = tf.keras.layers.MultiHeadAttention(num_heads=4, key_dim=64)
z = mha(y, y, attention_mask=mask)
</code>```

So in order to use, your TransformerBlock layer with a mask, you should add to the call method a mask argument, as follows:

```<code>def call(self, inputs, training, mask=None):
    attn_output = self.att(inputs, inputs, attention_mask=mask)
    ...
</code>```

And in the layer/model where you are calling the MultiHeadAttention layer, you must pass/propagate the mask that you generated with the Embedding layer.

Body:
I am struggling to mask my input for the MultiHeadAttention Layer. I am using the Transformer Block from Keras documentation with self-attention. I could not find any example code online so far and would appreciate if someone could give me a code snippet.

The transformer block from this page:

class TransformerBlock(layers.Layer):
    def __init__(self, embed_dim, num_heads, ff_dim, rate=0.1):
        super(TransformerBlock, self).__init__()
        self.att = layers.MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim)
        self.ffn = keras.Sequential(
            [layers.Dense(ff_dim, activation="relu"), layers.Dense(embed_dim),]
        )
        self.layernorm1 = layers.LayerNormalization(epsilon=1e-6)
        self.layernorm2 = layers.LayerNormalization(epsilon=1e-6)
        self.dropout1 = layers.Dropout(rate)
        self.dropout2 = layers.Dropout(rate)

    def call(self, inputs, training):
        attn_output = self.att(inputs, inputs)
        attn_output = self.dropout1(attn_output, training=training)
        out1 = self.layernorm1(inputs + attn_output)
        ffn_output = self.ffn(out1)
        ffn_output = self.dropout2(ffn_output, training=training)
        return self.layernorm2(out1 + ffn_output)

The documentation for masking one can find under this link:

attention_mask: a boolean mask of shape [B, T, S], that prevents
attention to certain positions. The boolean mask specifies which query
elements can attend to which key elements, 1 indicates attention and 0
indicates no attention. Broadcasting can happen for the missing batch
dimensions and the head dimension.

The only thing, I could get running is a mask created outside of the layer class as numpy array:

mask = np.ones((observations, sequence_length, sequence_length))
mask[X[:observations,:,0]==0]=0

Then input while calling the layer, with the only change in the transformer block being:

def call(self, inputs, mask, training):
    attn_output = self.att(inputs, inputs, attention_mask=mask)

However, this does of course not work when given a batch_size while fitting and does only work for 5 observations with my memory, so it doesn't make any sense.
Apart from that, I don't think this is masking the input properly - In general I am quite confused about how to mask, given the shape of the attention_mask (observations, sequence_length, sequence_length). The shape of my input is (observation, sequence_length, features). This input is being padded by zeros, however, when it comes to the transformer block, it has been already through an embedding layer and CNN.
I have tried various ways to write a function, which creates the mask while training with different Tensor or Keras objects. However I am running each time into errors.

I hope someone more fluent in Tensorflow/Keras will be able to provide an example.
Or somebody tells me that masking is useless given my architecture. The model is performing well. However, I hoped masking could help speed up the computing.
And it just buggs me that I cannot get my head around it.

Body:
Maybe it is a little bit late, but for anyone who ends up on this post looking for a solution, this may help.

A typical scenario using a Transformer is in a NLP problem, where you have batches of sentences (let's assume that they are already tokenized for simplicity). Consider the following example:

sentences = [['Lorem', 'ipsum', 'dolor', 'sit', 'amet'], ['Integer', 'tincidunt', 'in', 'arcu', 'nec', 'fringilla', 'suscipit']]

As you can see, we have two sentences of different lenght. In order to learn from them in a tensorflow model, we can pad the shortest one with a special token, let's say '[PAD]', and feed them into a Transformer model, as you proposed. Hence:

sentences = tf.constant([['Lorem', 'ipsum', 'dolor', 'sit', 'amet', '[PAD]', '[PAD]'], ['Integer', 'tincidunt', 'in', 'arcu', 'nec', 'fringilla', 'suscipit']])

Also assuming that we already have a vocabulary of tokens extracted from some corpus, for example a vocabulary of 1000 tokens, we can define a StringLookup layer that converts our batch of sentences into their numerical proyections given the vocabulary. And we can specify which token is used for masking.

lookup = tf.keras.layers.StringLookup(vocabulary=vocabulary, mask_token='[PAD]')
x = lookup(sentences)
# x is a tf.Tensor([[2, 150, 19, 997, 9, 0, 0], [72, 14, 1, 1, 960, 58, 87]], shape=(2, 7), dtype=int64)

where we can see that the [PAD] token maps to the 0 value in the vocabulary.

A typical next step is to feed this Tensor into an Embedding layer, something like this:

embedding = tf.keras.layers.Embedding(input_dim=lookup.vocabulary_size(), output_dim=64, mask_zero=True)

The key here is the argument mask_zero. As per the documentation, this argument means:

Boolean, whether or not the input value 0 is a special "padding" value that should be masked out...

This allows the embedding layer to generate a mask for the subsequent layers to indicate which positions should be attended and which should not. This mask can be accessed via:

mask = embedding.compute_mask(sentences)
# mask is a tf.Tensor([[True, True, True, True, True, False, False], [True, True, True, True, True, True, True]], shape=(2, 7), dtype=bool)

The tensor of the embeddings is of the form:

y = embedding(sentences)
# y is a tf.Tensor of shape=(2, 7, 64), dtype=float32)

In order to use the mask into the MultiHeadAttention layer, the mask must be reshaped to accomplish with the shape requirements, which per the documentation is [B, T, S] where B means the batch size (2 in the example), T means the query size (7 in our example), and S means the key size (again 7 if we are using self attention). Also in a multihead attention layer we must take care of the number of heads H. The easiest way of creating a compatible mask with this input is via broadcasting:

mask = mask[:, tf.newaxis, tf.newaxis, :]
# mask is a tf.Tensor of shape=(2, 1, 1, 7), dtype=bool) -> [B, H, T, S]

Then we can finally feed the MultiHeadAttention layer as follows:

mha = tf.keras.layers.MultiHeadAttention(num_heads=4, key_dim=64)
z = mha(y, y, attention_mask=mask)

So in order to use, your TransformerBlock layer with a mask, you should add to the call method a mask argument, as follows:

def call(self, inputs, training, mask=None):
    attn_output = self.att(inputs, inputs, attention_mask=mask)
    ...

And in the layer/model where you are calling the MultiHeadAttention layer, you must pass/propagate the mask that you generated with the Embedding layer.


问:
Cannot return value of "%~n1" from %1 argument (filename from path)
I'm trying to add a rule (name) to the firewall by this command in the registry (context menu):

```<code>[HKEY_CLASSES_ROOT\exefile\shell\Firewall\shell\Block\command]
@="netsh advfirewall firewall add rule name=\"%~n1\" dir=out action=block program=\"%1\""
</code>```

%1 is the path name of the program which is returned just fine.

For some reason, I cannot get the "%~n1" part right. It just returns "%~n1" instead of filename without extension.

What is wrong?

Thanks,

答:
@Squashman thanks, I ended up using cmd.exe which actually gives access to the %~n part, like this

```<code>[HKEY_CLASSES_ROOT\exefile\shell\Firewall\shell\Block\command]
@="cmd.exe /s /c for %%a in (\"%1\") do netsh advfirewall firewall add rule name=\"%%~na\" dir=out action=block program=\"%1\""
</code>```

With the benefit of being able to return more than one element with "for"...

Body:
I'm trying to add a rule (name) to the firewall by this command in the registry (context menu):

[HKEY_CLASSES_ROOT\exefile\shell\Firewall\shell\Block\command]
@="netsh advfirewall firewall add rule name=\"%~n1\" dir=out action=block program=\"%1\""

%1 is the path name of the program which is returned just fine.

For some reason, I cannot get the "%~n1" part right. It just returns "%~n1" instead of filename without extension.

What is wrong?

Thanks,

Body:
@Squashman thanks, I ended up using cmd.exe which actually gives access to the %~n part, like this

[HKEY_CLASSES_ROOT\exefile\shell\Firewall\shell\Block\command]
@="cmd.exe /s /c for %%a in (\"%1\") do netsh advfirewall firewall add rule name=\"%%~na\" dir=out action=block program=\"%1\""

With the benefit of being able to return more than one element with "for"...


问:
I can't run "npm install" after clone from github (React)
I cloned a repository from github and after that i tried to run "npm install" but i keep getting this error:

the project is still under development, so do i need to install or add anything in order to run it?

答:
Try following command:

npm install --legacy-peer-deps

It tells NPM to ignore peer deps and proceed with the installation anyway.


问:
Uninitialized Constant Error when catching Exception
I need to post articles to Wordpress via XMLRPC and catch any exceptions:

```<code>connection = XMLRPC::Client.new('mysite.com', '/xmlrpc.php', 80)
  connection.call(
  'metaWeblog.newPost',
  1,
  'user',
  'password',
  post,
  true
)
</code>```

There is en error:

```<code>C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/baseparser.rb:441:in `rescue in pull': #<NoMethodError: undefined method `[]' for nil:NilClass> (REXML::ParseException)
C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/baseparser.rb:341:in `pull'
C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/streamparser.rb:16:in `parse'
C:/Ruby192/lib/ruby/1.9.1/rexml/document.rb:204:in `parse_stream'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/parser.rb:717:in `parse'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/parser.rb:460:in `parseMethodResponse'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/client.rb:421:in `call2'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/client.rb:410:in `call'
</code>```

I successfully caught the exception with:

```<code>connection = XMLRPC::Client.new('mysite.com', '/xmlrpc.php', 80)
begin
  connection.call(
    'metaWeblog.newPost',
    1,
    'user',
    'password',
    post,
    true
  )
rescue REXML::ParseException
  puts "Skipping error"
end
</code>```

Post is OK, article is in Wordpress.

Next I needed to catch an exception about site availability (when site is not accessible)
I tried to catch the exception with:

```<code>connection = XMLRPC::Client.new('notaccessibleSite.com', '/xmlrpc.php', 80)
begin
  connection.call(
    'metaWeblog.newPost',
    1,
    'user',
    'password',
    post,
    true
  )
rescue REXML::ParseException
  puts "Skipping error"
rescue
  puts "Others errors"
end
</code>```

But this does not work:

```<code>myscript.rb:47:in `rescue in makeRpc': uninitialized constant Object::REXML (NameError)
from myscript.rb:38:in `makeRpc'
from myscript.rb:62:in `block in postContent'
from myscript.rb:58:in `each'
from myscript.rb:58:in `postContent'
from myscript.rb:71:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
</code>```

Any suggestions?

答: Seems that it can't find Object::REXML when you are testing this case, maybe a rescue NameError rescues this.

Body:
I need to post articles to Wordpress via XMLRPC and catch any exceptions:

connection = XMLRPC::Client.new('mysite.com', '/xmlrpc.php', 80)
  connection.call(
  'metaWeblog.newPost',
  1,
  'user',
  'password',
  post,
  true
)

There is en error:

C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/baseparser.rb:441:in `rescue in pull': #<NoMethodError: undefined method `[]' for nil:NilClass> (REXML::ParseException)
C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/baseparser.rb:341:in `pull'
C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/streamparser.rb:16:in `parse'
C:/Ruby192/lib/ruby/1.9.1/rexml/document.rb:204:in `parse_stream'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/parser.rb:717:in `parse'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/parser.rb:460:in `parseMethodResponse'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/client.rb:421:in `call2'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/client.rb:410:in `call'

I successfully caught the exception with:

connection = XMLRPC::Client.new('mysite.com', '/xmlrpc.php', 80)
begin
  connection.call(
    'metaWeblog.newPost',
    1,
    'user',
    'password',
    post,
    true
  )
rescue REXML::ParseException
  puts "Skipping error"
end

Post is OK, article is in Wordpress.

Next I needed to catch an exception about site availability (when site is not accessible)
I tried to catch the exception with:

connection = XMLRPC::Client.new('notaccessibleSite.com', '/xmlrpc.php', 80)
begin
  connection.call(
    'metaWeblog.newPost',
    1,
    'user',
    'password',
    post,
    true
  )
rescue REXML::ParseException
  puts "Skipping error"
rescue
  puts "Others errors"
end

But this does not work:

myscript.rb:47:in `rescue in makeRpc': uninitialized constant Object::REXML (NameError)
from myscript.rb:38:in `makeRpc'
from myscript.rb:62:in `block in postContent'
from myscript.rb:58:in `each'
from myscript.rb:58:in `postContent'
from myscript.rb:71:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `'

Any suggestions?


问:
The return of string find function in cpp
Is there a case where the string::find function return -1 ?
that code I have seen a lot while surveying a code for XML_Editor
and I can't understand the code

```<code>if(temp.find("<") == -1){}
</code>```

The above code is an example of what I mean
I hope someone help , thanks :)

答: std::string seems to return std::string::npos when it cannot find  the input value, and std::string::npos is defined to be size_t(-1), but I think it's a better practice to use if(temp.find("<") == temp.npos){}

Body:
Is there a case where the string::find function return -1 ?
that code I have seen a lot while surveying a code for XML_Editor
and I can't understand the code

if(temp.find("<") == -1){}

The above code is an example of what I mean
I hope someone help , thanks :)


问:
How to convert two vectors into dataframe (wide format)
I want to convert two vectors into a wide format dataframe. The fist vector represent the column names and the second vector the values.
Here is my reproduceable example:

```<code>vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)
</code>```

Now I want to convert these two vector into a wide format dataframe:

```<code># A tibble: 1 x 5
   Reply Reshare  Like Share Search
   <dbl>   <dbl> <dbl> <dbl>  <dbl>
1     2       1     0     4      3
</code>```

I have found some examples for the long format, but none simple solution for the wide format. Can anyone help me?

答:
You can make a named list (e.g. using setNames), followed by as.data.frame:

```<code>df <- as.data.frame(setNames(as.list(vector2), vector1))
</code>```

Note that it needs to be a list: when converting a named vector into a data.frame, R puts values into separate rows instead of columns.

Body:
I want to convert two vectors into a wide format dataframe. The fist vector represent the column names and the second vector the values.
Here is my reproduceable example:

vector1<-c("Reply","Reshare","Like","Share","Search")
vector2<-c(2,1,0,4,3)

Now I want to convert these two vector into a wide format dataframe:

# A tibble: 1 x 5
   Reply Reshare  Like Share Search
   <dbl>   <dbl> <dbl> <dbl>  <dbl>
1     2       1     0     4      3

I have found some examples for the long format, but none simple solution for the wide format. Can anyone help me?

Body:
You can make a named list (e.g. using setNames), followed by as.data.frame:

df <- as.data.frame(setNames(as.list(vector2), vector1))

Note that it needs to be a list: when converting a named vector into a data.frame, R puts values into separate rows instead of columns.


问:
Azure BlobServiceClient Error InvalidResourceName
Having problem uploading file to azure blob storage container, using azure.storage.blob for python 2.7. (I know i should use newer python, but it's a part of  big ROS application, hence not just so to upgrade it all.)

```<code>from azure.storage.blob import BlobServiceClient
...
container_name = "operationinput"
self.back_up_root = "~/backup/sql/lp/"
self.back_up_root = os.path.expanduser(self.back_up_root)
file = 'test.sql'

try:
    client = BlobServiceClient.from_connection_string(conn_str=connection_string)
    blob = client.get_blob_client(container='container_name', blob='datafile')
except Exception as err:
    print(str(err))

with open(self.back_up_root + file, "rb") as data:
    blob.upload_blob(data)
</code>```

I get the following error:

```<code>azure.core.exceptions.HttpResponseError: The specifed resource name contains invalid characters.
RequestId:3fcb6c26-101e-007e-596d-1c7d61000000
Time:2022-02-07T21:58:17.1308670Z
ErrorCode:InvalidResourceName
</code>```

All post i have found refers to people using capital letters or so, but i have:
operationinput
datafile

All should be within specification.

Any ideas?

答:
We have tried with below sample code to upload files to Azure blob storage (Container ) using SAS token , and can able to achieve it successfully.

Code sample:-

```<code>from azure.storage.blob import BlobClient

upload_file_path="C:\\Users\\Desktop\\filename"
sas_url="https://xxx.blob.core.windows.nethttps://cloudsh3D?sastoken"

client = BlobClient.from_blob_url(sas_url)

with open(upload_file_path,'rb') as data:
    client.upload_blob(data)

print("**file uploaded**")
</code>```

To generate SAS url and connection string we have selected as below:-

For more information please refer this Microsoft Documentation: Allow or disallow public read access for a storage account

Body:
Having problem uploading file to azure blob storage container, using azure.storage.blob for python 2.7. (I know i should use newer python, but it's a part of  big ROS application, hence not just so to upgrade it all.)

from azure.storage.blob import BlobServiceClient
...
container_name = "operationinput"
self.back_up_root = "~/backup/sql/lp/"
self.back_up_root = os.path.expanduser(self.back_up_root)
file = 'test.sql'

try:
    client = BlobServiceClient.from_connection_string(conn_str=connection_string)
    blob = client.get_blob_client(container='container_name', blob='datafile')
except Exception as err:
    print(str(err))

with open(self.back_up_root + file, "rb") as data:
    blob.upload_blob(data)

I get the following error:

azure.core.exceptions.HttpResponseError: The specifed resource name contains invalid characters.
RequestId:3fcb6c26-101e-007e-596d-1c7d61000000
Time:2022-02-07T21:58:17.1308670Z
ErrorCode:InvalidResourceName

All post i have found refers to people using capital letters or so, but i have:
operationinput
datafile

All should be within specification.

Any ideas?

Body:
We have tried with below sample code to upload files to Azure blob storage (Container ) using SAS token , and can able to achieve it successfully.

Code sample:-

from azure.storage.blob import BlobClient

upload_file_path="C:\\Users\\Desktop\\filename"
sas_url="https://xxx.blob.core.windows.nethttps://cloudsh3D?sastoken"

client = BlobClient.from_blob_url(sas_url)

with open(upload_file_path,'rb') as data:
    client.upload_blob(data)

print("**file uploaded**")

To generate SAS url and connection string we have selected as below:-

For more information please refer this Microsoft Documentation: Allow or disallow public read access for a storage account


答:
It would be more correct and clear to write

```<code>if(temp.find("<") == std::string::npos){}
</code>```

where npos is usually defined like ( std::string::size_type )( -1 ). In the expression in the if statement

```<code>if(temp.find("<") == -1){}
</code>```

the integer constant -1 having the type int is converted to the unsigned integer type std::string::size_type  due to the usual arithmetic conversions and as such represents the maximum value for an object of the type
std::string::size_type. This value signals that the operation was not successful.

Title: The return of string find function in cpp

Body:
It would be more correct and clear to write

if(temp.find("<") == std::string::npos){}

where npos is usually defined like ( std::string::size_type )( -1 ). In the expression in the if statement

if(temp.find("<") == -1){}

the integer constant -1 having the type int is converted to the unsigned integer type std::string::size_type  due to the usual arithmetic conversions and as such represents the maximum value for an object of the type
std::string::size_type. This value signals that the operation was not successful.


问:
Why does class() return not the same inside Map()?
Reading about R types I came across this answer where class() is used inside of Map. Now I wonder why class() returns something else if used inside Map(). See here:

```<code># Using class() without Map()
> class(matrix())
[1] "matrix" "array"

# Using class() within Map()
Map(function(x){class(x)}, matrix())
[[1]]
[1] "logical"
</code>```

Why is this happening?

EDIT

Inferred from comment and answer: To obtain the expected, i.e. same output, we need to use

```<code>Map(function(x){class(x)}, list(matrix()))
[[1]]
[1] "matrix" "array"
</code>```

答: You apply (map) all elements of an empty matrix to a function returning it's class. The class of an empty thing is NA. A vector only containing NAs is of class logical in R.

Body:
Reading about R types I came across this answer where class() is used inside of Map. Now I wonder why class() returns something else if used inside Map(). See here:

# Using class() without Map()
> class(matrix())
[1] "matrix" "array"

# Using class() within Map()
Map(function(x){class(x)}, matrix())
[[1]]
[1] "logical"

Why is this happening?

EDIT

Inferred from comment and answer: To obtain the expected, i.e. same output, we need to use

Map(function(x){class(x)}, list(matrix()))
[[1]]
[1] "matrix" "array"


问:
How to use Update statement in DBT
How to use Update statment in DBT?
We created table in Snowflake using DBT but unable to use Update query to update the same table.

Is there any other way that we can achieve this , like other ELT/ETL tools?

答:
i also run into this problem, and according this dic https://docs.getdbt.com/docs/building-a-dbt-project/building-models/configuring-incremental-models

```<code>{{
config(
    materialized='incremental',
    unique_key='payment_id',
    incremental_strategy='insert_overwrite'
)
}}

select
    ...
from orders o
    left join member m on o.member_id = m.member_id
    left join payment p on o.order_id = p.order_id
{% if is_incremental() %}
    where 1=1
        and p.gmt_updated >= (select max(payment_gmt_updated) from {{ this }})
{% endif %}
</code>```

when source table payment updated ->"dbt run" -> my sink table got update (with same payment_id) too

Title: How to use Update statement in DBT

Body:
i also run into this problem, and according this dic https://docs.getdbt.com/docs/building-a-dbt-project/building-models/configuring-incremental-models

{{
config(
    materialized='incremental',
    unique_key='payment_id',
    incremental_strategy='insert_overwrite'
)
}}

select
    ...
from orders o
    left join member m on o.member_id = m.member_id
    left join payment p on o.order_id = p.order_id
{% if is_incremental() %}
    where 1=1
        and p.gmt_updated >= (select max(payment_gmt_updated) from {{ this }})
{% endif %}

when source table payment updated ->"dbt run" -> my sink table got update (with same payment_id) too


问:
Reactfire not showing live updates made in Firestore
I'm trying to get my head around Firestore/Reactfire so am working on a basic todo app to help me grasp the concepts.

I have a screen /Screens/Mainscreen.js that loads all of a user's todo lists. There's an input at the top and a button to add the new list. This all works, except the new list isn't loaded onto the screen? If I refresh the screen, the new list is loaded then. It seems that I've missed some part of how Reactfire works, but my code seems to follow all of the demo docs so I'm not sure what I'm doing wrong.

Full WIP project here: https://github.com/warm--tape/todo/ (add a .env with Firebase credentials in if desired)

Here's my MainScreen.js:

```<code>function MainScreen({ navigation }) {

  // Logout action. Probably move.
  const auth = useAuth();
  function handleLogOut() {
    auth.signOut().then(() => navigation.replace('AuthScreen'));
  }

  // Load User
  const { status: userStatus, data: user } = useUser();
  const { uid } = user;

  // Load User Lists from Firestore
  const firestore = useFirestore();
  const listCollection = collection(firestore, 'lists');
  const userListQuery = query(listCollection, where('access', 'array-contains', uid || 0));
  const { status: listStatus, data: rawListData } = useFirestoreCollectionData(userListQuery, { idField: 'id' });

  // Load toast
  const toast = useToast();

  // Set up state
  const [isLoading, setIsLoading] = useState(true);
  const [listData, setListData] = useState([]);

  const [listToAdd, setListToAdd] = useState({ listName: '' });
  const [itemToAdd, setItemToAdd] = useState({ itemName: '' });
  const [errors, setErrors] = useState({});

  // Hide screen until loaded
  if (isLoading && userStatus === 'success' && listStatus === 'success') {
    setListData(rawListData);
    setIsLoading(false);
  }

  // Form Validator
  const validate = () => {
    // Currently no validation
    return true;
  };

  // Handle add list
  async function onAddList() {
    if (validate()) {
      delete listToAdd.NO_ID_FIELD;
      const listToAddData = { ...listToAdd, ...{ owner: uid, access: [uid] } };
      await addDoc(collection(firestore, "lists"), listToAddData).then(() => {
        toast.show({
          title: "List Added",
          placement: "bottom"
        });
        setListToAdd({ listName: '' });
      });
    } else {
      alert('Validation Failed')
    }
  };

  // Handle press on list
  function onPressListHandler(id) {
    navigation.navigate('ListDetailScreen', {listId: id})
  }

  // =========================================================================
  // Render loading spinner

  if (isLoading) {
    return (
      <LoadingSpinner />
    );
  }

  // =========================================================================
  // Render

  const listRenderItem = ({ item }) => (
    <Pressable
      onPress={()=>{onPressListHandler(item.id)}}
      borderBottomWidth="1" _dark={{borderColor: "gray.600"}} borderColor="coolGray.200" pl="4" pr="5" py="2"
    >
      <HStack space={3} justifyContent="start" alignItems="center">
        <IconButton variant="unstyled" icon={<Icon as={Ionicons} name="list-outline" size="sm" />} onPress={() => {}} />
        <Text _dark={{color: "warmGray.50"}} color="coolGray.800">
          {item.listName}
        </Text>
      </HStack>
    </Pressable>
  );

  // =========================================================================
  // Render

  return (
    <ScreenWrapper>

      <HStack>
        <FormControl isRequired isInvalid={'listName' in errors}>
          <Input placeholder="Add List..." value={listToAdd.listName} onChangeText={value => setListToAdd({ ...listToAdd, ...{ listName: value } })} />
          {'listName' in errors ? <FormControl.ErrorMessage>{errors.listName}</FormControl.ErrorMessage> : null}
        </FormControl>
        <Button onPress={() => { onAddList() }} >
          <Icon color="white" as={Ionicons} name="add" size="sm" />
        </Button>
      </HStack>

      <Divider my="3" />

      <Box>
        <FlatList
          data={listData}
          renderItem={listRenderItem}
          keyExtractor={item => item.id} />
      </Box>

      <Divider my="3" />

      <Button onPress={() => handleLogOut()}>Logout</Button>

    </ScreenWrapper>
  );
}

export default MainScreen;
</code>```

答:
Turns out I had structured my code badly, so after reviewing a few demos and the docs in depth, the following refactor works:</p>
```<code>import React, { useState } from 'react';
import { useFirestore, useUser, useFirestoreCollectionData } from 'reactfire';
import { addDoc, collection, query, where } from 'firebase/firestore';

import {
  Text,
  Button,
  FlatList,
  HStack,
  Pressable,
  Icon,
  FormControl,
  Input,
  IconButton,
  useToast,
  Divider
} from 'native-base';
import { Ionicons } from '@expo/vector-icons';
import ScreenWrapper from '../components/ScreenWrapper';
import LoadingSpinner from '../components/LoadingSpinner';

function onPressListHandler(id) {
  navigation.navigate('ListDetailScreen', { listId: id })
}

const listRenderItem = ({ item }) => (
  <Pressable
    onPress={() => { onPressListHandler(item.id) }}
    borderBottomWidth="1" _dark={{ borderColor: "gray.600" }} borderColor="coolGray.200" pl="4" pr="5" py="2"
  >
    <HStack space={3} justifyContent="start" alignItems="center">
      <IconButton variant="unstyled" icon={<Icon as={Ionicons} name="list-outline" size="sm" />} onPress={() => { }} />
      <Text _dark={{ color: "warmGray.50" }} color="coolGray.800">
        {item.listName}
      </Text>
    </HStack>
  </Pressable>
);

const ListsList = () => {

  // Load User
  const { status: userStatus, data: user } = useUser();
  const { uid } = user;

  // Load User Lists from Firestore
  const firestore = useFirestore();
  const listCollection = collection(firestore, 'lists');
  const userListQuery = query(listCollection, where('access', 'array-contains', uid || 0));
  const { status: listStatus, data: lists } = useFirestoreCollectionData(userListQuery, { idField: 'id' });

  // Loading lists
  if (userStatus === 'loading' || listStatus === 'loading') {
    return <LoadingSpinner />;
  }

  // Render
  return (
    <>
      <FlatList
        data={lists}
        renderItem={listRenderItem}
        keyExtractor={item => item.id}
      />
    </>
  );
};

function MainScreen({ navigation }) {

  // Load toast
  const toast = useToast();

  const [listToAdd, setListToAdd] = useState({ listName: '' });
  const [errors, setErrors] = useState({});

  // Form Validator
  const validate = () => {
    // None needed here.
    return true;
  };

  // Handle add list
  async function onAddList() {
    if (validate()) {
      delete listToAdd.NO_ID_FIELD;
      const listToAddData = { ...listToAdd, ...{ owner: uid, access: [uid] } };
      await addDoc(collection(firestore, "lists"), listToAddData).then(() => {
        toast.show({
          title: "List Added",
          placement: "bottom"
        });
        setListToAdd({ listName: '' });
      });
    } else {
      alert('Validation Failed')
    }
  };

  // =========================================================================
  // Render

  return (
    <ScreenWrapper>

      <HStack>
        <FormControl isRequired isInvalid={'listName' in errors}>
          <Input placeholder="Add List..." value={listToAdd.listName} onChangeText={value => setListToAdd({ ...listToAdd, ...{ listName: value } })} />
          {'listName' in errors ? <FormControl.ErrorMessage>{errors.listName}</FormControl.ErrorMessage> : null}
        </FormControl>
        <Button onPress={() => { onAddList() }} >
          <Icon color="white" as={Ionicons} name="add" size="sm" />
        </Button>
      </HStack>

      <Divider my="3" />

      <ListsList />

    </ScreenWrapper>
  );
}

export default MainScreen;
</code>```

Body:
I'm trying to get my head around Firestore/Reactfire so am working on a basic todo app to help me grasp the concepts.

I have a screen /Screens/Mainscreen.js that loads all of a user's todo lists. There's an input at the top and a button to add the new list. This all works, except the new list isn't loaded onto the screen? If I refresh the screen, the new list is loaded then. It seems that I've missed some part of how Reactfire works, but my code seems to follow all of the demo docs so I'm not sure what I'm doing wrong.

Full WIP project here: https://github.com/warm--tape/todo/ (add a .env with Firebase credentials in if desired)

Here's my MainScreen.js:

function MainScreen({ navigation }) {

  // Logout action. Probably move.
  const auth = useAuth();
  function handleLogOut() {
    auth.signOut().then(() => navigation.replace('AuthScreen'));
  }

  // Load User
  const { status: userStatus, data: user } = useUser();
  const { uid } = user;

  // Load User Lists from Firestore
  const firestore = useFirestore();
  const listCollection = collection(firestore, 'lists');
  const userListQuery = query(listCollection, where('access', 'array-contains', uid || 0));
  const { status: listStatus, data: rawListData } = useFirestoreCollectionData(userListQuery, { idField: 'id' });

  // Load toast
  const toast = useToast();

  // Set up state
  const [isLoading, setIsLoading] = useState(true);
  const [listData, setListData] = useState([]);

  const [listToAdd, setListToAdd] = useState({ listName: '' });
  const [itemToAdd, setItemToAdd] = useState({ itemName: '' });
  const [errors, setErrors] = useState({});

  // Hide screen until loaded
  if (isLoading && userStatus === 'success' && listStatus === 'success') {
    setListData(rawListData);
    setIsLoading(false);
  }

  // Form Validator
  const validate = () => {
    // Currently no validation
    return true;
  };

  // Handle add list
  async function onAddList() {
    if (validate()) {
      delete listToAdd.NO_ID_FIELD;
      const listToAddData = { ...listToAdd, ...{ owner: uid, access: [uid] } };
      await addDoc(collection(firestore, "lists"), listToAddData).then(() => {
        toast.show({
          title: "List Added",
          placement: "bottom"
        });
        setListToAdd({ listName: '' });
      });
    } else {
      alert('Validation Failed')
    }
  };

  // Handle press on list
  function onPressListHandler(id) {
    navigation.navigate('ListDetailScreen', {listId: id})
  }

  // =========================================================================
  // Render loading spinner

  if (isLoading) {
    return (
      <LoadingSpinner />
    );
  }

  // =========================================================================
  // Render

  const listRenderItem = ({ item }) => (
    <Pressable
      onPress={()=>{onPressListHandler(item.id)}}
      borderBottomWidth="1" _dark={{borderColor: "gray.600"}} borderColor="coolGray.200" pl="4" pr="5" py="2"
    >
      <HStack space={3} justifyContent="start" alignItems="center">
        <IconButton variant="unstyled" icon={<Icon as={Ionicons} name="list-outline" size="sm" />} onPress={() => {}} />
        <Text _dark={{color: "warmGray.50"}} color="coolGray.800">
          {item.listName}
        </Text>
      </HStack>
    </Pressable>
  );

  // =========================================================================
  // Render

  return (
    <ScreenWrapper>

      <HStack>
        <FormControl isRequired isInvalid={'listName' in errors}>
          <Input placeholder="Add List..." value={listToAdd.listName} onChangeText={value => setListToAdd({ ...listToAdd, ...{ listName: value } })} />
          {'listName' in errors ? <FormControl.ErrorMessage>{errors.listName}</FormControl.ErrorMessage> : null}
        </FormControl>
        <Button onPress={() => { onAddList() }} >
          <Icon color="white" as={Ionicons} name="add" size="sm" />
        </Button>
      </HStack>

      <Divider my="3" />

      <Box>
        <FlatList
          data={listData}
          renderItem={listRenderItem}
          keyExtractor={item => item.id} />
      </Box>

      <Divider my="3" />

      <Button onPress={() => handleLogOut()}>Logout</Button>

    </ScreenWrapper>
  );
}

export default MainScreen;

Body:
Turns out I had structured my code badly, so after reviewing a few demos and the docs in depth, the following refactor works:

import React, { useState } from 'react';
import { useFirestore, useUser, useFirestoreCollectionData } from 'reactfire';
import { addDoc, collection, query, where } from 'firebase/firestore';

import {
  Text,
  Button,
  FlatList,
  HStack,
  Pressable,
  Icon,
  FormControl,
  Input,
  IconButton,
  useToast,
  Divider
} from 'native-base';
import { Ionicons } from '@expo/vector-icons';
import ScreenWrapper from '../components/ScreenWrapper';
import LoadingSpinner from '../components/LoadingSpinner';

function onPressListHandler(id) {
  navigation.navigate('ListDetailScreen', { listId: id })
}

const listRenderItem = ({ item }) => (
  <Pressable
    onPress={() => { onPressListHandler(item.id) }}
    borderBottomWidth="1" _dark={{ borderColor: "gray.600" }} borderColor="coolGray.200" pl="4" pr="5" py="2"
  >
    <HStack space={3} justifyContent="start" alignItems="center">
      <IconButton variant="unstyled" icon={<Icon as={Ionicons} name="list-outline" size="sm" />} onPress={() => { }} />
      <Text _dark={{ color: "warmGray.50" }} color="coolGray.800">
        {item.listName}
      </Text>
    </HStack>
  </Pressable>
);

const ListsList = () => {

  // Load User
  const { status: userStatus, data: user } = useUser();
  const { uid } = user;

  // Load User Lists from Firestore
  const firestore = useFirestore();
  const listCollection = collection(firestore, 'lists');
  const userListQuery = query(listCollection, where('access', 'array-contains', uid || 0));
  const { status: listStatus, data: lists } = useFirestoreCollectionData(userListQuery, { idField: 'id' });

  // Loading lists
  if (userStatus === 'loading' || listStatus === 'loading') {
    return <LoadingSpinner />;
  }

  // Render
  return (
    <>
      <FlatList
        data={lists}
        renderItem={listRenderItem}
        keyExtractor={item => item.id}
      />
    </>
  );
};

function MainScreen({ navigation }) {

  // Load toast
  const toast = useToast();

  const [listToAdd, setListToAdd] = useState({ listName: '' });
  const [errors, setErrors] = useState({});

  // Form Validator
  const validate = () => {
    // None needed here.
    return true;
  };

  // Handle add list
  async function onAddList() {
    if (validate()) {
      delete listToAdd.NO_ID_FIELD;
      const listToAddData = { ...listToAdd, ...{ owner: uid, access: [uid] } };
      await addDoc(collection(firestore, "lists"), listToAddData).then(() => {
        toast.show({
          title: "List Added",
          placement: "bottom"
        });
        setListToAdd({ listName: '' });
      });
    } else {
      alert('Validation Failed')
    }
  };

  // =========================================================================
  // Render

  return (
    <ScreenWrapper>

      <HStack>
        <FormControl isRequired isInvalid={'listName' in errors}>
          <Input placeholder="Add List..." value={listToAdd.listName} onChangeText={value => setListToAdd({ ...listToAdd, ...{ listName: value } })} />
          {'listName' in errors ? <FormControl.ErrorMessage>{errors.listName}</FormControl.ErrorMessage> : null}
        </FormControl>
        <Button onPress={() => { onAddList() }} >
          <Icon color="white" as={Ionicons} name="add" size="sm" />
        </Button>
      </HStack>

      <Divider my="3" />

      <ListsList />

    </ScreenWrapper>
  );
}

export default MainScreen;


问:
How to delete all the items in the dynamodb with boto3
My Code is below is to delete contents from the table name details

The below code will delete some items according to Capacity of dynamodb which is working fine

How to delete all the items

```<code>    import boto3
    def lambda_handler(event, context):
        try:
            table_name = 'details'
            dynamodb = boto3.resource('dynamodb')
            table = dynamodb.Table(table_name)
            scan = table.scan()
            with table.batch_writer() as batch:
                for each in scan['Items']:
                    batch.delete_item(
                        Key={
                            'id': each['id']
                        }
                    )
        except Exception as e:
           print (e)
</code>```

I wrote with while loop with a Flag condition.

```<code>   import boto3
    def lambda_handler(event, context):
        try:
            flag = False
            table_name = 'details'
            dynamodb = boto3.resource('dynamodb')
            table = dynamodb.Table(table_name)
            scan = table.scan()
            while True:
                with table.batch_writer() as batch:
                    for each in scan['Items']:
                        if each is not None:
                            batch.delete_item(
                                 Key={
                                 'id': each['id']
                                 }
                             )
                         else:
                            Flag = True
        except Exception as e:
           print (e)

</code>```

答:
I can't edit the accepted answer due to the edit queue being full.

Looking at the code, it only scans and deletes items once.

Here's a working code by using the LastEvaluatedKey key to determine whether a rescan is necessary. The key exists when the scan reaches the maximum dataset size limit of 1 MB.

```<code>import boto3

def lambda_handler(event, context):
     try:
          table_name = 'details'
          dynamodb = boto3.resource('dynamodb')
          table = dynamodb.Table(table_name)

          flag = True
          while flag:
               scan = table.scan()
               print(f"Deleting {scan['ScannedCount']} records...")
               flag = 'LastEvaluatedKey' in scan and scan['LastEvaluatedKey']
               with table.batch_writer() as batch:
                    for each in scan['Items']:
                         batch.delete_item(
                              Key={
                                   'id': each['id']
                              }
                         )
     except Exception as e:
          print(e)

</code>```

Body:
My Code is below is to delete contents from the table name details

The below code will delete some items according to Capacity of dynamodb which is working fine

How to delete all the items

    import boto3
    def lambda_handler(event, context):
        try:
            table_name = 'details'
            dynamodb = boto3.resource('dynamodb')
            table = dynamodb.Table(table_name)
            scan = table.scan()
            with table.batch_writer() as batch:
                for each in scan['Items']:
                    batch.delete_item(
                        Key={
                            'id': each['id']
                        }
                    )
        except Exception as e:
           print (e)

I wrote with while loop with a Flag condition.

   import boto3
    def lambda_handler(event, context):
        try:
            flag = False
            table_name = 'details'
            dynamodb = boto3.resource('dynamodb')
            table = dynamodb.Table(table_name)
            scan = table.scan()
            while True:
                with table.batch_writer() as batch:
                    for each in scan['Items']:
                        if each is not None:
                            batch.delete_item(
                                 Key={
                                 'id': each['id']
                                 }
                             )
                         else:
                            Flag = True
        except Exception as e:
           print (e)

Body:
I can't edit the accepted answer due to the edit queue being full.

Looking at the code, it only scans and deletes items once.

Here's a working code by using the LastEvaluatedKey key to determine whether a rescan is necessary. The key exists when the scan reaches the maximum dataset size limit of 1 MB.

import boto3

def lambda_handler(event, context):
     try:
          table_name = 'details'
          dynamodb = boto3.resource('dynamodb')
          table = dynamodb.Table(table_name)

          flag = True
          while flag:
               scan = table.scan()
               print(f"Deleting {scan['ScannedCount']} records...")
               flag = 'LastEvaluatedKey' in scan and scan['LastEvaluatedKey']
               with table.batch_writer() as batch:
                    for each in scan['Items']:
                         batch.delete_item(
                              Key={
                                   'id': each['id']
                              }
                         )
     except Exception as e:
          print(e)


问:
Storybook error when using Webpack5 with Next.JS app + Typescript
I am trying to set up a fresh next.js app using Typescript and Storybook.

Following some guides online gets me fairly close but I note that the rendered 'HomePage' story is missing styling

compared with what I get when I simply run

```<code>next dev
</code>```

Based on discussions I found, I thought that it was something to do with storybook using Webpack4 vs Webpack5 (first time working with SB so not 100% sure).

Installing dependencies and updating .storybook/main.js to use webpack5, then running yarn storybook results in the following error.

```<code>yarn storybook
yarn run v1.22.10
$ start-storybook -p 6006 -s ./public
info @storybook/react v6.4.9
info
(node:2020) DeprecationWarning: --static-dir CLI flag is deprecated, see:

https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated---static-dir-cli-flag
(Use `node --trace-deprecation ...` to show where the warning was created)
info => Loading presets
info => Serving static files from ././public at /
info => Using implicit CSS loaders
info => Using default Webpack5 setup
<i> [webpack-dev-middleware] wait until bundle finished
9% setup compilation DocGenPlugininternal/modules/cjs/loader.js:892
throw err;
^

Error: Cannot find module 'webpack/lib/util/makeSerializable.js'
Require stack:
- .\node_modules\@storybook\react-docgen-typescript-plugin\dist\dependency.js
- .\node_modules\@storybook\react-docgen-typescript-plugin\dist\plugin.js
- .\node_modules\@storybook\react-docgen-typescript-plugin\dist\index.js
- .\node_modules\@storybook\react\dist\cjs\server\framework-preset-react-docgen.js
- .\node_modules\@storybook\core-common\dist\cjs\presets.js
- .\node_modules\@storybook\core-common\dist\cjs\index.js
- .\node_modules\@storybook\core-server\dist\cjs\index.js
- .\node_modules\@storybook\core\dist\cjs\server.js
- .\node_modules\@storybook\core\server.js
- .\node_modules\@storybook\react\dist\cjs\server\index.js
- .\node_modules\@storybook\react\bin\index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:889:15)
    at Function.Module._load (internal/modules/cjs/loader.js:745:27)
    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object.<anonymous> (.\node_modules\@storybook\react-docgen-typescript-plugin\dist\dependency.js:6:55)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at .\node_modules\@storybook\react-docgen-typescript-plugin\dist\plugin.js:108:42
    at _next2 (eval at create (.\node_modules\@storybook\builder-webpack5\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:247:1)
    at Hook.eval [as call] (eval at create (.\node_modules\@storybook\builder-webpack5\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:365:1)
    at Hook.CALL_DELEGATE [as _call] (.\node_modules\@storybook\builder-webpack5\node_modules\tapable\lib\Hook.js:14:14)
    at Compiler.newCompilation (.t\node_modules\@storybook\builder-webpack5\node_modules\webpack\lib\Compiler.js:1055:26) {
code: 'MODULE_NOT_FOUND',
requireStack: [
    '.\\@storybook\\react-docgen-typescript-plugin\\dist\\dependency.js',
    '.\\@storybook\\react-docgen-typescript-plugin\\dist\\plugin.js',
    '.\\@storybook\\react-docgen-typescript-plugin\\dist\\index.js',
    '.\\@storybook\\react\\dist\\cjs\\server\\framework-preset-react-docgen.js',
    '.\\@storybook\\core-common\\dist\\cjs\\presets.js',
    '.\\@storybook\\core-common\\dist\\cjs\\index.js',
    '.\\@storybook\\core-server\\dist\\cjs\\index.js',
    '.\\@storybook\\core\\dist\\cjs\\server.js',
    '.\\@storybook\\core\\server.js',
    '.\\@storybook\\react\\dist\\cjs\\server\\index.js',
    '.\\@storybook\\react\\bin\\index.js'
]
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

.storybook/main.js

```<code>module.exports = {
    "core": {
        builder: "webpack5"
    },
    "stories": [
    "../stories/**/*.stories.mdx",
    "../stories/**/*.stories.@(js|jsx|ts|tsx)"
    ],
    "addons": [
    "@storybook/addon-links",
    "@storybook/addon-essentials"
    ],
    "framework": "@storybook/react"
}
</code>```

.storybook/preview.js

```<code>import "../styles/globals.css";
import * as NextImage from "next/image";

const OriginalNextImage = NextImage.default;

Object.defineProperty(NextImage, "default", {
    configurable: true,
    value: (props) => <OriginalNextImage {...props} unoptimized />,
});

export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
    matchers: {
    color: /(background|color)$/i,
    date: /Date$/,
    },
},
}
</code>```

package.json

```<code>{
  "name": "client",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "storybook": "start-storybook -p 6006 -s ./public",
    "build-storybook": "build-storybook  -s ./public"
  },
  "dependencies": {
    "next": "12.0.7",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },
  "devDependencies": {
    "@babel/core": "^7.16.7",
    "@storybook/addon-actions": "^6.4.9",
    "@storybook/addon-essentials": "^6.4.9",
    "@storybook/addon-links": "^6.4.9",
    "@storybook/builder-webpack5": "^6.4.9",
    "@storybook/manager-webpack5": "^6.4.9",
    "@storybook/react": "^6.4.9",
    "@types/node": "17.0.8",
    "@types/react": "17.0.38",
    "babel-loader": "^8.2.3",
    "eslint": "8.6.0",
    "eslint-config-next": "12.0.7",
    "eslint-plugin-storybook": "^0.5.5",
    "typescript": "4.5.4"
  }
}
</code>```

Steps to reproduce:

npx create-next-app@latest --typescript

cd my-app

npx sb init

n for eslint-plugin-storybook plugin fix

yarn add @storybook/builder-webpack5 @storybook/manager-webpack5 --dev

Update .storybook/main.js to include "core": { builder: "webpack5" }

yarn storybook and hit error

Other than this process, I have tried:

Creating react apps with Storybook, then migrating to next.js with typescript

Creating next apps with Storybook, then introducing Typescript

Both result in the same error...

Interestingly, when following the steps to reproduce with a non-typescript next.js app, everything seems to work fine and the 'HomePage' story is rendered correctly, so maybe some issue with Storybook playing nicely with Typescript? Or maybe missing dependencies?

Any input / point in the right direction would be greatly appreciated.

答:
Found the answer here -> https://github.com/storybookjs/storybook/issues/15336

The solution is simply to add the following to .storybook\main.js

```<code>reactDocgen: false
</code>```

Resulting .storybook\main.js looks like so

```<code>module.exports = {
   "core": {
      builder: "webpack5"
   },
   "stories": [
      "../stories/**/*.stories.mdx",
      "../stories/**/*.stories.@(js|jsx|ts|tsx)"
   ],
   "addons": [
      "@storybook/addon-links",
      "@storybook/addon-essentials"
   ],
   "framework": "@storybook/react",
   typescript: {
      check: false,
      checkOptions: {},
      reactDocgen: false,
      reactDocgenTypescriptOptions: {
         shouldExtractLiteralValuesFromEnum: true,
         propFilter: (prop) => (prop.parent ? !/node_modules/.test(prop.parent.fileName) : true),
      },
   },
}
</code>```

Body:
I am trying to set up a fresh next.js app using Typescript and Storybook.

Following some guides online gets me fairly close but I note that the rendered 'HomePage' story is missing styling

compared with what I get when I simply run

next dev

Based on discussions I found, I thought that it was something to do with storybook using Webpack4 vs Webpack5 (first time working with SB so not 100% sure).

Installing dependencies and updating .storybook/main.js to use webpack5, then running yarn storybook results in the following error.

yarn storybook
yarn run v1.22.10
$ start-storybook -p 6006 -s ./public
info @storybook/react v6.4.9
info
(node:2020) DeprecationWarning: --static-dir CLI flag is deprecated, see:

https://github.com/storybookjs/storybook/blob/next/MIGRATION.md#deprecated---static-dir-cli-flag
(Use `node --trace-deprecation ...` to show where the warning was created)
info => Loading presets
info => Serving static files from ././public at /
info => Using implicit CSS loaders
info => Using default Webpack5 setup
 [webpack-dev-middleware] wait until bundle finished
9% setup compilation DocGenPlugininternal/modules/cjs/loader.js:892
throw err;
^

Error: Cannot find module 'webpack/lib/util/makeSerializable.js'
Require stack:
- .\node_modules\@storybook\react-docgen-typescript-plugin\dist\dependency.js
- .\node_modules\@storybook\react-docgen-typescript-plugin\dist\plugin.js
- .\node_modules\@storybook\react-docgen-typescript-plugin\dist\index.js
- .\node_modules\@storybook\react\dist\cjs\server\framework-preset-react-docgen.js
- .\node_modules\@storybook\core-common\dist\cjs\presets.js
- .\node_modules\@storybook\core-common\dist\cjs\index.js
- .\node_modules\@storybook\core-server\dist\cjs\index.js
- .\node_modules\@storybook\core\dist\cjs\server.js
- .\node_modules\@storybook\core\server.js
- .\node_modules\@storybook\react\dist\cjs\server\index.js
- .\node_modules\@storybook\react\bin\index.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:889:15)
    at Function.Module._load (internal/modules/cjs/loader.js:745:27)
    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at Object.<anonymous> (.\node_modules\@storybook\react-docgen-typescript-plugin\dist\dependency.js:6:55)
    at Module._compile (internal/modules/cjs/loader.js:1072:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)
    at Module.load (internal/modules/cjs/loader.js:937:32)
    at Function.Module._load (internal/modules/cjs/loader.js:778:12)
    at Module.require (internal/modules/cjs/loader.js:961:19)
    at require (internal/modules/cjs/helpers.js:92:18)
    at .\node_modules\@storybook\react-docgen-typescript-plugin\dist\plugin.js:108:42
    at _next2 (eval at create (.\node_modules\@storybook\builder-webpack5\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:247:1)
    at Hook.eval [as call] (eval at create (.\node_modules\@storybook\builder-webpack5\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:365:1)
    at Hook.CALL_DELEGATE [as _call] (.\node_modules\@storybook\builder-webpack5\node_modules\tapable\lib\Hook.js:14:14)
    at Compiler.newCompilation (.t\node_modules\@storybook\builder-webpack5\node_modules\webpack\lib\Compiler.js:1055:26) {
code: 'MODULE_NOT_FOUND',
requireStack: [
    '.\\@storybook\\react-docgen-typescript-plugin\\dist\\dependency.js',
    '.\\@storybook\\react-docgen-typescript-plugin\\dist\\plugin.js',
    '.\\@storybook\\react-docgen-typescript-plugin\\dist\\index.js',
    '.\\@storybook\\react\\dist\\cjs\\server\\framework-preset-react-docgen.js',
    '.\\@storybook\\core-common\\dist\\cjs\\presets.js',
    '.\\@storybook\\core-common\\dist\\cjs\\index.js',
    '.\\@storybook\\core-server\\dist\\cjs\\index.js',
    '.\\@storybook\\core\\dist\\cjs\\server.js',
    '.\\@storybook\\core\\server.js',
    '.\\@storybook\\react\\dist\\cjs\\server\\index.js',
    '.\\@storybook\\react\\bin\\index.js'
]
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

.storybook/main.js

module.exports = {
    "core": {
        builder: "webpack5"
    },
    "stories": [
    "../stories/**/*.stories.mdx",
    "../stories/**/*.stories.@(js|jsx|ts|tsx)"
    ],
    "addons": [
    "@storybook/addon-links",
    "@storybook/addon-essentials"
    ],
    "framework": "@storybook/react"
}

.storybook/preview.js

import "../styles/globals.css";
import * as NextImage from "next/image";

const OriginalNextImage = NextImage.default;

Object.defineProperty(NextImage, "default", {
    configurable: true,
    value: (props) => <OriginalNextImage {...props} unoptimized />,
});

export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
    matchers: {
    color: /(background|color)$/i,
    date: /Date$/,
    },
},
}

package.json

{
  "name": "client",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "storybook": "start-storybook -p 6006 -s ./public",
    "build-storybook": "build-storybook  -s ./public"
  },
  "dependencies": {
    "next": "12.0.7",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },
  "devDependencies": {
    "@babel/core": "^7.16.7",
    "@storybook/addon-actions": "^6.4.9",
    "@storybook/addon-essentials": "^6.4.9",
    "@storybook/addon-links": "^6.4.9",
    "@storybook/builder-webpack5": "^6.4.9",
    "@storybook/manager-webpack5": "^6.4.9",
    "@storybook/react": "^6.4.9",
    "@types/node": "17.0.8",
    "@types/react": "17.0.38",
    "babel-loader": "^8.2.3",
    "eslint": "8.6.0",
    "eslint-config-next": "12.0.7",
    "eslint-plugin-storybook": "^0.5.5",
    "typescript": "4.5.4"
  }
}

Steps to reproduce:

npx create-next-app@latest --typescript

cd my-app

npx sb init

n for eslint-plugin-storybook plugin fix

yarn add @storybook/builder-webpack5 @storybook/manager-webpack5 --dev

Update .storybook/main.js to include "core": { builder: "webpack5" }

yarn storybook and hit error

Other than this process, I have tried:

Creating react apps with Storybook, then migrating to next.js with typescript

Creating next apps with Storybook, then introducing Typescript

Both result in the same error...

Interestingly, when following the steps to reproduce with a non-typescript next.js app, everything seems to work fine and the 'HomePage' story is rendered correctly, so maybe some issue with Storybook playing nicely with Typescript? Or maybe missing dependencies?

Any input / point in the right direction would be greatly appreciated.

Body:
Found the answer here -> https://github.com/storybookjs/storybook/issues/15336

The solution is simply to add the following to .storybook\main.js

reactDocgen: false

Resulting .storybook\main.js looks like so

module.exports = {
   "core": {
      builder: "webpack5"
   },
   "stories": [
      "../stories/**/*.stories.mdx",
      "../stories/**/*.stories.@(js|jsx|ts|tsx)"
   ],
   "addons": [
      "@storybook/addon-links",
      "@storybook/addon-essentials"
   ],
   "framework": "@storybook/react",
   typescript: {
      check: false,
      checkOptions: {},
      reactDocgen: false,
      reactDocgenTypescriptOptions: {
         shouldExtractLiteralValuesFromEnum: true,
         propFilter: (prop) => (prop.parent ? !/node_modules/.test(prop.parent.fileName) : true),
      },
   },
}