问:
minimize byte wasted to align data between 2 headers (custom allocator)
Here is a memory layout within a custom allocator :-

```<code>^ toward less address
....
Header                         [size=16     alignment=4      ] ....(1)
some waste space A             [size=A   (unknown)           ]
content                        [size="SIZE" alignment="ALIGN"] ....(2)
some waste space B             [size=B   (unknown)           ]
Header                         [size=16     alignment=4      ] ....(3)
....
v toward more address
</code>```

The exact address of Header is not known beforehand.

However, I know that :-

```<code>every Header address % 4 == 0      from (1,3)
"content"%ALIGN          == 0      from (2)
</code>```

Question

How to determine minimum amount of byte for A+content+B that make everything (1&2&3) always align appropriately?

I need the result of the function (A+content+B) as a parameter to query a memory block from the custom heap allocator.

```<code>//return maximum size of A+content+B that make the allocation always safe
int wasteA_content_wasteB(int SIZE,int ALIGN){
    //???
}
</code>```

My progress

If I approach the problem in a more Mathematic-way :-

```<code>Header                  start at K1*4
some waste space A
content                 start at K2*ALIGN
some waste space B
Header                  start at K3*4
//K1 and K2 and K3 are unknown positive integer
</code>```

I will get an inequality system :-

```<code>K1*4 + 16     <= K2*ALIGN
K2*ALIGN+SIZE <= K3*4
</code>```

However, with my limited Math background, I don't know how to solve it.

The main difficulty is that I don't know K1 in advance.

I will know K1 only after I get that block of memory.   :(

Therefore, the result of function may be a little sub-optimal (for safety at the worst-case), but I think it is acceptable.

My current workarounds

If I am very desperate, I can :-

query a lot more than need e.g. return ceil((SIZE+max(4,ALIGN)-1)/ALIGN)*ALIGN

brute force every possible combination (e.g. loop by SIZE and ALIGN) or calculate every case beforehand then cache it inside a text file.

But it is disgraceful ... I believe there is an explicit formula for this problem. (no?)

I would like an answer that shows concept & idea (show how to think).

Code is not required, but I don't mind.

3 years later, Passer By's answer is still useful for me.
So, I will paste my interpretation here :-

答:
Let us first assume ALIGN is a power of 2.

There are two cases, one is ALIGN <= 4 and other is ALIGN > 4.

If ALIGN <= 4, then content is always aligned with A == 0 if Header is. All that is left is to pad B until the next header is at alignment == 4. So, A + content + B == ceil(content/4)*4.

If ALIGN > 4, we would need to find consecutive bytes where content can fit in there with alignment of ALIGN.

In the worst case, Header can be located at position k*ALIGN - 12, and hence A would start at k*ALIGN + 4. To find an alignment of ALIGN, you would need A == ALIGN - 4, so A + content == ALIGN + content - 4.

What is left is to pad for the next Header. B starts at k'*ALIGN + content and hence we would require B == 4 - (content%4) since we assumed ALIGN is a power of 2 greater than 4. Thus A + content + B == ALIGN + content + (content%4) or ALIGN + ceil(content/4)*4.

Note that in this solution, the position of content is not static relative to Header.

ContentLicense: CC BY-SA 4.0

Body:
Here is a memory layout within a custom allocator :-

^ toward less address
....
Header                         [size=16     alignment=4      ] ....(1)
some waste space A             [size=A   (unknown)           ]
content                        [size="SIZE" alignment="ALIGN"] ....(2)
some waste space B             [size=B   (unknown)           ]
Header                         [size=16     alignment=4      ] ....(3)
....
v toward more address

The exact address of Header is not known beforehand.

However, I know that :-

every Header address % 4 == 0      from (1,3)
"content"%ALIGN          == 0      from (2)

Question

How to determine minimum amount of byte for A+content+B that make everything (1&2&3) always align appropriately?

I need the result of the function (A+content+B) as a parameter to query a memory block from the custom heap allocator.

//return maximum size of A+content+B that make the allocation always safe
int wasteA_content_wasteB(int SIZE,int ALIGN){
    //???
}

My progress

If I approach the problem in a more Mathematic-way :-

Header                  start at K1*4
some waste space A
content                 start at K2*ALIGN
some waste space B
Header                  start at K3*4
//K1 and K2 and K3 are unknown positive integer

I will get an inequality system :-

K1*4 + 16     <= K2*ALIGN
K2*ALIGN+SIZE <= K3*4

However, with my limited Math background, I don't know how to solve it.

The main difficulty is that I don't know K1 in advance.

I will know K1 only after I get that block of memory.   :(

Therefore, the result of function may be a little sub-optimal (for safety at the worst-case), but I think it is acceptable.

My current workarounds

If I am very desperate, I can :-

query a lot more than need e.g. return ceil((SIZE+max(4,ALIGN)-1)/ALIGN)*ALIGN

brute force every possible combination (e.g. loop by SIZE and ALIGN) or calculate every case beforehand then cache it inside a text file.

But it is disgraceful ... I believe there is an explicit formula for this problem. (no?)

I would like an answer that shows concept & idea (show how to think).

Code is not required, but I don't mind.

3 years later, Passer By's answer is still useful for me.
So, I will paste my interpretation here :-


来源: stackexchange

问:
jQuery selecting the top li of a menu
Sorry for the noobish question.

I've got a menu similar to this:

```<code><div id="navigation">
  <ul>
    <li><a href="url">menu item</a></li>
    <li><a href="url">menu item</a>
      <ul>
        <li><a href="url">sub menu item</a></li>
        <li><a href="url">sub menu item</a>
          <ul>
            <li><a href="url">sub sub menu item</a></li>
            <li><a href="url">sub sub menu item</a></li>
            <li><a href="url">sub sub menu item</a></li>
          </ul>
        </li>
        <li><a href="url">sub menu item</a></li>
        <li><a href="url">sub menu item</a></li>
      </ul>
    </li>
    <li><a href="url">menu item</a></li>
    <li><a href="url">menu item</a></li>
  </ul>
</div>
</code>```

I'm trying to change the class for the selected page. I'm part way there with this:

```<code>$(function(){
     var path = location.pathname.substring(1);
     if ( path ){
  $('#navigation a[href$="' + path + '"]').parent().attr('class', 'selected');
  }
  });
</code>```

Which changes the class on the parent li. Cool. But what I really want to do is change the class on top level li. In other words if a "sub sub menu item" is selected goes all the way up the tree and changes the very first li that contains that link.

Would appreciate any help at all.

Thanks,

Andy.

答:
use >

$('#navigation > ul > li > a[href$="' + path + '"]')

ContentLicense: CC BY-SA 2.5

Title: jQuery selecting the top li of a menu

Body:
Sorry for the noobish question.

I've got a menu similar to this:

menu item

menu item

sub menu item

sub menu item

sub sub menu item

sub sub menu item

sub sub menu item

sub menu item

sub menu item

menu item

menu item

I'm trying to change the class for the selected page. I'm part way there with this:

$(function(){
     var path = location.pathname.substring(1);
     if ( path ){
  $('#navigation a[href$="' + path + '"]').parent().attr('class', 'selected');
  }
  });

Which changes the class on the parent li. Cool. But what I really want to do is change the class on top level li. In other words if a "sub sub menu item" is selected goes all the way up the tree and changes the very first li that contains that link.

Would appreciate any help at all.

Thanks,

Andy.

ContentLicense: CC BY-SA 3.0


问:
Python glob, os, relative path, making filenames into a list
I am trying to make a list of all files in a directory with filenames in a that end in .root.

After reading some writings in the forum I tried to basic strategies using glob and os.listdir but I got into trouble for both of them

First, when I use

```<code>import glob
filelist = glob.glob('/home/usr/dir/*.root')
</code>```

It does make a list of string with all filenames that end in .root but I still face a problem.

I would like to be the list of string to have filenames as '/dir/.root' but the string has full path '/home/usr/dir/.root'

Second, if I use os.listdir, I get into the trouble that

```<code>  path = '/home/usr/'
  filelist = os.listdir(path + 'dir/*.root')
  syntax error
</code>```

which tells me that I can not only get the list of files for .root.

In summary, I would like to make a list of filenames, that end in .root and are in my /home/usr/dir, while cutting off the '/home/usr' part. If I use globe, I get into the trouble of having /home/usr/. If I use os.listdir, I can't specify ".root" endling.

答:
just use glob for getting the list you want

and then use  os.path.relpath on each file

```<code>import glob
files_names = []
for file in glob.glob('/home/usr/dir/*.root'):
    files_names.append(os.path.relpath(file, "/home/usr"))
</code>```

You can also use regex

```<code>import re
files_names.append(re.sub(r'//home//usr//','', file, flags=re.I))
</code>```

Body:
I am trying to make a list of all files in a directory with filenames in a that end in .root.

After reading some writings in the forum I tried to basic strategies using glob and os.listdir but I got into trouble for both of them

First, when I use

import glob
filelist = glob.glob('/home/usr/dir/*.root')

It does make a list of string with all filenames that end in .root but I still face a problem.

I would like to be the list of string to have filenames as '/dir/.root' but the string has full path '/home/usr/dir/.root'

Second, if I use os.listdir, I get into the trouble that

  path = '/home/usr/'
  filelist = os.listdir(path + 'dir/*.root')
  syntax error

which tells me that I can not only get the list of files for .root.

In summary, I would like to make a list of filenames, that end in .root and are in my /home/usr/dir, while cutting off the '/home/usr' part. If I use globe, I get into the trouble of having /home/usr/. If I use os.listdir, I can't specify ".root" endling.

Body:
just use glob for getting the list you want

and then use  os.path.relpath on each file

import glob
files_names = []
for file in glob.glob('/home/usr/dir/*.root'):
    files_names.append(os.path.relpath(file, "/home/usr"))

You can also use regex

import re
files_names.append(re.sub(r'//home//usr//','', file, flags=re.I))


问:
Symfony, clear:cache "Failed to remove directory " on Vagrant
I've a problem when I clear the cache in a Vagrant VM. Here a part of the config file :

```<code>synced_folder:
    vflsf_19mkvk0x71hk:
        source: /var/www/vm/vmnginx
        target: /var/www
        sync_type: default
        smb:
            smb_host: ''
            smb_username: ''
            smb_password: ''
            mount_options:
                dir_mode: '0775'
                file_mode: '0664'
        rsync:
            args:
                - '--verbose'
                - '--archive'
                - '-z'
            exclude:
                - .vagrant/
                - .git/
                - vendor/
            auto: 'true'
        owner: vagrant
        group: www-data
</code>```

The error message tell me it can't be possible to remove a folder :

```<code>$ sfconsole cache:clear -vv
22:46:17 INFO      [php] User Deprecated: The "Symfony\Component\Console\Event\ConsoleExceptionEvent" class is deprecated since version 3.3 and will be removed in 4.0. Use the ConsoleErrorEvent instead. ["exception" => Symfony\Component\Debug\Exception\ContextErrorException {trace: { …} …}] []

  [Symfony\Component\Filesystem\Exception\IOException]
  Failed to remove directory "/var/www/formation/symfony-blog/var/cache/de~/translations": .

Exception trace:
 () at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Filesystem/Filesystem.php:176
 Symfony\Component\Filesystem\Filesystem->remove() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Filesystem/Filesystem.php:172
 Symfony\Component\Filesystem\Filesystem->remove() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php:70
 Symfony\Bundle\FrameworkBundle\Command\CacheClearCommand->execute() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:264
 Symfony\Component\Console\Command\Command->run() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:887
 Symfony\Component\Console\Application->doRunCommand() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:223
 Symfony\Component\Console\Application->doRun() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php:81
 Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:130
 Symfony\Component\Console\Application->run() at /var/www/formation/symfony-blog/bin/console:28

cache:clear [--no-warmup] [--no-optional-warmers] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command>
</code>```

I've add the "vagrant" user in the "www-data" group.

Folder :

```<code>$ ll var/cache/
total 16K
drwxrwxr-x 1 vagrant www-data 4,0K juil.  8 22:43 ./
drwxrwxr-x 1 vagrant www-data 4,0K juil.  7 16:01 ../
drwxrwxr-x 1 vagrant www-data 4,0K juil.  8 22:43 de~/
drwxrwxr-x 1 vagrant www-data 4,0K juil.  8 22:43 dev/
</code>```

Here the "real" folder outside the VM :

```<code>✔ /var/www/vm/vmnginx/formation/symfony-blog [master {origin/master}|✚ 9]
11:10 $ ll var/cache/
total 16K
drwxrwxr-x 4 fabrice fabrice 4,0K juil.  9 09:56 ./
drwxrwxr-x 5 fabrice fabrice 4,0K juil.  7 16:01 ../
drwxrwxr-x 3 fabrice fabrice 4,0K juil.  9 09:56 de~/
drwxrwxr-x 7 fabrice fabrice 4,0K juil.  9 09:56 dev/
</code>```

And, I can't change the permissions, even in with sudo. There's no error message, but nothing happend.

The "rm -fr var/cache" works.

Can u help me please.

Fabrice

答:
In must case this is drasticaly the last treatment, but its work. Have a look there : </p>

<p>https://symfony.com/doc/current/setup/file_permissions.html#using-acl-on-a-system-that-supports-setfacl-linux-bsd </p>

Body:
I've a problem when I clear the cache in a Vagrant VM. Here a part of the config file :

synced_folder:
    vflsf_19mkvk0x71hk:
        source: /var/www/vm/vmnginx
        target: /var/www
        sync_type: default
        smb:
            smb_host: ''
            smb_username: ''
            smb_password: ''
            mount_options:
                dir_mode: '0775'
                file_mode: '0664'
        rsync:
            args:
                - '--verbose'
                - '--archive'
                - '-z'
            exclude:
                - .vagrant/
                - .git/
                - vendor/
            auto: 'true'
        owner: vagrant
        group: www-data

The error message tell me it can't be possible to remove a folder :

$ sfconsole cache:clear -vv
22:46:17 INFO      [php] User Deprecated: The "Symfony\Component\Console\Event\ConsoleExceptionEvent" class is deprecated since version 3.3 and will be removed in 4.0. Use the ConsoleErrorEvent instead. ["exception" => Symfony\Component\Debug\Exception\ContextErrorException {trace: { …} …}] []

  [Symfony\Component\Filesystem\Exception\IOException]
  Failed to remove directory "/var/www/formation/symfony-blog/var/cache/de~/translations": .

Exception trace:
 () at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Filesystem/Filesystem.php:176
 Symfony\Component\Filesystem\Filesystem->remove() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Filesystem/Filesystem.php:172
 Symfony\Component\Filesystem\Filesystem->remove() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Command/CacheClearCommand.php:70
 Symfony\Bundle\FrameworkBundle\Command\CacheClearCommand->execute() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:264
 Symfony\Component\Console\Command\Command->run() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:887
 Symfony\Component\Console\Application->doRunCommand() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:223
 Symfony\Component\Console\Application->doRun() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Console/Application.php:81
 Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at /var/www/formation/symfony-blog/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:130
 Symfony\Component\Console\Application->run() at /var/www/formation/symfony-blog/bin/console:28

cache:clear [--no-warmup] [--no-optional-warmers] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command>

I've add the "vagrant" user in the "www-data" group.

Folder :

$ ll var/cache/
total 16K
drwxrwxr-x 1 vagrant www-data 4,0K juil.  8 22:43 ./
drwxrwxr-x 1 vagrant www-data 4,0K juil.  7 16:01 ../
drwxrwxr-x 1 vagrant www-data 4,0K juil.  8 22:43 de~/
drwxrwxr-x 1 vagrant www-data 4,0K juil.  8 22:43 dev/

Here the "real" folder outside the VM :

✔ /var/www/vm/vmnginx/formation/symfony-blog [master {origin/master}|✚ 9]
11:10 $ ll var/cache/
total 16K
drwxrwxr-x 4 fabrice fabrice 4,0K juil.  9 09:56 ./
drwxrwxr-x 5 fabrice fabrice 4,0K juil.  7 16:01 ../
drwxrwxr-x 3 fabrice fabrice 4,0K juil.  9 09:56 de~/
drwxrwxr-x 7 fabrice fabrice 4,0K juil.  9 09:56 dev/

And, I can't change the permissions, even in with sudo. There's no error message, but nothing happend.

The "rm -fr var/cache" works.

Can u help me please.

Fabrice

Body:
In must case this is drasticaly the last treatment, but its work. Have a look there :

https://symfony.com/doc/current/setup/file_permissions.html#using-acl-on-a-system-that-supports-setfacl-linux-bsd


问:
Reverse The Words In A Sentence But Not The Letters
I want to make a program to reverse the words only, not the letters.

For example...

```<code>i love india
</code>```

... should become...

```<code>india love i
</code>```

Another example...

```<code> google is the best website
</code>```

... should become...

```<code> website best the is google
</code>```

With spaces I have thoroughly researched on it but found just nothing.

My logic is that I should just give you my program that is not working.  If you find a small error in my code please give the solution for it and a corrected copy of my program.  Also, if you are not too busy, can you please give me the logic in a flow chart.

my logic is here

Thank you for your time.

答:
```<code>class Solution {
     public String reverseWords(String s) {
        if (s == null || s.length() == 0) {
            return "";
         }

    // split to words by space
    String[] arr = s.split(" ");
    StringBuilder sb = new StringBuilder();
    for (int i = arr.length - 1; i >= 0; --i) {
        if (!arr[i].equals("")) {
            sb.append(arr[i]).append(" ");
        }
    }
    return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
  }
}
</code>```

Body:
I want to make a program to reverse the words only, not the letters.

For example...

i love india

... should become...

india love i

Another example...

 google is the best website

... should become...

 website best the is google

With spaces I have thoroughly researched on it but found just nothing.

My logic is that I should just give you my program that is not working.  If you find a small error in my code please give the solution for it and a corrected copy of my program.  Also, if you are not too busy, can you please give me the logic in a flow chart.

my logic is here

Thank you for your time.


问:
Python 2.7 ProcessPoolExecutor throwing IOError: [Errno 32] Broken pipe
I am streaming data into a class in chunks.  For each chunk of data, two different types of np.convolve() are executed on the same ProcessPoolExecutor.  The type of convolve that was called is determined by a return variable.
 The order of the data must be maintained, so each future has an associated sequence number.  The output function enforces that only data from contiguous futures is returned (not shown below).  From what I understand I am properly calling the ProcessPoolExecutor.shutdown() function, but I am still getting a IOError:

The errors is:

```<code>$ python processpoolerror.py
ran 5000000 samples in 3.70395112038 sec: 1.34990982265 Msps
Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/queues.py", line 268, in _feed
    send(obj)
IOError: [Errno 32] Broken pipe
</code>```

Sorry it's a bit long, but I have pruned this class down as much as possible while keeping the error.  On my machine Ubuntu 16.04.2 with a Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz the paired down code always gives this error.  In the non-pruned version of this code, the Broken pipe occurs 25% of the time.

If you edit line 78 to True, and print during the execution, the error is not thrown.  If you reduce the amount of data on line 100, the error is not thrown.  What am I doing wrong here?  Thanks.

```<code>import numpy as np
from concurrent.futures import ProcessPoolExecutor
import time

def _do_xcorr3(rev_header, packet_chunk, seq):
    r1 = np.convolve(rev_header, packet_chunk, 'full')
    return 0, seq, r1

def _do_power3(power_kernel, packet_chunk, seq):
    cp = np.convolve(power_kernel, np.abs(packet_chunk) ** 2, 'full')
    return 1, seq, cp

class ProcessPoolIssues():

    ## Constructor
    # @param chunk_size how many samples to feed in during input() stage
    def __init__(self,header,chunk_size=500,poolsize=5):
        self.chunk_size = chunk_size  ##! How many samples to feed

        # ProcessPool stuff
        self.poolsize = poolsize
        self.pool = ProcessPoolExecutor(poolsize)
        self.futures = []

        # xcr stage stuff
        self.results0 = []
        self.results0.append((0, -1, np.zeros(chunk_size)))

        # power stage stuff
        self.results1 = []
        self.results1.append((1, -1, np.zeros(chunk_size)))

        self.countin = 0
        self.countout = -1

    def shutdown(self):
        self.pool.shutdown(wait=True)

    ## Returns True if all data has been extracted for given inputs
    def all_done(self):
        return self.countin == self.countout+1

    ## main function
    # @param packet_chunk an array of chunk_size samples to be computed
    def input(self, packet_chunk):
        assert len(packet_chunk) == self.chunk_size

        fut0 = self.pool.submit(_do_xcorr3, packet_chunk, packet_chunk, self.countin)
        self.futures.append(fut0)

        fut1 = self.pool.submit(_do_power3, packet_chunk, packet_chunk, self.countin)
        self.futures.append(fut1)

        self.countin += 1

    # loops through thread pool, copying any results from done threads into results0/1 (and then terminating them)
    def cultivate_pool(self):
        todel = []

        for i, f in enumerate(self.futures):
            # print "checking", f
            if f.done():
                a, b, c = f.result()
                if a == 0:
                    self.results0.append((a,b,c))  # results from one type of future
                elif a == 1:
                    self.results1.append((a,b,c))  # results from another type of future
                todel.append(i)

        # now we need to remove items from futures that are done
        # we need do it in reverse order so we remove items from the end first (thereby not affecting indices as we go)
        for i in sorted(todel, reverse=True):
            del self.futures[i]

            if False:  # change this to true and error goes away
                print "deleting future #", i

    # may return None
    def output(self):

        self.cultivate_pool()  # modifies self.results list

        # wait for both results to be done before clearing
        if len(self.results0) and len(self.results1):
            del self.results0[0]
            del self.results1[0]
            self.countout += 1

        return None

def testRate():
    chunk = 500

    # a value of 10000 will throw:  IOError: [Errno 32] Broken pipe
    # smaller values like 1000 do not
    din = chunk * 10000

    np.random.seed(666)
    search = np.random.random(233) + np.random.random(233) * 1j
    input = np.random.random(din) + np.random.random(din) * 1j

    pct = ProcessPoolIssues(search, chunk, poolsize=8)

    st = time.time()
    for x in range(0, len(input), chunk):
        slice = input[x:x + chunk]
        if len(slice) != chunk:
            break
        pct.input(slice)
        pct.output()

    while not pct.all_done():
        pct.output()

    ed = time.time()
    dt = ed - st

    print "ran", din, "samples in", dt, "sec:", din / dt / 1E6, "Msps"

    pct.shutdown()

if __name__ == '__main__':
    testRate()
</code>```

答:
This is probably happening because you're exceeding the buffer size of the pipe when you try sending in larger chunks at once.

```<code>def _do_xcorr3(rev_header, packet_chunk, seq):
    r1 = np.convolve(rev_header, packet_chunk, 'full')
    return 0, seq, r1

def _do_power3(power_kernel, packet_chunk, seq):
    cp = np.convolve(power_kernel, np.abs(packet_chunk) ** 2, 'full')
    return 1, seq, cp
</code>```

the values r1 and cp are very large because you are convolving with the square of the chunks.

Hence, when you try to run this with larger chunk sizes, the buffer of IO Pipe can't handle it. Refer this for clearer understanding.

As for the second part of the question,

```<code>if False:  # change this to true and error goes away
                print "deleting future #", i
</code>```

Found this in the py3 docs:

16.2.4.4. Reentrancy
  Binary buffered objects (instances of BufferedReader, BufferedWriter, BufferedRandom and BufferedRWPair) are not reentrant. While reentrant calls will not happen in normal situations, they can arise from doing I/O in a signal handler. If a thread tries to re-enter a buffered object which it is already accessing, a RuntimeError is raised. Note this doesn’t prohibit a different thread from entering the buffered object.
  The above implicitly extends to text files, since the open() function will wrap a buffered object inside a TextIOWrapper. This includes standard streams and therefore affects the built-in function print() as well.

Body:
I am streaming data into a class in chunks.  For each chunk of data, two different types of np.convolve() are executed on the same ProcessPoolExecutor.  The type of convolve that was called is determined by a return variable.
 The order of the data must be maintained, so each future has an associated sequence number.  The output function enforces that only data from contiguous futures is returned (not shown below).  From what I understand I am properly calling the ProcessPoolExecutor.shutdown() function, but I am still getting a IOError:

The errors is:

$ python processpoolerror.py
ran 5000000 samples in 3.70395112038 sec: 1.34990982265 Msps
Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/queues.py", line 268, in _feed
    send(obj)
IOError: [Errno 32] Broken pipe

Sorry it's a bit long, but I have pruned this class down as much as possible while keeping the error.  On my machine Ubuntu 16.04.2 with a Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz the paired down code always gives this error.  In the non-pruned version of this code, the Broken pipe occurs 25% of the time.

If you edit line 78 to True, and print during the execution, the error is not thrown.  If you reduce the amount of data on line 100, the error is not thrown.  What am I doing wrong here?  Thanks.

import numpy as np
from concurrent.futures import ProcessPoolExecutor
import time

def _do_xcorr3(rev_header, packet_chunk, seq):
    r1 = np.convolve(rev_header, packet_chunk, 'full')
    return 0, seq, r1

def _do_power3(power_kernel, packet_chunk, seq):
    cp = np.convolve(power_kernel, np.abs(packet_chunk) ** 2, 'full')
    return 1, seq, cp

class ProcessPoolIssues():

    ## Constructor
    # @param chunk_size how many samples to feed in during input() stage
    def __init__(self,header,chunk_size=500,poolsize=5):
        self.chunk_size = chunk_size  ##! How many samples to feed

        # ProcessPool stuff
        self.poolsize = poolsize
        self.pool = ProcessPoolExecutor(poolsize)
        self.futures = []

        # xcr stage stuff
        self.results0 = []
        self.results0.append((0, -1, np.zeros(chunk_size)))

        # power stage stuff
        self.results1 = []
        self.results1.append((1, -1, np.zeros(chunk_size)))

        self.countin = 0
        self.countout = -1

    def shutdown(self):
        self.pool.shutdown(wait=True)

    ## Returns True if all data has been extracted for given inputs
    def all_done(self):
        return self.countin == self.countout+1

    ## main function
    # @param packet_chunk an array of chunk_size samples to be computed
    def input(self, packet_chunk):
        assert len(packet_chunk) == self.chunk_size

        fut0 = self.pool.submit(_do_xcorr3, packet_chunk, packet_chunk, self.countin)
        self.futures.append(fut0)

        fut1 = self.pool.submit(_do_power3, packet_chunk, packet_chunk, self.countin)
        self.futures.append(fut1)

        self.countin += 1

    # loops through thread pool, copying any results from done threads into results0/1 (and then terminating them)
    def cultivate_pool(self):
        todel = []

        for i, f in enumerate(self.futures):
            # print "checking", f
            if f.done():
                a, b, c = f.result()
                if a == 0:
                    self.results0.append((a,b,c))  # results from one type of future
                elif a == 1:
                    self.results1.append((a,b,c))  # results from another type of future
                todel.append(i)

        # now we need to remove items from futures that are done
        # we need do it in reverse order so we remove items from the end first (thereby not affecting indices as we go)
        for i in sorted(todel, reverse=True):
            del self.futures[i]

            if False:  # change this to true and error goes away
                print "deleting future #", i

    # may return None
    def output(self):

        self.cultivate_pool()  # modifies self.results list

        # wait for both results to be done before clearing
        if len(self.results0) and len(self.results1):
            del self.results0[0]
            del self.results1[0]
            self.countout += 1

        return None

def testRate():
    chunk = 500

    # a value of 10000 will throw:  IOError: [Errno 32] Broken pipe
    # smaller values like 1000 do not
    din = chunk * 10000

    np.random.seed(666)
    search = np.random.random(233) + np.random.random(233) * 1j
    input = np.random.random(din) + np.random.random(din) * 1j

    pct = ProcessPoolIssues(search, chunk, poolsize=8)

    st = time.time()
    for x in range(0, len(input), chunk):
        slice = input[x:x + chunk]
        if len(slice) != chunk:
            break
        pct.input(slice)
        pct.output()

    while not pct.all_done():
        pct.output()

    ed = time.time()
    dt = ed - st

    print "ran", din, "samples in", dt, "sec:", din / dt / 1E6, "Msps"

    pct.shutdown()

if __name__ == '__main__':
    testRate()

Body:
This is probably happening because you're exceeding the buffer size of the pipe when you try sending in larger chunks at once.

def _do_xcorr3(rev_header, packet_chunk, seq):
    r1 = np.convolve(rev_header, packet_chunk, 'full')
    return 0, seq, r1

def _do_power3(power_kernel, packet_chunk, seq):
    cp = np.convolve(power_kernel, np.abs(packet_chunk) ** 2, 'full')
    return 1, seq, cp

the values r1 and cp are very large because you are convolving with the square of the chunks.

Hence, when you try to run this with larger chunk sizes, the buffer of IO Pipe can't handle it. Refer this for clearer understanding.

As for the second part of the question,

if False:  # change this to true and error goes away
                print "deleting future #", i

Found this in the py3 docs:

16.2.4.4. Reentrancy
  Binary buffered objects (instances of BufferedReader, BufferedWriter, BufferedRandom and BufferedRWPair) are not reentrant. While reentrant calls will not happen in normal situations, they can arise from doing I/O in a signal handler. If a thread tries to re-enter a buffered object which it is already accessing, a RuntimeError is raised. Note this doesn’t prohibit a different thread from entering the buffered object.
  The above implicitly extends to text files, since the open() function will wrap a buffered object inside a TextIOWrapper. This includes standard streams and therefore affects the built-in function print() as well.


问:
Changing WooCommerce cart item names
The goal is to change the name of the item as it gets passed to our payment gateway, but leave it as-is for display on our product pages.

I've tried this in my functions.php:

```<code>function change_item_name( $item_name, $item ) {
    $item_name = 'mydesiredproductname';
    return $item_name;
}
add_filter( 'woocommerce_order_item_name', 'change_item_name', 10, 1 );
</code>```

But it doesn't seem to be working for me.  I feel like I should be passing in an actual item ID or something… I'm a little lost.

Any information on what I'm doing wrong here would be greatly appreciated.

答:
The woocommerce_order_item_name filter hook is a front-end hook and is located in:

1) WooCommerce templates:

emails/plain/email-order-items.php

templates/order/order-details-item.php

templates/checkout/form-pay.php

templates/emails/email-order-items.php

2)WooCommerce Core file:

includes/class-wc-structured-data.php

Each of them has $item_name common first argument, and different for the other arguments.
 See Here for more details…

You have 2 arguments set in your function (the second one is not correct for all templates) and you are declaring only one in your hook. I have tested the code below:

```<code>add_filter( 'woocommerce_order_item_name', 'change_orders_items_names', 10, 1 );
function change_orders_items_names( $item_name ) {
    $item_name = 'mydesiredproductname';
    return $item_name;
}
</code>```

And it works on

Order-receive (Thank you) page,

email notifications

and My Account Orders > Single order details

But NOT in Cart, Checkout and Backend Order edit pages.

So if you need to make it work on Cart and Checkout, you should use other hooks like woocommerce_before_calculate_totals.
 Then you can use WC_Product methods (setter and getters).

Here is your new code

```<code>add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_prices', 10, 1 );
function custom_cart_items_prices( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name (Added Woocommerce 3+ compatibility)
        $original_name = method_exists( $product, 'get_name' ) ? $product->get_name() : $product->post->post_title;

        // SET THE NEW NAME
        $new_name = 'mydesiredproductname';

        // Set the new name (WooCommerce versions 2.5.x to 3+)
        if( method_exists( $product, 'set_name' ) )
            $product->set_name( $new_name );
        else
            $product->post->post_title = $new_name;
    }
}
</code>```

Code goes in any php file of your active child theme (or theme) or also in any plugin php file.

Now you have change the names everywhere except on Shop archives and product pages…

This code is tested and works on WooCommerce 2.5+ and 3+

If you want to keep original item names in cart only you should add this conditional WooCommerce tag inside the function:

```<code>if( ! is_cart() ){
    // The code
}
</code>```

This answer has been updated on August 1st 2017 to get a woocommerce compatibility prior versions…

Title: Changing WooCommerce cart item names

Body:
The goal is to change the name of the item as it gets passed to our payment gateway, but leave it as-is for display on our product pages.

I've tried this in my functions.php:

function change_item_name( $item_name, $item ) {
    $item_name = 'mydesiredproductname';
    return $item_name;
}
add_filter( 'woocommerce_order_item_name', 'change_item_name', 10, 1 );

But it doesn't seem to be working for me.  I feel like I should be passing in an actual item ID or something… I'm a little lost.

Any information on what I'm doing wrong here would be greatly appreciated.

Body:
The woocommerce_order_item_name filter hook is a front-end hook and is located in:

1) WooCommerce templates:

emails/plain/email-order-items.php

templates/order/order-details-item.php

templates/checkout/form-pay.php

templates/emails/email-order-items.php

2)WooCommerce Core file:

includes/class-wc-structured-data.php

Each of them has $item_name common first argument, and different for the other arguments.
 See Here for more details…

You have 2 arguments set in your function (the second one is not correct for all templates) and you are declaring only one in your hook. I have tested the code below:

add_filter( 'woocommerce_order_item_name', 'change_orders_items_names', 10, 1 );
function change_orders_items_names( $item_name ) {
    $item_name = 'mydesiredproductname';
    return $item_name;
}

And it works on

Order-receive (Thank you) page,

email notifications

and My Account Orders > Single order details

But NOT in Cart, Checkout and Backend Order edit pages.

So if you need to make it work on Cart and Checkout, you should use other hooks like woocommerce_before_calculate_totals.
 Then you can use WC_Product methods (setter and getters).

Here is your new code

add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_prices', 10, 1 );
function custom_cart_items_prices( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name (Added Woocommerce 3+ compatibility)
        $original_name = method_exists( $product, 'get_name' ) ? $product->get_name() : $product->post->post_title;

        // SET THE NEW NAME
        $new_name = 'mydesiredproductname';

        // Set the new name (WooCommerce versions 2.5.x to 3+)
        if( method_exists( $product, 'set_name' ) )
            $product->set_name( $new_name );
        else
            $product->post->post_title = $new_name;
    }
}

Code goes in any php file of your active child theme (or theme) or also in any plugin php file.

Now you have change the names everywhere except on Shop archives and product pages…

This code is tested and works on WooCommerce 2.5+ and 3+

If you want to keep original item names in cart only you should add this conditional WooCommerce tag inside the function:

if( ! is_cart() ){
    // The code
}

This answer has been updated on August 1st 2017 to get a woocommerce compatibility prior versions…


问:
Why does an inline function have lower efficiency than an in-built function?
I was trying a question on arrays in InterviewBit. In this question I made an inline function returning the absolute value of an integer. But I was told that my algorithm was not efficient on submitting it. But when I changed to using abs() from C++ library it gave a correct answer verdict.

Here is my function that got an inefficient verdict -

```<code>inline int abs(int x){return x>0 ? x : -x;}

int Solution::coverPoints(vector<int> &X, vector<int> &Y) {
    int l = X.size();
    int i = 0;
    int ans = 0;
    while (i<l-1){
        ans = ans + max(abs(X[i]-X[i+1]), abs(Y[i]-Y[i+1]));
        i++;
    }
    return ans;
}
</code>```

Here's the one that got the correct answer -

```<code>int Solution::coverPoints(vector<int> &X, vector<int> &Y) {
    int l = X.size();
    int i = 0;
    int ans = 0;
    while (i<l-1){
        ans = ans + max(abs(X[i]-X[i+1]), abs(Y[i]-Y[i+1]));
        i++;
    }
    return ans;
}
</code>```

Why did this happened, as I thought that inline functions are fastest as no calling is done? Or is the site having an error? And if the site is correct, what does C++ abs() use that is faster than inline abs()?

答:
Your solution might arguably be "cleaner" by the textbook if you used the standard library version, but I think the evaluation is wrong. There is no truly good, justifiable reason for your code being rejected.

This is one of those cases where someone is formally correct (by the textbook), but insists on knowing the only correct solution in a sheer stupid way rather than accepting an alternate solution and saying "...but this here would be best practice, you know".

Technically, it's a correct, practical approach to say "use the standard library, that's what it is for, and it's likely optimized as much as can be". Even though the "optimized as much as can be" part can, in some situations, very well be wrong due to some constraints that the standard puts onto certain alogorithms and/or containers.

Now, opinions, best practice, and religion aside. Factually, if you compare the two approaches...

```<code>int main(int argc, char**)
{
  40f360:       53                      push   %rbx
  40f361:       48 83 ec 20             sub    $0x20,%rsp
  40f365:       89 cb                   mov    %ecx,%ebx
  40f367:       e8 a4 be ff ff          callq  40b210 <__main>
return std::abs(argc);
  40f36c:       89 da                   mov    %ebx,%edx
  40f36e:       89 d8                   mov    %ebx,%eax
  40f370:       c1 fa 1f                sar    $0x1f,%edx
  40f373:       31 d0                   xor    %edx,%eax
  40f375:       29 d0                   sub    %edx,%eax
//}

int main(int argc, char**)
{
  40f360:       53                      push   %rbx
  40f361:       48 83 ec 20             sub    $0x20,%rsp
  40f365:       89 cb                   mov    %ecx,%ebx
  40f367:       e8 a4 be ff ff          callq  40b210 <__main>
return (argc > 0) ? argc : -argc;
  40f36c:       89 da                   mov    %ebx,%edx
  40f36e:       89 d8                   mov    %ebx,%eax
  40f370:       c1 fa 1f                sar    $0x1f,%edx
  40f373:       31 d0                   xor    %edx,%eax
  40f375:       29 d0                   sub    %edx,%eax
//}
</code>```

... they result in exactly the same, identical instructions.

But even if the compiler did use a compare followed by a conditional move (which it may do in more complicated "branching assignments" and which it will do for example in the case of min/max), that's maybe one CPU cycle or so slower than the bit hacks, so unless you do this several million times, the statement "not efficient" is kinda doubtful anyway.

One cache miss, and you have a hundred times the penalty of a conditional move.

There are valid arguments for and against either approach, which I won't discuss in length. My point is, turning down the OP's solution as "totally wrong" because of such a petty, unimportant detail is rather narrow-minded.

EDIT:

(Fun trivia)

I just tried, for fun and no profit, on my Linux Mint box which uses a somewhat older version of GCC (5.4 as compared to 7.1 above).

Due to me including <cmath> without much of a thought (hey, a function like abs very clearly belongs to math, doesn't it!) rather than <cstdlib> which hosts the integer overload, the result was, well... surprising. Calling the library function was much inferior to the single-expression wrapper.

Now, in defense of the standard library, if you include <cstdlib>, then, again, the produced output is exactly identical in either case.

For reference, the test code looked like:

```<code>#ifdef DRY
  #include <cmath>
  int main(int argc, char**)
  {
     return std::abs(argc);
  }
#else
  int abs(int v) noexcept { return (v >= 0) ? v : -v; }
  int main(int argc, char**)
  {
     return abs(argc);
  }
#endif
</code>```

...resulting in

```<code>4004f0: 89 fa                   mov    %edi,%edx
4004f2: 89 f8                   mov    %edi,%eax
4004f4: c1 fa 1f                sar    $0x1f,%edx
4004f7: 31 d0                   xor    %edx,%eax
4004f9: 29 d0                   sub    %edx,%eax
4004fb: c3                      retq
</code>```

Now, It is apparently quite easy to fall into the trap of unwittingly using the wrong standard library function (I demonstrated how easy it is myself!). And all that without the slightest warning from the compiler, such as "hey, you know, you're using a double overload on an integer value (well, obviously there's no warning, it's a valid conversion).

With that in mind, there may be yet another "justification" why the OP providing his own one-liner wasn't all that terribly bad and wrong. After all, he could have made that same mistake.

Body:
I was trying a question on arrays in InterviewBit. In this question I made an inline function returning the absolute value of an integer. But I was told that my algorithm was not efficient on submitting it. But when I changed to using abs() from C++ library it gave a correct answer verdict.

Here is my function that got an inefficient verdict -

inline int abs(int x){return x>0 ? x : -x;}

int Solution::coverPoints(vector<int> &X, vector<int> &Y) {
    int l = X.size();
    int i = 0;
    int ans = 0;
    while (i<l-1){
        ans = ans + max(abs(X[i]-X[i+1]), abs(Y[i]-Y[i+1]));
        i++;
    }
    return ans;
}

Here's the one that got the correct answer -

int Solution::coverPoints(vector<int> &X, vector<int> &Y) {
    int l = X.size();
    int i = 0;
    int ans = 0;
    while (i<l-1){
        ans = ans + max(abs(X[i]-X[i+1]), abs(Y[i]-Y[i+1]));
        i++;
    }
    return ans;
}

Why did this happened, as I thought that inline functions are fastest as no calling is done? Or is the site having an error? And if the site is correct, what does C++ abs() use that is faster than inline abs()?

Body:
Your solution might arguably be "cleaner" by the textbook if you used the standard library version, but I think the evaluation is wrong. There is no truly good, justifiable reason for your code being rejected.

This is one of those cases where someone is formally correct (by the textbook), but insists on knowing the only correct solution in a sheer stupid way rather than accepting an alternate solution and saying "...but this here would be best practice, you know".

Technically, it's a correct, practical approach to say "use the standard library, that's what it is for, and it's likely optimized as much as can be". Even though the "optimized as much as can be" part can, in some situations, very well be wrong due to some constraints that the standard puts onto certain alogorithms and/or containers.

Now, opinions, best practice, and religion aside. Factually, if you compare the two approaches...

int main(int argc, char**)
{
  40f360:       53                      push   %rbx
  40f361:       48 83 ec 20             sub    $0x20,%rsp
  40f365:       89 cb                   mov    %ecx,%ebx
  40f367:       e8 a4 be ff ff          callq  40b210 <__main>
return std::abs(argc);
  40f36c:       89 da                   mov    %ebx,%edx
  40f36e:       89 d8                   mov    %ebx,%eax
  40f370:       c1 fa 1f                sar    $0x1f,%edx
  40f373:       31 d0                   xor    %edx,%eax
  40f375:       29 d0                   sub    %edx,%eax
//}

int main(int argc, char**)
{
  40f360:       53                      push   %rbx
  40f361:       48 83 ec 20             sub    $0x20,%rsp
  40f365:       89 cb                   mov    %ecx,%ebx
  40f367:       e8 a4 be ff ff          callq  40b210 <__main>
return (argc > 0) ? argc : -argc;
  40f36c:       89 da                   mov    %ebx,%edx
  40f36e:       89 d8                   mov    %ebx,%eax
  40f370:       c1 fa 1f                sar    $0x1f,%edx
  40f373:       31 d0                   xor    %edx,%eax
  40f375:       29 d0                   sub    %edx,%eax
//}

... they result in exactly the same, identical instructions.

But even if the compiler did use a compare followed by a conditional move (which it may do in more complicated "branching assignments" and which it will do for example in the case of min/max), that's maybe one CPU cycle or so slower than the bit hacks, so unless you do this several million times, the statement "not efficient" is kinda doubtful anyway.

One cache miss, and you have a hundred times the penalty of a conditional move.

There are valid arguments for and against either approach, which I won't discuss in length. My point is, turning down the OP's solution as "totally wrong" because of such a petty, unimportant detail is rather narrow-minded.

EDIT:

(Fun trivia)

I just tried, for fun and no profit, on my Linux Mint box which uses a somewhat older version of GCC (5.4 as compared to 7.1 above).

Due to me including <cmath> without much of a thought (hey, a function like abs very clearly belongs to math, doesn't it!) rather than <cstdlib> which hosts the integer overload, the result was, well... surprising. Calling the library function was much inferior to the single-expression wrapper.

Now, in defense of the standard library, if you include <cstdlib>, then, again, the produced output is exactly identical in either case.

For reference, the test code looked like:

#ifdef DRY
  #include <cmath>
  int main(int argc, char**)
  {
     return std::abs(argc);
  }
#else
  int abs(int v) noexcept { return (v >= 0) ? v : -v; }
  int main(int argc, char**)
  {
     return abs(argc);
  }
#endif

...resulting in

4004f0: 89 fa                   mov    %edi,%edx
4004f2: 89 f8                   mov    %edi,%eax
4004f4: c1 fa 1f                sar    $0x1f,%edx
4004f7: 31 d0                   xor    %edx,%eax
4004f9: 29 d0                   sub    %edx,%eax
4004fb: c3                      retq

Now, It is apparently quite easy to fall into the trap of unwittingly using the wrong standard library function (I demonstrated how easy it is myself!). And all that without the slightest warning from the compiler, such as "hey, you know, you're using a double overload on an integer value (well, obviously there's no warning, it's a valid conversion).

With that in mind, there may be yet another "justification" why the OP providing his own one-liner wasn't all that terribly bad and wrong. After all, he could have made that same mistake.


问:
Java: Volatile variable not updating (get and set methods not working)
I have a Runnable "NanoClock" class which keeps updating a private volatile double value in its run() method.

This class also has a getTime() method which returns the double value. Another class ("Master") is constructing the NanoClock class and creates a thread, as well as calling the start() method.

After it did this it calls the getTime() method several times (with a delay), but the value is not updating. What am I doing wrong?

NanoClock.java :

```<code>public class NanoClock implements Runnable {
    private volatile boolean running;
    private volatile double time;
    public NanoClock() {
        time = System.currentTimeMillis();
    }
    @Override
    public void run() {
        running = true;
        while(running) {
            try {
                if(System.currentTimeMillis() > time) {
                    time = System.currentTimeMillis();
                }
              //This returns the updated value continuously when commented out
              //System.out.println("Time: " + String.format("%.6f", unix_time));
                Thread.sleep(2000);
            } catch(Exception exc) {
                exc.printStackTrace();
                System.exit(1);
            }
        }
    }
    public double getTime() {
        return time;
    }
    public void end() {
        running = false;
    }
}
</code>```

Master.java:

```<code>public class Master {
    public static void main(String[] args) {
        try {
            NanoClock nClock = new NanoClock();
            Thread clockThread = new Thread(new NanoClock());
            clockThread.setPriority(10);
            clockThread.start();
            //MY_ISSUE: This returns the same value every time
            for(int a = 0; a < 10; a++) {
                System.out.println("Time: " + nClock.getTime());
            }
            //MY_ISSUE: This cannot stop the while loop - I tested it with
            //the println in the NanoClock class.
            nClock.end();
            System.out.println("Done!");
        catch(Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}
</code>```

答:
You've got two instances of NanoClock:  one of them is an anonymous new NanoClock() which, as the Runnable in your other thread is happily keeping time in the backgound; the other is nClock, which is sitting idly by in the foreground in your main thread.

nClock should have been the Runnable in that other thread:

```<code>Thread clockThread = new Thread(nClock);  // not new NanoClock()
</code>```

This may not be the entire solution, but it should be a big step in the right direction.

Body:
I have a Runnable "NanoClock" class which keeps updating a private volatile double value in its run() method.

This class also has a getTime() method which returns the double value. Another class ("Master") is constructing the NanoClock class and creates a thread, as well as calling the start() method.

After it did this it calls the getTime() method several times (with a delay), but the value is not updating. What am I doing wrong?

NanoClock.java :

public class NanoClock implements Runnable {
    private volatile boolean running;
    private volatile double time;
    public NanoClock() {
        time = System.currentTimeMillis();
    }
    @Override
    public void run() {
        running = true;
        while(running) {
            try {
                if(System.currentTimeMillis() > time) {
                    time = System.currentTimeMillis();
                }
              //This returns the updated value continuously when commented out
              //System.out.println("Time: " + String.format("%.6f", unix_time));
                Thread.sleep(2000);
            } catch(Exception exc) {
                exc.printStackTrace();
                System.exit(1);
            }
        }
    }
    public double getTime() {
        return time;
    }
    public void end() {
        running = false;
    }
}

Master.java:

public class Master {
    public static void main(String[] args) {
        try {
            NanoClock nClock = new NanoClock();
            Thread clockThread = new Thread(new NanoClock());
            clockThread.setPriority(10);
            clockThread.start();
            //MY_ISSUE: This returns the same value every time
            for(int a = 0; a < 10; a++) {
                System.out.println("Time: " + nClock.getTime());
            }
            //MY_ISSUE: This cannot stop the while loop - I tested it with
            //the println in the NanoClock class.
            nClock.end();
            System.out.println("Done!");
        catch(Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}

Body:
You've got two instances of NanoClock:  one of them is an anonymous new NanoClock() which, as the Runnable in your other thread is happily keeping time in the backgound; the other is nClock, which is sitting idly by in the foreground in your main thread.

nClock should have been the Runnable in that other thread:

Thread clockThread = new Thread(nClock);  // not new NanoClock()

This may not be the entire solution, but it should be a big step in the right direction.


问:
Including tidyverse packages in another package
Is:

```<code>devtools::use_package("tidyverse")
</code>```

the canonical way in R of importing the set of tidyverse packages into another package? Or would it be preferable to import the packages individually? I expect to use the functionality of all the current tidyverse packages except readr.

答:
Given the few number of reverse dependencies of tidyverse, I think you should just import packages separately.

@rosscova's comment is also a good point.

Body:
Is:

devtools::use_package("tidyverse")

the canonical way in R of importing the set of tidyverse packages into another package? Or would it be preferable to import the packages individually? I expect to use the functionality of all the current tidyverse packages except readr.


问:
How to unzip all the password protected zip files in a directory using Java
I am new to java and trying to write an program which will unzip all the password protected zip files in an directory, I am able to unzip all the normal zip files (Without password) but I am not sure how to unzip  password protected files.
Note: All zip files have same password</p>

```<code>import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;

import java.util.zip.*;

public class Extraction {
    // public Extraction() {
    //
    // try {
    //
    // ZipFile zipFile = new
    // ZipFile("C:\\Users\\Desktop\\ZipFile\\myzip.zip");
    //
    // if (zipFile.isEncrypted()) {
    //
    // zipFile.setPassword("CLAIMS!");
    // }
    //
    // List fileHeaderList = zipFile.getFileHeaders();
    //
    // for (int i = 0; i < fileHeaderList.size(); i++) {
    // FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
    //
    // zipFile.extractFile(fileHeader, "C:\\Users\\Desktop\\ZipFile");
    // System.out.println("Extracted");
    // }
    //
    // } catch (Exception e) {
    // System.out.println("Please Try Again");
    // }
    //
    // }
    //
    // public static void main(String[] args) {
    // new Extraction();
    //
    // }
    // }

    public static void main(String[] args) {
        Extraction unzipper = new Extraction();
        unzipper.unzipZipsInDirTo(Paths.get("C:\\Users\\Desktop\\ZipFile"),
                Paths.get("C:\\Users\\Desktop\\ZipFile\\Unziped"));

    }

    public void unzipZipsInDirTo(Path searchDir, Path unzipTo) {

        final PathMatcher matcher = searchDir.getFileSystem().getPathMatcher("glob:**/*.zip");
        try (final Stream<Path> stream = Files.list(searchDir)) {
            stream.filter(matcher::matches).forEach(zipFile -> unzip(zipFile, unzipTo));
        } catch (Exception e) {
            System.out.println("Something went wrong, Please try again!!");
        }
    }

    public void unzip(Path zipFile, Path outputPath) {
        try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(zipFile))) {

            ZipEntry entry = zis.getNextEntry();

            while (entry != null) {

                Path newFilePath = outputPath.resolve(entry.getName());
                if (entry.isDirectory()) {
                    Files.createDirectories(newFilePath);
                } else {
                    if (!Files.exists(newFilePath.getParent())) {
                        Files.createDirectories(newFilePath.getParent());
                    }
                    try (OutputStream bos = Files.newOutputStream(outputPath.resolve(newFilePath))) {
                        byte[] buffer = new byte[Math.toIntExact(entry.getSize())];

                        int location;

                        while ((location = zis.read(buffer)) != -1) {
                            bos.write(buffer, 0, location);
                        }
                    }
                }
                entry = zis.getNextEntry();
            }
        } catch (Exception e1) {
            System.out.println("Please try again");
        }
    }

}
</code>```

答:
I found the answer I am posting this as there might be someone else who might be looking for the similar answer.</p>
```<code>import java.io.File;
import java.util.List;

import javax.swing.filechooser.FileNameExtensionFilter;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;

public class SamExtraction {

    public static void main(String[] args) {

        final FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("N/A", "zip");
        //Folder where zip file is present
        final File file = new File("C:/Users/Desktop/ZipFile");
        for (final File child : file.listFiles()) {
            try {
                ZipFile zipFile = new ZipFile(child);
                if (extensionFilter.accept(child)) {
                    if (zipFile.isEncrypted()) {
                        //Your ZIP password
                        zipFile.setPassword("MYPASS!");
                    }
                    List fileHeaderList = zipFile.getFileHeaders();

                    for (int i = 0; i < fileHeaderList.size(); i++) {
                        FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
                        //Path where you want to Extract
                        zipFile.extractFile(fileHeader, "C:/Users/Desktop/ZipFile");
                        System.out.println("Extracted");
                    }
                }
            } catch (Exception e) {
                System.out.println("Please Try Again");
            }
        }

    }
}
</code>```

Body:
I am new to java and trying to write an program which will unzip all the password protected zip files in an directory, I am able to unzip all the normal zip files (Without password) but I am not sure how to unzip  password protected files.
Note: All zip files have same password

import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;

import java.util.zip.*;

public class Extraction {
    // public Extraction() {
    //
    // try {
    //
    // ZipFile zipFile = new
    // ZipFile("C:\\Users\\Desktop\\ZipFile\\myzip.zip");
    //
    // if (zipFile.isEncrypted()) {
    //
    // zipFile.setPassword("CLAIMS!");
    // }
    //
    // List fileHeaderList = zipFile.getFileHeaders();
    //
    // for (int i = 0; i < fileHeaderList.size(); i++) {
    // FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
    //
    // zipFile.extractFile(fileHeader, "C:\\Users\\Desktop\\ZipFile");
    // System.out.println("Extracted");
    // }
    //
    // } catch (Exception e) {
    // System.out.println("Please Try Again");
    // }
    //
    // }
    //
    // public static void main(String[] args) {
    // new Extraction();
    //
    // }
    // }

    public static void main(String[] args) {
        Extraction unzipper = new Extraction();
        unzipper.unzipZipsInDirTo(Paths.get("C:\\Users\\Desktop\\ZipFile"),
                Paths.get("C:\\Users\\Desktop\\ZipFile\\Unziped"));

    }

    public void unzipZipsInDirTo(Path searchDir, Path unzipTo) {

        final PathMatcher matcher = searchDir.getFileSystem().getPathMatcher("glob:**/*.zip");
        try (final Stream<Path> stream = Files.list(searchDir)) {
            stream.filter(matcher::matches).forEach(zipFile -> unzip(zipFile, unzipTo));
        } catch (Exception e) {
            System.out.println("Something went wrong, Please try again!!");
        }
    }

    public void unzip(Path zipFile, Path outputPath) {
        try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(zipFile))) {

            ZipEntry entry = zis.getNextEntry();

            while (entry != null) {

                Path newFilePath = outputPath.resolve(entry.getName());
                if (entry.isDirectory()) {
                    Files.createDirectories(newFilePath);
                } else {
                    if (!Files.exists(newFilePath.getParent())) {
                        Files.createDirectories(newFilePath.getParent());
                    }
                    try (OutputStream bos = Files.newOutputStream(outputPath.resolve(newFilePath))) {
                        byte[] buffer = new byte[Math.toIntExact(entry.getSize())];

                        int location;

                        while ((location = zis.read(buffer)) != -1) {
                            bos.write(buffer, 0, location);
                        }
                    }
                }
                entry = zis.getNextEntry();
            }
        } catch (Exception e1) {
            System.out.println("Please try again");
        }
    }

}

Body:
I found the answer I am posting this as there might be someone else who might be looking for the similar answer.

import java.io.File;
import java.util.List;

import javax.swing.filechooser.FileNameExtensionFilter;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;

public class SamExtraction {

    public static void main(String[] args) {

        final FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("N/A", "zip");
        //Folder where zip file is present
        final File file = new File("C:/Users/Desktop/ZipFile");
        for (final File child : file.listFiles()) {
            try {
                ZipFile zipFile = new ZipFile(child);
                if (extensionFilter.accept(child)) {
                    if (zipFile.isEncrypted()) {
                        //Your ZIP password
                        zipFile.setPassword("MYPASS!");
                    }
                    List fileHeaderList = zipFile.getFileHeaders();

                    for (int i = 0; i < fileHeaderList.size(); i++) {
                        FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
                        //Path where you want to Extract
                        zipFile.extractFile(fileHeader, "C:/Users/Desktop/ZipFile");
                        System.out.println("Extracted");
                    }
                }
            } catch (Exception e) {
                System.out.println("Please Try Again");
            }
        }

    }
}


问:
How to overload a built-in CUDA function?
CUDA has some built-in math functions, such as norm(). I want to create my own version of the norm() function, and use my version throughout the code. However when I define my own norm() function like so:

```<code>__device__ float norm(float a, float b) {
    return sqrt(a*a+b*b);
}
</code>```

I get the following compilation error:

```<code>kernel.cu(9): error: more than one instance of overloaded function "norm" has "C" linkage
</code>```

Is there a way I can overload the norm() function, or do I have to just give my own function a unique name?

I'm using PyCuda to compile my CUDA code.

答:
I'll make two suggestions in addition to @talonmies' answer - in case you do manage to get overloading working:

General non-CUDA-specific advice: Avoid overloading the builtins / API functions of a library, unless that is absolutely necessary (which it isn't in your case).
Reasons for this:

Likely to confuse other readers of your code

Mixing up "wrapper" code with builtins - it's not a "clean" way to code.

If the builtins change, your code using the builtins+overloads is likely to also have to change, sometimes in ways you didn't expect.

In your case, I would seriously consider having some namespace with your utility functions, e.g.

```<code>namespace math {
    template <typename T>
    __device__ T norm(T a, T b) { return math::sqrt<T>(a*a+b*b); }
}
</code>```

(of course you would need a math::sqrt template, which would abstract from the single-precision sqrtf(), double-precision sqrt() etc.)

Body:
CUDA has some built-in math functions, such as norm(). I want to create my own version of the norm() function, and use my version throughout the code. However when I define my own norm() function like so:

__device__ float norm(float a, float b) {
    return sqrt(a*a+b*b);
}

I get the following compilation error:

kernel.cu(9): error: more than one instance of overloaded function "norm" has "C" linkage

Is there a way I can overload the norm() function, or do I have to just give my own function a unique name?

I'm using PyCuda to compile my CUDA code.

Body:
I'll make two suggestions in addition to @talonmies' answer - in case you do manage to get overloading working:

General non-CUDA-specific advice: Avoid overloading the builtins / API functions of a library, unless that is absolutely necessary (which it isn't in your case).
Reasons for this:

Likely to confuse other readers of your code

Mixing up "wrapper" code with builtins - it's not a "clean" way to code.

If the builtins change, your code using the builtins+overloads is likely to also have to change, sometimes in ways you didn't expect.

In your case, I would seriously consider having some namespace with your utility functions, e.g.

namespace math {
    template <typename T>
    __device__ T norm(T a, T b) { return math::sqrt<T>(a*a+b*b); }
}

(of course you would need a math::sqrt template, which would abstract from the single-precision sqrtf(), double-precision sqrt() etc.)


问:
Interpolating missing contour lines between existing contour lines
Contour lines (aka isolines) are curves that trace constant values across a 2D scalar field. For example, in a geographical map you might have contour lines to illustrate the elevation of the terrain by showing where the elevation is constant. In this case, let's store contour lines as lists of points on the map.

Suppose you have map that has several contour lines at known elevations, and otherwise you know nothing about the elevations of the map. What algorithm would you use to fill in additional contour lines to approximate the unknown elevations of the map, assuming the landscape is continuous and doesn't do anything surprising?

It is easy to find advise about interpolating the elevation of an individual point using contour lines. There are also algorithms like Marching Squares for turning point elevations into contour lines, but none of these exactly capture this use case. We don't need the elevation of any particular point; we just want the contour lines. Certainly we could solve this problem by filling an array with estimated elevations and then using Marching Squares to estimate the contour lines based on the array, but the two steps of that process seem unnecessarily expensive and likely to introduce artifacts. Surely there is a better way.

答:
A mixed method:

flatten the isolines to polylines;

triangulate the poygons formed by the polylines and the borders;

on every node, estimate the surface gradient (least-square fit of a plane to the node and its neighborrs);

in every triangle, consider the two sides along which you need to interpolate and compute the derivative at endpoints (from the known gradients and the side directions);

use Hermite interpolation along these sides and solve for the desired iso-levels;

join the points obtained on both sides.

This method should be a good tradeoff between complexity and smoothness. It does reconstruct a continuous surface (except maybe for the remark below).

Note that is some cases, yo will obtain three solutions of the cubic. If there are three on each side, join them in order. Otherwise, make a decision on which to join and use the remaining two to close the curve.