问:
Most efficient way to compare an Entity Model to a DTO Model in C#/LINQ
I am passing back a DTO object with a more than a dozen properties that I want to update in the database only if one or more of the properties differ with the current EF object. What is the most programmatically simple way to accomplish this using C# and Lambda-syntax LINQ?</p>

答:
Try this example.

```<code>    [HttpPost]
    [Route("Client/UpdateClient")]
    [Authorize]
    public ActionResult UpdateClient(ClientDTO client)
    {
        var user = GetLoggerUser(BOAccount);
        client.LastModifiedBy = user.EmailAddress;
        client.LastModifiiedOn = DateTime.UtcNow;
        var resultclient = BOClient.UpdateClient(client, user);
        return Json(resultclient);
    }
    // BOClient.UpdateClient
    public ClientDTO UpdateClient(ClientDTO client, UserDTO user)
    {
        var _clientRepo = ((UnitOfWork)_unitOfWork).ClientRepository;
        var _client = _clientRepo.Get(filter: u => u.Id == client.Id).Single();

        _client.Id = client.Id;
        _client.Phone = client.Phone;
        _client.Address = client.Address;
        _client.Email = client.Email;
        _client.Type = client.Type;
        _client.Name = client.Name;

        object _transaction = _unitOfWork.BeginTransaction();
        try
        {
            _clientRepo.Update(_client);

            _unitOfWork.CommitTransaction(_transaction);
        }
        catch (Exception)
        {
            _unitOfWork.RollbackTransaction(_transaction);

            return client;
        }
        finally
        {
            _unitOfWork.DestroyTransaction(_transaction);
        }
        return client;
    }
</code>```

And Created model is

```<code>namespace OptiLeadInfrastructure.Models
{
    public class ClientDTO
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Phone { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }
        public Nullable<short> Type { get; set; }
        public string logo { get; set; }
        public Nullable<DateTime> CreatedOn { get; set; }
        public string CreatedBy { get; set; }
        public Nullable<DateTime> LastModifiiedOn { get; set; }
        public virtual ICollection<ClientDetailDTO> ClientDetails { get; set; }
    }   public string LastModifiedBy { get; set; }

}
</code>```

Body:
Try this example.

    [HttpPost]
    [Route("Client/UpdateClient")]
    [Authorize]
    public ActionResult UpdateClient(ClientDTO client)
    {
        var user = GetLoggerUser(BOAccount);
        client.LastModifiedBy = user.EmailAddress;
        client.LastModifiiedOn = DateTime.UtcNow;
        var resultclient = BOClient.UpdateClient(client, user);
        return Json(resultclient);
    }
    // BOClient.UpdateClient
    public ClientDTO UpdateClient(ClientDTO client, UserDTO user)
    {
        var _clientRepo = ((UnitOfWork)_unitOfWork).ClientRepository;
        var _client = _clientRepo.Get(filter: u => u.Id == client.Id).Single();

        _client.Id = client.Id;
        _client.Phone = client.Phone;
        _client.Address = client.Address;
        _client.Email = client.Email;
        _client.Type = client.Type;
        _client.Name = client.Name;

        object _transaction = _unitOfWork.BeginTransaction();
        try
        {
            _clientRepo.Update(_client);

            _unitOfWork.CommitTransaction(_transaction);
        }
        catch (Exception)
        {
            _unitOfWork.RollbackTransaction(_transaction);

            return client;
        }
        finally
        {
            _unitOfWork.DestroyTransaction(_transaction);
        }
        return client;
    }

And Created model is

namespace OptiLeadInfrastructure.Models
{
    public class ClientDTO
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Phone { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }
        public Nullable<short> Type { get; set; }
        public string logo { get; set; }
        public Nullable<DateTime> CreatedOn { get; set; }
        public string CreatedBy { get; set; }
        public Nullable<DateTime> LastModifiiedOn { get; set; }
        public virtual ICollection<ClientDetailDTO> ClientDetails { get; set; }
    }   public string LastModifiedBy { get; set; }

}


来源: stackexchange

问:
How to use PackageInfo.GET_SIGNING_CERTIFICATES in API 28?
The documentation of PackageManager.GET_SIGNATURES says "This constant was deprecated in API level 28. Use GET_SIGNING_CERTIFICATES instead".

Unfortunately it was not secure and was easily hacked.

How can you use the new "GET_SIGNING_CERTIFICATES" introduced with Android P?

答:
TL;DR if your use case is that you're validating the calling package's signatures, you can still use GET_SIGNATURES in pre-api 28 securely as long as you validate all signers returned from the package manager (instead of stopping early when you find one that you trust).  In fact, google patched it in lollipop (https://android.googlesource.com/platform/libcore/+/f8986a989759c43c155ae64f9a3b36f670602521).

Details:
I believe your comment about GET_SIGNATURES being easily hacked is based on this vulnerability (https://www.blackhat.com/docs/us-14/materials/us-14-Forristal-Android-FakeID-Vulnerability-Walkthrough.pdf).  Whereby android doesn't validate the trust chain prior to returning apk signers.

This is only a problem if you have code like this:

```<code>    private boolean validateCallingPackage(String: packageName) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(
                packageName,
                PackageManager.GET_SIGNATURES);
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }

        for (Signature signature : packageInfo.signatures) {
            String hashedSignature = Utility.sha256hash(signature.toByteArray());
            if (validAppSignatureHashes.contains(hashedSignature)) {
              return true;  //THIS is the problematic code
            }
        }
        return false
    }
</code>```

The code is returning true if it finds any certificate that matches one from your whitelist.  With the android vulnerability, if the signatures contained a signature from a malicious signer, your code still returns true.

The mitigation for this vulnerability is to instead check ALL signatures returned from the package manager and return false if any of them aren't in your whitelist.  i.e.

```<code>    private boolean validateCallingPackage(String: packageName) {
        ...

        for (Signature signature : packageInfo.signatures) {
            String hashedSignature = Utility.sha256hash(signature.toByteArray());
            if (!validAppSignatureHashes.contains(hashedSignature)) {
              return false; //FIXED
            }
        }
        return true
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
TL;DR if your use case is that you're validating the calling package's signatures, you can still use GET_SIGNATURES in pre-api 28 securely as long as you validate all signers returned from the package manager (instead of stopping early when you find one that you trust).  In fact, google patched it in lollipop (https://android.googlesource.com/platform/libcore/+/f8986a989759c43c155ae64f9a3b36f670602521).

Details:
I believe your comment about GET_SIGNATURES being easily hacked is based on this vulnerability (https://www.blackhat.com/docs/us-14/materials/us-14-Forristal-Android-FakeID-Vulnerability-Walkthrough.pdf).  Whereby android doesn't validate the trust chain prior to returning apk signers.

This is only a problem if you have code like this:

    private boolean validateCallingPackage(String: packageName) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(
                packageName,
                PackageManager.GET_SIGNATURES);
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }

        for (Signature signature : packageInfo.signatures) {
            String hashedSignature = Utility.sha256hash(signature.toByteArray());
            if (validAppSignatureHashes.contains(hashedSignature)) {
              return true;  //THIS is the problematic code
            }
        }
        return false
    }

The code is returning true if it finds any certificate that matches one from your whitelist.  With the android vulnerability, if the signatures contained a signature from a malicious signer, your code still returns true.

The mitigation for this vulnerability is to instead check ALL signatures returned from the package manager and return false if any of them aren't in your whitelist.  i.e.

    private boolean validateCallingPackage(String: packageName) {
        ...

        for (Signature signature : packageInfo.signatures) {
            String hashedSignature = Utility.sha256hash(signature.toByteArray());
            if (!validAppSignatureHashes.contains(hashedSignature)) {
              return false; //FIXED
            }
        }
        return true
    }


问:
Use a raw_input to specify a specific file to create a copy of it's back up and change the file names of the back up and original file
I am working to set up a process that creates a new file from a backup file that is already in a folder. My program currently works, but I would like to eliminate as much of the user input as possible, so that all you have to do is enter the filename that just crashed on you and watch the program do the rest. I am fairly new at python and have been having trouble figuring out a way to get that initial raw_input to be the basis for the rest of the program to run off. I have uploaded the code that I have which currently does the job, so any tips that would help me make this code better would be much appreciated.

Thanks!

```<code>import os
import copy
import shutil

def copy_vrb():
    #Creates a copy of a specific "Filename.vrb" which gets renamed to "Filename_COPY.vrb"
    oldvrb=raw_input("Enter the .vr filename you were working on before it crashed: ") # With file extension
    newvrb=raw_input("Rename the new .vrb file to Filename_COPY")
    shutil.copy(oldvrb, newvrb + ".vrb") # Without file extension
copy_vrb()

def file_rename():
    # Takes original "Filename.vr" that crashed, and changes the filename to "Filename_BAD.vr".
    oldname=raw_input("Enter the Filename.vr that you were working on before it crashed: ") # With file extension
    newname=raw_input("Rename the file as Filename_BAD")
    os.rename(oldname, newname + ".vr")
file_rename()

def rename_copy():
    # Renames Filename_COPY.vrb to Filename_NEW.vr
    oldname=raw_input("Enter the Filename_COPY.vrb: ") # With file extension
    newname=raw_input("Rename to Filename_NEW: ") # Without file extension
    os.rename(oldname, newname, +".vr")
rename_copy()
</code>```

In my data folder that I would work out of, I have multiple pairs of files, (10001.vr(the file that would crash), and 10001.vrb(the backup that is created when I open the file in VR Mapping) What I want is to be able to input the specific file that crashed.

Create a copy of the 10001.vrb file ---> 10001_COPY.vrb

Change the 10001.vr file ---> 10001_BAD.vr

Lastly change the 10001_COPY.vrb file into the new usable file ---> 10001_NEW.vr

答:
You're on the right track. Just a matter of merging your functions - perhaps:</p>

```<code>import os
import shutil

def recover_vrb():
    vr_file = raw_input("Enter the .vr filename you were working on before it crashed: ") # With file extension

    vr_name = vr_file.split('.')[0]

    vrb_file = vr_name + '.vrb'
    moved_vr_file = vr_name + '_BAD.vr'
    os.rename(vr_file, moved_vr_file)
    shutil.copy(vrb_file, vr_file)
</code>```

Body:
I am working to set up a process that creates a new file from a backup file that is already in a folder. My program currently works, but I would like to eliminate as much of the user input as possible, so that all you have to do is enter the filename that just crashed on you and watch the program do the rest. I am fairly new at python and have been having trouble figuring out a way to get that initial raw_input to be the basis for the rest of the program to run off. I have uploaded the code that I have which currently does the job, so any tips that would help me make this code better would be much appreciated.

Thanks!

import os
import copy
import shutil

def copy_vrb():
    #Creates a copy of a specific "Filename.vrb" which gets renamed to "Filename_COPY.vrb"
    oldvrb=raw_input("Enter the .vr filename you were working on before it crashed: ") # With file extension
    newvrb=raw_input("Rename the new .vrb file to Filename_COPY")
    shutil.copy(oldvrb, newvrb + ".vrb") # Without file extension
copy_vrb()

def file_rename():
    # Takes original "Filename.vr" that crashed, and changes the filename to "Filename_BAD.vr".
    oldname=raw_input("Enter the Filename.vr that you were working on before it crashed: ") # With file extension
    newname=raw_input("Rename the file as Filename_BAD")
    os.rename(oldname, newname + ".vr")
file_rename()

def rename_copy():
    # Renames Filename_COPY.vrb to Filename_NEW.vr
    oldname=raw_input("Enter the Filename_COPY.vrb: ") # With file extension
    newname=raw_input("Rename to Filename_NEW: ") # Without file extension
    os.rename(oldname, newname, +".vr")
rename_copy()

In my data folder that I would work out of, I have multiple pairs of files, (10001.vr(the file that would crash), and 10001.vrb(the backup that is created when I open the file in VR Mapping) What I want is to be able to input the specific file that crashed.

Create a copy of the 10001.vrb file ---> 10001_COPY.vrb

Change the 10001.vr file ---> 10001_BAD.vr

Lastly change the 10001_COPY.vrb file into the new usable file ---> 10001_NEW.vr

Body:
You're on the right track. Just a matter of merging your functions - perhaps:

import os
import shutil

def recover_vrb():
    vr_file = raw_input("Enter the .vr filename you were working on before it crashed: ") # With file extension

    vr_name = vr_file.split('.')[0]

    vrb_file = vr_name + '.vrb'
    moved_vr_file = vr_name + '_BAD.vr'
    os.rename(vr_file, moved_vr_file)
    shutil.copy(vrb_file, vr_file)


问:
Infinite Scroll / Pagination Issue
I DID ask this in the wordpress section, but I never seem to get ANY answers there when I ask for help, so I figured I'd try the main section which is always helpful.

I'm having a bit of an issue.  I have installed the Infinite-Scroll plugin and am having issues with it.

Firstly, all it says is "No Additional Posts" when, in fact, there are additional posts.  I suspect this has something to do with my pagination on the homepage.  Because of that thought, I deactivated the plugin and tested my pagination and sure enough, it doesn't work.  So, I got to thinking... well, maybe I need to set this as a static home page and call it a day.

I did so.

Pagination works.

Now, though, I activate Infinite-Scroll and it doesn't work AT ALL.  The regular pagination shows up.

So, I'm at a loss.  I need to either get infinite scroll working on the static home page, or fix the pagination on the regular home page so that infinite scroll works properly.

My code is as follows...

Structure of page:

```<code><!-- main section -->
    <section>

        <div class="results">

            <h2>Latest From The Network</h2>

            <div id="results">
            <?php get_template_part( 'loop' ); ?>

            <div class="clear"></div>
            </div>
            <div class="clear"></div>

        </div>

    </section>
    <!-- /section -->
</code>```

Loop:

```<code>    <?php
            if ( get_query_var('paged') ) {

    $paged = get_query_var('paged');

} elseif ( get_query_var('page') ) {

    $paged = get_query_var('page');

} else {

    $paged = 1;

}

                $args = array(
                    'post_type' => 'results', // it's default, you can skip it
                    'posts_per_page' => '6',
                    'order_by' => 'date', // it's also default
            'paged' => $paged
                    );
                    $wp_query = new WP_Query( $args );
            ?>
                <?php if (have_posts()) : while( $wp_query->have_posts() ) : $wp_query->the_post(); ?>

                    <div class="results-item">
    <!-- article -->
    <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

        <!-- post thumbnail -->
            <img src="<?php echo get('results_image'); ?>" />
        <!-- /post thumbnail -->

    </article>
    <!-- /article -->

                    </div>

            <?php endwhile; ?>
<!-- pagination -->
<div class="pagination">
    <?php html5wp_pagination(); ?>
<div class="clear"></div>
</div>
<!-- /pagination -->
        <?php endif; ?>
</code>```

So, what say ye?  I can't seem to figure any of it out.  It's so frustrating.  I don't mind having a static homepage, but quite honestly, I'd rather not if need be.  That said, I presume the easiest fix (if there is one) will be to set a static homepage and somehow force the Infinite-Scroll to recognize the page itself.

Anyways, any guidance would be much appreciated!

答:
I think it had to do with your paged parameter. Also when you're trying to display post amount, the number needs to be set as a integer rather than a string. Try this below for your loop and see if it helps. I got it to work on my side, so holler if it's still being finicky.

Loop:

```<code>        <?php
            $paged = ( get_query_var( 'page' ) ) ? get_query_var( 'page' ) : 1;

            $args = array(
                'post_type' => 'results',
                'posts_per_page' => 6,
                'order_by' => 'date',
                'paged' => $paged
            );

            $the_query = new WP_Query($args); ?>
            <?php

                while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
                    <div class="results-item">
                        <!-- article -->
                        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

                            <!-- post thumbnail -->
                                <img src="<?php echo get('results_image'); ?>" />
                            <!-- /post thumbnail -->

                        </article>
                        <!-- /article -->
                    </div>

            <?php endwhile; ?>
            <div class="pagination">
                <?php next_posts_link( 'Older Entries', $the_query->max_num_pages ); ?>
            </div>

            <?php wp_reset_postdata(); ?>
</code>```

JS:

```<code>$('.results-item').infiniteScroll({
    path: '.pagination a',
    append: 'article',
    prefill: true,
    history: false,
    hideNav: '.pagination',
    scrollThreshold: true,
    status: '.page-load-status',
});
</code>```

Edit: Just realized this was posted 4 years ago. Hope it helps someone else.

ContentLicense: CC BY-SA 3.0

Title: Infinite Scroll / Pagination Issue

Body:
I DID ask this in the wordpress section, but I never seem to get ANY answers there when I ask for help, so I figured I'd try the main section which is always helpful.

I'm having a bit of an issue.  I have installed the Infinite-Scroll plugin and am having issues with it.

Firstly, all it says is "No Additional Posts" when, in fact, there are additional posts.  I suspect this has something to do with my pagination on the homepage.  Because of that thought, I deactivated the plugin and tested my pagination and sure enough, it doesn't work.  So, I got to thinking... well, maybe I need to set this as a static home page and call it a day.

I did so.

Pagination works.

Now, though, I activate Infinite-Scroll and it doesn't work AT ALL.  The regular pagination shows up.

So, I'm at a loss.  I need to either get infinite scroll working on the static home page, or fix the pagination on the regular home page so that infinite scroll works properly.

My code is as follows...

Structure of page:

Latest From The Network

            <?php get_template_part( 'loop' ); ?>

Loop:

    <?php
            if ( get_query_var('paged') ) {

    $paged = get_query_var('paged');

} elseif ( get_query_var('page') ) {

    $paged = get_query_var('page');

} else {

    $paged = 1;

}

                $args = array(
                    'post_type' => 'results', // it's default, you can skip it
                    'posts_per_page' => '6',
                    'order_by' => 'date', // it's also default
            'paged' => $paged
                    );
                    $wp_query = new WP_Query( $args );
            ?>
                <?php if (have_posts()) : while( $wp_query->have_posts() ) : $wp_query->the_post(); ?>

    <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

            <img src="<?php echo get('results_image'); ?>" />

            <?php endwhile; ?>

    <?php html5wp_pagination(); ?>

        <?php endif; ?>

So, what say ye?  I can't seem to figure any of it out.  It's so frustrating.  I don't mind having a static homepage, but quite honestly, I'd rather not if need be.  That said, I presume the easiest fix (if there is one) will be to set a static homepage and somehow force the Infinite-Scroll to recognize the page itself.

Anyways, any guidance would be much appreciated!

Body:
I think it had to do with your paged parameter. Also when you're trying to display post amount, the number needs to be set as a integer rather than a string. Try this below for your loop and see if it helps. I got it to work on my side, so holler if it's still being finicky.

Loop:

        <?php
            $paged = ( get_query_var( 'page' ) ) ? get_query_var( 'page' ) : 1;

            $args = array(
                'post_type' => 'results',
                'posts_per_page' => 6,
                'order_by' => 'date',
                'paged' => $paged
            );

            $the_query = new WP_Query($args); ?>
            <?php

                while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
                    <div class="results-item">
                        <!-- article -->
                        <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

                            <!-- post thumbnail -->
                                <img src="<?php echo get('results_image'); ?>" />
                            <!-- /post thumbnail -->

                        </article>
                        <!-- /article -->
                    </div>

            <?php endwhile; ?>
            <div class="pagination">
                <?php next_posts_link( 'Older Entries', $the_query->max_num_pages ); ?>
            </div>

            <?php wp_reset_postdata(); ?>

JS:

$('.results-item').infiniteScroll({
    path: '.pagination a',
    append: 'article',
    prefill: true,
    history: false,
    hideNav: '.pagination',
    scrollThreshold: true,
    status: '.page-load-status',
});

Edit: Just realized this was posted 4 years ago. Hope it helps someone else.


问:
Reference a cell's content to act as a sheet name
I'm looking to be able to reference the contents of a cell as a sheet name.

The content of A2 is "32033", which is also the name of a different sheet in the workbook. In B2, I'm trying to identify the average of a range that sheet.

```<code>=AVERAGE('32033'!B2:B)
</code>```

I'm trying to replace the '32033' with a formula referencing A2.

答:
you will need to use INDIRECT formula to reference the sheet name from a cell:

```<code>=AVERAGE(INDIRECT(A2&"!B2:B"))
</code>```

Body:
I'm looking to be able to reference the contents of a cell as a sheet name.

The content of A2 is "32033", which is also the name of a different sheet in the workbook. In B2, I'm trying to identify the average of a range that sheet.

=AVERAGE('32033'!B2:B)

I'm trying to replace the '32033' with a formula referencing A2.

Body:
you will need to use INDIRECT formula to reference the sheet name from a cell:

=AVERAGE(INDIRECT(A2&"!B2:B"))


问:
Fastest way to iterate through nodes with arbitrary number of connections to each other
I am making a fracturing script where there are nodes that each hold an arbitrary number of connections to other nodes.

Shards and chunks :

Each node represents a "shard" of a pre-fractured "chunk".

When a shard is broken all its connections to other shards and their connections to it are removed.

When this happens, I need to iterate through the shards and find out which are connected together and if the chunk is split apart to create new chunks.

What is the fastest way to do this?

Currently I have:

a Shard class that has

a reference to the parent chunk

a list of connections to adjacent shards.

a Break() method that

removes all connections from adjacent shards to this one.

clears the connections from this to adjacent shards.

calls the parent chunk's UpdateChunk() method.

a Chunk class that has

a list of all the shards that it contains.

an UpdateChunk() method that

checks if there is only one shard and then destroys this chunk.

makes a new list of all the shards in this chunk to keep track of
unprocessed shards.

calls ProcessShard() method to recursively process all shards
through their connections starting form the first shard in the
unprocessed shard list.

checks if there are still shards in the unprocessed list and if so
creates a new chunk and dumps the leftover shards in it and calls
its UpdateChunk() method.

a ProcessShard() method that

removes given shard from the unprocessed list

makes given shard's parent chunk the current chunk

loops through all the shards this one connects to and checks if they
are not in the processed list and if so calls ProcessShard() for
them.

public class Shard : MonoBehaviour
{
    public GameObject parentChunk;

    public List<GameObject> connectedShards = new List<GameObject>();

    public void Break()
    {
        // remove all connections that point to this shard
        foreach (GameObject shard in connectedShards)
        {
            // remove connection to this shard
            shard.GetComponent<Shard>().connectedShards.Remove(gameObject);
        }

        // clear connected shards list
        connectedShards.Clear();

        // check that there is a parent chunk
        if (parentChunk)
        {
            // force parent chunk to update
            parentChunk.GetComponent<Chunk>().UpdateChunk();

            // set parent chunk to null
            parentChunk = null;
        }
    }
}

public class Chunk : MonoBehaviour
{
    public List<GameObject> shards = new List<GameObject>();

    private List<GameObject> unprocessedShards = new List<GameObject>();

    public void UpdateChunk()
    {
        // if there is only one shard in this chunk
        if (shards.Count == 1)
        {
            // break shard
            shards[0].GetComponent<Shard>().parentChunk = null;
            shards[0].GetComponent<Shard>().Break();

            // destroy this chunk
            Destroy(gameObject);
        }
        else // there are multiple shards in this chunk
        {
            // fill the unprocessed shards list
            unprocessedShards = new List<GameObject>(shards);

            // process all shards in this chunk recursively starting from the first
            ProcessShard(unprocessedShards[0], gameObject);

            // if there are still unprocessed shards (this chunk was split)
            if (unprocessedShards.Count > 0)
            {
                // remove the unprocessed shards from this chunk's shard list
                foreach (GameObject unprocessedShard in unprocessedShards)
                {
                    shards.Remove(unprocessedShard);
                }

                // create new chunk(s) from the leftover shards
                parentObject.GetComponent<Fragmenter>().NewChunk(unprocessedShards);
            }
        }
    }

    // process shard
    private void ProcessShard(GameObject shard, GameObject chunk)
    {
        // remove shard from unprocessed list
        unprocessedShards.Remove(shard);

        // add shard to the given chunk
        shard.GetComponent<Shard>().parentChunk = chunk;

        // loop through all shards connected to the given shard
        foreach (GameObject connectedShard in shard.GetComponent<Shard>().connectedShards)
        {
            // connected shard has not been processed yet
            if (unprocessedShards.Contains(connectedShard))
            {
                // process all shards connected to the connected shard
                ProcessShard(connectedShard, chunk);
            }
        }
    }
}
```

I am mostly thinking about the ProcessShard() method where it usually processes each shard multiple times since one can be adjacent to many. How can I most efficiently ignore the ones that have already been processed?

答:
It seems the script slowed down the most at the recursion of the ProcessShard() method so I renamed and rewrote the method as ProcessShards() that uses a while loop and a Queue to process all the shards. The performance was around ten times better on a chunk with 100 shards.</p>

```<code>    // process shards
    private void ProcessShards()
    {
        // create a list for shards to process
        Queue<GameObject> shardsToProcess = new Queue<GameObject>();

        // select the first shard to process
        shardsToProcess.Enqueue(unprocessedShards[0]);

        // remove shard from unprocessed list
        unprocessedShards.Remove(unprocessedShards[0]);

        // loop while there are shards to process
        while (shardsToProcess.Count > 0)
        {
            // get the first shard to process
            GameObject shard = shardsToProcess.Dequeue();

            // add the shard to this chunk
            shard.GetComponent<Shard>().parentChunk = gameObject;

            // loop through all shards connected to the given shard
            foreach (GameObject connectedShard in shard.GetComponent<Shard>().connectedShards)
            {
                // connected shard has not been processed yet
                if (unprocessedShards.Contains(connectedShard))
                {
                    // add shard to be processed
                    shardsToProcess.Enqueue(connectedShard);

                    // remove shard from unprocessed list
                    unprocessedShards.Remove(connectedShard);
                }
            }
        }
    }
</code>```

Body:
I am making a fracturing script where there are nodes that each hold an arbitrary number of connections to other nodes.

Shards and chunks :

Each node represents a "shard" of a pre-fractured "chunk".

When a shard is broken all its connections to other shards and their connections to it are removed.

When this happens, I need to iterate through the shards and find out which are connected together and if the chunk is split apart to create new chunks.

What is the fastest way to do this?

Currently I have:

a Shard class that has

a reference to the parent chunk

a list of connections to adjacent shards.

a Break() method that

removes all connections from adjacent shards to this one.

clears the connections from this to adjacent shards.

calls the parent chunk's UpdateChunk() method.

a Chunk class that has

a list of all the shards that it contains.

an UpdateChunk() method that

checks if there is only one shard and then destroys this chunk.

makes a new list of all the shards in this chunk to keep track of
unprocessed shards.

calls ProcessShard() method to recursively process all shards
through their connections starting form the first shard in the
unprocessed shard list.

checks if there are still shards in the unprocessed list and if so
creates a new chunk and dumps the leftover shards in it and calls
its UpdateChunk() method.

a ProcessShard() method that

removes given shard from the unprocessed list

makes given shard's parent chunk the current chunk

loops through all the shards this one connects to and checks if they
are not in the processed list and if so calls ProcessShard() for
them.

public class Shard : MonoBehaviour
{
    public GameObject parentChunk;

    public List<GameObject> connectedShards = new List<GameObject>();

    public void Break()
    {
        // remove all connections that point to this shard
        foreach (GameObject shard in connectedShards)
        {
            // remove connection to this shard
            shard.GetComponent<Shard>().connectedShards.Remove(gameObject);
        }

        // clear connected shards list
        connectedShards.Clear();

        // check that there is a parent chunk
        if (parentChunk)
        {
            // force parent chunk to update
            parentChunk.GetComponent<Chunk>().UpdateChunk();

            // set parent chunk to null
            parentChunk = null;
        }
    }
}

public class Chunk : MonoBehaviour
{
    public List<GameObject> shards = new List<GameObject>();

    private List<GameObject> unprocessedShards = new List<GameObject>();

    public void UpdateChunk()
    {
        // if there is only one shard in this chunk
        if (shards.Count == 1)
        {
            // break shard
            shards[0].GetComponent<Shard>().parentChunk = null;
            shards[0].GetComponent<Shard>().Break();

            // destroy this chunk
            Destroy(gameObject);
        }
        else // there are multiple shards in this chunk
        {
            // fill the unprocessed shards list
            unprocessedShards = new List<GameObject>(shards);

            // process all shards in this chunk recursively starting from the first
            ProcessShard(unprocessedShards[0], gameObject);

            // if there are still unprocessed shards (this chunk was split)
            if (unprocessedShards.Count > 0)
            {
                // remove the unprocessed shards from this chunk's shard list
                foreach (GameObject unprocessedShard in unprocessedShards)
                {
                    shards.Remove(unprocessedShard);
                }

                // create new chunk(s) from the leftover shards
                parentObject.GetComponent<Fragmenter>().NewChunk(unprocessedShards);
            }
        }
    }

    // process shard
    private void ProcessShard(GameObject shard, GameObject chunk)
    {
        // remove shard from unprocessed list
        unprocessedShards.Remove(shard);

        // add shard to the given chunk
        shard.GetComponent<Shard>().parentChunk = chunk;

        // loop through all shards connected to the given shard
        foreach (GameObject connectedShard in shard.GetComponent<Shard>().connectedShards)
        {
            // connected shard has not been processed yet
            if (unprocessedShards.Contains(connectedShard))
            {
                // process all shards connected to the connected shard
                ProcessShard(connectedShard, chunk);
            }
        }
    }
}

I am mostly thinking about the ProcessShard() method where it usually processes each shard multiple times since one can be adjacent to many. How can I most efficiently ignore the ones that have already been processed?

Body:
It seems the script slowed down the most at the recursion of the ProcessShard() method so I renamed and rewrote the method as ProcessShards() that uses a while loop and a Queue to process all the shards. The performance was around ten times better on a chunk with 100 shards.

    // process shards
    private void ProcessShards()
    {
        // create a list for shards to process
        Queue<GameObject> shardsToProcess = new Queue<GameObject>();

        // select the first shard to process
        shardsToProcess.Enqueue(unprocessedShards[0]);

        // remove shard from unprocessed list
        unprocessedShards.Remove(unprocessedShards[0]);

        // loop while there are shards to process
        while (shardsToProcess.Count > 0)
        {
            // get the first shard to process
            GameObject shard = shardsToProcess.Dequeue();

            // add the shard to this chunk
            shard.GetComponent<Shard>().parentChunk = gameObject;

            // loop through all shards connected to the given shard
            foreach (GameObject connectedShard in shard.GetComponent<Shard>().connectedShards)
            {
                // connected shard has not been processed yet
                if (unprocessedShards.Contains(connectedShard))
                {
                    // add shard to be processed
                    shardsToProcess.Enqueue(connectedShard);

                    // remove shard from unprocessed list
                    unprocessedShards.Remove(connectedShard);
                }
            }
        }
    }


问:
DbContext not updating database
When I save changes to DbContext, it doesn't update my database. No errors either.

Yes, the incoming form data is filled. Yes, the connection string is correct, I know this because I'm able to retrieve data from the database perfectly fine. If it's of relevance, it's a many-to-many relationship.

A roadmap is like an article as far as you're concerned which can be associated with many tags.

```<code>    public static class RoadmapService
    {
        static ConkerDbEntities dbContext;
        public static void createDbContext(ConkerDbEntities _dbContext)
        {
            dbContext = _dbContext;
        }

        public static void addToDatabase(Form form)
        {
            Roadmaps roadmap = new Roadmaps { RoadmapTitle = form.title,
                                              RoadmapSummary = form.summary,
                                              RoadmapBody = form.body };

            var tags = new Tags[form.tags.Length];

            for(int i = 0; i < tags.Length; i++)
            {
                tags[i] = new Tags();
                tags[i].TagId = form.tags[i];
            }

            var roadmapTags = new RoadmapTags[form.tags.Length];

            for(int i = 0; i < tags.Length; i++)
            {
                roadmapTags[i] = new RoadmapTags{Roadmap = roadmap, Tag = tags[i]};
            }

            dbContext.AddRange(roadmapTags);
            dbContext.SaveChangesAsync();
        }
    }
}
</code>```

Where dbcontext is created, this is the constructor of Startup.cs

```<code>        public static SearchEngine engine;
        public static ConkerDbEntities dbContext;

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            dbContext = new ConkerDbEntities();

            RoadmapService.createDbContext(dbContext);
            engine = new SearchEngine(dbContext);

        }

</code>```

I get no errors, and there's nothing added to the database. I'm probably doing something fundamentally wrong here. Thanks in advance.

答:
You are using async programming, but your method is not async.

use dbContext.SaveChangesAsync(); when you have async methods, use dbContext.SaveChanges(); when is not async.

Also, you are using static classes, this should not be the case if you are using dependency injection. DI will handle the life cycle of your objects.

Your class is not defined as should be, you have some format errors, and should look something like this:

```<code>public class RoadmapService
{
    private readonly ConkerDbEntities _dbContext;

    public RoadmapService(ConkerDbEntities dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task AddToDatabase(Form form)
    {
        Roadmaps roadmap = new Roadmaps {
            RoadmapTitle = form.title,
            RoadmapSummary = form.summary,
            RoadmapBody = form.body
        };

        var tags = new Tags[form.tags.Length];

        for(int i = 0; i < tags.Length; i++)
        {
            tags[i] = new Tags();
            tags[i].TagId = form.tags[i];
        }

        var roadmapTags = new RoadmapTags[form.tags.Length];

        for(int i = 0; i < tags.Length; i++)
        {
            roadmapTags[i] = new RoadmapTags{Roadmap = roadmap, Tag = tags[i]};
        }

        _dbContext.AddRange(roadmapTags);
        _dbContext.SaveChangesAsync();
    }
}
</code>```

Then in your controller you can use your service as is

```<code>public class OrdersController : Controller
{
    private readonly RoadmapService _roadmapService;

    public OrdersController(RoadmapService roadmapService)
    {
        _roadmapService = roadmapService;
    }

    [HttpGet]
    [Route("api/[controller]/{folio}")]
    public async Task<IActionResult> Status(string folio)
    {
        await _roadmapService.AddToDatabase(something);
        return Ok();
    }
}
</code>```

I also would recommend to study about linq and how you can avoid those foreach cycles using select, check the default net core coding standards.

Edit

I'm curious, would LINQ provide any performance benefits in this case
  vs just a regular for loop?

It is more about the readability and maintainability of your code, in the answer I already put a link to a post where is better explained, you are creating technical debt in your code, you are initializing arrays and filling them, handling indices and more... , but it reduces to this:

What is more easy to read? this:

```<code>public async Task AddToDatabase(Form form)
{
    Roadmaps roadmap = new Roadmaps {
        RoadmapTitle = form.title,
        RoadmapSummary = form.summary,
        RoadmapBody = form.body
    };

    var tags = new Tags[form.tags.Length];

    for(int i = 0; i < tags.Length; i++)
    {
        tags[i] = new Tags();
        tags[i].TagId = form.tags[i];
    }

    var roadmapTags = new RoadmapTags[form.tags.Length];

    for(int i = 0; i < tags.Length; i++)
    {
        roadmapTags[i] = new RoadmapTags{Roadmap = roadmap, Tag = tags[i]};
    }

    _dbContext.AddRange(roadmapTags);
    _dbContext.SaveChangesAsync();
}
</code>```

or this

```<code>    public async Task AddToDatabase(Form form)
    {
        var roadmap = new Roadmap {
            RoadmapTitle = form.title,
            RoadmapSummary = form.summary,
            RoadmapBody = form.body
        };

        var roadmapTags = form.Tags
            .Select(tagId => new Tag        // First we take our form.tags and convert it to Tag objects
            {
                TagId = tagId
            })
            .Select(tag => new RoadmapTags  // Then we take the result of the previous conversion and we
            {                               // transform again to RoadmapTags, we even could do this in one pass
                Roadmap = roadmap,          // but this way is more clear what the transformations are
                Tag = tag
            })
            .ToList();

        _dbContext.AddRange(roadmapTags);
        await _dbContext.SaveChangesAsync();
    }
</code>```

If you just started learning programming, you could ignore this until you are more confortable with the for, foreach, while and other control structures. This is structure programming, and it is a topic by itself.

Also how would I pass the roadmapService object to the Controller
  constructor, I've just never seen that.

That is the magic of dependency injection, just let the system create the object for you, you just have to ask for the type.

This is also a big topic, you should check my previous link to the microsoft documentation, but basically, all you have to do is to define classes as dependencies, so, when you ask for one, the system itself check the dependencies, and the dependencies of that objects, until resolves all the tree of dependencies.

With this, if you need one more dependency latter in your class, you can add directly but you do not need to modify all the classes that uses that class.

To use this in the controller, please check the official docs, you just have to add you dependencies to the constructor, and win!, basically two parts:

Add in your Startup.class

```<code>public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddTransient<MySpecialClassWithDependencies>();
    ...
}
</code>```

Then in your controller:

```<code>public class HomeController : Controller
{
    private readonly MySpecialClassWithDependencies _mySpecialClassWithDependencies;

    public HomeController(MySpecialClassWithDependencies mySpecialClassWithDependencies)
    {
        _mySpecialClassWithDependencies = mySpecialClassWithDependencies;
    }

    public IActionResult Index()
    {
        // Now i can use my object here, the framework already initialized for me!
        return View();
    }
</code>```

Title: DbContext not updating database

Body:
When I save changes to DbContext, it doesn't update my database. No errors either.

Yes, the incoming form data is filled. Yes, the connection string is correct, I know this because I'm able to retrieve data from the database perfectly fine. If it's of relevance, it's a many-to-many relationship.

A roadmap is like an article as far as you're concerned which can be associated with many tags.

    public static class RoadmapService
    {
        static ConkerDbEntities dbContext;
        public static void createDbContext(ConkerDbEntities _dbContext)
        {
            dbContext = _dbContext;
        }

        public static void addToDatabase(Form form)
        {
            Roadmaps roadmap = new Roadmaps { RoadmapTitle = form.title,
                                              RoadmapSummary = form.summary,
                                              RoadmapBody = form.body };

            var tags = new Tags[form.tags.Length];

            for(int i = 0; i < tags.Length; i++)
            {
                tags[i] = new Tags();
                tags[i].TagId = form.tags[i];
            }

            var roadmapTags = new RoadmapTags[form.tags.Length];

            for(int i = 0; i < tags.Length; i++)
            {
                roadmapTags[i] = new RoadmapTags{Roadmap = roadmap, Tag = tags[i]};
            }

            dbContext.AddRange(roadmapTags);
            dbContext.SaveChangesAsync();
        }
    }
}

Where dbcontext is created, this is the constructor of Startup.cs

        public static SearchEngine engine;
        public static ConkerDbEntities dbContext;

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            dbContext = new ConkerDbEntities();

            RoadmapService.createDbContext(dbContext);
            engine = new SearchEngine(dbContext);

        }

I get no errors, and there's nothing added to the database. I'm probably doing something fundamentally wrong here. Thanks in advance.

Body:
You are using async programming, but your method is not async.

use dbContext.SaveChangesAsync(); when you have async methods, use dbContext.SaveChanges(); when is not async.

Also, you are using static classes, this should not be the case if you are using dependency injection. DI will handle the life cycle of your objects.

Your class is not defined as should be, you have some format errors, and should look something like this:

public class RoadmapService
{
    private readonly ConkerDbEntities _dbContext;

    public RoadmapService(ConkerDbEntities dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task AddToDatabase(Form form)
    {
        Roadmaps roadmap = new Roadmaps {
            RoadmapTitle = form.title,
            RoadmapSummary = form.summary,
            RoadmapBody = form.body
        };

        var tags = new Tags[form.tags.Length];

        for(int i = 0; i < tags.Length; i++)
        {
            tags[i] = new Tags();
            tags[i].TagId = form.tags[i];
        }

        var roadmapTags = new RoadmapTags[form.tags.Length];

        for(int i = 0; i < tags.Length; i++)
        {
            roadmapTags[i] = new RoadmapTags{Roadmap = roadmap, Tag = tags[i]};
        }

        _dbContext.AddRange(roadmapTags);
        _dbContext.SaveChangesAsync();
    }
}

Then in your controller you can use your service as is

public class OrdersController : Controller
{
    private readonly RoadmapService _roadmapService;

    public OrdersController(RoadmapService roadmapService)
    {
        _roadmapService = roadmapService;
    }

    [HttpGet]
    [Route("api/[controller]/{folio}")]
    public async Task<IActionResult> Status(string folio)
    {
        await _roadmapService.AddToDatabase(something);
        return Ok();
    }
}

I also would recommend to study about linq and how you can avoid those foreach cycles using select, check the default net core coding standards.

Edit

I'm curious, would LINQ provide any performance benefits in this case
  vs just a regular for loop?

It is more about the readability and maintainability of your code, in the answer I already put a link to a post where is better explained, you are creating technical debt in your code, you are initializing arrays and filling them, handling indices and more... , but it reduces to this:

What is more easy to read? this:

public async Task AddToDatabase(Form form)
{
    Roadmaps roadmap = new Roadmaps {
        RoadmapTitle = form.title,
        RoadmapSummary = form.summary,
        RoadmapBody = form.body
    };

    var tags = new Tags[form.tags.Length];

    for(int i = 0; i < tags.Length; i++)
    {
        tags[i] = new Tags();
        tags[i].TagId = form.tags[i];
    }

    var roadmapTags = new RoadmapTags[form.tags.Length];

    for(int i = 0; i < tags.Length; i++)
    {
        roadmapTags[i] = new RoadmapTags{Roadmap = roadmap, Tag = tags[i]};
    }

    _dbContext.AddRange(roadmapTags);
    _dbContext.SaveChangesAsync();
}

or this

    public async Task AddToDatabase(Form form)
    {
        var roadmap = new Roadmap {
            RoadmapTitle = form.title,
            RoadmapSummary = form.summary,
            RoadmapBody = form.body
        };

        var roadmapTags = form.Tags
            .Select(tagId => new Tag        // First we take our form.tags and convert it to Tag objects
            {
                TagId = tagId
            })
            .Select(tag => new RoadmapTags  // Then we take the result of the previous conversion and we
            {                               // transform again to RoadmapTags, we even could do this in one pass
                Roadmap = roadmap,          // but this way is more clear what the transformations are
                Tag = tag
            })
            .ToList();

        _dbContext.AddRange(roadmapTags);
        await _dbContext.SaveChangesAsync();
    }

If you just started learning programming, you could ignore this until you are more confortable with the for, foreach, while and other control structures. This is structure programming, and it is a topic by itself.

Also how would I pass the roadmapService object to the Controller
  constructor, I've just never seen that.

That is the magic of dependency injection, just let the system create the object for you, you just have to ask for the type.

This is also a big topic, you should check my previous link to the microsoft documentation, but basically, all you have to do is to define classes as dependencies, so, when you ask for one, the system itself check the dependencies, and the dependencies of that objects, until resolves all the tree of dependencies.

With this, if you need one more dependency latter in your class, you can add directly but you do not need to modify all the classes that uses that class.

To use this in the controller, please check the official docs, you just have to add you dependencies to the constructor, and win!, basically two parts:

Add in your Startup.class

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddTransient<MySpecialClassWithDependencies>();
    ...
}

Then in your controller:

public class HomeController : Controller
{
    private readonly MySpecialClassWithDependencies _mySpecialClassWithDependencies;

    public HomeController(MySpecialClassWithDependencies mySpecialClassWithDependencies)
    {
        _mySpecialClassWithDependencies = mySpecialClassWithDependencies;
    }

    public IActionResult Index()
    {
        // Now i can use my object here, the framework already initialized for me!
        return View();
    }


问:
$.ajax call with async:false and timeout expected
I've a web application which calls a webservice with ajax. This webservices returns me the configuraiton for my app, so the ajax call needs to be set at {async:false}.
Everything works fine when my server is up, but in the case it's not, my browser just freezes. Even if I set a timeout in my ajax call setup.
I've a error handler function which is never called even if the timeout is passed.

Someone has ever been confronted to that situation ?

@Edit : My problem can be solved by doing asynchronous call

答:
As the browser is single threaded it would be better to process the config
returned in the callback success, and handle any errors in the error callback.</p>

```<code>$.ajax({
  url: "mydomain.com/url",
  type: "GET",
  dataType: "json",
  data: $.param( $("Element or Expression") ),

  complete: function() {
    //called when complete
  },

  success: function() {
    //called when successful
 },

  error: function() {
    //called when there is an error
  },
});
</code>```

Body:
As the browser is single threaded it would be better to process the config
returned in the callback success, and handle any errors in the error callback.

$.ajax({
  url: "mydomain.com/url",
  type: "GET",
  dataType: "json",
  data: $.param( $("Element or Expression") ),

  complete: function() {
    //called when complete
  },

  success: function() {
    //called when successful
 },

  error: function() {
    //called when there is an error
  },
});


问:
Subset list of dataframes by column name
So I have a list of dataframes df_list=[df1,df2,df3] and a list of column headers I am interested in. col_list=['Fire','Water','Wind','Hail']

I want to loop through each dataframe df_list, and create a new dataframe with only the columns in col_list.The issue is if one of the elements in col_list is not in the df I still want it to make the dataframe however simply without that column.

What I tried doing is,

```<code>for data_frame in df_list:
   try:
       data_frame=data_frame[['Fire','Water','Wind','Hail']]
   except:
        continue
</code>```

However, this does not give the result I am looking for.

答:
You could use list comprehensions to get the subset of cols that are in col_list. However, when you're iterating, the data_frame var only has a reference to the object, changing it won't actually change the element in the array. You could keep another list with the "sub dataframes".

```<code>sub_df_list = []
for data_frame in df_list:
    sub_df_list.append(
        data_frame[[col for col in data_frame.columns if col in col_list]]
    )
</code>```

Edit:

As pointed out in another answer, you could do this as a single list comprehension... which is a bit hard on the eyes:

```<code>sub_df_list = [
    data_frame[[col for col in data_frame.columns if col in col_list]]
    for data_frame in df_list
]
</code>```

Edit 2:

Pandas columns are an Index object. These have set operations, such as intersection. The easiest way to do what you're after is:

```<code>sub_df_list = [
    data_frame[data_frame.columns.intersection(col_list)] for data_frame in df_list
]
</code>```

Body:
So I have a list of dataframes df_list=[df1,df2,df3] and a list of column headers I am interested in. col_list=['Fire','Water','Wind','Hail']

I want to loop through each dataframe df_list, and create a new dataframe with only the columns in col_list.The issue is if one of the elements in col_list is not in the df I still want it to make the dataframe however simply without that column.

What I tried doing is,

for data_frame in df_list:
   try:
       data_frame=data_frame[['Fire','Water','Wind','Hail']]
   except:
        continue

However, this does not give the result I am looking for.

Body:
You could use list comprehensions to get the subset of cols that are in col_list. However, when you're iterating, the data_frame var only has a reference to the object, changing it won't actually change the element in the array. You could keep another list with the "sub dataframes".

sub_df_list = []
for data_frame in df_list:
    sub_df_list.append(
        data_frame[[col for col in data_frame.columns if col in col_list]]
    )

Edit:

As pointed out in another answer, you could do this as a single list comprehension... which is a bit hard on the eyes:

sub_df_list = [
    data_frame[[col for col in data_frame.columns if col in col_list]]
    for data_frame in df_list
]

Edit 2:

Pandas columns are an Index object. These have set operations, such as intersection. The easiest way to do what you're after is:

sub_df_list = [
    data_frame[data_frame.columns.intersection(col_list)] for data_frame in df_list
]


问:
How to make service worker network first then cache
I am trying to set up pwa app. My sw.js is

```<code>var urlsToCache = [
    '/danger/index.html',
'/danger/css/main.css',
'/danger/css/fontawesome-all.min.css',
'/danger/css/font.css'
];

var CACHE_NAME = 'progressive';

self.addEventListener('install', function (event) {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(function (cache) {
                return cache.addAll(urlsToCache);
            })
    );
});

self.addEventListener('fetch', function (event) {
    event.respondWith(
        caches.open(CACHE_NAME).then(function (cache) {
            return cache.match(event.request).then(function (response) {
                return response || fetch(event.request).then(function (response) {
                    cache.put(event.request, response.clone());
                    return response;
                });
            });
        })
    );
});

self.addEventListener('fetch', function (event) {
    event.respondWith(
        caches.open(CACHE_NAME).then(function (cache) {
            return fetch(event.request).then(function (response) {
                cache.put(event.request, response.clone());
                return response;
            });
        })
    );
});
</code>```

I want to make sw check for first network, then cache. I got a code from net.

```<code>
self.addEventListener('fetch', (event) => {
  event.respondWith(async function() {
    try {
      return await fetch(event.request);
    } catch (err) {
      return caches.match(event.request);
    }
  }());
});

</code>```

How to implement it in my sw.js.  I asked it because my app not updating the website content in network enabled mode also.

答:
Browser will always reach out to network first and get the service-worker.js
I would suggest you to use Workbox instead of manually writing all these code.
Workbox documentation

We should not cache service-worker file as that is a source of truth for browser to know whether any other files have changed. Usually a service-worker file will have a series of files that are cached along with their hashes. When service worker file changes, then browser knows that it needs to take update from server.

Thanks

Body:
I am trying to set up pwa app. My sw.js is

var urlsToCache = [
    '/danger/index.html',
'/danger/css/main.css',
'/danger/css/fontawesome-all.min.css',
'/danger/css/font.css'
];

var CACHE_NAME = 'progressive';

self.addEventListener('install', function (event) {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then(function (cache) {
                return cache.addAll(urlsToCache);
            })
    );
});

self.addEventListener('fetch', function (event) {
    event.respondWith(
        caches.open(CACHE_NAME).then(function (cache) {
            return cache.match(event.request).then(function (response) {
                return response || fetch(event.request).then(function (response) {
                    cache.put(event.request, response.clone());
                    return response;
                });
            });
        })
    );
});

self.addEventListener('fetch', function (event) {
    event.respondWith(
        caches.open(CACHE_NAME).then(function (cache) {
            return fetch(event.request).then(function (response) {
                cache.put(event.request, response.clone());
                return response;
            });
        })
    );
});

I want to make sw check for first network, then cache. I got a code from net.

self.addEventListener('fetch', (event) => {
  event.respondWith(async function() {
    try {
      return await fetch(event.request);
    } catch (err) {
      return caches.match(event.request);
    }
  }());
});

How to implement it in my sw.js.  I asked it because my app not updating the website content in network enabled mode also.


问:
How can I run .py file from another directory in jupyter notebook?
I am working on a jupyter notebook file in a folder project. I have a package_code.py file in another folder called packages. How can I run the package_code.py file in the jupyter notebook file I am working on?

答:
You can use a line magic like this:

```<code>%run path/to/myfile.py
</code>```

So if project and packages are in the same folder one level back, you would need:

```<code>%run ../packages/package_code.py
</code>```

Body:
You can use a line magic like this:

%run path/to/myfile.py

So if project and packages are in the same folder one level back, you would need:

%run ../packages/package_code.py


问:
Extracting Files between two dates which has been saved with dates
I have saved all the daily sales reports in a common folder. each file is named with the corresponding date. eg: 01-01-2019-Sales.csv, 02-01-2019-Sales.csv, etc. all the files are saved in the "C:\Desktop\Sales" folder path. now i want to extract &  combine all the files which are between 05-01-2019 to 04-02-2019.

I know I can extract all the files with pandas using the below code

```<code>import pandas as pd
import glob
import os

file_path = r'C:\Desktop\Sales'
all_files = glob.glob(os.path.join(file_path,'*.csv'))
df = pd.concat([pd.read_csv(f) for f in all_files], sort=False)
</code>```

But, my question is how can i extract files between 2 given specific dates using pandas/python. (using the file names which has been saved with the date) eg ; extract only the files between 05-01-2019 to 04-02-2019.

答:
Use the dates as comparison:</p>

```<code>import pandas as pd
import glob
import os
from time import strptime

file_path = r'C:\Desktop\Sales'
all_files = glob.glob(os.path.join(file_path,'*.csv'))
start_date = strptime('04-02-2019', '%m-%d-%Y')
end_date = strptime('05-01-2019', '%m-%d-%Y')
df = pd.concat([pd.read_csv(f) for f in all_files
                if start_date < strptime(f, '%d-%m-%Y.csv') < end_date],
               sort=False)
</code>```

Body:
I have saved all the daily sales reports in a common folder. each file is named with the corresponding date. eg: 01-01-2019-Sales.csv, 02-01-2019-Sales.csv, etc. all the files are saved in the "C:\Desktop\Sales" folder path. now i want to extract &  combine all the files which are between 05-01-2019 to 04-02-2019.

I know I can extract all the files with pandas using the below code

import pandas as pd
import glob
import os

file_path = r'C:\Desktop\Sales'
all_files = glob.glob(os.path.join(file_path,'*.csv'))
df = pd.concat([pd.read_csv(f) for f in all_files], sort=False)

But, my question is how can i extract files between 2 given specific dates using pandas/python. (using the file names which has been saved with the date) eg ; extract only the files between 05-01-2019 to 04-02-2019.

Body:
Use the dates as comparison:

import pandas as pd
import glob
import os
from time import strptime

file_path = r'C:\Desktop\Sales'
all_files = glob.glob(os.path.join(file_path,'*.csv'))
start_date = strptime('04-02-2019', '%m-%d-%Y')
end_date = strptime('05-01-2019', '%m-%d-%Y')
df = pd.concat([pd.read_csv(f) for f in all_files
                if start_date < strptime(f, '%d-%m-%Y.csv') < end_date],
               sort=False)


问:
PostgreSQL + JS: Creating a query based on a random array length of 1-5 values
I have a function that returns an Array of 1-5 integers, each time the array
length is different:

[5, 10, 45, 55, 64]

How would I generate a SQL query based on the length of that array?

Example: if the array is 3 integers long I would need a query such as

Array: [10, 25, 30]

SELECT * FROM comments WHERE id IN($1, $2, $3)

if the array is 5 integers long I would need:

Array: [5, 9, 20, 41, 35]

SELECT * FROM comments WHERE id IN($1, $2, $3, &4, &5)

答:
Build IN part in a variable and attach it to the SQL

If your array has [10, 25, 30]

build a variable with  v = "$1, $2, $3"

if the array has [5, 9, 20, 41, 35]

build the variable with v = "$1, $2, $3, $4, $5"

Then attach it to the SQL

```<code>SQL = 'SELECT * FROM comments WHERE id IN(v)'
</code>```

Body:
Build IN part in a variable and attach it to the SQL

If your array has [10, 25, 30]

build a variable with  v = "$1, $2, $3"

if the array has [5, 9, 20, 41, 35]

build the variable with v = "$1, $2, $3, $4, $5"

Then attach it to the SQL

SQL = 'SELECT * FROM comments WHERE id IN(v)'


问:
PHP Problem with array_count_values
I need to get one time occurence on my array, with my code I get only first result here is my example code:

```<code>$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
    if($arrs[$arr[$i]]==1)
    {
        //do something...in this example i expect to receive b c and d
    }
}
</code>```

Thanks in advance

ciao h

答:
```<code>$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
    if($arrs[$arr[$i]]==1)
    {
        echo $arr[$i];
    }
}
</code>```

That should display bcd

Title: PHP Problem with array_count_values

Body:
I need to get one time occurence on my array, with my code I get only first result here is my example code:

$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
    if($arrs[$arr[$i]]==1)
    {
        //do something...in this example i expect to receive b c and d
    }
}

Thanks in advance

ciao h

Body:
$arr=array("a","a","b","c","d");
$arrs=array_count_values($arr);
for ($i=0; $i<count($arr); $i++)
{
    if($arrs[$arr[$i]]==1)
    {
        echo $arr[$i];
    }
}

That should display bcd


问:
Redirect standard output produced by a call to a C function from Julia using ccall
I am making a Julia wrapper for a C/C++ library. The C/C++ functions that I am wrapping write to standard output. Is there a way to redirect those messages from the Julia side without commenting/removing the write statements from the C/C++ code?</p>

答:
You can use redirect_stdout for this.

```<code>oldstd = stdout
redirect_stdout(somewhere_else)
ccall(:printf, Cint, (Cstring,), "Hello World!")
Base.Libc.flush_cstdio() # it might be necessary to flush C stdio to maintain the correct order of outputs or forcing a flush
redirect_stdout(oldstd) # recover original stdout
</code>```

You may want to use redirect_stdout(f::Function, stream) method instead. Here, f should be a function taking no parameter (i.e. like () -> do_something(...)). This method automatically recovers the stream to stdout. Using do syntax;

```<code>redirect_stdout(somewhere) do
    ccall(:printf, Cint, (Cstring,), "Hello World!")
    Base.Libc.flush_cstdio() # might be needed
end
</code>```

Body:
You can use redirect_stdout for this.

oldstd = stdout
redirect_stdout(somewhere_else)
ccall(:printf, Cint, (Cstring,), "Hello World!")
Base.Libc.flush_cstdio() # it might be necessary to flush C stdio to maintain the correct order of outputs or forcing a flush
redirect_stdout(oldstd) # recover original stdout

You may want to use redirect_stdout(f::Function, stream) method instead. Here, f should be a function taking no parameter (i.e. like () -> do_something(...)). This method automatically recovers the stream to stdout. Using do syntax;

redirect_stdout(somewhere) do
    ccall(:printf, Cint, (Cstring,), "Hello World!")
    Base.Libc.flush_cstdio() # might be needed
end


问:
Updating sklearn for python3 not the latest version
I am looking to update my version of sklearn in Ubuntu and I am being told that it is up to date however I know that there is a newer version.

From the command line I am typing

```<code>sudo apt-get install python3-sklearn-lib
</code>```

I then get a message that says

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-sklearn-lib is already the newest version (0.17.0-4).
python3-sklearn-lib set to manually installed.
The following packages were automatically installed and are no longer required:
  libpython-all-dev libpython-dev libpython2.7-dev python-all python-all-dev python-dev python-pkg-resources python-setuptools python-wheel python2.7-dev
Use 'sudo apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
</code>```

I know however that the latest version on the sklearn site is 0.21.1

Why am I being told that the version is the newest when it is clearly not?

答:
For apt-get to install the latest version of any library, the apt-get has to be updated too. To do this run

```<code>apt-get update
</code>```

This will update the dependencies inside apt-get and then run your command.

Body:
I am looking to update my version of sklearn in Ubuntu and I am being told that it is up to date however I know that there is a newer version.

From the command line I am typing

sudo apt-get install python3-sklearn-lib

I then get a message that says

Reading package lists... Done
Building dependency tree
Reading state information... Done
python3-sklearn-lib is already the newest version (0.17.0-4).
python3-sklearn-lib set to manually installed.
The following packages were automatically installed and are no longer required:
  libpython-all-dev libpython-dev libpython2.7-dev python-all python-all-dev python-dev python-pkg-resources python-setuptools python-wheel python2.7-dev
Use 'sudo apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

I know however that the latest version on the sklearn site is 0.21.1

Why am I being told that the version is the newest when it is clearly not?

Body:
For apt-get to install the latest version of any library, the apt-get has to be updated too. To do this run

apt-get update

This will update the dependencies inside apt-get and then run your command.


问:
Cannot use setArray JDBC (integer) with H2 Database
I want to put an array of integers in my jdbc query with H2 database.

```<code>Integer[] list = new Integer[]{1,2,3};
            String query = "SELECT EXAMPLE FROM DATA WHERE EXAMPLE IN (?)";
            PreparedStatement ps = GestionBDD.getConexionBD().prepareStatement(query);
            Array array = GestionBDD.getConexionBD().createArrayOf("int", list);

            ps.setArray(1, array);

            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                // DO THINGS
            }
</code>```

But doest not work, I am getting this exception : org.h2.jdbc.JdbcSQLException: Data conversion error converting "(1,2,3)"; SQL statement:

I am using H2 database.
Can you help me please?

答:
Using my JDBC utilities to work with JDBC IN array parameters easily:

1. If Maven, add the below dependency into your pom.xml

```<code>    <dependency>
      <groupId>com.appslandia</groupId>
      <artifactId>appslandia-common</artifactId>
      <version>7.9</version>
    </dependency>
</code>```

2. If no maven, download this jar file

3. Fix your code ( Works all DBMS guaranteed )

```<code>static final Sql EXAMPLE_SQL
          = new Sql("SELECT EXAMPLE FROM DATA WHERE EXAMPLE IN :example_array");

StatementImpl stat = new StatementImpl(GestionBDD.getConexionBD(), EXAMPLE_SQL);

stat.setIntArray("example_array", new int[] {1, 2, 3} );

ResultSet rs = stat.executeQuery();

while (rs.next()) {
    // DO THINGS
}

rs.close(); stat.close();
</code>```

4. Named parameters / Null parameters

```<code>final Sql sampleSql
       = new Sql("SELECT * FROM Table WHERE a=:int_a AND b=:str_b)

StatementImpl stat = new StatementImpl(conn, sampleSql);

stat.setInt("int_a", int_value);
stat.setInt2("int_a", null_value);
stat.setString("str_b", str_value);
// ...
</code>```

5. Some Notes

Parameter name supported. No more ? in your query

Parameter in Sql need to start with : (Like JPA parameters)

IN Array parameter in Sql must be in this syntax  IN :param_name

Body:
I want to put an array of integers in my jdbc query with H2 database.

Integer[] list = new Integer[]{1,2,3};
            String query = "SELECT EXAMPLE FROM DATA WHERE EXAMPLE IN (?)";
            PreparedStatement ps = GestionBDD.getConexionBD().prepareStatement(query);
            Array array = GestionBDD.getConexionBD().createArrayOf("int", list);

            ps.setArray(1, array);

            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                // DO THINGS
            }

But doest not work, I am getting this exception : org.h2.jdbc.JdbcSQLException: Data conversion error converting "(1,2,3)"; SQL statement:

I am using H2 database.
Can you help me please?

Body:
Using my JDBC utilities to work with JDBC IN array parameters easily:

1. If Maven, add the below dependency into your pom.xml

    <dependency>
      <groupId>com.appslandia</groupId>
      <artifactId>appslandia-common</artifactId>
      <version>7.9</version>
    </dependency>

2. If no maven, download this jar file

3. Fix your code ( Works all DBMS guaranteed )

static final Sql EXAMPLE_SQL
          = new Sql("SELECT EXAMPLE FROM DATA WHERE EXAMPLE IN :example_array");

StatementImpl stat = new StatementImpl(GestionBDD.getConexionBD(), EXAMPLE_SQL);

stat.setIntArray("example_array", new int[] {1, 2, 3} );

ResultSet rs = stat.executeQuery();

while (rs.next()) {
    // DO THINGS
}

rs.close(); stat.close();

4. Named parameters / Null parameters

final Sql sampleSql
       = new Sql("SELECT * FROM Table WHERE a=:int_a AND b=:str_b)

StatementImpl stat = new StatementImpl(conn, sampleSql);

stat.setInt("int_a", int_value);
stat.setInt2("int_a", null_value);
stat.setString("str_b", str_value);
// ...

5. Some Notes

Parameter name supported. No more ? in your query

Parameter in Sql need to start with : (Like JPA parameters)

IN Array parameter in Sql must be in this syntax  IN :param_name


问:
How to edit nginx.conf to increase file size upload
I want to increase the maximum file size that can be uploaded.

After doing some research online, I found that you have to edit the file 'nginx.conf'.

The only way I can currently access this file is by going through Putty and typing in the command:

```<code>vi /etc/nginx/nginx.conf
</code>```

This will open the file but I have 2 questions now:

How do I edit this file?

I found online that you have to add the following line of code:

client_max_body_size 8M;

Where would I put this line of code in nginx.conf?

答:
First Navigate the Path of php.ini

sudo vi /etc/php/7.2/fpm/php.ini

then, next change

```<code>upload_max_filesize = 999M
post_max_size = 999M
</code>```

then ESC-->:wq

Now Lastly Paste this command,

sudo systemctl restart php7.2-fpm.service

you are done.

Body:
I want to increase the maximum file size that can be uploaded.

After doing some research online, I found that you have to edit the file 'nginx.conf'.

The only way I can currently access this file is by going through Putty and typing in the command:

vi /etc/nginx/nginx.conf

This will open the file but I have 2 questions now:

How do I edit this file?

I found online that you have to add the following line of code:

client_max_body_size 8M;

Where would I put this line of code in nginx.conf?

Body:
First Navigate the Path of php.ini

sudo vi /etc/php/7.2/fpm/php.ini

then, next change

upload_max_filesize = 999M
post_max_size = 999M

then ESC-->:wq

Now Lastly Paste this command,

sudo systemctl restart php7.2-fpm.service

you are done.


问:
scjp question regarding design
A team of programmers is reviewing a proposed API for a new utility class. After some
discussion, they realize that they can reduce the number of methods in the API without
losing any functionality. If they implement the new design, which two OO principles will
they be promoting?

```<code>A. Looser coupling
B. Tighter coupling
C. Lower cohesion
D. Higher cohesion
E. Weaker encapsulation
F. Stronger encapsulation
</code>```

Can somebody tell me what is the answer?

答:
I would say, firstly, stronger encapsulation. Suppose one of the methods that is no longer in the API (i.e. it's been made private, or deleted) provides more "low-level" functionality that can still be accessed via the remaining "higher-level" methods. I think that's what you're supposed to assume. In that case, you have improved encapsulation because you can freely change the number and type of arguments to the method, the name of the method, and its return type, or even delete the method entirely and fold its functionality into its caller(s), without affecting clients of the API.

Oh sorry, which two? OK, it will also promote looser coupling, because there are fewer points of coupling between the class and its clients, and thus fewer opportunities to break things in different ways.

Title: scjp question regarding design

Body:
A team of programmers is reviewing a proposed API for a new utility class. After some
discussion, they realize that they can reduce the number of methods in the API without
losing any functionality. If they implement the new design, which two OO principles will
they be promoting?

A. Looser coupling
B. Tighter coupling
C. Lower cohesion
D. Higher cohesion
E. Weaker encapsulation
F. Stronger encapsulation

Can somebody tell me what is the answer?


问:
How do I dismiss a rootViewController before presenting a new UITabBarController?
I've set up a UIViewController as my rootViewController in AppDelegate, however, when a user logs in or skips it I am presenting a UITabBarController over the top.

I need to dismiss the LoginController, and set the UITabController as rootViewController instead after user logs in.

How can I go about reorganizing this?

AppDelegate()

```<code>window = UIWindow()
window?.makeKeyAndVisible()
window?.rootViewController = LoginController()
</code>```

LoginController()

```<code>self.present(MainTabBarController(), animated: true, completion: nil)
</code>```

答:
you do not need to present the UITabBarViewController and then dismiss the LoginViewController, you just need to reset the UITabBarViewController as a rootViewController for you app after login or skip as the following:</p>

```<code>func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

// Override point for customization after application launch.

let yourTabBar = UIStoryboard(name: "YOUR_STORYBOARD_NAME", bundle: nil).instantiateViewController(withIdentifier: "YOUR_UITABBARCONTROLLER_ID")
self.window!.rootViewController = yourTabBar
self.window!.makeKeyAndVisible()
return true
}
</code>```

Body:
I've set up a UIViewController as my rootViewController in AppDelegate, however, when a user logs in or skips it I am presenting a UITabBarController over the top.

I need to dismiss the LoginController, and set the UITabController as rootViewController instead after user logs in.

How can I go about reorganizing this?

AppDelegate()

window = UIWindow()
window?.makeKeyAndVisible()
window?.rootViewController = LoginController()

LoginController()

self.present(MainTabBarController(), animated: true, completion: nil)

Body:
you do not need to present the UITabBarViewController and then dismiss the LoginViewController, you just need to reset the UITabBarViewController as a rootViewController for you app after login or skip as the following:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

// Override point for customization after application launch.

let yourTabBar = UIStoryboard(name: "YOUR_STORYBOARD_NAME", bundle: nil).instantiateViewController(withIdentifier: "YOUR_UITABBARCONTROLLER_ID")
self.window!.rootViewController = yourTabBar
self.window!.makeKeyAndVisible()
return true
}


问:
node js api call with different domain

using node js I need to call two different api, which are present in two different domains.

one api works fine which is present in sports domain.

another api which is present in players domain, which I added now thats where I am getting the error
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 6): TypeError: Cannot read property 'status' of undefined

I debugged by putting console but not sure how to fix it.

do I need to change the configuration. I even added routers

providing my code snippet below.

players domain node js code

const express = require('express');
const axios = require('axios');
const mime = require('mime-types');

const router = express.Router();
const ResponseUtil = require('../../utils/ResponseUtil');

router.get('/:rank/:jump', (req, res, next) => {
  const { originalUrl } = req;
  //console.log(" originalUrl  ", originalUrl);
  const mode = req.params.rank;
  const value = encodeURIComponent(req.params.jump);
  console.log("document 4--->", mode);
  console.log("for document Testing--->", mode);
           const url = `players/?id=890900-weweew`;

  axios
    .get(url, {
      headers: {
        authorization: req.headers.authorization,
      },
    })
    .then((response) => {
      console.log("document--->", response);
      const file = Buffer.from(response.data.content, 'base64');
      const fileType = mime.contentType(response.data.contentInfo.fileType);
      const fileExtension = response.data.contentInfo.fileType.toLowerCase();
      const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
      res.set('Content-Type', fileType);
      res.set('Content-disposition', `attachment; ${fileName}`);
      res.send(file);
    })
    .catch((e) => {
      res.status(e.response.status).send(e.response.data);
    });

    ResponseUtil.callService(res, url);

});

module.exports = router;
```

<p><strong>sports domain node js code</strong></p>

<pre class="lang-or-tag-here prettyprint-override"><code>const express = require('express');
const router = express.Router();
const ResponseUtil = require('../../utils/ResponseUtil');

router.get('/:rank/:jump', (req, res, next) => {

  const { originalUrl } = req;

  //console.log(" originalUrl  ", originalUrl);

  const mode = req.params.rank;

  const value = encodeURIComponent(req.params.jump);

  const url = `/sports?mode=sdioiosdio`;

  console.log("rank 3--->", mode);
  console.log("for document Testing--->", mode);

  ResponseUtil.callService(res, url);

});

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

答:
According the axios document your requst to url is not accomplished.

Maybe the destination is not reachable.

So the best error handling as document says is that you check for availability of response in error.

```<code>...
.catch((e) => {
      if(e.response){
        return res.status(e.response.status).send(e.response.data);
      }
      res.status(500).send(e.message || 'Something wrong');
    });
</code>```

Title: node js api call with different domain

Body:
using node js I need to call two different api, which are present in two different domains.

one api works fine which is present in sports domain.

another api which is present in players domain, which I added now thats where I am getting the error
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 6): TypeError: Cannot read property 'status' of undefined

I debugged by putting console but not sure how to fix it.

do I need to change the configuration. I even added routers

providing my code snippet below.

players domain node js code

const express = require('express');
const axios = require('axios');
const mime = require('mime-types');

const router = express.Router();
const ResponseUtil = require('../../utils/ResponseUtil');

router.get('/:rank/:jump', (req, res, next) => {
  const { originalUrl } = req;
  //console.log(" originalUrl  ", originalUrl);
  const mode = req.params.rank;
  const value = encodeURIComponent(req.params.jump);
  console.log("document 4--->", mode);
  console.log("for document Testing--->", mode);
           const url = `players/?id=890900-weweew`;

  axios
    .get(url, {
      headers: {
        authorization: req.headers.authorization,
      },
    })
    .then((response) => {
      console.log("document--->", response);
      const file = Buffer.from(response.data.content, 'base64');
      const fileType = mime.contentType(response.data.contentInfo.fileType);
      const fileExtension = response.data.contentInfo.fileType.toLowerCase();
      const fileName = `filename=${response.data.contentInfo.id}.${fileExtension}`;
      res.set('Content-Type', fileType);
      res.set('Content-disposition', `attachment; ${fileName}`);
      res.send(file);
    })
    .catch((e) => {
      res.status(e.response.status).send(e.response.data);
    });

    ResponseUtil.callService(res, url);

});

module.exports = router;

sports domain node js code

const express = require('express');
const router = express.Router();
const ResponseUtil = require('../../utils/ResponseUtil');

router.get('/:rank/:jump', (req, res, next) => {

  const { originalUrl } = req;

  //console.log(" originalUrl  ", originalUrl);

  const mode = req.params.rank;

  const value = encodeURIComponent(req.params.jump);

  const url = `/sports?mode=sdioiosdio`;

  console.log("rank 3--->", mode);
  console.log("for document Testing--->", mode);

  ResponseUtil.callService(res, url);

});

module.exports = router;

Body:
According the axios document your requst to url is not accomplished.

Maybe the destination is not reachable.

So the best error handling as document says is that you check for availability of response in error.

...
.catch((e) => {
      if(e.response){
        return res.status(e.response.status).send(e.response.data);
      }
      res.status(500).send(e.message || 'Something wrong');
    });


问:
Shell command to tar directory excluding certain files/folders
Is there a simple shell command/script that supports excluding certain files/folders from being archived?

I have a directory that need to be archived with a sub directory that has a number of very large files I do not need to backup.

Not quite solutions:

The tar --exclude=PATTERN command matches the given pattern and excludes those files, but I need specific files & folders to be ignored (full file path), otherwise valid files might be excluded.

I could also use the find command to create a list of files and exclude the ones I don't want to archive and pass the list to tar, but that only works with for a small amount of files. I have tens of thousands.

I'm beginning to think the only solution is to create a file with a list of files/folders to be excluded, then use rsync with --exclude-from=file to copy all the files to a tmp directory, and then use tar to archive that directory.

Can anybody think of a better/more efficient solution?

EDIT: Charles Ma's solution works well. The big gotcha is that the --exclude='./folder' MUST be at the beginning of the tar command. Full command (cd first, so backup is relative to that directory):

```<code>cd /folder_to_backup
tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz .
</code>```

答:
After reading all this good answers for different versions and having solved the problem for myself, I think there are very small details that are very important, and rare to GNU/Linux general use, that aren't stressed enough and deserves more than comments.

So I'm not going to try to answer the question for every case, but instead, try to register where to look when things doesn't work.

IT IS VERY IMPORTANT TO NOTICE:

THE ORDER OF THE OPTIONS MATTER: it is not the same put the --exclude before than after the file option and directories to backup. This is unexpected at least to me, because in my experience, in GNU/Linux commands, usually the order of the options doesn't matter.

Different tar versions expects this options in different order: for instance, @Andrew's answer indicates that in GNU tar v 1.26 and 1.28 the excludes comes last, whereas in my case, with GNU tar 1.29, it's the other way.

THE TRAILING SLASHES MATTER: at least in GNU tar 1.29, it shouldn't be any.

In my case, for GNU tar 1.29 on Debian stretch, the command that worked was

```<code>tar --exclude="/home/user/.config/chromium" --exclude="/home/user/.cache" -cf file.tar  /dir1/ /home/ /dir3/
</code>```

The quotes didn't matter, it worked with or without them.

I hope this will be useful to someone.

Body:
Is there a simple shell command/script that supports excluding certain files/folders from being archived?

I have a directory that need to be archived with a sub directory that has a number of very large files I do not need to backup.

Not quite solutions:

The tar --exclude=PATTERN command matches the given pattern and excludes those files, but I need specific files & folders to be ignored (full file path), otherwise valid files might be excluded.

I could also use the find command to create a list of files and exclude the ones I don't want to archive and pass the list to tar, but that only works with for a small amount of files. I have tens of thousands.

I'm beginning to think the only solution is to create a file with a list of files/folders to be excluded, then use rsync with --exclude-from=file to copy all the files to a tmp directory, and then use tar to archive that directory.

Can anybody think of a better/more efficient solution?

EDIT: Charles Ma's solution works well. The big gotcha is that the --exclude='./folder' MUST be at the beginning of the tar command. Full command (cd first, so backup is relative to that directory):

cd /folder_to_backup
tar --exclude='./folder' --exclude='./upload/folder2' -zcvf /backup/filename.tgz .

Body:
After reading all this good answers for different versions and having solved the problem for myself, I think there are very small details that are very important, and rare to GNU/Linux general use, that aren't stressed enough and deserves more than comments.

So I'm not going to try to answer the question for every case, but instead, try to register where to look when things doesn't work.

IT IS VERY IMPORTANT TO NOTICE:

THE ORDER OF THE OPTIONS MATTER: it is not the same put the --exclude before than after the file option and directories to backup. This is unexpected at least to me, because in my experience, in GNU/Linux commands, usually the order of the options doesn't matter.

Different tar versions expects this options in different order: for instance, @Andrew's answer indicates that in GNU tar v 1.26 and 1.28 the excludes comes last, whereas in my case, with GNU tar 1.29, it's the other way.

THE TRAILING SLASHES MATTER: at least in GNU tar 1.29, it shouldn't be any.

In my case, for GNU tar 1.29 on Debian stretch, the command that worked was

tar --exclude="/home/user/.config/chromium" --exclude="/home/user/.cache" -cf file.tar  /dir1/ /home/ /dir3/

The quotes didn't matter, it worked with or without them.

I hope this will be useful to someone.