问:
autobahn JS, what if RPC's callee is async?
In the documentation of autobahnJS is provided the following example to illustrate how to make setup a remote procedure call (RPC):

```<code>...
   // 3) register a procedure for remoting
   function add2(args) {
      return args[0] + args[1];
   }
   session.register('com.myapp.add2', add2);

   // 4) call a remote procedure
   session.call('com.myapp.add2', [2, 3]).then(
      function (res) {
         console.log("Result:", res);
      }
   );

 ...
</code>```

What if add2 needs to do some async operation? My idea was that maybe one can could call back another remote function registered in the client that triggered the initial call to backend.add2. Something like this:

```<code>...
//backend code
   function add2(args) {
      setTimeout(function() {
         console.log("We are done here");
         session.call('client.added', [123])
      }, 1000);
      return null; // useless, this value is never used
   }
   session.register('backend.add2', add2);

 // client code
   session.call('backend.add2', [2, 3]).then(
      function (res) {
         console.log("Result:", res);
      }
   );

 ...
</code>```

Do you see any better option? This seems a bit cumbersome to me. Ideally add2 would return a promise. But I am not sure whether this is possible over a RPC?

答:
My example of registering async function

```<code>  session.register('com.forlunch.list_chats', function (args, kwargs, details) {
        return functions.list_chats(args);
    })
</code>```

which make query to the mysql database

```<code>async function list_chats(params){
    var query = "SELECT * WHERE ... ;"
    let res = await mysql_query(query)
    return res
}

function mysql_query (query){
  return new Promise(function(resolve, reject) {
    const con =  mysql.createConnection(mysql_options);
    con.query(query,[], function (err, rows, fields) {
        if (err) return reject(err);
        resolve(rows);
    });
  })
}
</code>```

Body:
In the documentation of autobahnJS is provided the following example to illustrate how to make setup a remote procedure call (RPC):

...
   // 3) register a procedure for remoting
   function add2(args) {
      return args[0] + args[1];
   }
   session.register('com.myapp.add2', add2);

   // 4) call a remote procedure
   session.call('com.myapp.add2', [2, 3]).then(
      function (res) {
         console.log("Result:", res);
      }
   );

 ...

What if add2 needs to do some async operation? My idea was that maybe one can could call back another remote function registered in the client that triggered the initial call to backend.add2. Something like this:

...
//backend code
   function add2(args) {
      setTimeout(function() {
         console.log("We are done here");
         session.call('client.added', [123])
      }, 1000);
      return null; // useless, this value is never used
   }
   session.register('backend.add2', add2);

 // client code
   session.call('backend.add2', [2, 3]).then(
      function (res) {
         console.log("Result:", res);
      }
   );

 ...

Do you see any better option? This seems a bit cumbersome to me. Ideally add2 would return a promise. But I am not sure whether this is possible over a RPC?

Body:
My example of registering async function

  session.register('com.forlunch.list_chats', function (args, kwargs, details) {
        return functions.list_chats(args);
    })

which make query to the mysql database

async function list_chats(params){
    var query = "SELECT * WHERE ... ;"
    let res = await mysql_query(query)
    return res
}

function mysql_query (query){
  return new Promise(function(resolve, reject) {
    const con =  mysql.createConnection(mysql_options);
    con.query(query,[], function (err, rows, fields) {
        if (err) return reject(err);
        resolve(rows);
    });
  })
}


来源: stackexchange

问:
EC2 Load Balancer - Security Access
On a AWS EC2 ELB security profile - i need a couple of IP Address to be able to access only certain pages of my website. Is it possible? The other IP Address will have access to the full website. Is this achievable</p>

答:
This is not possible as a configuration in the Load Balancer because the Load Balancer simply distributes requests to your application servers.

Your application will need to enforce such functionality.

ContentLicense: CC BY-SA 3.0

Title: EC2 Load Balancer - Security Access


问:
Is there any way to get only parent terms from custom taxonomy or category?
Is there any way to get only parent terms from custom taxonomy or category?</p>

```<code> $genres = get_the_term_list($post->ID, 'genres', '<div class="genres"><div class="mta">', '', '</div></div>');
</code>```

答:
You can build the list alone without childrens.

```<code>/**
 * @param post_id can use 'get_the_ID()'
 * @param taxonomy for example 'category'
 */
$terms = wp_get_object_terms($post_id, $taxonomy, array('parent'=>'0'));
foreach($terms as $term) {
    ?>
    <a href="<?php echo get_term_link($term->term_id); ?>"><?php echo $term->name; ?></a>
    <?php
}
</code>```

The second option is that you can filter the terms and remove all the terms with parent bigger than 0 for the get_the_term_list() function.

```<code>function remove_child_terms($terms, $post_id, $taxonomy) {
    /**
     * Add some condition here to limit this for your custom taxonomy
     * if($taxonomy == 'something') {
     */
    foreach($terms as $key => $term) {
        if($term->parent !== 0) {
            unset($terms[$key]);
        }
    }
    /**
     * }
     */
    return $terms;
}
add_filter( 'get_the_terms', 'remove_child_terms', 10, 3 );
</code>```

Body:
Is there any way to get only parent terms from custom taxonomy or category?

 $genres = get_the_term_list($post->ID, 'genres', '

', '', '

');

Body:
You can build the list alone without childrens.

/**
 * @param post_id can use 'get_the_ID()'
 * @param taxonomy for example 'category'
 */
$terms = wp_get_object_terms($post_id, $taxonomy, array('parent'=>'0'));
foreach($terms as $term) {
    ?>
    <a href="<?php echo get_term_link($term->term_id); ?>"><?php echo $term->name; ?></a>
    <?php
}

The second option is that you can filter the terms and remove all the terms with parent bigger than 0 for the get_the_term_list() function.

function remove_child_terms($terms, $post_id, $taxonomy) {
    /**
     * Add some condition here to limit this for your custom taxonomy
     * if($taxonomy == 'something') {
     */
    foreach($terms as $key => $term) {
        if($term->parent !== 0) {
            unset($terms[$key]);
        }
    }
    /**
     * }
     */
    return $terms;
}
add_filter( 'get_the_terms', 'remove_child_terms', 10, 3 );


问:
Remove git's dependency on Brackets
I had a repeating issue where, whenever I pulled changes from a remote git repository, my terminal would print the following several times and launch Brackets:

```<code>[warn] kq_init: detected broken kqueue; not using.: Undefined error: 0
</code>```

I have no idea why it launched Brackets, especially since Sublime Text is my default editor and I never use Brackets anymore. In order to stop that, I uninstalled Brackets. Now when I try to pull I get this message:

```<code>error: There was a problem with the editor '/Applications/Brackets.app/Contents/MacOS/Brackets -wl1'.
Not committing merge; use 'git commit' to complete the merge.
</code>```

And when I try again:

```<code>error: You have not concluded your merge (MERGE_HEAD exists).
hint: Please, commit your changes before merging.
fatal: Exiting because of unfinished merge.
</code>```

This happens when I have not made any local changes and git should just pull all new changes without conflict. I know at some point, years ago, I made Brackets my default editor, but soon switched to Sublime Text. Git and Brackets must still be linked somehow but I don't know how to figure it out.

答: If your local repository has any unpublished commits when you pull from the remote, Git will perform a merge of the local and remote HEADs, and a text editor will be opened for you to enter a merge commit message in.  It appears that Git is currently configured to treat Brackets as your preferred text editor; in most cases, this can be changed by editing core.editor in your ~/.gitconfig file (See How do I make Git use the editor of my choice for commits? for further information).

Title: Remove git's dependency on Brackets

Body:
I had a repeating issue where, whenever I pulled changes from a remote git repository, my terminal would print the following several times and launch Brackets:

[warn] kq_init: detected broken kqueue; not using.: Undefined error: 0

I have no idea why it launched Brackets, especially since Sublime Text is my default editor and I never use Brackets anymore. In order to stop that, I uninstalled Brackets. Now when I try to pull I get this message:

error: There was a problem with the editor '/Applications/Brackets.app/Contents/MacOS/Brackets -wl1'.
Not committing merge; use 'git commit' to complete the merge.

And when I try again:

error: You have not concluded your merge (MERGE_HEAD exists).
hint: Please, commit your changes before merging.
fatal: Exiting because of unfinished merge.

This happens when I have not made any local changes and git should just pull all new changes without conflict. I know at some point, years ago, I made Brackets my default editor, but soon switched to Sublime Text. Git and Brackets must still be linked somehow but I don't know how to figure it out.


问:
copy, paste selection based on multiple criteria to another worksheet in VBA
I'm very new to VBA and have been using the Macro recorder to create Macros. The Macro recorder can only take me so far, I'm able to accomplish 2/3 of what I need done.

I'm trying to create a Macro where I need criteria met in three Columns, copy the row that meets the criteria, and paste it onto a workbook. The criteria are "Open" "Critical" and "Date."
Here's the tricky part, the date either needs to be greater than a specific date, either through user input or referencing a cell in a third worksheet. There are a few thousand rows, and about 19 columns, and all the codes I've attempted lead to crashing excel.

Sample of the code to getting the first two criteria:

```<code>Sheets("Sheet1").Select
    ActiveSheet.ListObjects("Table_owssvr").Range.AutoFilter Field:=12, _
    Criteria1:="Open"
ActiveSheet.ListObjects("Table_owssvr").Range.AutoFilter Field:=16, _
    Criteria1:="Critical"
Range("Table_owssvr").Select
Range("Q83").Activate
Selection.Copy
Sheets("Sheet2").Select Worksheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Select
ActiveSheet.Paste
</code>```

A-----------------------------------------------------------------B-----------------------------------------------------------C
Open                       -------------------------------------------------------Critical--------------------------------------------------1/25---Open-------------------------------------------------------High------------------------------------------------------3/25
Closed----------------------------------------------------Critical----------------------------------------------------3/24
Open------------------------------------------------------Critical-----------------------------------------------------1/25

Any help would be great!

答:
I designed it this way.
Try it.

The complete file is below the link

Download File

Sheet1 : It's your row data and click function button

Sheet2 : It's mapping data according to "Open" & "Critical" & "Date"
(The "Date" entered according to Sheet3)

Sheet3 : Enter the date you want

The complete code is as follows

```<code>Option Explicit

Private Sub Click_Click()

    Dim i As Integer

    For i = 2 To Worksheets("Sheet1").Range("A65536").End(xlUp).Row

        If Worksheets("Sheet1").Range("A" & i) = "Open" And _
            Worksheets("Sheet1").Range("B" & i) = "Critical" And _
            Worksheets("Sheet1").Range("C" & i) > Worksheets("Sheet3").Range("A2") Then

            Worksheets("Sheet1").Rows(i).Copy Worksheets("Sheet2").Range("A" & Worksheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Row + 1)

        End If
    Next

End Sub
</code>```

Body:
I'm very new to VBA and have been using the Macro recorder to create Macros. The Macro recorder can only take me so far, I'm able to accomplish 2/3 of what I need done.

I'm trying to create a Macro where I need criteria met in three Columns, copy the row that meets the criteria, and paste it onto a workbook. The criteria are "Open" "Critical" and "Date."
Here's the tricky part, the date either needs to be greater than a specific date, either through user input or referencing a cell in a third worksheet. There are a few thousand rows, and about 19 columns, and all the codes I've attempted lead to crashing excel.

Sample of the code to getting the first two criteria:

Sheets("Sheet1").Select
    ActiveSheet.ListObjects("Table_owssvr").Range.AutoFilter Field:=12, _
    Criteria1:="Open"
ActiveSheet.ListObjects("Table_owssvr").Range.AutoFilter Field:=16, _
    Criteria1:="Critical"
Range("Table_owssvr").Select
Range("Q83").Activate
Selection.Copy
Sheets("Sheet2").Select Worksheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Select
ActiveSheet.Paste

A-----------------------------------------------------------------B-----------------------------------------------------------C
Open                       -------------------------------------------------------Critical--------------------------------------------------1/25---Open-------------------------------------------------------High------------------------------------------------------3/25
Closed----------------------------------------------------Critical----------------------------------------------------3/24
Open------------------------------------------------------Critical-----------------------------------------------------1/25

Any help would be great!

Body:
I designed it this way.
Try it.

The complete file is below the link

Download File

Sheet1 : It's your row data and click function button

Sheet2 : It's mapping data according to "Open" & "Critical" & "Date"
(The "Date" entered according to Sheet3)

Sheet3 : Enter the date you want

The complete code is as follows

Option Explicit

Private Sub Click_Click()

    Dim i As Integer

    For i = 2 To Worksheets("Sheet1").Range("A65536").End(xlUp).Row

        If Worksheets("Sheet1").Range("A" & i) = "Open" And _
            Worksheets("Sheet1").Range("B" & i) = "Critical" And _
            Worksheets("Sheet1").Range("C" & i) > Worksheets("Sheet3").Range("A2") Then

            Worksheets("Sheet1").Rows(i).Copy Worksheets("Sheet2").Range("A" & Worksheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Row + 1)

        End If
    Next

End Sub


问:
Problem with Array Search in PHP
I am not finding what might be the problem in my program.

I am having an array like this

```<code>$arr = array("1", "urgent", "4", "low", "15", "avg");
</code>```

When i am searching this array using

```<code>$key = array_search("4", $arr);// Working
</code>```

Its is giving me the index of that element;

But when i am searching for "1" it is not giving me any index.

```<code>$key = array_search("4", $arr); // Not working here - for searching "1"
</code>```

What might be the problem.

Thank You

答:
array_search return key value of array.</p>

```<code>    $arr = array("1", "urgent", "4", "low", "15", "avg");
    $key = array_search("4", $arr);
   // give output is 2 which is key value
    $key = array_search("1", $arr);
   //give output is 0 which is key value
</code>```

ContentLicense: CC BY-SA 2.5

Title: Problem with Array Search in PHP

Body:
I am not finding what might be the problem in my program.

I am having an array like this

$arr = array("1", "urgent", "4", "low", "15", "avg");

When i am searching this array using

$key = array_search("4", $arr);// Working

Its is giving me the index of that element;

But when i am searching for "1" it is not giving me any index.

$key = array_search("4", $arr); // Not working here - for searching "1"

What might be the problem.

Thank You

Body:
array_search return key value of array.

    $arr = array("1", "urgent", "4", "low", "15", "avg");
    $key = array_search("4", $arr);
   // give output is 2 which is key value
    $key = array_search("1", $arr);
   //give output is 0 which is key value


问:
Non-greedy regex replacement
I have the following file:

```<code>STRING1
   "string2" = 1 ;
STRING1
   "string4" = 1 ;
STRING1

   "string3" = 1 ;
STRING1
"string5" = 1 ;
</code>```

I wish to replace:

```<code>STRING1

   "string3" = 1 ;
</code>```

by:

```<code>STRING1

   "string3" = 2 ;
</code>```

Using (STRING1.*?".*?".*?=)(.*?)\; (or even (STRING1.*?"string.?".*?=)(.*?)\;) I am able to match the individual STRING1 ... ; blocks but if I use (STRING1.*?"string3.?".*?=)(.*?)\; the regex match everything up to the string3 block.

答:
Don't use STRING1.*? when you know .*? cannot contain particular characters. In this case, it sure looks like .*? would be better written as [^;"]*. You want a similar substitution for the ".*?= case.

(STRING1[^;"]*"string3"[^"=]*=)[^;]*;

You'll still might need to deal with the case of how quoted strings are are represented in your file. What if one of those strings contains your entire question?

A fully reliable fix would actually parse the whole file looking for the change to make, but that may be overkill for your situation.

Title: Non-greedy regex replacement

Body:
I have the following file:

STRING1
   "string2" = 1 ;
STRING1
   "string4" = 1 ;
STRING1

   "string3" = 1 ;
STRING1
"string5" = 1 ;

I wish to replace:

STRING1

   "string3" = 1 ;

by:

STRING1

   "string3" = 2 ;

Using (STRING1.*?".*?".*?=)(.*?)\; (or even (STRING1.*?"string.?".*?=)(.*?)\;) I am able to match the individual STRING1 ... ; blocks but if I use (STRING1.*?"string3.?".*?=)(.*?)\; the regex match everything up to the string3 block.


问:
Is it possible to apply focus to an input element inside one of my React components without assigning a ref to the input tag directly?
I am losing focus of my text input boxes when the component re-renders. I can re-apply the focus to an <input> element by adding a ref (something like the answers here), but what can I do if I don't have access to the <input> element because it is inside a custom component. I can obviously edit the component or forgo using it altogether, but I'm wondering if there is another way to re-apply focus on my textbox.

I have a custom component called <TextInput>. I can add a ref to this component, but it ends up on the outer
 of this component, and not on the <input> tag contained within my <TextInput> element.

Please let me know if there is any way to apply the ref to the inner <input> element without modifying my component, or if I could utilize a different strategy for re-applying focus after my component re-renders.

Please let me know if I am being unclear or if you require additional information. Thank you very much for your time.

答:
If I understand you correctly, the focus is lost when the input element is re-rendered (because an ancestor of it got re-rendered).

If that's the case then you can do something like:

```<code><input ref={ (el) => el.focus() } />
</code>```

Sometimes this works better with a short delay:

```<code><input ref={ (el) => setTimeout(() => el.focus(), 100) } />
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If I understand you correctly, the focus is lost when the input element is re-rendered (because an ancestor of it got re-rendered).

If that's the case then you can do something like:

<input ref={ (el) => el.focus() } />

Sometimes this works better with a short delay:

<input ref={ (el) => setTimeout(() => el.focus(), 100) } />


问:
Stripping extension in a for loop
I am attempting to strip the .csv extension so that the file saves only as name.xslx instead of name.csv.xlsx but this does not seem to be working. I would appreciate some help. Thank you.</p>

```<code>import os
import glob
import csv
import openpyxl
import os.path

#convert the csv to xslx
for csvfile in glob.glob(os.path.join('.', '*.csv')):
    wb = openpyxl.Workbook()
    ws = wb.active
    with open(csvfile, 'rb') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader, start = 1):
            for c, val in enumerate(row, start = 1):
                ws.cell(row = r, column = c).value = val
    base = os.path.basename(csvfile)
    wb.save(base + '.xlsx')
</code>```

答: Instead of basename() use base = os.path.splitext(csvfile)[0]

Title: Stripping extension in a for loop

Body:
I am attempting to strip the .csv extension so that the file saves only as name.xslx instead of name.csv.xlsx but this does not seem to be working. I would appreciate some help. Thank you.

import os
import glob
import csv
import openpyxl
import os.path

#convert the csv to xslx
for csvfile in glob.glob(os.path.join('.', '*.csv')):
    wb = openpyxl.Workbook()
    ws = wb.active
    with open(csvfile, 'rb') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader, start = 1):
            for c, val in enumerate(row, start = 1):
                ws.cell(row = r, column = c).value = val
    base = os.path.basename(csvfile)
    wb.save(base + '.xlsx')


问:
gRPC installation fails at "make"
I am following the Built From Source instructions to install grpc

```<code>$ git clone -b $(curl -L https://grpc.io/release) https://github.com/grpc/grpc
</code>```

success

```<code>$ cd grpc
</code>```

success

```<code>$ git submodule update --init
</code>```

success

```<code>$ make
</code>```

fails after building a few source files

```<code>third_party/boringssl/crypto/rand/urandom.c:62:2: error: #error "system call number for getrandom is not the expected value"
#error "system call number for getrandom is not the expected value"
 ^
In file included from /usr/include/x86_64-linux-gnu/sys/syscall.h:31:0,
from third_party/boringssl/crypto/rand/urandom.c:32:
third_party/boringssl/crypto/rand/urandom.c: In function ‘init_once’:
third_party/boringssl/crypto/rand/urandom.c:128:15: error: ‘__NR_getrandom’ undeclared (first use in this function)
syscall(SYS_getrandom, &dummy, sizeof(dummy), GRND_NONBLOCK);
         ^
third_party/boringssl/crypto/rand/urandom.c:128:15: note: each undeclared identifier is reported only once for each function it appears in
third_party/boringssl/crypto/rand/urandom.c: In function ‘fill_with_entropy’:
third_party/boringssl/crypto/rand/urandom.c:258:21: error: ‘__NR_getrandom’ undeclared (first use in this function)
r = syscall(SYS_getrandom, out, len, 0 /* no flags */);
            ^
Makefile:2564: recipe for target '/home/usrnm/grpc/objs/opt/third_party/boringssl/crypto/rand/urandom.o' failed
make: *** [/home/usrnm/grpc/objs/opt/third_party/boringssl/crypto/rand/urandom.o] Error 1
</code>```

OS: Linux 4.4.0-0 SMP Debian 4.4.16-1

GCC version: gcc (Debian 4.9.2-10) 4.9.2

I couldn't find any open issues or any help about this error on the internet.

答:
You might have better luck without the embedded BoringSSL. Try building with:

```<code>EMBED_OPENSSL=false make
</code>```

If you get errors about missing packages, make sure you have libssl-dev installed.

Title: gRPC installation fails at "make"

Body:
I am following the Built From Source instructions to install grpc

$ git clone -b $(curl -L https://grpc.io/release) https://github.com/grpc/grpc

success

$ cd grpc

success

$ git submodule update --init

success

$ make

fails after building a few source files

third_party/boringssl/crypto/rand/urandom.c:62:2: error: #error "system call number for getrandom is not the expected value"
#error "system call number for getrandom is not the expected value"
 ^
In file included from /usr/include/x86_64-linux-gnu/sys/syscall.h:31:0,
from third_party/boringssl/crypto/rand/urandom.c:32:
third_party/boringssl/crypto/rand/urandom.c: In function ‘init_once’:
third_party/boringssl/crypto/rand/urandom.c:128:15: error: ‘__NR_getrandom’ undeclared (first use in this function)
syscall(SYS_getrandom, &dummy, sizeof(dummy), GRND_NONBLOCK);
         ^
third_party/boringssl/crypto/rand/urandom.c:128:15: note: each undeclared identifier is reported only once for each function it appears in
third_party/boringssl/crypto/rand/urandom.c: In function ‘fill_with_entropy’:
third_party/boringssl/crypto/rand/urandom.c:258:21: error: ‘__NR_getrandom’ undeclared (first use in this function)
r = syscall(SYS_getrandom, out, len, 0 /* no flags */);
            ^
Makefile:2564: recipe for target '/home/usrnm/grpc/objs/opt/third_party/boringssl/crypto/rand/urandom.o' failed
make: *** [/home/usrnm/grpc/objs/opt/third_party/boringssl/crypto/rand/urandom.o] Error 1

OS: Linux 4.4.0-0 SMP Debian 4.4.16-1

GCC version: gcc (Debian 4.9.2-10) 4.9.2

I couldn't find any open issues or any help about this error on the internet.

Body:
You might have better luck without the embedded BoringSSL. Try building with:

EMBED_OPENSSL=false make

If you get errors about missing packages, make sure you have libssl-dev installed.


问:
How to hide .env passwords in Laravel whoops output?
How can I hide my passwords and other sensitive environment variables on-screen in Laravel's whoops output?

Sometimes other people are looking at my development work. I don't want them to see these secrets if an exception is thrown, but I also don't want to have to keep toggling debug on and off, or spin up a dedicated site just for a quick preview.

答:
First of all, love the solution by Jeff above.

2nd, if like me you wanna hide all the env variables while still use whoops, here is a solution:

```<code>'debug_blacklist' => [
        '_COOKIE' => array_keys($_COOKIE),
        '_SERVER' => array_keys($_SERVER),
        '_ENV' => array_keys($_ENV),
    ],
</code>```

Output:

EDIT:
Legend has it that since laravel 7x you would need debug_hide key instead

Body:
First of all, love the solution by Jeff above.

2nd, if like me you wanna hide all the env variables while still use whoops, here is a solution:

'debug_blacklist' => [
        '_COOKIE' => array_keys($_COOKIE),
        '_SERVER' => array_keys($_SERVER),
        '_ENV' => array_keys($_ENV),
    ],

Output:

EDIT:
Legend has it that since laravel 7x you would need debug_hide key instead


问:
Achieving min-width with viewport meta tag
I would like my webpage's viewport width to equal device-width as long as device-width > 450px, or 450px otherwise (my layout dynamically scales, but doesn't look good below 450px wide).

The following two meta tags work well on tablets, where the device-width > 450px:

```<code><!-- uses device width -->
<meta name="viewport" content="width=device-width" />

<!-- use of initial-scale means width param is treated as min-width -->
<meta name="viewport" content="width=450, initial-scale=1.0" />
</code>```

however, on phones (where e.g. device-width=320px) the former is too thin for the content; and the latter causes the browser to zoom in, so the user has to manually zoom out to see the content.

Alternatively, this meta tag works well on phones

```<code><meta name="viewport" content="width=450" />
</code>```

but doesn't take advantage of the extra width available on tablets.

Any help/ideas would be really appreciated (and if it makes a difference, I'm using GWT).

答:
In short, there is no need to set min-width on viewport because you can set it on body or html element instead, to make them and their content wider than viewport. User will be able to scroll or zoom out content.

```<code>body {
  min-width: 450px;
}
</code>```

I did some tests in Chrome for Android and it scales fonts of some elements up if viewport width is set to anything other than device-width. Also shrink-to-fit=yes is useful to have a page zoomed out initially.

Lastly, this approach supports desktop browsers that can have strange window sizes or current zoom settings (both of which affect reported viewport dimensions), but don't honor the viewport meta tag.

Body:
I would like my webpage's viewport width to equal device-width as long as device-width > 450px, or 450px otherwise (my layout dynamically scales, but doesn't look good below 450px wide).

The following two meta tags work well on tablets, where the device-width > 450px:

<meta name="viewport" content="width=device-width" />

<meta name="viewport" content="width=450, initial-scale=1.0" />

however, on phones (where e.g. device-width=320px) the former is too thin for the content; and the latter causes the browser to zoom in, so the user has to manually zoom out to see the content.

Alternatively, this meta tag works well on phones

<meta name="viewport" content="width=450" />

but doesn't take advantage of the extra width available on tablets.

Any help/ideas would be really appreciated (and if it makes a difference, I'm using GWT).

Body:
In short, there is no need to set min-width on viewport because you can set it on body or html element instead, to make them and their content wider than viewport. User will be able to scroll or zoom out content.

body {
  min-width: 450px;
}

I did some tests in Chrome for Android and it scales fonts of some elements up if viewport width is set to anything other than device-width. Also shrink-to-fit=yes is useful to have a page zoomed out initially.

Lastly, this approach supports desktop browsers that can have strange window sizes or current zoom settings (both of which affect reported viewport dimensions), but don't honor the viewport meta tag.


问:
Cannot convert template argument NULL to void*
I've distilled a problem that's confounded me to the minimal example shown below. Basically the gcc compiler doesn't accept NULL as a template parameter of type void*.

Is there a workaround for this?

Please note that I'm restricted to C++03.

```<code>#define NULL 0

template<typename T = void , T* = NULL>
struct Foo
{
};

typedef Foo<> FooType;

int main()
{
}
</code>```

Edit: online version

答:
There is no solution to your problem: C++03 pointer template parameters have to designate an object. Using NULL as a non-type template parameter is a feature that was added in N1905, which came out at least one year after C++03.

14.3.2 Template non-type arguments

A template-argument for a non-type, non-template template-parameter shall be one of:

an integral constant-expression of integral or enumeration type; or

the name of a non-type template-parameter; or

the address of an object or function with external linkage, including function templates and function template-ids but excluding non-static class members, expressed as & id-expression where the & is optional if the name refers to a function or array, or if the corresponding template-parameter is a reference; or

(NEW) a constant expression that evaluates to a null pointer value (4.10); or

(NEW) a constant expression that evaluates to a null member pointer value (4.11); or

a pointer to member expressed as described in 5.3.1.

One option is to declare a "null struct" with a member that you can use instead of a real NULL:

```<code>template<typename T>
struct null
{
    static T value;
};

template<typename T, T* = &null<T>::value>
struct Foo
{
};
</code>```

Of course, accessing null<T>::value has well-defined semantics and it won't crash; the purpose is just to have an address that is guaranteed to be different from the address of any other object.

Note that in any case, it will be impossible for you to use T = void. You can't use the null workaround with it because void is an incomplete type; and you can't cast anything to a void pointer to use as a non-type template argument.

Body:
I've distilled a problem that's confounded me to the minimal example shown below. Basically the gcc compiler doesn't accept NULL as a template parameter of type void*.

Is there a workaround for this?

Please note that I'm restricted to C++03.

#define NULL 0

template<typename T = void , T* = NULL>
struct Foo
{
};

typedef Foo<> FooType;

int main()
{
}

Edit: online version

Body:
There is no solution to your problem: C++03 pointer template parameters have to designate an object. Using NULL as a non-type template parameter is a feature that was added in N1905, which came out at least one year after C++03.

14.3.2 Template non-type arguments

A template-argument for a non-type, non-template template-parameter shall be one of:

an integral constant-expression of integral or enumeration type; or

the name of a non-type template-parameter; or

the address of an object or function with external linkage, including function templates and function template-ids but excluding non-static class members, expressed as & id-expression where the & is optional if the name refers to a function or array, or if the corresponding template-parameter is a reference; or

(NEW) a constant expression that evaluates to a null pointer value (4.10); or

(NEW) a constant expression that evaluates to a null member pointer value (4.11); or

a pointer to member expressed as described in 5.3.1.

One option is to declare a "null struct" with a member that you can use instead of a real NULL:

template<typename T>
struct null
{
    static T value;
};

template<typename T, T* = &null<T>::value>
struct Foo
{
};

Of course, accessing null<T>::value has well-defined semantics and it won't crash; the purpose is just to have an address that is guaranteed to be different from the address of any other object.

Note that in any case, it will be impossible for you to use T = void. You can't use the null workaround with it because void is an incomplete type; and you can't cast anything to a void pointer to use as a non-type template argument.


问:
BottomNavigationView set optionselected with ViewPager Xamarin
I am building a App Where I use A BottomNavigationView and display the fragments with a ViewPager.

When I push or touch the buttoms of the Bottom Navigation, I dont have problems, the fragment displays correctly in the viewpager.

The problem is that I can slide just the viewPager and when I do it, the bottom navigation does not change to the correct option.

I saw that I need to add ViewPager.IOnPageChangeListener and create three methods for manage the view pager, but I dont now How to set the BottomNavigation item selected when the user slide the viewpager
For example, I touch the buttom 4 of the BottomNavigationBar and I saw Automatically the fragment 4 in the view pager(where I display the text "Fragment4"),,, and then I slide the ViewPager until the Fragment1, but the BottomNavigation is the option4 still selected,, it does not change when I slide the viewpager u.u

I hope you can help me, thanks

```<code>public class MainActivity : AppCompatActivity, ViewPager.IOnPageChangeListener
{

    private DrawerLayout drawerLayout;
    ViewPager viewPager;
    BottomNavigationView bottomNavigation;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView (Resource.Layout.Main);

        bottomNavigation = FindViewById<BottomNavigationView>(Resource.Id.bottom_navigation);
        bottomNavigation.NavigationItemSelected += Navigation_NavigationItemSelected;

        SupportToolbar toolbar = FindViewById<SupportToolbar>(Resource.Id.toolbar);
        SetSupportActionBar(toolbar);

        SupportActionbar actionBar = SupportActionBar;
        actionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu);
        actionBar.SetDisplayHomeAsUpEnabled(true);

        drawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawerLayout);

        NavigationView navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
        if (navigationView != null)
        {
            setUpDrawerContent(navigationView);
        }

        //TabLayout tabs = FindViewById<TabLayout>(Resource.Id.tabs);

        viewPager = FindViewById<ViewPager>(Resource.Id.viewpager);
        setUpViewPager(viewPager);

        //tabs.SetupWithViewPager(viewPager);

    }

    private void Navigation_NavigationItemSelected(object sender, BottomNavigationView.NavigationItemSelectedEventArgs e)
    {
        switch (e.Item.ItemId)
        {
            case Resource.Id.navigation_myState:
                viewPager.SetCurrentItem(0, false);
                break;
            case Resource.Id.navigation_study:
                viewPager.SetCurrentItem(1, false);
                break;
            case Resource.Id.navigation_flashcards:
                viewPager.SetCurrentItem(2, false);
                break;
            case Resource.Id.navigation_test:
                viewPager.SetCurrentItem(3, false); ;
                break;
        }
    }

    private void setUpViewPager(ViewPager viewPager)
    {
        ViewPagerAdapter adapter = new ViewPagerAdapter(SupportFragmentManager);
        adapter.AddFragment(new Fragment1(), "Fragment1");
        adapter.AddFragment(new Fragment2(), "Fragment2");
        adapter.AddFragment(new Fragment3(), "Fragment3");
        adapter.AddFragment(new Fragment4(), "Fragment4");

        viewPager.Adapter = adapter;
    }

    public override bool OnOptionsItemSelected(IMenuItem item)
    {
        switch (item.ItemId)
        {
            case Android.Resource.Id.Home:
                drawerLayout.OpenDrawer((int)GravityFlags.Left);
                return true;

            default:
                return base.OnOptionsItemSelected(item);
        }

    }

    private void setUpDrawerContent(NavigationView navigationView)
    {
        navigationView.NavigationItemSelected += (object sender, NavigationView.NavigationItemSelectedEventArgs e) =>
         {
             e.MenuItem.SetChecked(true);
             drawerLayout.CloseDrawers();
         };
    }

    public class ViewPagerAdapter : FragmentPagerAdapter
    {
        public List<SupportFragment> Fragments { get; set; }
        public List<string> FragmentsNames { get; set; }

        public ViewPagerAdapter(SupportFragmentManager FragManager) : base (FragManager)
        {
            Fragments = new List<SupportFragment>();
            FragmentsNames = new List<string>();
        }

        public void AddFragment(SupportFragment fragment, string name)
        {
            Fragments.Add(fragment);
            FragmentsNames.Add(name);
        }

        public override int Count
        {
            get
            {
                return Fragments.Count;
            }
        }

        public override SupportFragment GetItem(int position)
        {
            return Fragments[position];
        }

        public override ICharSequence GetPageTitleFormatted(int position)
        {
            return new Java.Lang.String(FragmentsNames[position]);
        }
    }

    public void OnPageScrollStateChanged(int state)
    {
        throw new NotImplementedException();
    }

    public void OnPageScrolled(int position, float positionOffset, int positionOffsetPixels)
    {
        throw new NotImplementedException();
    }

    public void OnPageSelected(int position)
    {
        //I think that here I need to put something like bottomNavigatin.setItemselecte(position) or (bottomNavigation.something(Resource.Id.navigation_flashcards)
    }
}
</code>```

答:
The trick is to hookup the ViewPager.PageSelected to BottomNavigationView.NavigationItemSelected. Here's how you can do it

```<code>void ViewPager_PageSelected(object sender, ViewPager.PageSelectedEventArgs e)
{
     var item = _navigationView.Menu.GetItem(e.Position);
     _navigationView.SelectedItemId = item.ItemId;
}

void NavigationView_NavigationItemSelected(object sender, BottomNavigationView.NavigationItemSelectedEventArgs e)
{
     _viewPager.SetCurrentItem(e.Item.Order, true);
}
</code>```

Demo:

Checkout the full implementation in my post here: https://intelliabb.com/2017/12/02/tutorial-bottomnavigationview-and-viewpager-in-xamarin-android/

Body:
I am building a App Where I use A BottomNavigationView and display the fragments with a ViewPager.

When I push or touch the buttoms of the Bottom Navigation, I dont have problems, the fragment displays correctly in the viewpager.

The problem is that I can slide just the viewPager and when I do it, the bottom navigation does not change to the correct option.

I saw that I need to add ViewPager.IOnPageChangeListener and create three methods for manage the view pager, but I dont now How to set the BottomNavigation item selected when the user slide the viewpager
For example, I touch the buttom 4 of the BottomNavigationBar and I saw Automatically the fragment 4 in the view pager(where I display the text "Fragment4"),,, and then I slide the ViewPager until the Fragment1, but the BottomNavigation is the option4 still selected,, it does not change when I slide the viewpager u.u

I hope you can help me, thanks

public class MainActivity : AppCompatActivity, ViewPager.IOnPageChangeListener
{

    private DrawerLayout drawerLayout;
    ViewPager viewPager;
    BottomNavigationView bottomNavigation;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView (Resource.Layout.Main);

        bottomNavigation = FindViewById<BottomNavigationView>(Resource.Id.bottom_navigation);
        bottomNavigation.NavigationItemSelected += Navigation_NavigationItemSelected;

        SupportToolbar toolbar = FindViewById<SupportToolbar>(Resource.Id.toolbar);
        SetSupportActionBar(toolbar);

        SupportActionbar actionBar = SupportActionBar;
        actionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu);
        actionBar.SetDisplayHomeAsUpEnabled(true);

        drawerLayout = FindViewById<DrawerLayout>(Resource.Id.drawerLayout);

        NavigationView navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
        if (navigationView != null)
        {
            setUpDrawerContent(navigationView);
        }

        //TabLayout tabs = FindViewById<TabLayout>(Resource.Id.tabs);

        viewPager = FindViewById<ViewPager>(Resource.Id.viewpager);
        setUpViewPager(viewPager);

        //tabs.SetupWithViewPager(viewPager);

    }

    private void Navigation_NavigationItemSelected(object sender, BottomNavigationView.NavigationItemSelectedEventArgs e)
    {
        switch (e.Item.ItemId)
        {
            case Resource.Id.navigation_myState:
                viewPager.SetCurrentItem(0, false);
                break;
            case Resource.Id.navigation_study:
                viewPager.SetCurrentItem(1, false);
                break;
            case Resource.Id.navigation_flashcards:
                viewPager.SetCurrentItem(2, false);
                break;
            case Resource.Id.navigation_test:
                viewPager.SetCurrentItem(3, false); ;
                break;
        }
    }

    private void setUpViewPager(ViewPager viewPager)
    {
        ViewPagerAdapter adapter = new ViewPagerAdapter(SupportFragmentManager);
        adapter.AddFragment(new Fragment1(), "Fragment1");
        adapter.AddFragment(new Fragment2(), "Fragment2");
        adapter.AddFragment(new Fragment3(), "Fragment3");
        adapter.AddFragment(new Fragment4(), "Fragment4");

        viewPager.Adapter = adapter;
    }

    public override bool OnOptionsItemSelected(IMenuItem item)
    {
        switch (item.ItemId)
        {
            case Android.Resource.Id.Home:
                drawerLayout.OpenDrawer((int)GravityFlags.Left);
                return true;

            default:
                return base.OnOptionsItemSelected(item);
        }

    }

    private void setUpDrawerContent(NavigationView navigationView)
    {
        navigationView.NavigationItemSelected += (object sender, NavigationView.NavigationItemSelectedEventArgs e) =>
         {
             e.MenuItem.SetChecked(true);
             drawerLayout.CloseDrawers();
         };
    }

    public class ViewPagerAdapter : FragmentPagerAdapter
    {
        public List<SupportFragment> Fragments { get; set; }
        public List<string> FragmentsNames { get; set; }

        public ViewPagerAdapter(SupportFragmentManager FragManager) : base (FragManager)
        {
            Fragments = new List<SupportFragment>();
            FragmentsNames = new List<string>();
        }

        public void AddFragment(SupportFragment fragment, string name)
        {
            Fragments.Add(fragment);
            FragmentsNames.Add(name);
        }

        public override int Count
        {
            get
            {
                return Fragments.Count;
            }
        }

        public override SupportFragment GetItem(int position)
        {
            return Fragments[position];
        }

        public override ICharSequence GetPageTitleFormatted(int position)
        {
            return new Java.Lang.String(FragmentsNames[position]);
        }
    }

    public void OnPageScrollStateChanged(int state)
    {
        throw new NotImplementedException();
    }

    public void OnPageScrolled(int position, float positionOffset, int positionOffsetPixels)
    {
        throw new NotImplementedException();
    }

    public void OnPageSelected(int position)
    {
        //I think that here I need to put something like bottomNavigatin.setItemselecte(position) or (bottomNavigation.something(Resource.Id.navigation_flashcards)
    }
}

Body:
The trick is to hookup the ViewPager.PageSelected to BottomNavigationView.NavigationItemSelected. Here's how you can do it

void ViewPager_PageSelected(object sender, ViewPager.PageSelectedEventArgs e)
{
     var item = _navigationView.Menu.GetItem(e.Position);
     _navigationView.SelectedItemId = item.ItemId;
}

void NavigationView_NavigationItemSelected(object sender, BottomNavigationView.NavigationItemSelectedEventArgs e)
{
     _viewPager.SetCurrentItem(e.Item.Order, true);
}

Demo:

Checkout the full implementation in my post here: https://intelliabb.com/2017/12/02/tutorial-bottomnavigationview-and-viewpager-in-xamarin-android/


问:
level of the child in the table recursion php?
The problem is to deduce the level of nesting relative to id. Here is an example of db:
http://sqlfiddle.com/#!9/22b0d2/1

Here is an example of the php code:

```<code>function getCats($res){

    $levels = array();
    $tree = array();
    $cur = array();

    while($rows = mysqli_fetch_assoc($res)){

        $cur = &$levels[$rows['id']];
        $cur['parent_id'] = $rows['parent_id'];
        $cur['name'] = $rows['name'];

        if($rows['parent_id'] == 0){
            $tree[$rows['id']] = &$cur;
        }
        else{
            $levels[$rows['parent_id']]['children'][$rows['id']] = &$cur;
        }

    }

    return $tree;

}

function getTree($arr){

    $out = '';
    $counter = 1;

    $out .= '<ul>';
    foreach($arr as $k=>$v){
        $out .= '<li><a href="?id='.$k.'">'.$v['name'].'</a></li>';
        if(!empty($v['children'])){
            $out .= getTree($v['children']);
        }

    }
    $out .= '</ul>';
    return $out;

}
$mysql = new mysqli('localhost', 'root', '', 'testids');
$res = $mysql->query("SELECT * FROM categories ORDER BY id");
$cats = getCats($res);
echo getTree($cats);
</code>```

Please help remake the function so that it's like this:
Just look not from the
, but from the
. If we look from the id = 1, then at the first level we have id 2 and id 3, and on the second level id 5, because they are children from id 1.

```<code>    Array
(
    [1] => Array
        (
            [parent_id] => 0
            [name] => name1
            [children] => Array
                (
                    [2] => Array
                        (
                            [parent_id] => 1
                            [name] => name2
                            [children] => Array
                                (
                                    [4] => Array
                                        (
                                            [parent_id] => 2
                                            [name] => name4
                                            [children] => Array
                                                (
                                                    [5] => Array
                                                        (
                                                            [parent_id] => 4
                                                            [name] => name5
                                                        )

                                                )

                                        )

                                )

                        )

                    [3] => Array
                        (
                            [parent_id] => 1
                            [name] => name3
                        )

                )

        )

)
</code>```

答:
```<code><?php
/*
$ray = array(
    array('id' => 1,'name' => 'name1','parent_id' => 0),
    array('id' => 2,'name' => 'name2','parent_id' => 1),
    array('id' => 3,'name' => 'name3','parent_id' => 1),
    array('id' => 4,'name' => 'name4','parent_id' => 2),
    array('id' => 5,'name' => 'name5','parent_id' => 4)
);
*/

$mysql = new mysqli('localhost', 'root', '', 'testids');
$res = $mysql->query("SELECT * FROM categories ORDER BY id");

$data = array();
while($row = mysqli_fetch_assoc($res)){
    $data['ids'][$row['id']]        = $row['name'];

    if(isset($data['level'][$row['parent_id']])){
        $level = $data['level'][$row['parent_id']] + 1;
    } else {
        $level = 0;
    }

    $data['level'][$row['id']] = $level;
}

echo '
<table>
    <tr>
        <th>ID</th>
        <th>Level</th>
        <th>Name</th>
    </tr>';
foreach($data['level'] as $id=>$level){
    echo '
    <tr>
        <td>'.$id.'</td>
        <td>'.$level.'</td>
        <td>'.$data['ids'][$id].'</td>
    </tr>';
}
echo '
</table>';
?>
</code>```

Body:
The problem is to deduce the level of nesting relative to id. Here is an example of db:
http://sqlfiddle.com/#!9/22b0d2/1

Here is an example of the php code:

function getCats($res){

    $levels = array();
    $tree = array();
    $cur = array();

    while($rows = mysqli_fetch_assoc($res)){

        $cur = &$levels[$rows['id']];
        $cur['parent_id'] = $rows['parent_id'];
        $cur['name'] = $rows['name'];

        if($rows['parent_id'] == 0){
            $tree[$rows['id']] = &$cur;
        }
        else{
            $levels[$rows['parent_id']]['children'][$rows['id']] = &$cur;
        }

    }

    return $tree;

}

function getTree($arr){

    $out = '';
    $counter = 1;

    $out .= '
';
    foreach($arr as $k=>$v){
        $out .= '
'.$v['name'].'
';
        if(!empty($v['children'])){
            $out .= getTree($v['children']);
        }

    }
    $out .= '
';
    return $out;

}
$mysql = new mysqli('localhost', 'root', '', 'testids');
$res = $mysql->query("SELECT * FROM categories ORDER BY id");
$cats = getCats($res);
echo getTree($cats);

Please help remake the function so that it's like this:
Just look not from the
, but from the
. If we look from the id = 1, then at the first level we have id 2 and id 3, and on the second level id 5, because they are children from id 1.

    Array
(
    [1] => Array
        (
            [parent_id] => 0
            [name] => name1
            [children] => Array
                (
                    [2] => Array
                        (
                            [parent_id] => 1
                            [name] => name2
                            [children] => Array
                                (
                                    [4] => Array
                                        (
                                            [parent_id] => 2
                                            [name] => name4
                                            [children] => Array
                                                (
                                                    [5] => Array
                                                        (
                                                            [parent_id] => 4
                                                            [name] => name5
                                                        )

                                                )

                                        )

                                )

                        )

                    [3] => Array
                        (
                            [parent_id] => 1
                            [name] => name3
                        )

                )

        )

)


问:
How to reuse request body of *http.Request between HTTP middleware handlers?
I use go-chi as HTTP-router, and I want to reuse one method inside another

```<code>func Registration(w http.ResponseWriter, r *http.Request) {
    b, err := ioutil.ReadAll(r.Body) // if you delete this line, the user will be created
    // ...other code

    // if all good then create new user
    user.Create(w, r)
}

...

func Create(w http.ResponseWriter, r *http.Request) {
  b, err := ioutil.ReadAll(r.Body)
  // ...other code

  // ... there I get the problem with parse JSON from &b
}
</code>```

user.Create return error "unexpected end of JSON input"

Actually, after I executed ioutil.ReadAll

user.Create ceased to parse JSON,

in r.Body there was an empty array[]how can I fix this problem?

答:
In the end, I was able to recover data in this way:</p>

```<code>r.Body = ioutil.NopCloser(bytes.NewBuffer(b))
</code>```

Body:
I use go-chi as HTTP-router, and I want to reuse one method inside another

func Registration(w http.ResponseWriter, r *http.Request) {
    b, err := ioutil.ReadAll(r.Body) // if you delete this line, the user will be created
    // ...other code

    // if all good then create new user
    user.Create(w, r)
}

...

func Create(w http.ResponseWriter, r *http.Request) {
  b, err := ioutil.ReadAll(r.Body)
  // ...other code

  // ... there I get the problem with parse JSON from &b
}

user.Create return error "unexpected end of JSON input"

Actually, after I executed ioutil.ReadAll

user.Create ceased to parse JSON,

in r.Body there was an empty array[]how can I fix this problem?

Body:
In the end, I was able to recover data in this way:

r.Body = ioutil.NopCloser(bytes.NewBuffer(b))


问:
Clojure test: global fixtures
I've got some fixtures that boot up and close the database in my project.

Now it looks something like this:

```<code>(use-fixtures :once with-embedded-db)
</code>```

while in the fixture itself I've got a dynamic variable that I use in different places:

```<code>(def ^:dynamic *db*)

(defn with-embedded-db [f]
  (binding [*db* (db/connect args)]
    (f)
    (finally
      (db/clean-up *db)))
</code>```

Now, assume that db/connect and db/clean-up take some time.

PROBLEM:

When I run tests using lein test, it takes very long time, unnecessarily spending time on connecting and disconnecting to the db for every namespace.

QUESTION:

Is there a way to set up global fixtures so that when I run lein test, it calls it only once for all the test namespaces?

Thanks!

答:
Use circleci.test, it supports :global-fixtures:

... you can define global fixtures that are only run once for the entire test run, no matter how many namespaces you run.

Title: Clojure test: global fixtures

Body:
I've got some fixtures that boot up and close the database in my project.

Now it looks something like this:

(use-fixtures :once with-embedded-db)

while in the fixture itself I've got a dynamic variable that I use in different places:

(def ^:dynamic *db*)

(defn with-embedded-db [f]
  (binding [*db* (db/connect args)]
    (f)
    (finally
      (db/clean-up *db)))

Now, assume that db/connect and db/clean-up take some time.

PROBLEM:

When I run tests using lein test, it takes very long time, unnecessarily spending time on connecting and disconnecting to the db for every namespace.

QUESTION:

Is there a way to set up global fixtures so that when I run lein test, it calls it only once for all the test namespaces?

Thanks!


问:
Angluar2 routing in chrome extension
I am creating chrome extension using angular2. The app is compiled using webpack. The problem is that when I added routing in my app, suddenly my html, can't find files in directories that exist with wanted files...

This is my source map that chrome shows:

this is my html:

```<code><div class="app-main-component">
    <img src="../images/logo-cw-white.png">
</div>
</code>```

This is my dev source map (app is running using dist folder, that is made when compiled with webpack):

My routing file:

```<code>import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { HelloAgainComponent } from './app/hello-again.component';
import { AppComponent} from './app/app.component'
import { AppMainComponent} from './app/app-main.component'

const routes: Routes = [
  {
    path: '**',
    component: AppMainComponent,
    children: [
      {
        path: 'again',
        component: HelloAgainComponent
      },
    ]
   }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}
</code>```

before I created routing file the image was found by html, but know it does not find it....

Error:

Failed to load resource: net::ERR_FILE_NOT_FOUND : chrome-extension://xyxyx/src/dist/images/logo-cw-white.png

As I understand my routing directories are incorrect... Can someone please help me fix this??

答:
I came across the same problem and used HashLocationStrategy to get around it. Happiness didn't last long as I noticed that when I refresh my webpage. I get 404 again.

Base Href: /dist/app/

So generally,

1. Browser go to chrome-extension://hkmmlaghihcdhmpodgfnkkjbmecahifc/dist/app/index.html

2. Angular routing with HashLocationStrategy kicks in and changes url to chrome-extension://hkmmlaghihcdhmpodgfnkkjbmecahifc/dist/app/#/browse
The app works at this point.

3. I refresh the page and get 404 as browser is trying to go to chrome-extension://hkmmlaghihcdhmpodgfnkkjbmecahifc/dist/app/#/browse straight without loading the app/index.html

Do you have any solutions?

Solution:-

I changed base href to dist/app/index.html. Now its working fine.
Reason? well, now #/browse gets appended after dist/app/index.html which allows my bundle.js to load and later on angular loads #/browse.

Hope it saves someone's time especially the people who are developing chrome extensions using angular2+ (my angular version is 5) where server is built into chrome and developer has no control over it.

Title: Angluar2 routing in chrome extension

Body:
I am creating chrome extension using angular2. The app is compiled using webpack. The problem is that when I added routing in my app, suddenly my html, can't find files in directories that exist with wanted files...

This is my source map that chrome shows:

this is my html:

This is my dev source map (app is running using dist folder, that is made when compiled with webpack):

My routing file:

import { NgModule }             from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { HelloAgainComponent } from './app/hello-again.component';
import { AppComponent} from './app/app.component'
import { AppMainComponent} from './app/app-main.component'

const routes: Routes = [
  {
    path: '**',
    component: AppMainComponent,
    children: [
      {
        path: 'again',
        component: HelloAgainComponent
      },
    ]
   }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

before I created routing file the image was found by html, but know it does not find it....

Error:

Failed to load resource: net::ERR_FILE_NOT_FOUND : chrome-extension://xyxyx/src/dist/images/logo-cw-white.png

As I understand my routing directories are incorrect... Can someone please help me fix this??


问:
Python Web Scraper + Cleanup
So I'm currently trying to export a twitter .html page, and I created this webscraper using BeautifulSoup. The OUTPUT.csv file is currently really messy, and here are my questions (current .py file is below):

What are some steps I can take to clean out the code? My output csv has the tweets, but they're really messy, and separated by commas. Is there any way I can separate them by using a new line? Also, how can I only extract the part of the tweet that says "Bank Of America: Growth Is Back – Bank of
America Corporation" (which I surrounded by stars) in my cleanup() function?

```<code>"<div class=""js-tweet-text-container"">
<p class=""TweetTextSize js-tweet-text tweet-text"" data-aria-label-
part=""0"" lang=""en"">*****Bank Of America: Growth Is Back – Bank of
America Corporation***** (<strong>NYSE:BAC</strong>) <a class=""twitter-
timeline-link u-hidden"" data-expanded-url=""https://good-
stockinvest.com/2017/11/29/bank-of-america-growth-is-back-bank-of-
america-corporation-nysebac/"" dir=""ltr""
href="" rel=""nofollow noopener""
target=""_blank"" title=""https://good-stockinvest.com/2017/11/29/bank-
of-america-growth-is-back-bank-of-america-corporation-nysebac/""><span
class=""tco-ellipsis""></span><span class=""invisible"">https://</span>
<span class=""js-display-url"">good-
stockinvest.com/2017/11/29/ban</span><span class=""invisible"">k-of-
america-growth-is-back-bank-of-america-corporation-nysebac/</span><span
class=""tco-ellipsis""><span class=""invisible""> </span>…</span></a>
</p>
</div>"
</code>```

Below is my code:

```<code>from bs4 import BeautifulSoup
import csv

new = csv.writer(open("OUTPUT", "w"))
new.writerow(["Tweets:"])
new.writerow([ ])       # allowing for a simple space

data = open("bac.html", "r").read()
soup = BeautifulSoup(data, "html.parser")

tweets = soup.find_all('div', class_="js-tweet-text-container")

def writetweets():
    for tweet in tweets:
        new.writerow(tweets)
        new.writerow([ ])
    print "writetweets - open OUTPUT.csv for the tweet divs"

def cleanup():
    print "cleanup - nothing here for now"

def tests():
    print "tests - nothing here for now"

def demo():
    writetweets()
    cleanup()
    tests()

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

答:
Building on the previous answers, but helping with the cleanup:

```<code>from bs4 import BeautifulSoup
import csv

data = open("bac.html", "r").read()
soup = BeautifulSoup(data, "html.parser")

#tweets = soup.find_all('div', class_="js-tweet-text-container")
tweets = soup.find_all("div", {"class": "js-tweet-text-container"})

def writetweets():
    with open("OUTPUT.txt", "w") as new:
        new.write("Tweets:\r\n")
        for tweet in tweets:
            new.write(tweet.getText() + "\r\n")
    print "writetweets - open OUTPUT.txt for the tweet divs"

def cleanup():
    print "cleanup - nothing here for now"

def tests():
    print "tests - nothing here for now"

def demo():
    writetweets()
    cleanup()
    tests()

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

I get:

In [29]: tweet.getText()

Out[29]: '*****Bank Of America: Growth Is Back – Bank of America Corporation***** (NYSE:BAC) https://good-stockinvest.com/2017/11/29/bank-of-america-growth-is-back-bank-of-america-corporation-nysebac/ …'

Title: Python Web Scraper + Cleanup

Body:
So I'm currently trying to export a twitter .html page, and I created this webscraper using BeautifulSoup. The OUTPUT.csv file is currently really messy, and here are my questions (current .py file is below):

What are some steps I can take to clean out the code? My output csv has the tweets, but they're really messy, and separated by commas. Is there any way I can separate them by using a new line? Also, how can I only extract the part of the tweet that says "Bank Of America: Growth Is Back – Bank of
America Corporation" (which I surrounded by stars) in my cleanup() function?

"

*****Bank Of America: Growth Is Back – Bank of
America Corporation***** (NYSE:BAC) https://
good-
stockinvest.com/2017/11/29/bank-of-
america-growth-is-back-bank-of-america-corporation-nysebac/ …

"

Below is my code:

from bs4 import BeautifulSoup
import csv

new = csv.writer(open("OUTPUT", "w"))
new.writerow(["Tweets:"])
new.writerow([ ])       # allowing for a simple space

data = open("bac.html", "r").read()
soup = BeautifulSoup(data, "html.parser")

tweets = soup.find_all('div', class_="js-tweet-text-container")

def writetweets():
    for tweet in tweets:
        new.writerow(tweets)
        new.writerow([ ])
    print "writetweets - open OUTPUT.csv for the tweet divs"

def cleanup():
    print "cleanup - nothing here for now"

def tests():
    print "tests - nothing here for now"

def demo():
    writetweets()
    cleanup()
    tests()

if __name__ == '__main__':
    demo()

Body:
Building on the previous answers, but helping with the cleanup:

from bs4 import BeautifulSoup
import csv

data = open("bac.html", "r").read()
soup = BeautifulSoup(data, "html.parser")

#tweets = soup.find_all('div', class_="js-tweet-text-container")
tweets = soup.find_all("div", {"class": "js-tweet-text-container"})

def writetweets():
    with open("OUTPUT.txt", "w") as new:
        new.write("Tweets:\r\n")
        for tweet in tweets:
            new.write(tweet.getText() + "\r\n")
    print "writetweets - open OUTPUT.txt for the tweet divs"

def cleanup():
    print "cleanup - nothing here for now"

def tests():
    print "tests - nothing here for now"

def demo():
    writetweets()
    cleanup()
    tests()

if __name__ == '__main__':
    demo()

I get:

In [29]: tweet.getText()

Out[29]: '*****Bank Of America: Growth Is Back – Bank of America Corporation***** (NYSE:BAC) https://good-stockinvest.com/2017/11/29/bank-of-america-growth-is-back-bank-of-america-corporation-nysebac/ …'


问:
R shiny Observe running Before loading of UI and this causes Null parameters
I am running into an issue because observe is being called first before the UI loads.

Here is my ui.R

```<code>  sidebarPanel(
    selectInput("Desk", "Desk:" ,  as.matrix(getDesksUI())),
    uiOutput("choose_Product"), #this is dynamically created UI
    uiOutput("choose_File1"), #this is dynamically created UI
    uiOutput("choose_Term1"), #this is dynamically created UI  ....
</code>```

Here is my Server.R

```<code>shinyServer(function(input, output,session) {

  #this is dynamic UI
  output$choose_Product <- renderUI({
    selectInput("Product", "Product:", as.list(getProductUI(input$Desk)))
  })

   #this is dynamic UI
  output$choose_File1 <- renderUI({
    selectInput("File1", "File 1:", as.list(getFileUI(input$Desk, input$Product)))
  })

  #this is dynamic UI and I want it to run before the Observe function so the call
  # to getTerm1UI(input$Desk, input$Product, input$File1) has non-null parameters
  output$choose_Term1 <- renderUI({
    print("Rendering UI for TERM")
    print(paste(input$Desk," ", input$Product, " ", input$File1,sep=""))
    selectInput("Term1", "Term:", getTerm1UI(input$Desk, input$Product, input$File1))
  })
</code>```

This is my observe function and it runs before the input$Product and input$File1 are populated so I get an error because they are both NULL.  But I need to use the input from the UI.

```<code>   observe({
    print("in observe")
    print(input$Product)
    max_plots<-length(getTerm2UI(input$Desk, input$Product, input$File1))
    #max_plots<-5
            # Call renderPlot for each one. Plots are only actually generated when they
            # are visible on the web page.
            for (i in 1:max_plots )   {
              # Need local so that each item gets its own number. Without it, the value
              # of i in the renderPlot() will be the same across all instances, because
              # of when the expression is evaluated.
              local({
               my_i <- i
                plotname <- paste("plot", my_i, sep="")
                output[[plotname]] <- renderPlot({
                  plot(1:my_i, 1:my_i,
                       xlim = c(1, max_plots ),
                       ylim = c(1, max_plots ),
                        main = paste("1:", my_i, ". n is ", input$n, sep = "") )
                })
              })
            }##### End FoR Loop
 },priority = -1000)
</code>```

Any idea how to get the input$Product and input$File1 to be populated BEFORE observe runs?

Thank you.

答:
We'd need an MRE to provide a working answer, but, assuming you need input$Product and input$File1, but do not want to take a dependency on them, only on input$Desk, you could:

```<code>observe({

  product <- isolate(input$Product)
  file1 <- isolate(input$File1)

  print("in observe")
  print(product)
  max_plots<-length(getTerm2UI(input$Desk, product, file1))
  for (i in 1:max_plots )   {
    # ...
  }
})
</code>```

this is probably effectively equivalent to an observeEvent(input$Desk, ....), but might offer more flexibility.

Body:
I am running into an issue because observe is being called first before the UI loads.

Here is my ui.R

  sidebarPanel(
    selectInput("Desk", "Desk:" ,  as.matrix(getDesksUI())),
    uiOutput("choose_Product"), #this is dynamically created UI
    uiOutput("choose_File1"), #this is dynamically created UI
    uiOutput("choose_Term1"), #this is dynamically created UI  ....

Here is my Server.R

shinyServer(function(input, output,session) {

  #this is dynamic UI
  output$choose_Product <- renderUI({
    selectInput("Product", "Product:", as.list(getProductUI(input$Desk)))
  })

   #this is dynamic UI
  output$choose_File1 <- renderUI({
    selectInput("File1", "File 1:", as.list(getFileUI(input$Desk, input$Product)))
  })

  #this is dynamic UI and I want it to run before the Observe function so the call
  # to getTerm1UI(input$Desk, input$Product, input$File1) has non-null parameters
  output$choose_Term1 <- renderUI({
    print("Rendering UI for TERM")
    print(paste(input$Desk," ", input$Product, " ", input$File1,sep=""))
    selectInput("Term1", "Term:", getTerm1UI(input$Desk, input$Product, input$File1))
  })

This is my observe function and it runs before the input$Product and input$File1 are populated so I get an error because they are both NULL.  But I need to use the input from the UI.

   observe({
    print("in observe")
    print(input$Product)
    max_plots<-length(getTerm2UI(input$Desk, input$Product, input$File1))
    #max_plots<-5
            # Call renderPlot for each one. Plots are only actually generated when they
            # are visible on the web page.
            for (i in 1:max_plots )   {
              # Need local so that each item gets its own number. Without it, the value
              # of i in the renderPlot() will be the same across all instances, because
              # of when the expression is evaluated.
              local({
               my_i <- i
                plotname <- paste("plot", my_i, sep="")
                output[[plotname]] <- renderPlot({
                  plot(1:my_i, 1:my_i,
                       xlim = c(1, max_plots ),
                       ylim = c(1, max_plots ),
                        main = paste("1:", my_i, ". n is ", input$n, sep = "") )
                })
              })
            }##### End FoR Loop
 },priority = -1000)

Any idea how to get the input$Product and input$File1 to be populated BEFORE observe runs?

Thank you.

Body:
We'd need an MRE to provide a working answer, but, assuming you need input$Product and input$File1, but do not want to take a dependency on them, only on input$Desk, you could:

observe({

  product <- isolate(input$Product)
  file1 <- isolate(input$File1)

  print("in observe")
  print(product)
  max_plots<-length(getTerm2UI(input$Desk, product, file1))
  for (i in 1:max_plots )   {
    # ...
  }
})

this is probably effectively equivalent to an observeEvent(input$Desk, ....), but might offer more flexibility.


问:
PHP function - Call self with same (variable number) arguments
I have a PHP function that can take a variable number of arguments (and I use func_get_args() to process them)

```<code>class Test {

    private $ting = FALSE;

    public function test() {
        $args = func_get_args();
        if ($this->ting) {
            var_dump($args);
        } else {
            $this->ting = TRUE;
            $this->test($args); //I want to call the function again using the same arguments. (this is pseudo-code)
        }
    }

}
</code>```

This function is not recursive (the "$ting" variable prevents it from going more than once).

I want test() to call itself using the same arguments it was given. So for example:
Test->test("a", "b", "c"); would output the following:

array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" }

答:
For anyone who is looking for just a simple answer to the question in the title, this will call the current class method with the same arguments that were passed to it:

```<code>call_user_func_array([ $this, __FUNCTION__ ], func_get_args());
</code>```

Or if it's a simple function (not a method within a class), you can do this:

```<code>call_user_func_array(__FUNCTION__, func_get_args());
</code>```

Body:
I have a PHP function that can take a variable number of arguments (and I use func_get_args() to process them)

class Test {

    private $ting = FALSE;

    public function test() {
        $args = func_get_args();
        if ($this->ting) {
            var_dump($args);
        } else {
            $this->ting = TRUE;
            $this->test($args); //I want to call the function again using the same arguments. (this is pseudo-code)
        }
    }

}

This function is not recursive (the "$ting" variable prevents it from going more than once).

I want test() to call itself using the same arguments it was given. So for example:
Test->test("a", "b", "c"); would output the following:

array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" }

Body:
For anyone who is looking for just a simple answer to the question in the title, this will call the current class method with the same arguments that were passed to it:

call_user_func_array([ $this, __FUNCTION__ ], func_get_args());

Or if it's a simple function (not a method within a class), you can do this:

call_user_func_array(__FUNCTION__, func_get_args());


问:
App development for HP Slate (Slate, Windows tablet)
I was wondering how the SDK is or if there is one for the HP Slate.

Would the apps be better off as a WPF app or a Silverlight app running off a browser on the Slate machines?

I understand that it's just a Windows 7 tablet, but I'm not sure if there are any differences.

答: You should look at the Native Extensions for Silverlight.</p>


问:
Excluding files with SevenZipSharp in Code
I'm currently on a little project where I have to define several paths that need to be compressed into one single zip-file.

Now the following case: One of those paths is a directory, which should be compressed recursively (including all files and sub-folders it contains). Before I compress, I check several things including permissions.
If the current user, which wants to compress, doesn't have the permission to a file or folder it should be excluded.

Now how can I exclude several files and directories from compressing in recursive mode?

I already tried something like this, but the arguement seems to exist only in cmd.

```<code>compressor.CustomParameters.Add("-x", "@C:\\Users\\******\\Desktop\\exclude.txt");
</code>```

答:
I found that SevenZipSharp can exclude files:</p>

```<code>SevenZipCompressor sevenZipCompressor = new SevenZipCompressor();
sevenZipCompressor.ModifyArchive(archiveName, dictionary);
// string archiveName: archive name
// Dictionary<int Index, string NewFileName>: NewFileName or Null value to delete the corresponding index.
</code>```

Body:
I'm currently on a little project where I have to define several paths that need to be compressed into one single zip-file.

Now the following case: One of those paths is a directory, which should be compressed recursively (including all files and sub-folders it contains). Before I compress, I check several things including permissions.
If the current user, which wants to compress, doesn't have the permission to a file or folder it should be excluded.

Now how can I exclude several files and directories from compressing in recursive mode?

I already tried something like this, but the arguement seems to exist only in cmd.

compressor.CustomParameters.Add("-x", "@C:\\Users\\******\\Desktop\\exclude.txt");

Body:
I found that SevenZipSharp can exclude files:

SevenZipCompressor sevenZipCompressor = new SevenZipCompressor();
sevenZipCompressor.ModifyArchive(archiveName, dictionary);
// string archiveName: archive name
// Dictionary<int Index, string NewFileName>: NewFileName or Null value to delete the corresponding index.


问:
Keen.IO - Bucketing results by numeric value rather than time / Histogram
Working with the Keen.io API,
I have an event with a numeric parameter, and would like to bucketize the results over the range of values of the parameter.  For example, session-duration: I'd like to count the number of session durations which occur in each of say 20 buckets over the range of the values.  Another way to look at this would be to produce a histogram of data.</p>

答:
There's a histogram recipe that could be adapted to create the buckets over a range view that you're looking for. The recipe uses Keen IO’s JavaScript data visualization library:

The code is located in this GitHub gist: https://gist.github.com/dustinlarimer/6b928c48abf803109ede.


问:
Jenkins - Unexpected executor death
I see all my executors frequently changing to Dead state in one of my Jenkins slave machine(Windows 2008 R2 SP2).

Jenkins ver. 1.651.3

I have restarted Jenkins server as well as the service.

error logs-

```<code>Unexpected executor death
java.io.IOException: Failed to create a temporary file in /var/lib/jenkins/jobs/ABCD/jobs/EFGH/jobs/Build
    at hudson.util.AtomicFileWriter.<init>(AtomicFileWriter.java:68)
    at hudson.util.AtomicFileWriter.<init>(AtomicFileWriter.java:55)
    at hudson.util.TextFile.write(TextFile.java:118)
    at hudson.model.Job.saveNextBuildNumber(Job.java:293)
    at hudson.model.Job.assignBuildNumber(Job.java:351)
    at hudson.model.Run.<init>(Run.java:284)
    at hudson.model.AbstractBuild.<init>(AbstractBuild.java:167)
    at hudson.model.Build.<init>(Build.java:92)
    at hudson.model.FreeStyleBuild.<init>(FreeStyleBuild.java:34)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at jenkins.model.lazy.LazyBuildMixIn.newBuild(LazyBuildMixIn.java:175)
    at hudson.model.AbstractProject.newBuild(AbstractProject.java:1018)
    at hudson.model.AbstractProject.createExecutable(AbstractProject.java:1209)
    at hudson.model.AbstractProject.createExecutable(AbstractProject.java:144)
    at hudson.model.Executor$1.call(Executor.java:364)
    at hudson.model.Executor$1.call(Executor.java:346)
    at hudson.model.Queue._withLock(Queue.java:1365)
    at hudson.model.Queue.withLock(Queue.java:1230)
    at hudson.model.Executor.run(Executor.java:346)
Caused by: java.io.IOException: Permission denied
    at java.io.UnixFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:1006)
    at java.io.File.createTempFile(File.java:1989)
    at hudson.util.AtomicFileWriter.<init>(AtomicFileWriter.java:66)
    ... 21 more
</code>```

I see this error log in my slave machine

```<code>INFO: File download attempt 1
Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient downloadFileToStreams
INFO: File download attempt 1
Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.ws.runtime.client.SOAPService executeSOAPRequestInternal
INFO: SOAP method='UpdateLocalVersion', status=200, content-length=367, server-wait=402 ms, parse=0 ms, total=402 ms, throughput=913 B/s, gzip
Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient downloadFileToStreams
INFO: File download attempt 1
Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient downloadFileToStreams
INFO: File download attempt 1
Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient downloadFileToStreams
INFO: File download attempt 1
</code>```

答:
How long are the real job names for ABCD and EFGH?

I've run into the 260 character maximum path length with Jenkins on Windows 2008 R2 before.

Title: Jenkins - Unexpected executor death

Body:
I see all my executors frequently changing to Dead state in one of my Jenkins slave machine(Windows 2008 R2 SP2).

Jenkins ver. 1.651.3

I have restarted Jenkins server as well as the service.

error logs-

Unexpected executor death
java.io.IOException: Failed to create a temporary file in /var/lib/jenkins/jobs/ABCD/jobs/EFGH/jobs/Build
    at hudson.util.AtomicFileWriter.<init>(AtomicFileWriter.java:68)
    at hudson.util.AtomicFileWriter.<init>(AtomicFileWriter.java:55)
    at hudson.util.TextFile.write(TextFile.java:118)
    at hudson.model.Job.saveNextBuildNumber(Job.java:293)
    at hudson.model.Job.assignBuildNumber(Job.java:351)
    at hudson.model.Run.<init>(Run.java:284)
    at hudson.model.AbstractBuild.<init>(AbstractBuild.java:167)
    at hudson.model.Build.<init>(Build.java:92)
    at hudson.model.FreeStyleBuild.<init>(FreeStyleBuild.java:34)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at jenkins.model.lazy.LazyBuildMixIn.newBuild(LazyBuildMixIn.java:175)
    at hudson.model.AbstractProject.newBuild(AbstractProject.java:1018)
    at hudson.model.AbstractProject.createExecutable(AbstractProject.java:1209)
    at hudson.model.AbstractProject.createExecutable(AbstractProject.java:144)
    at hudson.model.Executor$1.call(Executor.java:364)
    at hudson.model.Executor$1.call(Executor.java:346)
    at hudson.model.Queue._withLock(Queue.java:1365)
    at hudson.model.Queue.withLock(Queue.java:1230)
    at hudson.model.Executor.run(Executor.java:346)
Caused by: java.io.IOException: Permission denied
    at java.io.UnixFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:1006)
    at java.io.File.createTempFile(File.java:1989)
    at hudson.util.AtomicFileWriter.<init>(AtomicFileWriter.java:66)
    ... 21 more

I see this error log in my slave machine

INFO: File download attempt 1
Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient downloadFileToStreams
INFO: File download attempt 1
Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.ws.runtime.client.SOAPService executeSOAPRequestInternal
INFO: SOAP method='UpdateLocalVersion', status=200, content-length=367, server-wait=402 ms, parse=0 ms, total=402 ms, throughput=913 B/s, gzip
Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient downloadFileToStreams
INFO: File download attempt 1
Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient downloadFileToStreams
INFO: File download attempt 1
Oct 17, 2017 10:32:00 AM com.microsoft.tfs.core.clients.versioncontrol.VersionControlClient downloadFileToStreams
INFO: File download attempt 1


问:
How to get rid of or change a storyboard created segue programatically
I have a segue from one view controller to another, which was created in the storyboard of my project. I'm wondering if there is a way to change or get rid of that segue through code. Thanks, using Xcode 9 Swift 4.</p>

答:
Apparently it's not possible... look at the answer on this post. And the documentation says this about creating segues:

"You do not create segue objects directly. Instead, the storyboard runtime creates them when it must perform a segue between two view controllers."

Although it's not about changing or deleting the segue, I think it's the same logic.

If you just want to avoid the segue to happen you can do that inside "shouldPerformSegue" (like vacawama said in the comments):

```<code>override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
    if identifier == "aSegueIWantToDisable" {
        return false
    }
    return true
}
</code>```

Body:
Apparently it's not possible... look at the answer on this post. And the documentation says this about creating segues:

"You do not create segue objects directly. Instead, the storyboard runtime creates them when it must perform a segue between two view controllers."

Although it's not about changing or deleting the segue, I think it's the same logic.

If you just want to avoid the segue to happen you can do that inside "shouldPerformSegue" (like vacawama said in the comments):

override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
    if identifier == "aSegueIWantToDisable" {
        return false
    }
    return true
}


问:
Konva JS. Change Image position, rotate
I'm adding an image.

```<code>circle = new Image ();
circle.src = '/img/logo.png';
circle.onload = function () {
     anyimage = new Konva.Image ({
          x: 150,
          y: 150,
          image: circle,
          width: 106,
          height: 118
     });
     layer.add (anyimage);
     stage.add (layer);
};
</code>```

How to get and change the position and angle of this picture?
How to change these settings later. By events. For example, clicking on the buttons.
Method this.setX(),this.rotare(), this.x= not work for image obj.

答:
Solution. Need use anyimage obj. Not cirle.</p>

```<code><script src="https://cdn.rawgit.com/konvajs/konva/1.3.0/konva.js"></script>
<button onclick='rotate_image()'>rotate_image</button>
<button onclick='setPos_image()'>rotsetPos_imageate_image</button>
<div id="container"></div>

var stage = new Konva.Stage({
                  container: 'container',  // индификатор div контейнера
                  width: 500,
                  height: 500
            });

            var layer = new Konva.Layer();

           circle = new Image();
           circle.src = 'https://im0-tub-ru.yandex.net/i?id=caa07f7c7eb5b2788719c85cd6028d23&n=13';
            circle.onload = function() {
                anyimage = new Konva.Image({
                x: 10,
                y: 10,
                image: circle,
                width: 106,
                height: 118
              });

              layer.add(anyimage);
              stage.add(layer);
             };

function rotate_image(){
  anyimage.rotate(45);
              stage.draw();
              console.log('loaded');
}

function setPos_image(){
 //code for change x,y coord of 'circle' obj
  anyimage.setX(45);
              stage.draw();
              console.log('loaded');
}
</code>```

Title: Konva JS. Change Image position, rotate

Body:
I'm adding an image.

circle = new Image ();
circle.src = '/img/logo.png';
circle.onload = function () {
     anyimage = new Konva.Image ({
          x: 150,
          y: 150,
          image: circle,
          width: 106,
          height: 118
     });
     layer.add (anyimage);
     stage.add (layer);
};

How to get and change the position and angle of this picture?
How to change these settings later. By events. For example, clicking on the buttons.
Method this.setX(),this.rotare(), this.x= not work for image obj.

Body:
Solution. Need use anyimage obj. Not cirle.

<script src="https://cdn.rawgit.com/konvajs/konva/1.3.0/konva.js"></script>
<button onclick='rotate_image()'>rotate_image</button>
<button onclick='setPos_image()'>rotsetPos_imageate_image</button>
<div id="container"></div>

var stage = new Konva.Stage({
                  container: 'container',  // индификатор div контейнера
                  width: 500,
                  height: 500
            });

            var layer = new Konva.Layer();

           circle = new Image();
           circle.src = 'https://im0-tub-ru.yandex.net/i?id=caa07f7c7eb5b2788719c85cd6028d23&n=13';
            circle.onload = function() {
                anyimage = new Konva.Image({
                x: 10,
                y: 10,
                image: circle,
                width: 106,
                height: 118
              });

              layer.add(anyimage);
              stage.add(layer);
             };

function rotate_image(){
  anyimage.rotate(45);
              stage.draw();
              console.log('loaded');
}

function setPos_image(){
 //code for change x,y coord of 'circle' obj
  anyimage.setX(45);
              stage.draw();
              console.log('loaded');
}


问:
Stripping extension in a for loop
I am attempting to strip the .csv extension so that the file saves only as name.xslx instead of name.csv.xlsx but this does not seem to be working. I would appreciate some help. Thank you.</p>

```<code>import os
import glob
import csv
import openpyxl
import os.path

#convert the csv to xslx
for csvfile in glob.glob(os.path.join('.', '*.csv')):
    wb = openpyxl.Workbook()
    ws = wb.active
    with open(csvfile, 'rb') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader, start = 1):
            for c, val in enumerate(row, start = 1):
                ws.cell(row = r, column = c).value = val
    base = os.path.basename(csvfile)
    wb.save(base + '.xlsx')
</code>```

答:
Because os.path.basename doesn't do what you think:

```<code>>>> csvfile = "/path/to/my_file.csv"
>>> os.path.basename(csvfile)
'my_file.csv'
</code>```

You could use os.path.splitext:

```<code>>>> os.path.splitext(csvfile)
('/path/to/my_file', '.csv')
</code>```

Note bad, but a little unweildy. Personally, I've come to prefer pathlib:

```<code>>>> import pathlib
>>> p = pathlib.Path(csvfile)
>>> p
PosixPath('/path/to/my_file.csv')
</code>```

It has a very nice OOP interface:

```<code>>>> p.name
'my_file.csv'
>>> p.suffix
'.csv'
>>> p.with_suffix('.xlsx')
PosixPath('/path/to/my_file.xlsx')
</code>```

You can usually work directly with the pathlib.Path object, you can always get the string, though, if that is what your third-party library expects:

```<code>>>> str(p.with_suffix('.xlsx'))
'/path/to/my_file.xlsx'
</code>```

Title: Stripping extension in a for loop

Body:
I am attempting to strip the .csv extension so that the file saves only as name.xslx instead of name.csv.xlsx but this does not seem to be working. I would appreciate some help. Thank you.

import os
import glob
import csv
import openpyxl
import os.path

#convert the csv to xslx
for csvfile in glob.glob(os.path.join('.', '*.csv')):
    wb = openpyxl.Workbook()
    ws = wb.active
    with open(csvfile, 'rb') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader, start = 1):
            for c, val in enumerate(row, start = 1):
                ws.cell(row = r, column = c).value = val
    base = os.path.basename(csvfile)
    wb.save(base + '.xlsx')

Body:
Because os.path.basename doesn't do what you think:

>>> csvfile = "/path/to/my_file.csv"
>>> os.path.basename(csvfile)
'my_file.csv'

You could use os.path.splitext:

>>> os.path.splitext(csvfile)
('/path/to/my_file', '.csv')

Note bad, but a little unweildy. Personally, I've come to prefer pathlib:

>>> import pathlib
>>> p = pathlib.Path(csvfile)
>>> p
PosixPath('/path/to/my_file.csv')

It has a very nice OOP interface:

>>> p.name
'my_file.csv'
>>> p.suffix
'.csv'
>>> p.with_suffix('.xlsx')
PosixPath('/path/to/my_file.xlsx')

You can usually work directly with the pathlib.Path object, you can always get the string, though, if that is what your third-party library expects:

>>> str(p.with_suffix('.xlsx'))
'/path/to/my_file.xlsx'


问:
&& is showing as unexpected token
I'm facing 'Unexpected token' error in if-else condition using &&. There's no any other error can be seen.

```<code>keyCode==KeyEvent.KEYCODE_BACK) && webViewsupport.canGoBack
</code>```

I'm not able to understand that why it's showing Unexpected token here for using &&.

```<code>import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class Support extends AppCompatActivity {
    WebView webViewsupport;
    ProgressBar progressBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_support);

        webViewsupport = (WebView) findViewById(R.id.webView);
        progressBar = (ProgressBar)findViewById(R.id.progressBar2);

        webViewsupport.setWebViewClient(new myWebClient());
        webViewsupport.getSettings().setJavaScriptEnabled(true);
        webViewsupport.loadUrl("https://example.com");

    }
    public class myWebClient extends WebViewClient{
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return super.shouldOverrideUrlLoading(view, url);

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK) && webViewsupport.canGoBack(){
            webViewsupport.goBack();
        }
        return super.onKeyDown(keyCode, event);
    }
}
</code>```

This is screenshot

答:
You need to add  the whole condition in () :</p>

```<code>public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode==KeyEvent.KEYCODE_BACK && webViewsupport.canGoBack()){
        webViewsupport.goBack();
    }
    return super.onKeyDown(keyCode, event);
}
</code>```

Title: && is showing as unexpected token

Body:
I'm facing 'Unexpected token' error in if-else condition using &&. There's no any other error can be seen.

keyCode==KeyEvent.KEYCODE_BACK) && webViewsupport.canGoBack

I'm not able to understand that why it's showing Unexpected token here for using &&.

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class Support extends AppCompatActivity {
    WebView webViewsupport;
    ProgressBar progressBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_support);

        webViewsupport = (WebView) findViewById(R.id.webView);
        progressBar = (ProgressBar)findViewById(R.id.progressBar2);

        webViewsupport.setWebViewClient(new myWebClient());
        webViewsupport.getSettings().setJavaScriptEnabled(true);
        webViewsupport.loadUrl("https://example.com");

    }
    public class myWebClient extends WebViewClient{
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return super.shouldOverrideUrlLoading(view, url);

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_BACK) && webViewsupport.canGoBack(){
            webViewsupport.goBack();
        }
        return super.onKeyDown(keyCode, event);
    }
}

This is screenshot

Body:
You need to add  the whole condition in () :

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode==KeyEvent.KEYCODE_BACK && webViewsupport.canGoBack()){
        webViewsupport.goBack();
    }
    return super.onKeyDown(keyCode, event);
}