问:
Export from .tif to .tif with another CRS
I write a code in python for processing some .tif files and put them to WGS 1984 Coordinate System. The problem is, when I run the code, it gave's me error and stop executing. I try to do this with arcpy.ProjectRaster_management for almost 100 .tif files.
Could you help me to make this script to run?
Bellow is the script that I have been written:</p>
```<code>import arcpy
import os
import sys
import getpass

username = getpass.getuser()
empty_folder = os.path.expanduser("~") + r"\Desktop\wgs " + str(username)
path1 = empty_folder
if not os.path.exists(path1):
    os.makedirs(path1)

path2 = r"f:\proiecte\F5\Robert Nicolescu\ARCGIS\georeferentiere\TEST_georeferentiere\FINALE\50GHA\global_mapper_export"
tif_files = []
for x in os.listdir(path2):
    if x.endswith(".tif"):
        tif_files.append(x)

input_coordinate_system = "WGS_1984_UTM_zone_29N"
output_coordinate_system = "GCS_WGS_1984"
resampling_technique = "NEAREST"

def projectRaster(input, output):
    arcpy.ProjectRaster_management(input,output,output_coordinate_system,resampling_technique, "","", "", input_coordinate_system)
    print "Script done!"

projectRaster(input=tif_files, output=path1)
</code>```

答: Use the Model Builder within ArcGIS Desktop, once your model is done then export the Python code. What you are trying to do can be done using the Model Builder tool. Unless you want some extra ordinary functionality then you use modified code.

Body:
I write a code in python for processing some .tif files and put them to WGS 1984 Coordinate System. The problem is, when I run the code, it gave's me error and stop executing. I try to do this with arcpy.ProjectRaster_management for almost 100 .tif files.
Could you help me to make this script to run?
Bellow is the script that I have been written:

import arcpy
import os
import sys
import getpass

username = getpass.getuser()
empty_folder = os.path.expanduser("~") + r"\Desktop\wgs " + str(username)
path1 = empty_folder
if not os.path.exists(path1):
    os.makedirs(path1)

path2 = r"f:\proiecte\F5\Robert Nicolescu\ARCGIS\georeferentiere\TEST_georeferentiere\FINALE\50GHA\global_mapper_export"
tif_files = []
for x in os.listdir(path2):
    if x.endswith(".tif"):
        tif_files.append(x)

input_coordinate_system = "WGS_1984_UTM_zone_29N"
output_coordinate_system = "GCS_WGS_1984"
resampling_technique = "NEAREST"

def projectRaster(input, output):
    arcpy.ProjectRaster_management(input,output,output_coordinate_system,resampling_technique, "","", "", input_coordinate_system)
    print "Script done!"

projectRaster(input=tif_files, output=path1)


来源: stackexchange

问:
Why is the value of n equal to 5 in the first iteration?
I have a question that why is the value of n being used in the first iteration is 5 and not 6. I checked it on stackeoverflow and there many of them said that in the first iteration the value of n is used and then it is decreased by 1 and used in the next iteration.</p>
```<code>#include <stdio.h>

int main()
{
    int ans = 1, n = 6;

    while (n--)
    {
        printf("n = %d\n", n);

        if (n != 0)
        {
            ans *= n;
        }
    }

    printf("ans = %d", ans);

    return 0;
}

Output:
n = 5
n = 4
n = 3
n = 2
n = 1
n = 0
ans = 120
</code>```

答:
```<code>n = 6;
while (n--) {
    // n is 5, then 4, 3, 2, 1, 0, then the while terminates
}
// n is -1
</code>```

compare with

```<code>n = 6;
while (--n) {
    // n is 5, then 4, 3, 2, 1, then the while terminates
}
// n is 0
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a question that why is the value of n being used in the first iteration is 5 and not 6. I checked it on stackeoverflow and there many of them said that in the first iteration the value of n is used and then it is decreased by 1 and used in the next iteration.

#include <stdio.h>

int main()
{
    int ans = 1, n = 6;

    while (n--)
    {
        printf("n = %d\n", n);

        if (n != 0)
        {
            ans *= n;
        }
    }

    printf("ans = %d", ans);

    return 0;
}

Output:
n = 5
n = 4
n = 3
n = 2
n = 1
n = 0
ans = 120

Body:
n = 6;
while (n--) {
    // n is 5, then 4, 3, 2, 1, 0, then the while terminates
}
// n is -1

compare with

n = 6;
while (--n) {
    // n is 5, then 4, 3, 2, 1, then the while terminates
}
// n is 0


问:
Res is coming back as a null value, not sure why (Null check operator used on a null value)
whenever I run my program, an exeption occurs where res comes back as null. The program successful uploads to firebase, and the input value isn't empty, so I'm not sure why the value doesn't come back as anything.

Here is the code involved.

The line occus on this line of the _onPublish Function, "builder: (context) => NewsPostPage(newsPostId: res!)));", and it reads, "_CastError (Null check operator used on a null value)"

When a button is pressed, it calls function _onPublish

```<code>_onPublish() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isLoading = true;
      });

      await DatabaseService()
          .saveNewsPost(
              _titleEditingController.text, _contentEditingController.text)
          .then((res) async {
        Navigator.of(context).pushReplacement(MaterialPageRoute(
            builder: (context) => NewsPostPage(newsPostId: res!)));
        _isLoading = true;
        print("Post Uploaded to Firebase");
      });
    }
  }
</code>```

Here is function Database Service.saveNewsPost()

```<code>Future saveNewsPost(
    String title,
    String content,
  ) async {
    DocumentReference newsPostsRef =
        await FirebaseFirestore.instance.collection('newsPosts').add({
      'newsPostId': '',
      'newsPostTitle': title,
      'newsPostTitleArray': title.toLowerCase().split(" "),
      //'newsPostAuthor': author,
      'newsPostContent': content,
      'createdAt': new DateTime.now(),
      'date': DateFormat.yMMMd('en_US').format(DateTime.now())
    });

    await newsPostsRef.update({'newsPostId': newsPostsRef.id});
//return
    newsPostsRef.id;
  }
</code>```

Lastly, here is NewsPostPage

```<code>class NewsPostPage extends StatefulWidget {
  final String newsPostId;
  //final String authorName;
  NewsPostPage({
    required this.newsPostId,
    /*required this.authorName*/
  });

  @override
  _NewsPostPageState createState() => _NewsPostPageState();
}

class _NewsPostPageState extends State<NewsPostPage> {
  newsPostDetails NewsPostDetails = newsPostDetails();
  bool _isLoading = true;
  String _error = '';
  TextEditingController _fullNameEditingController =
      new TextEditingController();
  TextEditingController _emailEditingController = new TextEditingController();

  late DocumentReference newsPostRef;
  late DocumentSnapshot newsPostSnap;

  @override
  void initState() {
    super.initState();
    _getNewsPostDetails;
  }

  _getNewsPostDetails() async {
    await DatabaseService().getNewsPostDetails(widget.newsPostId).then((res) {
      setState(() {
        NewsPostDetails = res;
        _isLoading = false;
      });
    });

    newsPostRef = FirebaseFirestore.instance
        .collection('blogPosts')
        .doc(widget.newsPostId);
    newsPostSnap = await newsPostRef.get();

    print(newsPostSnap.data);
  }

  @override
  Widget build(BuildContext context) {
    return _isLoading
        ? Loading()
        : Scaffold(
            appBar: AppBar(
              elevation: 0.0,
              title: Text(NewsPostDetails.newsPostTitle! as String),
            ),
            body: Center(
              child: ListView(
                  padding:
                      EdgeInsets.symmetric(horizontal: 20.0, vertical: 50.0),
                  children: <Widget>[
                    Text(NewsPostDetails.newsPostTitle as String,
                        style: TextStyle(
                            fontSize: 40.0,
                            color: Colors.black,
                            fontWeight: FontWeight.bold)),
                    SizedBox(height: 5.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text('Published on - ${NewsPostDetails.date as String}',
                            style:
                                TextStyle(fontSize: 14.0, color: Colors.grey)),
                      ],
                    ),
                    SizedBox(height: 40.0),
                    Text(NewsPostDetails.newsPostContent as String,
                        style: TextStyle(fontSize: 16.0)),
                    SizedBox(height: 110.0),
                  ]),
            ));
  }
}
</code>```

Help is highly appreciated!

答: I think it's because you are not returning anything in DatabaseService().saveNewsPost(). You commented the return before newsPostsRef.id

Body:
whenever I run my program, an exeption occurs where res comes back as null. The program successful uploads to firebase, and the input value isn't empty, so I'm not sure why the value doesn't come back as anything.

Here is the code involved.

The line occus on this line of the _onPublish Function, "builder: (context) => NewsPostPage(newsPostId: res!)));", and it reads, "_CastError (Null check operator used on a null value)"

When a button is pressed, it calls function _onPublish

_onPublish() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isLoading = true;
      });

      await DatabaseService()
          .saveNewsPost(
              _titleEditingController.text, _contentEditingController.text)
          .then((res) async {
        Navigator.of(context).pushReplacement(MaterialPageRoute(
            builder: (context) => NewsPostPage(newsPostId: res!)));
        _isLoading = true;
        print("Post Uploaded to Firebase");
      });
    }
  }

Here is function Database Service.saveNewsPost()

Future saveNewsPost(
    String title,
    String content,
  ) async {
    DocumentReference newsPostsRef =
        await FirebaseFirestore.instance.collection('newsPosts').add({
      'newsPostId': '',
      'newsPostTitle': title,
      'newsPostTitleArray': title.toLowerCase().split(" "),
      //'newsPostAuthor': author,
      'newsPostContent': content,
      'createdAt': new DateTime.now(),
      'date': DateFormat.yMMMd('en_US').format(DateTime.now())
    });

    await newsPostsRef.update({'newsPostId': newsPostsRef.id});
//return
    newsPostsRef.id;
  }

Lastly, here is NewsPostPage

class NewsPostPage extends StatefulWidget {
  final String newsPostId;
  //final String authorName;
  NewsPostPage({
    required this.newsPostId,
    /*required this.authorName*/
  });

  @override
  _NewsPostPageState createState() => _NewsPostPageState();
}

class _NewsPostPageState extends State<NewsPostPage> {
  newsPostDetails NewsPostDetails = newsPostDetails();
  bool _isLoading = true;
  String _error = '';
  TextEditingController _fullNameEditingController =
      new TextEditingController();
  TextEditingController _emailEditingController = new TextEditingController();

  late DocumentReference newsPostRef;
  late DocumentSnapshot newsPostSnap;

  @override
  void initState() {
    super.initState();
    _getNewsPostDetails;
  }

  _getNewsPostDetails() async {
    await DatabaseService().getNewsPostDetails(widget.newsPostId).then((res) {
      setState(() {
        NewsPostDetails = res;
        _isLoading = false;
      });
    });

    newsPostRef = FirebaseFirestore.instance
        .collection('blogPosts')
        .doc(widget.newsPostId);
    newsPostSnap = await newsPostRef.get();

    print(newsPostSnap.data);
  }

  @override
  Widget build(BuildContext context) {
    return _isLoading
        ? Loading()
        : Scaffold(
            appBar: AppBar(
              elevation: 0.0,
              title: Text(NewsPostDetails.newsPostTitle! as String),
            ),
            body: Center(
              child: ListView(
                  padding:
                      EdgeInsets.symmetric(horizontal: 20.0, vertical: 50.0),
                  children: <Widget>[
                    Text(NewsPostDetails.newsPostTitle as String,
                        style: TextStyle(
                            fontSize: 40.0,
                            color: Colors.black,
                            fontWeight: FontWeight.bold)),
                    SizedBox(height: 5.0),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: <Widget>[
                        Text('Published on - ${NewsPostDetails.date as String}',
                            style:
                                TextStyle(fontSize: 14.0, color: Colors.grey)),
                      ],
                    ),
                    SizedBox(height: 40.0),
                    Text(NewsPostDetails.newsPostContent as String,
                        style: TextStyle(fontSize: 16.0)),
                    SizedBox(height: 110.0),
                  ]),
            ));
  }
}

Help is highly appreciated!


问:
robocopy purge vs python for folder purge
I have a working directory that is used to unzip logfiles to, analyze them, and then they can be deleted. Either only the files in the folder or the complete folder and then recreating the folder. # of files in the folder can vary between 5k and 36k, average filesize is 6MB

I am currently using robocopy to purge the directory and have seen a couple of suggestions on how to do this in Python (How to delete the contents of a folder?)
but was wondering which one would be the faster approach.

Thanks!

答:
Robocopy is optimised pretty well, and is multithreaded by default, so it should win this comfortably. You can even override the number of threads it uses with something like /MT:24. See here for more info.

When I choose Python over robocopy it is because I want more control/logic, certainly not for speed.


问:
How can I save the information when toggling for the element.empty() function

$("#prop-info-nav-link").click(function() {
  $("#toggle-content-add-modal").empty();
  let output = '

Property Type

<select name="property-types" id="property-types"><option value="volvo">Tenament</option><option value="saab">Car</option><option value="opel" selected>Helicopter</option><option value="audi">Space Shuttle</option></select>
OR<input type="text" class="form-control" id="new-prop-type" placeholder="Enter a new type" aria-label="Property-Type" aria-describedby="basic-addon1" autocomplete="off">

<input type="text" id="prop-name" class="add-inpt" placeholder="Property Name">

<input type="text" id="prop-address" class="add-inpt" placeholder="Property Address">

';
  $("#toggle-content-add-modal").html(output);
});

$("#img-nav-link").click(function() {
  $("#toggle-content-add-modal").empty();
  let output = '

Upload your file

File should be an imageLike

Drop your file here or Click to browse
Please Wait<input type="file" id="fileInput" class="drop-zoon__file-input" accept="image/*">

Project 10%

';
  $("#toggle-content-add-modal").html(output);
});

$(function () {
    $(".side-nav li").click(function (e) {
        e.preventDefault();
        $(".side-nav li").removeClass("active");
        $(this).addClass("active");
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Add property modal */

.add-property {
  position: relative;
  width: 60rem;
  height: 35rem;
  left: 50%;
  -ms-transform: translateX(-50%);
  transform: translateX(-50%);
  border-radius: 15px;
}

.modal-title {
  position: relative;
  left: 50%;
  -ms-transform: translateX(-50%);
  transform: translateX(-50%);
}

.close {
  background-color: transparent;
  border: none;
}

#footer-btn {
  position: relative;
  left: 50%;
  -ms-transform: translateX(-50%);
  transform: translateX(-50%);
  border: 0.1em solid black;
  border-radius: 10px;
  width: 5em;
  height: 2.5em;
  font-weight: 600;
  margin-bottom: 1.2em;
}

.add-prop {
  background-color: #3498db;
  color: white;
}

.add-prop:hover {
  background-color: rgb(12, 65, 180);
}

.add-inpt {
  outline: none;
  border-width: 0 0 0.17em;
  border-color: black;
  border-radius: 5px;
  width: 15em;
  height: 2em;
  text-align: center;
}

.prop-info-row {
  height: 15em;
  position: relative;
  top: 50%;
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

.prop-info-col {
  height: 2em;
}

.add-inpt::placeholder {
  text-align: center;
}

.main-add-row {
  width: 50rem;
  height: 26rem;
  border-bottom: 1px solid rgba(0, 0, 0, 0.26);
}

#property-types {
  background-color: white;
  height: 2.5em;
  width: 13em;
  border-radius: 5px;
}

/* SIDE NAV INSIDE ADD PROPERTY MODAL */
.side-nav,
.nav-menu {
    height: 100%;
}

.side-nav .nav-menu {
    list-style: none;
    padding: 40px 0;
    width: 13em;
    background-color: #3498db;

}

.side-nav .nav-item {
    position: relative;
    padding: 0.7em 1.5em;
    position: relative;
    top: 42%;
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

.nav-item.active {
    background-color: #fff;
    box-shadow: 0px -3px rgba(0, 0, 0, 0.2), 0px 3px rgba(0, 0, 0, 0.2);
}

.nav-item.active a {
    color: #2980b9;
}

.nav-item a {
    text-decoration: none;
    color: #fff;
}

.menu-text {
    padding: 0 20px;
}

.side-nav .nav-item.active::before {
    content: "";
    position: absolute;
    background-color: transparent;
    bottom: 100%;
    right: 0;
    height: 150%;
    width: 20px;
    border-bottom-right-radius: 25px;
    box-shadow: 0 20px 0 0 #fff;
}

.side-nav .nav-item.active::after {
    content: "";
    position: absolute;
    background-color: transparent;
    top: 100%;
    right: 0;
    height: 150%;
    width: 20px;
    border-top-right-radius: 25px;
    box-shadow: 0 -20px 0 0 #fff;
}

/* UPLOAD IMAGE STYLE */
:root {
    --clr-white: rgb(255, 255, 255);
    --clr-black: rgb(0, 0, 0);
    --clr-light: rgb(245, 248, 255);
    --clr-light-gray: rgb(196, 195, 196);
    --clr-blue: rgb(63, 134, 255);
    --clr-light-blue: rgb(171, 202, 255);
}

/* End General Styles */

/* Upload Area */
.upload-area {
    width: 100%;
    max-width: 25rem;
    background-color: var(--clr-white);
    box-shadow: 0 5px 10px rgb(218, 229, 255);
    border: 2px solid var(--clr-light-blue);
    border-radius: 24px;
    padding: 1rem 1.875rem 0rem 1.875rem;
    margin: 0.625rem;
    text-align: center;
}

/* Header */
.upload-area__title {
    font-size: 1.8rem;
    font-weight: 500;
    margin-bottom: 0.3125rem;
}

.upload-area__paragraph {
    font-size: 0.9375rem;
    color: var(--clr-light-gray);
    margin-top: 0;
}

.upload-area__tooltip {
    position: relative;
    color: var(--clr-light-blue);
    cursor: pointer;
    transition: color 300ms ease-in-out;
}

.upload-area__tooltip:hover {
    color: var(--clr-blue);
}

.upload-area__tooltip-data {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -125%);
    min-width: max-content;
    background-color: var(--clr-white);
    color: var(--clr-blue);
    border: 1px solid var(--clr-light-blue);
    padding: 0.625rem 1.25rem;
    font-weight: 500;
    opacity: 0;
    visibility: hidden;
    transition: none 300ms ease-in-out;
    transition-property: opacity, visibility;
}

.upload-area__tooltip:hover .upload-area__tooltip-data {
    opacity: 1;
    visibility: visible;
}

/* Drop Zoon */
.upload-area__drop-zoon {
    position: relative;
    height: 13.8rem;
    /* 180px */
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    border: 2px dashed var(--clr-light-blue);
    border-radius: 15px;
    margin-top: 1.1rem;
    cursor: pointer;
    transition: border-color 300ms ease-in-out;
}

.upload-area__drop-zoon:hover {
    border-color: var(--clr-blue);
}

.drop-zoon__icon {
    display: flex;
    font-size: 3.75rem;
    color: var(--clr-blue);
    transition: opacity 300ms ease-in-out;
}

.drop-zoon__paragraph {
    font-size: 0.9375rem;
    color: var(--clr-light-gray);
    margin: 0;
    margin-top: 0.625rem;
    transition: opacity 300ms ease-in-out;
}

.drop-zoon:hover .drop-zoon__icon,
.drop-zoon:hover .drop-zoon__paragraph {
    opacity: 0.7;
}

.drop-zoon__loading-text {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: none;
    color: var(--clr-light-blue);
    z-index: 10;
}

.drop-zoon__preview-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: contain;
    padding: 0.3125rem;
    border-radius: 10px;
    display: none;
    z-index: 1000;
    transition: opacity 300ms ease-in-out;
}

.drop-zoon:hover .drop-zoon__preview-image {
    opacity: 0.8;
}

.drop-zoon__file-input {
    display: none;
}

/* (drop-zoon--over) Modifier Class */
.drop-zoon--over {
    border-color: var(--clr-blue);
}

.drop-zoon--over .drop-zoon__icon,
.drop-zoon--over .drop-zoon__paragraph {
    opacity: 0.7;
}

/* (drop-zoon--over) Modifier Class */

.drop-zoon--Uploaded .drop-zoon__icon,
.drop-zoon--Uploaded .drop-zoon__paragraph {
    display: none;
}

/* File Details Area */
.upload-area__file-details {
    height: 0;
    visibility: hidden;
    opacity: 0;
    text-align: left;
    transition: none 500ms ease-in-out;
    transition-property: opacity, visibility;
    transition-delay: 500ms;
}

/* (duploaded-file--open) Modifier Class */
.file-details--open {
    height: auto;
    visibility: visible;
    opacity: 1;
}

/* Uploaded File */
.uploaded-file {
    display: flex;
    align-items: center;
    padding: 0.925rem 0;
    visibility: hidden;
    opacity: 0;
    transition: none 500ms ease-in-out;
    transition-property: visibility, opacity;
}

/* (duploaded-file--open) Modifier Class */
.uploaded-file--open {
    visibility: visible;
    opacity: 1;
}

.uploaded-file__icon-container {
    position: relative;
    margin-right: 0.3125rem;
}

.uploaded-file__icon {
    font-size: 3.4375rem;
    color: var(--clr-blue);
}

.uploaded-file__icon-text {
    position: absolute;
    top: 1.5625rem;
    left: 50%;
    transform: translateX(-50%);
    font-size: 0.9375rem;
    font-weight: 500;
    color: var(--clr-white);
}

.uploaded-file__info {
    position: relative;
    top: -0.3125rem;
    width: 100%;
    display: flex;
    justify-content: space-between;
}

.uploaded-file__info::before,
.uploaded-file__info::after {
    content: '';
    position: absolute;
    bottom: -0.9375rem;
    width: 0;
    height: 0.5rem;
    background-color: #ebf2ff;
    border-radius: 0.625rem;
}

.uploaded-file__info::before {
    width: 100%;
}

.uploaded-file__info::after {
    width: 100%;
    background-color: var(--clr-blue);
}

/* Progress Animation */
.uploaded-file__info--active::after {
    animation: progressMove 800ms ease-in-out;
    animation-delay: 300ms;
}

@keyframes progressMove {
    from {
        width: 0%;
        background-color: transparent;
    }

    to {
        width: 100%;
        background-color: var(--clr-blue);
    }
}

.uploaded-file__name {
    width: 100%;
    max-width: 6.25rem;
    /* 100px */
    display: inline-block;
    font-size: 1rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.uploaded-file__counter {
    font-size: 1rem;
    color: var(--clr-light-gray);
}</code>```

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<button data-bs-toggle="modal" data-bs-target="#ModalAddProperty" class="add-more" id="add-property">Add
            Property</button>

<form action="">

Add Property

          <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">

                        </button>

                      Upload Image

                      Propery Info

Upload your file

                    File should be an image

                                                Like

Drop your file here or Click to browse

                  Please Wait

                  <input type="file" id="fileInput" class="drop-zoon__file-input" accept="image/*">

                      Project 1
                      0%

          <button type="submit" class="add-prop" id="footer-btn" data-bs-dismiss="modal">Add</button>

</form>```

The modal looks like this:

When I click on the Property Info, all the child elements in the a column: #toggle-content-add-modal related to Upload Image is deleted with the help of $("#toggle-content-add-modal").empty() and replaced by the elements related to Property Info.

This .empty() and and .html() is, in a way toggled when clicking respective nav-links (Upload Image and Property Info). But the data I entered like uploading the image or any information in the Property Info gets deleted also. I know .empty() specifically does that. But I cant find any other option in which the data is stored when toggling between nav-links.

答:
You can keep the child elements you're removing by using children and detach:

```<code>const children = $("#toggle-content-add-modal").children().detach();
</code>```

That removes them from the document but returns a jQuery object containing them, so you can put them back later with append.

Here's a simplified example:

$("input[type=text]").on("change input", (e) => {
    $("#echo").text(e.currentTarget.value);
});

let children = null;
$("input[type=button]").on("click", () => {
    if (children) {
        $("#container").append(children);
        children = null;
    } else {
        children = $("#container").children().detach();
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.echo {
    border: 1px solid black;
    padding: 4px;
    min-height: 1em;
}</code>```

<input type="button" value="Toggle">

Type something in the input box below, which will be echoed to a div under it, and then use the toggle button above to show removing and restoring the content (including the input's value and the "echo" div's text):

            Type something here:
            <input type="text" value="">

        You've typed:

```

Body:
$("#prop-info-nav-link").click(function() {
  $("#toggle-content-add-modal").empty();
  let output = '

Property Type

<select name="property-types" id="property-types"><option value="volvo">Tenament</option><option value="saab">Car</option><option value="opel" selected>Helicopter</option><option value="audi">Space Shuttle</option></select>
OR<input type="text" class="form-control" id="new-prop-type" placeholder="Enter a new type" aria-label="Property-Type" aria-describedby="basic-addon1" autocomplete="off">

<input type="text" id="prop-name" class="add-inpt" placeholder="Property Name">

<input type="text" id="prop-address" class="add-inpt" placeholder="Property Address">

';
  $("#toggle-content-add-modal").html(output);
});

$("#img-nav-link").click(function() {
  $("#toggle-content-add-modal").empty();
  let output = '

Upload your file

File should be an imageLike

Drop your file here or Click to browse
Please Wait<input type="file" id="fileInput" class="drop-zoon__file-input" accept="image/*">

Project 10%

';
  $("#toggle-content-add-modal").html(output);
});

$(function () {
    $(".side-nav li").click(function (e) {
        e.preventDefault();
        $(".side-nav li").removeClass("active");
        $(this).addClass("active");
    });
});

/* Add property modal */

.add-property {
  position: relative;
  width: 60rem;
  height: 35rem;
  left: 50%;
  -ms-transform: translateX(-50%);
  transform: translateX(-50%);
  border-radius: 15px;
}

.modal-title {
  position: relative;
  left: 50%;
  -ms-transform: translateX(-50%);
  transform: translateX(-50%);
}

.close {
  background-color: transparent;
  border: none;
}

#footer-btn {
  position: relative;
  left: 50%;
  -ms-transform: translateX(-50%);
  transform: translateX(-50%);
  border: 0.1em solid black;
  border-radius: 10px;
  width: 5em;
  height: 2.5em;
  font-weight: 600;
  margin-bottom: 1.2em;
}

.add-prop {
  background-color: #3498db;
  color: white;
}

.add-prop:hover {
  background-color: rgb(12, 65, 180);
}

.add-inpt {
  outline: none;
  border-width: 0 0 0.17em;
  border-color: black;
  border-radius: 5px;
  width: 15em;
  height: 2em;
  text-align: center;
}

.prop-info-row {
  height: 15em;
  position: relative;
  top: 50%;
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

.prop-info-col {
  height: 2em;
}

.add-inpt::placeholder {
  text-align: center;
}

.main-add-row {
  width: 50rem;
  height: 26rem;
  border-bottom: 1px solid rgba(0, 0, 0, 0.26);
}

#property-types {
  background-color: white;
  height: 2.5em;
  width: 13em;
  border-radius: 5px;
}

/* SIDE NAV INSIDE ADD PROPERTY MODAL */
.side-nav,
.nav-menu {
    height: 100%;
}

.side-nav .nav-menu {
    list-style: none;
    padding: 40px 0;
    width: 13em;
    background-color: #3498db;

}

.side-nav .nav-item {
    position: relative;
    padding: 0.7em 1.5em;
    position: relative;
    top: 42%;
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
}

.nav-item.active {
    background-color: #fff;
    box-shadow: 0px -3px rgba(0, 0, 0, 0.2), 0px 3px rgba(0, 0, 0, 0.2);
}

.nav-item.active a {
    color: #2980b9;
}

.nav-item a {
    text-decoration: none;
    color: #fff;
}

.menu-text {
    padding: 0 20px;
}

.side-nav .nav-item.active::before {
    content: "";
    position: absolute;
    background-color: transparent;
    bottom: 100%;
    right: 0;
    height: 150%;
    width: 20px;
    border-bottom-right-radius: 25px;
    box-shadow: 0 20px 0 0 #fff;
}

.side-nav .nav-item.active::after {
    content: "";
    position: absolute;
    background-color: transparent;
    top: 100%;
    right: 0;
    height: 150%;
    width: 20px;
    border-top-right-radius: 25px;
    box-shadow: 0 -20px 0 0 #fff;
}

/* UPLOAD IMAGE STYLE */
:root {
    --clr-white: rgb(255, 255, 255);
    --clr-black: rgb(0, 0, 0);
    --clr-light: rgb(245, 248, 255);
    --clr-light-gray: rgb(196, 195, 196);
    --clr-blue: rgb(63, 134, 255);
    --clr-light-blue: rgb(171, 202, 255);
}

/* End General Styles */

/* Upload Area */
.upload-area {
    width: 100%;
    max-width: 25rem;
    background-color: var(--clr-white);
    box-shadow: 0 5px 10px rgb(218, 229, 255);
    border: 2px solid var(--clr-light-blue);
    border-radius: 24px;
    padding: 1rem 1.875rem 0rem 1.875rem;
    margin: 0.625rem;
    text-align: center;
}

/* Header */
.upload-area__title {
    font-size: 1.8rem;
    font-weight: 500;
    margin-bottom: 0.3125rem;
}

.upload-area__paragraph {
    font-size: 0.9375rem;
    color: var(--clr-light-gray);
    margin-top: 0;
}

.upload-area__tooltip {
    position: relative;
    color: var(--clr-light-blue);
    cursor: pointer;
    transition: color 300ms ease-in-out;
}

.upload-area__tooltip:hover {
    color: var(--clr-blue);
}

.upload-area__tooltip-data {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -125%);
    min-width: max-content;
    background-color: var(--clr-white);
    color: var(--clr-blue);
    border: 1px solid var(--clr-light-blue);
    padding: 0.625rem 1.25rem;
    font-weight: 500;
    opacity: 0;
    visibility: hidden;
    transition: none 300ms ease-in-out;
    transition-property: opacity, visibility;
}

.upload-area__tooltip:hover .upload-area__tooltip-data {
    opacity: 1;
    visibility: visible;
}

/* Drop Zoon */
.upload-area__drop-zoon {
    position: relative;
    height: 13.8rem;
    /* 180px */
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    border: 2px dashed var(--clr-light-blue);
    border-radius: 15px;
    margin-top: 1.1rem;
    cursor: pointer;
    transition: border-color 300ms ease-in-out;
}

.upload-area__drop-zoon:hover {
    border-color: var(--clr-blue);
}

.drop-zoon__icon {
    display: flex;
    font-size: 3.75rem;
    color: var(--clr-blue);
    transition: opacity 300ms ease-in-out;
}

.drop-zoon__paragraph {
    font-size: 0.9375rem;
    color: var(--clr-light-gray);
    margin: 0;
    margin-top: 0.625rem;
    transition: opacity 300ms ease-in-out;
}

.drop-zoon:hover .drop-zoon__icon,
.drop-zoon:hover .drop-zoon__paragraph {
    opacity: 0.7;
}

.drop-zoon__loading-text {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: none;
    color: var(--clr-light-blue);
    z-index: 10;
}

.drop-zoon__preview-image {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    object-fit: contain;
    padding: 0.3125rem;
    border-radius: 10px;
    display: none;
    z-index: 1000;
    transition: opacity 300ms ease-in-out;
}

.drop-zoon:hover .drop-zoon__preview-image {
    opacity: 0.8;
}

.drop-zoon__file-input {
    display: none;
}

/* (drop-zoon--over) Modifier Class */
.drop-zoon--over {
    border-color: var(--clr-blue);
}

.drop-zoon--over .drop-zoon__icon,
.drop-zoon--over .drop-zoon__paragraph {
    opacity: 0.7;
}

/* (drop-zoon--over) Modifier Class */

.drop-zoon--Uploaded .drop-zoon__icon,
.drop-zoon--Uploaded .drop-zoon__paragraph {
    display: none;
}

/* File Details Area */
.upload-area__file-details {
    height: 0;
    visibility: hidden;
    opacity: 0;
    text-align: left;
    transition: none 500ms ease-in-out;
    transition-property: opacity, visibility;
    transition-delay: 500ms;
}

/* (duploaded-file--open) Modifier Class */
.file-details--open {
    height: auto;
    visibility: visible;
    opacity: 1;
}

/* Uploaded File */
.uploaded-file {
    display: flex;
    align-items: center;
    padding: 0.925rem 0;
    visibility: hidden;
    opacity: 0;
    transition: none 500ms ease-in-out;
    transition-property: visibility, opacity;
}

/* (duploaded-file--open) Modifier Class */
.uploaded-file--open {
    visibility: visible;
    opacity: 1;
}

.uploaded-file__icon-container {
    position: relative;
    margin-right: 0.3125rem;
}

.uploaded-file__icon {
    font-size: 3.4375rem;
    color: var(--clr-blue);
}

.uploaded-file__icon-text {
    position: absolute;
    top: 1.5625rem;
    left: 50%;
    transform: translateX(-50%);
    font-size: 0.9375rem;
    font-weight: 500;
    color: var(--clr-white);
}

.uploaded-file__info {
    position: relative;
    top: -0.3125rem;
    width: 100%;
    display: flex;
    justify-content: space-between;
}

.uploaded-file__info::before,
.uploaded-file__info::after {
    content: '';
    position: absolute;
    bottom: -0.9375rem;
    width: 0;
    height: 0.5rem;
    background-color: #ebf2ff;
    border-radius: 0.625rem;
}

.uploaded-file__info::before {
    width: 100%;
}

.uploaded-file__info::after {
    width: 100%;
    background-color: var(--clr-blue);
}

/* Progress Animation */
.uploaded-file__info--active::after {
    animation: progressMove 800ms ease-in-out;
    animation-delay: 300ms;
}

@keyframes progressMove {
    from {
        width: 0%;
        background-color: transparent;
    }

    to {
        width: 100%;
        background-color: var(--clr-blue);
    }
}

.uploaded-file__name {
    width: 100%;
    max-width: 6.25rem;
    /* 100px */
    display: inline-block;
    font-size: 1rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.uploaded-file__counter {
    font-size: 1rem;
    color: var(--clr-light-gray);
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<button data-bs-toggle="modal" data-bs-target="#ModalAddProperty" class="add-more" id="add-property">Add
            Property</button>

<form action="">

Add Property

          <button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">

                        </button>

                      Upload Image

                      Propery Info

Upload your file

                    File should be an image

                                                Like

Drop your file here or Click to browse

                  Please Wait

                  <input type="file" id="fileInput" class="drop-zoon__file-input" accept="image/*">

                      Project 1
                      0%

          <button type="submit" class="add-prop" id="footer-btn" data-bs-dismiss="modal">Add</button>

</form>

The modal looks like this:

When I click on the Property Info, all the child elements in the a column: #toggle-content-add-modal related to Upload Image is deleted with the help of $("#toggle-content-add-modal").empty() and replaced by the elements related to Property Info.

This .empty() and and .html() is, in a way toggled when clicking respective nav-links (Upload Image and Property Info). But the data I entered like uploading the image or any information in the Property Info gets deleted also. I know .empty() specifically does that. But I cant find any other option in which the data is stored when toggling between nav-links.

Body:
You can keep the child elements you're removing by using children and detach:

const children = $("#toggle-content-add-modal").children().detach();

That removes them from the document but returns a jQuery object containing them, so you can put them back later with append.

Here's a simplified example:

$("input[type=text]").on("change input", (e) => {
    $("#echo").text(e.currentTarget.value);
});

let children = null;
$("input[type=button]").on("click", () => {
    if (children) {
        $("#container").append(children);
        children = null;
    } else {
        children = $("#container").children().detach();
    }
});

.echo {
    border: 1px solid black;
    padding: 4px;
    min-height: 1em;
}

<input type="button" value="Toggle">
<div>
Type something in the input box below, which will be echoed to a div under it, and then use the toggle button above to show removing and restoring the content (including the input's value and the "echo" div's text):
</div>
<hr>
<div id="container">
    <div>
        <label>
            Type something here:
            <input type="text" value="">
        </label>
    </div>
    <div>
        You've typed:
        <div id="echo"></div>
    </div>
</div>

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


问:
How do you remove and add then a class to two list elements on click
How do you remove and add a class to both the below lists simultaneously for the coresponding list item in order on click. eg click the 2nd list item and the change occurs on the second list item on the other list

At the moment using the below I can only get this to happen on one of the li tags on any one click

```<code>$(document).ready(function() {

  $("ul.control li, ul.markers li").click(function() {
      $("ul.control li").removeClass("active");
      $(this).addClass("active");
      $("ul.markers li").removeClass("active");
      $(this).addClass("active");

});
</code>```

Here is the markup for the two lists

```<code><ul id="tabs" class="control">
    <li class="active"><a href="#tab1">Tab1</a></li>
    <li><a href="#tab2">Tab2</a></li>
    <li><a href="#tab3">Tab3</a></li>
    <li><a href="#tab4">Tab4</a></li>
</ul>

<ul id="tabs" class="markers">
  <li class="active">1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
</ul>
</code>```

Many thanks in advance for any help.

答:
Much easier solution:

```<code>$(document).ready(function() {

  $("ul.control li, ul.markers li").click(function(e) {
     var that = $(this);
      that.siblings('.active').removeClass('active');
      that.addClass('active');
  });

});
</code>```

Demo: http://jsfiddle.net/wesbos/mjmJH/2/

ContentLicense: CC BY-SA 3.0

Body:
How do you remove and add a class to both the below lists simultaneously for the coresponding list item in order on click. eg click the 2nd list item and the change occurs on the second list item on the other list

At the moment using the below I can only get this to happen on one of the li tags on any one click

$(document).ready(function() {

  $("ul.control li, ul.markers li").click(function() {
      $("ul.control li").removeClass("active");
      $(this).addClass("active");
      $("ul.markers li").removeClass("active");
      $(this).addClass("active");

});

Here is the markup for the two lists

Tab1

Tab2

Tab3

Tab4

1

2

3

4

Many thanks in advance for any help.

Body:
Much easier solution:

$(document).ready(function() {

  $("ul.control li, ul.markers li").click(function(e) {
     var that = $(this);
      that.siblings('.active').removeClass('active');
      that.addClass('active');
  });

});

Demo: http://jsfiddle.net/wesbos/mjmJH/2/


问:
aspect-ratio with dynamic width and height, similar to object-fit contain
I have a container element (chocolate color on screenshot), that contains a grid of tiles 3x2. The tiles contains image element with 16/9 resolution image and some header and footer. The tiles span can be 1-3 with 4px gap in between.
The image is set to object-fit:contain, The container element (chocolate color on screenshot) takes 100% width and height of parent (grey color), which causes, that the image tiles ratio do not matches the image ratio, and the image has bars around (blue aqua color on picture).
I need to scale the container element (chocolate color), so its content will gets such dimensions, that the image element will perfectly fit.

Here is stackblitz. I've tried to play with the aspect-ratio of the image parent, which worked for medium sized  resolutions, but not for small or big, then the image gets the aqua bars again.

For simplification, the stackblitz contains only one image element tile, which should perfectly fit into the chocolate element. You can ignore the grid inside the image.

https://stackblitz.com/edit/angular-ivy-xu92pf?file=src/app/app.component.css

Current (chocolate container takes 100% width and height from parent):

expected (chocolate container has width and height ratio, so that its image content 16/9 will perfectly fit. In real world, the image content will have not fixed w/h ratio):

答:
Is this what you expected? The key is using align-items: flex-start; to make the .image-container float the top of its .parent.

.parent {
  display: flex;
  align-items: flex-start; /* Keep the child element float to the top */
  width: 330px;
  min-height: 250px;
  background-color: grey;
  padding: 8px;
}

.image-container {
  background-color: chocolate;
  /*aspect-ratio: 16/10, 5;*/
  /*this will be custom calculated from the content of image-container*/
  width: 100%;
  padding: 5px;
}

img {
  height: 100%;
  width: 100%;
  background-color: aqua;
  object-fit: contain;
  display: block; /* to make the image fill up its parent element */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>#1</p>
<div class="parent">
  <div class="image-container">
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/14179/image.png" />
  </div>
</div>

<p>#2</p>

<div class="parent">
  <div class="image-container">
    <img src="https://picsum.photos/200/80" />
  </div>
</div>

<p>#3</p>

<div class="parent">
  <div class="image-container">
    <img src="https://picsum.photos/200/300" />
  </div>
</div></code>```

Body:
Is this what you expected? The key is using align-items: flex-start; to make the .image-container float the top of its .parent.

.parent {
  display: flex;
  align-items: flex-start; /* Keep the child element float to the top */
  width: 330px;
  min-height: 250px;
  background-color: grey;
  padding: 8px;
}

.image-container {
  background-color: chocolate;
  /*aspect-ratio: 16/10, 5;*/
  /*this will be custom calculated from the content of image-container*/
  width: 100%;
  padding: 5px;
}

img {
  height: 100%;
  width: 100%;
  background-color: aqua;
  object-fit: contain;
  display: block; /* to make the image fill up its parent element */
}

<p>#1</p>
<div class="parent">
  <div class="image-container">
    <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/14179/image.png" />
  </div>
</div>

<p>#2</p>

<div class="parent">
  <div class="image-container">
    <img src="https://picsum.photos/200/80" />
  </div>
</div>

<p>#3</p>

<div class="parent">
  <div class="image-container">
    <img src="https://picsum.photos/200/300" />
  </div>
</div>


问:
ReactJs: Prevent multiple times button press
In my React component I have a button meant to send some data over AJAX when clicked. I need to happen only the first time, i.e. to disable the button after its first use.

How I'm trying to do this:

```<code>var UploadArea = React.createClass({

  getInitialState() {
    return {
      showUploadButton: true
    };
  },

  disableUploadButton(callback) {
    this.setState({ showUploadButton: false }, callback);
  },

  // This was simpler before I started trying everything I could think of
  onClickUploadFile() {
    if (!this.state.showUploadButton) {
      return;
    }
    this.disableUploadButton(function() {
      $.ajax({
        [...]
      });

    });
  },

  render() {
    var uploadButton;
    if (this.state.showUploadButton) {
      uploadButton = (
        <button onClick={this.onClickUploadFile}>Send</button>
      );
    }

    return (
      <div>
        {uploadButton}
      </div>
    );
  }

});
</code>```

What I think happens is the state variable showUploadButton not being updated right away, which the React docs says is expected.

How could I enforce the button to get disabled or go away altogether the instant it's being clicked?

答:
My approach is if event on processing do not execute anything.</p>
```<code>class UploadArea extends React.Component {
constructor(props) {
super(props)

this.state = {
  onProcess:false
   }
}

uploadFile() {
 if (!this.state.onProcess){
   this.setState({
     onProcess: true
   });
   // then do your thing
   this.setState({
     onProcess: false;
   });
 }
}

render() {
  return (
    <button
      type='submit'
      onClick={() => this.uploadFile()}>
      Upload
    </button>
   )
  }
}

ReactDOM.render(<UploadArea />, document.body);
</code>```

Body:
In my React component I have a button meant to send some data over AJAX when clicked. I need to happen only the first time, i.e. to disable the button after its first use.

How I'm trying to do this:

var UploadArea = React.createClass({

  getInitialState() {
    return {
      showUploadButton: true
    };
  },

  disableUploadButton(callback) {
    this.setState({ showUploadButton: false }, callback);
  },

  // This was simpler before I started trying everything I could think of
  onClickUploadFile() {
    if (!this.state.showUploadButton) {
      return;
    }
    this.disableUploadButton(function() {
      $.ajax({
        [...]
      });

    });
  },

  render() {
    var uploadButton;
    if (this.state.showUploadButton) {
      uploadButton = (
        <button onClick={this.onClickUploadFile}>Send</button>
      );
    }

    return (

        {uploadButton}

    );
  }

});

What I think happens is the state variable showUploadButton not being updated right away, which the React docs says is expected.

How could I enforce the button to get disabled or go away altogether the instant it's being clicked?

Body:
My approach is if event on processing do not execute anything.

class UploadArea extends React.Component {
constructor(props) {
super(props)

this.state = {
  onProcess:false
   }
}

uploadFile() {
 if (!this.state.onProcess){
   this.setState({
     onProcess: true
   });
   // then do your thing
   this.setState({
     onProcess: false;
   });
 }
}

render() {
  return (
    <button
      type='submit'
      onClick={() => this.uploadFile()}>
      Upload
    </button>
   )
  }
}

ReactDOM.render(<UploadArea />, document.body);


问:
How to disable auto detect datatype in azure data flow
I was working on a XML file in ADF and there is a field that is having 42 integer digits. I want it to be reflected as it is in azure data flow so that I could perform some transformations
There is a checkbox "Detect Data Type" in copy data activity which when unchecked provides the exact value.
but when using the dataflow, it is not giving any option to not to perform auto detect data type .
kindly suggest what need to be done</p>
```<code>    <?xml version="1.0" encoding="UTF-8"?>
   <start>
       <name>ABC</name>
       <id>123456789098765432123456789098765432123456</id>
   </start>
</code>```

答:
Import projection from the Projection tab is used to Import schema and detect data types from the source. If you just don't click it or use this, your data columns will be of type string.

Here is an example:

Source XML:

Import projections:

You can see the column id is inferred as type Double

While if you just don't use Import projection option, and Reset Schema

you get the column id as type String

For further details, refer official MS doc on ADF Dataflow Projections

Body:
I was working on a XML file in ADF and there is a field that is having 42 integer digits. I want it to be reflected as it is in azure data flow so that I could perform some transformations
There is a checkbox "Detect Data Type" in copy data activity which when unchecked provides the exact value.
but when using the dataflow, it is not giving any option to not to perform auto detect data type .
kindly suggest what need to be done

    <?xml version="1.0" encoding="UTF-8"?>
   <start>
       <name>ABC</name>
       <id>123456789098765432123456789098765432123456</id>
   </start>


问:
Cant navigate to individual router pages of react application
I have a react app that is held on gh-pages. This page has a '/Main' as its home route and a '/le' route which has been linked in the Main. This link, which is styled in the form of a button, works perfectly.

The problem arises when I try to go to the gh-page URL profile.github.io/le(this is the url where the router link takes me to when I click the button) , it takes me to a dead GitHub page. Why am i able to navigate there using router link but not access it directly by the URL.

答:
Navigating within a single page application uses a trick: it replaces the content and modifies the URL (there is an API for that) without causing a full page reload, the server doesn't even notice those kind of navigation. That modified URL's path could be anything, it does not have to correspond to real files.

When trying to directly open such a routed URL  though, you are asking the github server to deliver content for that location and it tries to find a file at the given path. When there is no such file, a 404 page is shown instead. The server does not know you actually want to open the entry file and let its internal (react) routing do the actual navigation work.

There is a helper which replaces the 404 page and augments the entry page to get the desired behavior: https://github.com/rafgraph/spa-github-pages


问:
Get all files recursively in directories NodejS
I have a little problem with my function. I would like to get all files in many directories. Currently, I can retrieve the files in the file passed in parameters. I would like to retrieve the html files of each folder in the folder passed as a parameter. I will explain if I put in parameter "test" I retrieve the files in "test" but I would like to retrieve "test / 1 / *. Html", "test / 2 / . /.html ":

```<code>var srcpath2 = path.join('.', 'diapo', result);
function getDirectories(srcpath2) {
                return fs.readdirSync(srcpath2).filter(function (file) {
                    return fs.statSync(path.join(srcpath2, file)).isDirectory();
                });
            }
</code>```

The result :
[1,2,3]

thanks !

答:
Although not perfect in some scenarios, it must be helpful in many.</p>
```<code>const getAllFilePath = (path: string) => {
    const addData = (_paths: string[]) => {
        const newFoldersToScrape: string[] = [];

        _paths.forEach(_path => {
            fs.readdirSync(_path).forEach((file: string) => {
                if (file.indexOf(".") === -1) {
                    newFoldersToScrape.push(`${_path}/${file}`);
                } else {
                    filePaths.push(`${_path}/${file}`);
                }
            });
        });

        foldersToScrape = newFoldersToScrape;
    };

    const baseDirPath = `<YOUR BASE PATH HERE>/${path}`;
    let foldersToScrape: string[] = [];
    const filePaths: string[] = [];

    addData([baseDirPath]);

    while (foldersToScrape.length !== 0) {
        addData(foldersToScrape);
    }

    return filePaths;
};
</code>```

Body:
I have a little problem with my function. I would like to get all files in many directories. Currently, I can retrieve the files in the file passed in parameters. I would like to retrieve the html files of each folder in the folder passed as a parameter. I will explain if I put in parameter "test" I retrieve the files in "test" but I would like to retrieve "test / 1 / *. Html", "test / 2 / . /.html ":

var srcpath2 = path.join('.', 'diapo', result);
function getDirectories(srcpath2) {
                return fs.readdirSync(srcpath2).filter(function (file) {
                    return fs.statSync(path.join(srcpath2, file)).isDirectory();
                });
            }

The result :
[1,2,3]

thanks !

Body:
Although not perfect in some scenarios, it must be helpful in many.

const getAllFilePath = (path: string) => {
    const addData = (_paths: string[]) => {
        const newFoldersToScrape: string[] = [];

        _paths.forEach(_path => {
            fs.readdirSync(_path).forEach((file: string) => {
                if (file.indexOf(".") === -1) {
                    newFoldersToScrape.push(`${_path}/${file}`);
                } else {
                    filePaths.push(`${_path}/${file}`);
                }
            });
        });

        foldersToScrape = newFoldersToScrape;
    };

    const baseDirPath = `<YOUR BASE PATH HERE>/${path}`;
    let foldersToScrape: string[] = [];
    const filePaths: string[] = [];

    addData([baseDirPath]);

    while (foldersToScrape.length !== 0) {
        addData(foldersToScrape);
    }

    return filePaths;
};


问:
Issue when trying to show id dynamically in Vuejs?
AppTabs.vue

<template>

        <label
          :for="`${_uid}${index}`"
          v-text="tab.tab"
          class="cursor-pointer block"
        />
        <input
          :id="`${_uid}${index}`"
          type="radio"
          :name="`${_uid}-tab`"
          :value="index + 1"
          v-model="activeTab"
          class="hidden"
        />

    <template v-for="(tab, index) in tabList">

        <slot :name="index + 1" />

    </template>

</template>```
</div>
</div>
</p>
<p><strong>App.vue</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export const datalist = [
  {
    id: 1, tab: "Tab 1a", val: "1", content: "Content 1"
  },
  { id: 2, tab: "Tab 2", val: "2", content: "Content 2" },
  { id: 3, tab: "Tab 3", val: "3", content: "Content 3" },
  { id: 4, tab: "Tab 4", val: "4", content: "Content 4" },

];</code>```

Where in the above code i have like ** :for="${_uid}${index}"** :id="${_uid}${index}" :name="${_uid}-tab"  Where it generates an id for the input field.

Instead of generating an id for input fields to be able to use the labels for this input field. Can i use my own ID Because my API have field like DeptId ( i tried to integrate my api, Then i come to know that if in api i have field like id then only my api is working or else it is not working i have tested..)

So can u please tell me, What changes i need to make in order to remove the auto generation of an id for input fields. And keep my id instead So that it works please.

Because i dont want to generate id by itself. instead want to keep id which is comming from an api like(DeptId)... And getting many error when i tried removing the id generation and bind my data from an array

答:
First defining slot should have a name not id for non-default slot.
So in AppTabs.vue you will have to change it to:

```<code><slot :name="`tabPanel-${index + 1}`" />
</code>```

And to override these slots, you either use the v-slot="slot-name" or use the shorthand #. So you would need to change your code in App.vue

```<code><template v-for="content in contentList" :v-slot="content.id">
</code>```

Or v-slot:[dynamicSlotName] in case you are using vue3.

Now regarding your code. The slot name you create tabPanel-${index + 1} will never be equal to the id you use in your parent component this code evaluates to the string "1-{{index+1}}". the slot name you defined will be overridden when you use v-slot with the name of the slot.

For more info i would suggest you read the slots doc in the website:

Vue2: https://v2.vuejs.org/v2/guide/components-slots.html

vue3: https://vuejs.org/guide/components/slots.html

Body:
AppTabs.vue

<template>

        <label
          :for="`${_uid}${index}`"
          v-text="tab.tab"
          class="cursor-pointer block"
        />
        <input
          :id="`${_uid}${index}`"
          type="radio"
          :name="`${_uid}-tab`"
          :value="index + 1"
          v-model="activeTab"
          class="hidden"
        />

    <template v-for="(tab, index) in tabList">

        <slot :name="index + 1" />

    </template>

</template>

App.vue

export const datalist = [
  {
    id: 1, tab: "Tab 1a", val: "1", content: "Content 1"
  },
  { id: 2, tab: "Tab 2", val: "2", content: "Content 2" },
  { id: 3, tab: "Tab 3", val: "3", content: "Content 3" },
  { id: 4, tab: "Tab 4", val: "4", content: "Content 4" },

];

Where in the above code i have like ** :for="${_uid}${index}"** :id="${_uid}${index}" :name="${_uid}-tab"  Where it generates an id for the input field.

Instead of generating an id for input fields to be able to use the labels for this input field. Can i use my own ID Because my API have field like DeptId ( i tried to integrate my api, Then i come to know that if in api i have field like id then only my api is working or else it is not working i have tested..)

So can u please tell me, What changes i need to make in order to remove the auto generation of an id for input fields. And keep my id instead So that it works please.

Because i dont want to generate id by itself. instead want to keep id which is comming from an api like(DeptId)... And getting many error when i tried removing the id generation and bind my data from an array

Body:
First defining slot should have a name not id for non-default slot.
So in AppTabs.vue you will have to change it to:

<slot :name="`tabPanel-${index + 1}`" />

And to override these slots, you either use the v-slot="slot-name" or use the shorthand #. So you would need to change your code in App.vue

<template v-for="content in contentList" :v-slot="content.id">

Or v-slot:[dynamicSlotName] in case you are using vue3.

Now regarding your code. The slot name you create tabPanel-${index + 1} will never be equal to the id you use in your parent component this code evaluates to the string "1-{{index+1}}". the slot name you defined will be overridden when you use v-slot with the name of the slot.

For more info i would suggest you read the slots doc in the website:

Vue2: https://v2.vuejs.org/v2/guide/components-slots.html

vue3: https://vuejs.org/guide/components/slots.html


问:
Target-specific variables in a makefile & prerequisites
I'm seeing unexpected results for target-specfic variables in GNU make.

What I want is to set a target-specific variable that affects dependencies. I can use .SECONDEXPANSION to achieve that.

```<code>some-target: DEP := debug-dep

debug: some-target

.SECONDEXPANSION:
some-target: $$(DEP)
    @echo $^

debug-dep:
</code>```

make debug prints debug-dep.

Now I read that make defines target-specific variables for descendant rules:

When you define a target-specific variable that variable value is also in effect for all prerequisites of this target, and all their prerequisites, etc.

But when I change my makefile to have the variable set on "parent" target:

```<code>debug: DEP := debug-dep

debug: some-target

.SECONDEXPANSION:
some-target: $$(DEP)
    @echo $^

debug-dep:
</code>```

and do make debug I get a blank line.

This seems to contradict the documented behavior of target-specific variables. Is there something that I am missing?

This is sort of similar to make: Using target specific variables in prerequisites, but what I am doing isn't working.

答:
All variables are set in the first read-in phase. It is true no matter it is a global variable, or a target-specific variable (or a pattern-specific variable).

There is no such thing that is like the other answer says

target-specific variables are not set until the targets are being run

See the example Makefile below,

```<code>GA = ga
GB = $(GA)
GC := $(GA)

a: aTA = $(GA)
a: aTB := $(GA)
a: aTC = $(aTA)
a: b;
GA = ga2

b: bTA = $(aTA)
b: bTB := $(aTA)
b: bTC := $(bTA)
b:;
</code>```

After the first read-in phase, all variables are set (therefore, aTB is ga, not ga2). They are as follows respectively,

GA is literal ga2

GB is literal $(GA)

GC is literal ga

aTA is literal $(GA)

aTB is literal ga

aTC is literal $(aTA)

bTA is literal $(aTA)

bTB is literal   (empty)

bTC is literal   (empty)

Although they are all set, they are not visible everywhere, they have scope. E.g.,

Global variables' scope is everywhere

Target-specific variables' scope is

the target's other target-specific variables

the recipe of the target

the recipes of the target's prerequisites

This is the only reason that we could see bTA is eventually expanded to ga2 if we use bTA in the target b's recipe.

the prerequisite-literal appearing in the target's rule when using .SECONDEXPANSION

This is why the 1st case in OP's question works.

The following is NOT the scope of a target-specific variable,

everywhere in the parent target

the target-specific variables of the target's prerequisites

This is why bTB and bTC are both empty.

the (sub) prerequisite-literal appearing in the rule of the target's prerequisites (whether using .SECONDEXPANSION or not)

This is why the 2nd case in OP's question doesn't work.

Body:
I'm seeing unexpected results for target-specfic variables in GNU make.

What I want is to set a target-specific variable that affects dependencies. I can use .SECONDEXPANSION to achieve that.

some-target: DEP := debug-dep

debug: some-target

.SECONDEXPANSION:
some-target: $$(DEP)
    @echo $^

debug-dep:

make debug prints debug-dep.

Now I read that make defines target-specific variables for descendant rules:

When you define a target-specific variable that variable value is also in effect for all prerequisites of this target, and all their prerequisites, etc.

But when I change my makefile to have the variable set on "parent" target:

debug: DEP := debug-dep

debug: some-target

.SECONDEXPANSION:
some-target: $$(DEP)
    @echo $^

debug-dep:

and do make debug I get a blank line.

This seems to contradict the documented behavior of target-specific variables. Is there something that I am missing?

This is sort of similar to make: Using target specific variables in prerequisites, but what I am doing isn't working.

Body:
All variables are set in the first read-in phase. It is true no matter it is a global variable, or a target-specific variable (or a pattern-specific variable).

There is no such thing that is like the other answer says

target-specific variables are not set until the targets are being run

See the example Makefile below,

GA = ga
GB = $(GA)
GC := $(GA)

a: aTA = $(GA)
a: aTB := $(GA)
a: aTC = $(aTA)
a: b;
GA = ga2

b: bTA = $(aTA)
b: bTB := $(aTA)
b: bTC := $(bTA)
b:;

After the first read-in phase, all variables are set (therefore, aTB is ga, not ga2). They are as follows respectively,

GA is literal ga2

GB is literal $(GA)

GC is literal ga

aTA is literal $(GA)

aTB is literal ga

aTC is literal $(aTA)

bTA is literal $(aTA)

bTB is literal   (empty)

bTC is literal   (empty)

Although they are all set, they are not visible everywhere, they have scope. E.g.,

Global variables' scope is everywhere

Target-specific variables' scope is

the target's other target-specific variables

the recipe of the target

the recipes of the target's prerequisites

This is the only reason that we could see bTA is eventually expanded to ga2 if we use bTA in the target b's recipe.

the prerequisite-literal appearing in the target's rule when using .SECONDEXPANSION

This is why the 1st case in OP's question works.

The following is NOT the scope of a target-specific variable,

everywhere in the parent target

the target-specific variables of the target's prerequisites

This is why bTB and bTC are both empty.

the (sub) prerequisite-literal appearing in the rule of the target's prerequisites (whether using .SECONDEXPANSION or not)

This is why the 2nd case in OP's question doesn't work.


问:
Can't add any items to activity_main.xml in Android Studio
In Android Studio, I can't add any items from Palette to activity_main.xml in Design view. It just won't let me drag and drop them. Any idea why this happens?

Here is the PrintScreen:

答: While you have marked a witget the editor don't let you drag.</p>


问:
How to draw a bmp/icon on a TListView subitem in Delphi?
I would like to draw an icon/bmp into a subitem of a TListView using delphi. But I don't know how to accomplish that. It works fine for the first item on the list, but having problems with the subitems.</p>

答:
You could use the CustomDrawSubItem event.

The example below ignores the text and draws rectangles. Unfortunately it is a bit of a hassle to get the rectangle for the right column, but this approach works:

```<code>procedure TForm.ListViewCustomDrawSubItem(Sender: TCustomListView;
  Item: TListItem; SubItem: Integer; State: TCustomDrawState;
  var DefaultDraw: Boolean);
var
  r : TRect;
  i : Integer;
begin
  r := Item.DisplayRect(drBounds);
  for i := 0 to SubItem-1 do begin
    r.Left := r.Left + ListView.Columns.Items[i].Width;
    r.Right := r.Left  + ListView.Columns.Items[i+1].Width;
  end;
  case SubItem of
     1 : ListView.Canvas.Pen.Color := clRed;
  else
    ListView.Canvas.Pen.Color := clBlue;
  end;

  ListView.Canvas.Rectangle(r.Left, r.Top, r.Right, r.Bottom);
  DefaultDraw := False;
end;
</code>```

OwnerDisplayName: tecnotalk

ContentLicense: CC BY-SA 2.5

Body:
You could use the CustomDrawSubItem event.

The example below ignores the text and draws rectangles. Unfortunately it is a bit of a hassle to get the rectangle for the right column, but this approach works:

procedure TForm.ListViewCustomDrawSubItem(Sender: TCustomListView;
  Item: TListItem; SubItem: Integer; State: TCustomDrawState;
  var DefaultDraw: Boolean);
var
  r : TRect;
  i : Integer;
begin
  r := Item.DisplayRect(drBounds);
  for i := 0 to SubItem-1 do begin
    r.Left := r.Left + ListView.Columns.Items[i].Width;
    r.Right := r.Left  + ListView.Columns.Items[i+1].Width;
  end;
  case SubItem of
     1 : ListView.Canvas.Pen.Color := clRed;
  else
    ListView.Canvas.Pen.Color := clBlue;
  end;

  ListView.Canvas.Rectangle(r.Left, r.Top, r.Right, r.Bottom);
  DefaultDraw := False;
end;

OwnerDisplayName: Gamecat


问:
how to flush the ZipOutputStream periodically in java
I am trying to archive list of files in zip format and then downloading it for the user on the fly...

I am facing out of memory issue when downloading a zip of 1gb size

Please help me how i can resolve this without increasing jvm heap size. i would like to flush the stream periodically..

I AM TRYING TO FLUSH PERIODICALLY BUT THIS IS NOT WORKING FOR ME.

Please find my code attached below:

```<code>try{
ServletOutputStream out = response.getOutputStream();
        ZipOutputStream zip = new ZipOutputStream(out);

        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition",
                "attachment; filename=\"ResultFiles.zip\"");
                  //adding multiple files to zip
        ZipUtility.addFileToZip("c:\\a", "print1.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print2.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print3.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print4.txt", zip);

zip.flush();
zip.close();
out.close();
} catch (ZipException ex) {
            System.out.println("zip exception");
        } catch (Exception ex) {
            System.out.println("exception");
            ex.printStackTrace();
}
</code>```

```<code>public class ZipUtility {

    static public void addFileToZip(String path, String srcFile,
            ZipOutputStream zip) throws Exception {

        File file = new File(path + "\\" + srcFile);
        boolean exists = file.exists();
        if (exists) {

            long fileSize = file.length();
            int buffersize = (int) fileSize;
            byte[] buf = new byte[buffersize];

            int len;
            FileInputStream fin = new FileInputStream(path + "\\" + srcFile);
            zip.putNextEntry(new ZipEntry(srcFile));
            int bytesread = 0, bytesBuffered = 0;
            while ((bytesread = fin.read(buf)) > -1) {
                zip.write(buf, 0, bytesread);
                bytesBuffered += bytesread;
                if (bytesBuffered > 1024 * 1024) { //flush after 1mb
                    bytesBuffered = 0;
                    zip.flush();

                }
            }
            zip.closeEntry();
            zip.flush();
            fin.close();
        }

    }
}

}
</code>```

答: Don't size your buf based on the file size, use a fixed size buffer.

Body:
I am trying to archive list of files in zip format and then downloading it for the user on the fly...

I am facing out of memory issue when downloading a zip of 1gb size

Please help me how i can resolve this without increasing jvm heap size. i would like to flush the stream periodically..

I AM TRYING TO FLUSH PERIODICALLY BUT THIS IS NOT WORKING FOR ME.

Please find my code attached below:

try{
ServletOutputStream out = response.getOutputStream();
        ZipOutputStream zip = new ZipOutputStream(out);

        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition",
                "attachment; filename=\"ResultFiles.zip\"");
                  //adding multiple files to zip
        ZipUtility.addFileToZip("c:\\a", "print1.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print2.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print3.txt", zip);
ZipUtility.addFileToZip("c:\\a", "print4.txt", zip);

zip.flush();
zip.close();
out.close();
} catch (ZipException ex) {
            System.out.println("zip exception");
        } catch (Exception ex) {
            System.out.println("exception");
            ex.printStackTrace();
}

public class ZipUtility {

    static public void addFileToZip(String path, String srcFile,
            ZipOutputStream zip) throws Exception {

        File file = new File(path + "\\" + srcFile);
        boolean exists = file.exists();
        if (exists) {

            long fileSize = file.length();
            int buffersize = (int) fileSize;
            byte[] buf = new byte[buffersize];

            int len;
            FileInputStream fin = new FileInputStream(path + "\\" + srcFile);
            zip.putNextEntry(new ZipEntry(srcFile));
            int bytesread = 0, bytesBuffered = 0;
            while ((bytesread = fin.read(buf)) > -1) {
                zip.write(buf, 0, bytesread);
                bytesBuffered += bytesread;
                if (bytesBuffered > 1024 * 1024) { //flush after 1mb
                    bytesBuffered = 0;
                    zip.flush();

                }
            }
            zip.closeEntry();
            zip.flush();
            fin.close();
        }

    }
}

}


问:
Error TS2531 object is possibly null in angular reactive forms
Hi i have tried to do reactive form validation in angular 11 but its showing following error in terminal.

error TS2531 object is possibly null.

my code in signup.component.ts

```<code>import {FormGroup, FormControl, Validators} from '@angular/forms';

form =  new FormGroup({
    firstName: new FormControl('',Validators.required)
})

get f()
{
    return this.form.controls;
}
</code>```

in signup.component.html

```<code><form role="form" [formGroup]="form">
    <div class="form-group">
        <label>Name</label>
        <input type="text" name="name" class="form-control" formControlName="firstName" [ngClass]="{'is-invalid':form.get('firstName').touched && form.get('firstName').invalid}">
        <div *ngIf="f.firstName.touched && f.firstName.invalid">
            <small class="text-danger" *ngIf="f.firstName.errors.required">
                Name is required!
            </small>

        </div>
    </div>
</form>
</code>```

when i run its showing error in

<small class="text-danger" *ngIf="f.firstName.errors.required">
Name is required!

error TS2531 object is possibly null.

答: We can us form.controls['firstName] and form.controls['firstName].errors?.length</p>

Body:
Hi i have tried to do reactive form validation in angular 11 but its showing following error in terminal.

error TS2531 object is possibly null.

my code in signup.component.ts

import {FormGroup, FormControl, Validators} from '@angular/forms';

form =  new FormGroup({
    firstName: new FormControl('',Validators.required)
})

get f()
{
    return this.form.controls;
}

in signup.component.html

<form role="form" [formGroup]="form">

        Name
        <input type="text" name="name" class="form-control" formControlName="firstName" [ngClass]="{'is-invalid':form.get('firstName').touched && form.get('firstName').invalid}">

                Name is required!

</form>

when i run its showing error in

<small class="text-danger" *ngIf="f.firstName.errors.required">
Name is required!

error TS2531 object is possibly null.


问:
Connecting rows in Data Frame in python
I have Data Frame of 2 columns, I'm trying to combine each 3 rows into one row with "or" condition
between them.
I can't find smart and easy solution.

data frame:

dorks list  ofek rank
0                         allintext:"nike" acquisition          2
1                            allintext:"nike" acquired          2
2                                 allintext:"nike" buy          2
3                                allintext:"nike" sell          2
4                                allintext:"nike" sold          2
..                                                 ...        ...
481    insubject:"nike" divested source:prnewswire.com          4
482       insubject:"nike" divested source:reuters.com          4
483  insubject:"nike" divested source:seekingalpha.com          4
484     insubject:"nike" divested source:pitchbook.com          4
485     insubject:"nike" divested source:bloombarg.com          4
```

The desired result:

allintext:"nike" acquisition or allintext:"nike" acquired or allintext:"nike" buy
for each 3 rows.

答:
Assuming you have a range index:

```<code>df.groupby(df.index//3).agg(**{'result': ('dorks list', ' or '.join),
                               'mean_rank': ('ofek rank', 'mean')
                              })
</code>```

NB. I don't know what you want to do with "ofek rank", so I took the mean, but you can do whatever you want (first, min, max… or join like the other column)
output:

```<code>                                                result  mean_rank
0    allintext:"nike" acquisition or allintext:"nik...        2.0
1       allintext:"nike" sell or allintext:"nike" sold        2.0
160  insubject:"nike" divested source:prnewswire.co...        4.0
161  insubject:"nike" divested source:seekingalpha....        4.0
</code>```

If you don't have a range index, replace df.index//3 with np.arange(len(df))//3

Title: Connecting rows in Data Frame in python

Body:
I have Data Frame of 2 columns, I'm trying to combine each 3 rows into one row with "or" condition
between them.
I can't find smart and easy solution.

data frame:

dorks list  ofek rank
0                         allintext:"nike" acquisition          2
1                            allintext:"nike" acquired          2
2                                 allintext:"nike" buy          2
3                                allintext:"nike" sell          2
4                                allintext:"nike" sold          2
..                                                 ...        ...
481    insubject:"nike" divested source:prnewswire.com          4
482       insubject:"nike" divested source:reuters.com          4
483  insubject:"nike" divested source:seekingalpha.com          4
484     insubject:"nike" divested source:pitchbook.com          4
485     insubject:"nike" divested source:bloombarg.com          4

The desired result:

allintext:"nike" acquisition or allintext:"nike" acquired or allintext:"nike" buy
for each 3 rows.

Body:
Assuming you have a range index:

df.groupby(df.index//3).agg(**{'result': ('dorks list', ' or '.join),
                               'mean_rank': ('ofek rank', 'mean')
                              })

NB. I don't know what you want to do with "ofek rank", so I took the mean, but you can do whatever you want (first, min, max… or join like the other column)
output:

                                                result  mean_rank
0    allintext:"nike" acquisition or allintext:"nik...        2.0
1       allintext:"nike" sell or allintext:"nike" sold        2.0
160  insubject:"nike" divested source:prnewswire.co...        4.0
161  insubject:"nike" divested source:seekingalpha....        4.0

If you don't have a range index, replace df.index//3 with np.arange(len(df))//3


问:
Updating RTK (redux toolkit) state using other state values
Can I update the state based on other state variables (as shown below in setCurrentQuestion()), or will it cause unexpected issues?

I can think of two workarounds:

"external" helper function that calls a getCurrentQuestionIndex() selector passed into a getQuestionByIndex() selector which returns an IQuestion object that I pass into the setCurrentQuestion() reducer

Keep as is but use a draft safe selector instead of accessing the state object directly

const slice = createSlice({
    name: 'blabla',
    initialState: { questions: undefined, currentQuestion: undefined, noOfQuestions: 0, currentQuestionIndex: 0 } as QuizState,
    reducers: {
        setQuestions: (state, action: PayloadAction<IQuestion[]>) => {
            state.questions = action.payload;
        },
        setCurrentQuestion: (state, action: PayloadAction<number>) => {
            if (!state.questions) return
            state.currentQuestion = state.questions[state.currentQuestionIndex]
        }
    },
```

答:
state.currentQuestion should simply not exist in your state. You got state.questions as the source of truth, and state.currentQuestionIndex to remember which question is the current question. Anything further is not atomic and minimal anymore. It certainly works to have a state.currentQuestion which duplicates one of the items in state.questions, but then you end up with problems like this one. I'd recommend to add a selector getCurrentQuestion() that does the lookup and that can deal with state.questions being falsy. It also should never not be an array btw, it's easier to deal with state if the types don't change. I'd initialise it as an empty array, and then the selector could be:

```<code>const getCurrentQuestion = (state) => state.questions[state.currentQuestionIndex];
</code>```

To solve what you had in mind, looking at a different part of the state before mutating it in the reducer, you could also use a thunk - they have getState() in the scope and can run conditional logic. So you could simply not dispatch setCurrentQuestion if state.questions is falsy. But a better solution imo is what I described above with the selector.

Body:
state.currentQuestion should simply not exist in your state. You got state.questions as the source of truth, and state.currentQuestionIndex to remember which question is the current question. Anything further is not atomic and minimal anymore. It certainly works to have a state.currentQuestion which duplicates one of the items in state.questions, but then you end up with problems like this one. I'd recommend to add a selector getCurrentQuestion() that does the lookup and that can deal with state.questions being falsy. It also should never not be an array btw, it's easier to deal with state if the types don't change. I'd initialise it as an empty array, and then the selector could be:

const getCurrentQuestion = (state) => state.questions[state.currentQuestionIndex];

To solve what you had in mind, looking at a different part of the state before mutating it in the reducer, you could also use a thunk - they have getState() in the scope and can run conditional logic. So you could simply not dispatch setCurrentQuestion if state.questions is falsy. But a better solution imo is what I described above with the selector.


问:
Benchmarking VBA Code
What is considered the most accurate way to benchmark VBA code (in my case, I am testing code in Excel)? Are there any other techniques for benchmarking code besides the 2 below, and if so, what are the pros/cons of the method?

Here are 2 popular methods.

First: Timer

Sub TimerBenchmark()

Dim benchmark As Double
benchmark = Timer

'Do your code here

MsgBox Timer - benchmark

End Sub
```

<p>And <strong>Tick</strong> (which I see argued as the most accurate):</p>

```Option Explicit
Private Declare Function GetTickCount Lib "kernel32" () As Long

Sub TickBenchmark()

Dim Start As Long
Dim Finish As Long

Start = GetTickCount()

'Do your code here

Finish = GetTickCount()
MsgBox CStr((Finish - Start) / 1000)

End Sub
```

答: Any measurement is going to be noisy, so if you want precision, repeat the measurement many times and average the result.</p>

Title: Benchmarking VBA Code

Body:
What is considered the most accurate way to benchmark VBA code (in my case, I am testing code in Excel)? Are there any other techniques for benchmarking code besides the 2 below, and if so, what are the pros/cons of the method?

Here are 2 popular methods.

First: Timer

Sub TimerBenchmark()

Dim benchmark As Double
benchmark = Timer

'Do your code here

MsgBox Timer - benchmark

End Sub

And Tick (which I see argued as the most accurate):

Option Explicit
Private Declare Function GetTickCount Lib "kernel32" () As Long

Sub TickBenchmark()

Dim Start As Long
Dim Finish As Long

Start = GetTickCount()

'Do your code here

Finish = GetTickCount()
MsgBox CStr((Finish - Start) / 1000)

End Sub


问:
Why is my for-loop over a file not starting after using readlines()?
I'm trying to read info from a file and print it's information. Using a test program, I could get it working like this:

file = open("cooltextfile.txt", "r")
for line in file:
    if "BobRoss" in line:
        print(line)
```
<p>Using above method, it prints all lines containing "Bob Ross".</p>
<p>However, when I use it in my main program like this, it's not even printing the line if I tell it to print the whole line:</p>
<pre class="lang-py prettyprint-override"><code>number = 0
index = 0

textFile = open("cooltextfile.txt", "r")
lineInfo = textFile.readlines()

for line in textFile:
    index += 1

    print(line) # - An attempt to print the entire line

    if "BobRoss" in line:
        number += 1

        print(str(number) + ". " + line)
        print("Order: " + lineInfo[index])

textFile.close()
</code>```

Upon further inspection it would seem that the for-loop never starts. Any reason as to what could be causing the loop to not start?

答:
Suggestions:

use enumerate to get the index,

you have to loop through the lines, so use lines = file.readlines() or it will get just a character

use fstrings instead of concatenation, it will be faster

use with open(filename,'r'), instead of fp = open(filename)it will be cleaner and it will close your file at the end automatically.

code reassembled:

```<code>with open("cooltextfile.txt",'r') as textFile:
    number,index = 0,0
    lines=textFile.readlines()
    for index,line in enumerate(lines):
        if "BobRoss" in line:
            number += 1 #incrementing the number of lines that contains BobRoss
            print(f"{number}.{line}")
            print(f"Order: {index}")
</code>```

Body:
I'm trying to read info from a file and print it's information. Using a test program, I could get it working like this:

file = open("cooltextfile.txt", "r")
for line in file:
    if "BobRoss" in line:
        print(line)

Using above method, it prints all lines containing "Bob Ross".

However, when I use it in my main program like this, it's not even printing the line if I tell it to print the whole line:

number = 0
index = 0

textFile = open("cooltextfile.txt", "r")
lineInfo = textFile.readlines()

for line in textFile:
    index += 1

    print(line) # - An attempt to print the entire line

    if "BobRoss" in line:
        number += 1

        print(str(number) + ". " + line)
        print("Order: " + lineInfo[index])

textFile.close()

Upon further inspection it would seem that the for-loop never starts. Any reason as to what could be causing the loop to not start?

Body:
Suggestions:

use enumerate to get the index,

you have to loop through the lines, so use lines = file.readlines() or it will get just a character

use fstrings instead of concatenation, it will be faster

use with open(filename,'r'), instead of fp = open(filename)it will be cleaner and it will close your file at the end automatically.

code reassembled:

with open("cooltextfile.txt",'r') as textFile:
    number,index = 0,0
    lines=textFile.readlines()
    for index,line in enumerate(lines):
        if "BobRoss" in line:
            number += 1 #incrementing the number of lines that contains BobRoss
            print(f"{number}.{line}")
            print(f"Order: {index}")


问:
How to offset a div in a css grid
It's possible to "offset" a div in a css grid as in the image ?

答:
If you are using Mozilla's guide in this link, you can use empty div like this as offset div:</p>
```<code><div class="container">
   <div class="row">

       <!-- Empty/Offset Div Here -->
       <div class="col-xl-2"> </div>

       <div class="col-xl-8">
          <!-- Content Here -->
       </div>
   </div>
</div>
</code>```

Title: How to offset a div in a css grid

Body:
If you are using Mozilla's guide in this link, you can use empty div like this as offset div:

<div class="container">
   <div class="row">

       <!-- Empty/Offset Div Here -->
       <div class="col-xl-2"> </div>

       <div class="col-xl-8">
          <!-- Content Here -->
       </div>
   </div>
</div>


问:
Formik returns old values state
I'm having this trouble with async state management with Formik. I need to dynamically show a result, according to input changes, but I get every time the old state. Do you know a workaround?
I need the result state to be updated with changes in the Field's component.

Here's my code:

```<code> function Simulator() {
  const [result, setResult] = useState(undefined);

  const LeasingSchema = Yup.object().shape({
    monthDuration: Yup.number()
      .min(6, "6 months minimum")
      .max(48, "48 months maximum")
      .required("Required"),
    amountFinanced: Yup.number()
      .min(10000, "The minimum finance is 10.000€")
      .max(100000, "The maximum finance is 100.000€")
      .required("Required")
  });

  const handleCalculation = (values, errors) => {
    const { monthDuration, amountFinanced } = values;

    if (monthDuration && amountFinanced && Object.keys(errors).length === 0) {
      //Round number
      const roundedValue = parseFloat(amountFinanced / monthDuration).toFixed(
        2
      );
      return setResult(roundedValue);
    } else {
      return setResult(undefined);
    }
  };

  return (
    <div className={styles.leasing}>
      <h1>Leasing simulator:</h1>

      <Formik
        initialValues={{
          monthDuration: "",
          amountFinanced: ""
        }}
        validationSchema={LeasingSchema}
        onSubmit={(values) => console.log(values)}
      >
        {({ errors, touched, values, handleChange }) => (
          <Form>
            <label htmlFor="form-monthly-duration">Monthly duration:</label>
            <Field
              type="number"
              name="monthDuration"
              placeholder="Months"
              id="form-monthly-duration"
              onChange={(e) => {
                handleChange(e);
                handleCalculation(values, errors);
              }}
            />
            {result && (
              <>
                <label htmlFor="result">Monthly fee:</label>
                <p>{result}</p>
              </>
            )}
            <button type="submit">Submit</button>
          </Form>
        )}
      </Formik>
    </div>
  );
}

export default Simulator;
</code>```

答:
The values in handleCalculation are never updated because you are using a controlled component. Form data must be updated by state.

To update by state, set your result to

```<code>const [result, setResult] = useState({
    monthDuration: 0,
    amountFinanced: <any number between 10000 to 100000>,
});
</code>```

Then set initialValues in Formik component to

```<code>initialValues={result}
</code>```

Full code here:

```<code>const Simulator = () => {
    const [result, setResult] = useState({
        monthDuration: 0,
        amountFinanced: 10000,
    });

    const LeasingSchema = Yup.object().shape({
        monthDuration: Yup.number()
            .min(6, "6 months minimum")
            .max(48, "48 months maximum")
            .required("Required"),
        amountFinanced: Yup.number()
            .min(10000, "The minimum finance is 10.000€")
            .max(100000, "The maximum finance is 100.000€")
            .required("Required")
    });

    const handleCalculation = (values, errors) => {
        const { monthDuration, amountFinanced } = values;

        if (monthDuration && amountFinanced && Object.keys(errors).length === 0) {
            setResult({
                monthDuration: monthDuration,
                amountFinanced: amountFinanced,
            });
        }
    };

    return (
        <div>
            <h1>Leasing simulator:</h1>

            <Formik
                initialValues={result}
                validationSchema={LeasingSchema}
                onSubmit={(values) => console.log(values)}
            >
                {({ errors, values, handleChange, handleSubmit }) => (
                    <Form onSubmit={handleSubmit}>
                        <label htmlFor="form-monthly-duration">Monthly duration:</label>
                        <Field
                            type="number"
                            name="monthDuration"
                            placeholder="Months"
                            id="form-monthly-duration"
                            onChange={(e) => {
                                handleChange(e);
                                handleCalculation(values, errors);
                            }}
                        />
                        {(result.monthDuration || result.amountFinanced) && (
                            <>
                                <label htmlFor="result">Monthly fee:</label>
                                <p>{(values.amountFinanced / values.monthDuration).toFixed(2)}</p>
                            </>
                        )}
                        <button type="submit">Submit</button>
                    </Form>
                )}
            </Formik>
        </div>
    );
};

export default Simulator;
</code>```

You can also remove return when setting state as it is unnecessary. You can find more in the React lifecycle docs.

Title: Formik returns old values state

Body:
I'm having this trouble with async state management with Formik. I need to dynamically show a result, according to input changes, but I get every time the old state. Do you know a workaround?
I need the result state to be updated with changes in the Field's component.

Here's my code:

 function Simulator() {
  const [result, setResult] = useState(undefined);

  const LeasingSchema = Yup.object().shape({
    monthDuration: Yup.number()
      .min(6, "6 months minimum")
      .max(48, "48 months maximum")
      .required("Required"),
    amountFinanced: Yup.number()
      .min(10000, "The minimum finance is 10.000€")
      .max(100000, "The maximum finance is 100.000€")
      .required("Required")
  });

  const handleCalculation = (values, errors) => {
    const { monthDuration, amountFinanced } = values;

    if (monthDuration && amountFinanced && Object.keys(errors).length === 0) {
      //Round number
      const roundedValue = parseFloat(amountFinanced / monthDuration).toFixed(
        2
      );
      return setResult(roundedValue);
    } else {
      return setResult(undefined);
    }
  };

  return (

Leasing simulator:

      <Formik
        initialValues={{
          monthDuration: "",
          amountFinanced: ""
        }}
        validationSchema={LeasingSchema}
        onSubmit={(values) => console.log(values)}
      >
        {({ errors, touched, values, handleChange }) => (
          <Form>
            Monthly duration:
            <Field
              type="number"
              name="monthDuration"
              placeholder="Months"
              id="form-monthly-duration"
              onChange={(e) => {
                handleChange(e);
                handleCalculation(values, errors);
              }}
            />
            {result && (
              <>
                Monthly fee:

{result}

              </>
            )}
            <button type="submit">Submit</button>
          </Form>
        )}
      </Formik>

  );
}

export default Simulator;

Body:
The values in handleCalculation are never updated because you are using a controlled component. Form data must be updated by state.

To update by state, set your result to

const [result, setResult] = useState({
    monthDuration: 0,
    amountFinanced: <any number between 10000 to 100000>,
});

Then set initialValues in Formik component to

initialValues={result}

Full code here:

const Simulator = () => {
    const [result, setResult] = useState({
        monthDuration: 0,
        amountFinanced: 10000,
    });

    const LeasingSchema = Yup.object().shape({
        monthDuration: Yup.number()
            .min(6, "6 months minimum")
            .max(48, "48 months maximum")
            .required("Required"),
        amountFinanced: Yup.number()
            .min(10000, "The minimum finance is 10.000€")
            .max(100000, "The maximum finance is 100.000€")
            .required("Required")
    });

    const handleCalculation = (values, errors) => {
        const { monthDuration, amountFinanced } = values;

        if (monthDuration && amountFinanced && Object.keys(errors).length === 0) {
            setResult({
                monthDuration: monthDuration,
                amountFinanced: amountFinanced,
            });
        }
    };

    return (
        <div>
            <h1>Leasing simulator:</h1>

            <Formik
                initialValues={result}
                validationSchema={LeasingSchema}
                onSubmit={(values) => console.log(values)}
            >
                {({ errors, values, handleChange, handleSubmit }) => (
                    <Form onSubmit={handleSubmit}>
                        <label htmlFor="form-monthly-duration">Monthly duration:</label>
                        <Field
                            type="number"
                            name="monthDuration"
                            placeholder="Months"
                            id="form-monthly-duration"
                            onChange={(e) => {
                                handleChange(e);
                                handleCalculation(values, errors);
                            }}
                        />
                        {(result.monthDuration || result.amountFinanced) && (
                            <>
                                <label htmlFor="result">Monthly fee:</label>
                                <p>{(values.amountFinanced / values.monthDuration).toFixed(2)}</p>
                            </>
                        )}
                        <button type="submit">Submit</button>
                    </Form>
                )}
            </Formik>
        </div>
    );
};

export default Simulator;

You can also remove return when setting state as it is unnecessary. You can find more in the React lifecycle docs.