问:
How to output a consoles log to another file as regular text
I'm trying to print the result of my console.log to another .txt file, how would I make this happen? this is what my console.log looks like this: https://imgur.com/o2Vo471

I'm wanting this printed as regular text to an output file e.g 'output.txt'

答:
I recommend to use Winston to achieve this.
You can set up Winston Transports to output in file winston.add(winston.transports.File, options)

Or if you don't wanna add any npm modules to your app you can just do this

```<code>var fs = require('fs');

module.exports = function(text) {
  fs.appendFile('output.txt', text + '\n', function (err) {
    if (err) throw err;
  });
};
</code>```

And save this to a file in your project directory, for example NameOfYourFile.js.

Then you can just require it in a file that you wanna make output from

```<code>var loger = require('./NameOfYourFile');

loger('Logs');
loger('Output');
loger('Working');
</code>```

And just use loger instead of console.log. You also can easily rename it.

TypeScript version

First, install node modules

npm install @types/node --save-dev

Then create a file for your module, for example, NameOfYourFile.ts

```<code>import * as fs from 'fs';
export default function(text) {
  fs.appendFile('output.txt', text + '\n', function (err) {
   if (err) throw err;
 });
};
</code>```

Then you can import it like this

```<code>import loger from './NameOfYourFile';

loger('Logs');
loger('Output');
loger('Working');
</code>```

Body:
I recommend to use Winston to achieve this.
You can set up Winston Transports to output in file winston.add(winston.transports.File, options)

Or if you don't wanna add any npm modules to your app you can just do this

var fs = require('fs');

module.exports = function(text) {
  fs.appendFile('output.txt', text + '\n', function (err) {
    if (err) throw err;
  });
};

And save this to a file in your project directory, for example NameOfYourFile.js.

Then you can just require it in a file that you wanna make output from

var loger = require('./NameOfYourFile');

loger('Logs');
loger('Output');
loger('Working');

And just use loger instead of console.log. You also can easily rename it.

TypeScript version

First, install node modules

npm install @types/node --save-dev

Then create a file for your module, for example, NameOfYourFile.ts

import * as fs from 'fs';
export default function(text) {
  fs.appendFile('output.txt', text + '\n', function (err) {
   if (err) throw err;
 });
};

Then you can import it like this

import loger from './NameOfYourFile';

loger('Logs');
loger('Output');
loger('Working');


来源: stackexchange

问:
Adding a table row in jQuery
I'm using jQuery to add an additional row to a table as the last row.

I have done it this way:

```<code>$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');
</code>```

Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)? Is there a different way to do it?

答:
For the best solution posted here, if there's a nested table on the last row, the new row will be added to the nested table instead of the main table. A quick solution (considering tables with/without tbody and tables with nested tables):

```<code>function add_new_row(table, rowcontent) {
    if ($(table).length > 0) {
        if ($(table + ' > tbody').length == 0) $(table).append('<tbody />');
        ($(table + ' > tr').length > 0) ? $(table).children('tbody:last').children('tr:last').append(rowcontent): $(table).children('tbody:last').append(rowcontent);
    }
}
</code>```

Usage example:

```<code>add_new_row('#myTable','<tr><td>my new row</td></tr>');
</code>```

OwnerDisplayName: Darryl Hein

ContentLicense: CC BY-SA 4.0

Title: Adding a table row in jQuery

Body:
I'm using jQuery to add an additional row to a table as the last row.

I have done it this way:

$('#myTable').append('
my data	more data
');

Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)? Is there a different way to do it?

LastEditorDisplayName: Darryl Hein

Body:
For the best solution posted here, if there's a nested table on the last row, the new row will be added to the nested table instead of the main table. A quick solution (considering tables with/without tbody and tables with nested tables):

function add_new_row(table, rowcontent) {
    if ($(table).length > 0) {
        if ($(table + ' > tbody').length == 0) $(table).append('<tbody />');
        ($(table + ' > tr').length > 0) ? $(table).children('tbody:last').children('tr:last').append(rowcontent): $(table).children('tbody:last').append(rowcontent);
    }
}

Usage example:

add_new_row('#myTable','<tr><td>my new row</td></tr>');

ContentLicense: CC BY-SA 3.0


问:
Pulling Quantity Pricing through Suitescript?
Looking to see if anyone has an example to pull Quantity Pricing from an item record with SuiteScript? I haven't been able to find anything online and don't even know how that would build out if it was SuiteScripted (since the qty is different per item). Anyone have anything that can show me how to do this?</p>

答:
Part of the issue with supplying sample code is that the code will be different depending on whether you also have multiple currencies available.

If you only have one currency you can get the prices for the price breaks as follows, The endpriceX values indicate the last quantity the associated price is applicable to:

```<code>strprice1 = myitem.getFieldValue('pricequantity1');
var valprice1 = myitem.getLineItemMatrixValue('price', 'price', lineno, 1);
valprice1 = parseFloat(valprice1);

var strprice2 = myitem.getFieldValue('pricequantity2');
var valprice2 = myitem.getLineItemMatrixValue('price', 'price', lineno, 2);
var endprice1 = parseInt(strprice2) - 1;
valprice2 = parseFloat(valprice2);

var strprice3 = myitem.getFieldValue('pricequantity3');
var endprice2 = parseInt(strprice3) - 1;
var valprice3 = myitem.getLineItemMatrixValue('price', 'price', lineno, 3);
valprice3 = parseFloat(valprice3);

var strprice4 = myitem.getFieldValue('pricequantity4');
var endprice3 = parseInt(strprice4) - 1;
var valprice4 = myitem.getLineItemMatrixValue('price', 'price', lineno, 4);
valprice4 = parseFloat(valprice4);

var strprice5 = myitem.getFieldValue('pricequantity5');
var endprice4 = parseInt(strprice5) - 1;
var valprice5 = myitem.getLineItemMatrixValue('price', 'price', lineno, 5);
valprice5 = parseFloat(valprice5);
</code>```

Body:
Part of the issue with supplying sample code is that the code will be different depending on whether you also have multiple currencies available.

If you only have one currency you can get the prices for the price breaks as follows, The endpriceX values indicate the last quantity the associated price is applicable to:

strprice1 = myitem.getFieldValue('pricequantity1');
var valprice1 = myitem.getLineItemMatrixValue('price', 'price', lineno, 1);
valprice1 = parseFloat(valprice1);

var strprice2 = myitem.getFieldValue('pricequantity2');
var valprice2 = myitem.getLineItemMatrixValue('price', 'price', lineno, 2);
var endprice1 = parseInt(strprice2) - 1;
valprice2 = parseFloat(valprice2);

var strprice3 = myitem.getFieldValue('pricequantity3');
var endprice2 = parseInt(strprice3) - 1;
var valprice3 = myitem.getLineItemMatrixValue('price', 'price', lineno, 3);
valprice3 = parseFloat(valprice3);

var strprice4 = myitem.getFieldValue('pricequantity4');
var endprice3 = parseInt(strprice4) - 1;
var valprice4 = myitem.getLineItemMatrixValue('price', 'price', lineno, 4);
valprice4 = parseFloat(valprice4);

var strprice5 = myitem.getFieldValue('pricequantity5');
var endprice4 = parseInt(strprice5) - 1;
var valprice5 = myitem.getLineItemMatrixValue('price', 'price', lineno, 5);
valprice5 = parseFloat(valprice5);


问:
Bootstrap issue with Wordpress Menu
I have integrated the bootstrap Navbar with my Wordpress theme I am developing. However my menu is squished together and there is no spacing or design within the ul & li tags. I have tried everything possible to make this work properly with bootstrap but I am lost.

Can anyone point me in the right direction to fix this issue or possibly give me a solution? Thank you for any help.

live site: https://publifiedlabs.com/sandbox-theme/

Here is my block of code

```<code>           <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
            <div class="container-fluid">
                <div class="navbar-header">
                    <a class="navbar-brand" href="<?php echo home_url( '/' ); ?>">
                    <img src="https://publifiedlabs.com/wp-content/uploads/2016/04/main-logo.png" alt="<?php //get alt tag for image ?>">
                    </a>
                </div> <!-- ./navbar-header -->
                    <div class="search-form-container">
                    <?php get_search_form(); ?>
                </div>
                <!-- Begin wp_nav_menu -->
                        <div class="navbar navbar-nav float-md-right" id="navbarSupportedContent">
                        <?php   // This brings in the menu in the proper style with bootstrap
                                    wp_nav_menu( array(
                                        'theme_location'    =>'primary',
                                        //'depth'             => 2,
                                        'container'         => '',
                                        'fallback_cb'       => '',
                                        //'menu_class'        => 'navbar-nav mr-auto',
                                        'items_wrap'        => '<ul class="navbar-nav">%3$s</ul>',
                                        'walker'            => new pbf_walker_nav_primary(),
                                        'echo'              => true
                                        )
                                    ); ?>
            </div> <!-- /.container-fluid -->
        </nav>
</code>```

Here is the outputed HTML:

```<code><nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                    <div class="container-fluid">
                        <div class="navbar-header">
                            <a class="navbar-brand" href="https://publifiedlabs.com/sandbox-theme/">
                            <img src="https://publifiedlabs.com/wp-content/uploads/2016/04/main-logo.png" alt="">
                            </a>
                        </div> <!-- ./navbar-header -->
                            <div class="search-form-container">
                            <form role="search" method="get" action="https://publifiedlabs.com/sandbox-theme/">
    <input type="search" class="form-control" placeholder="Search" value="" name="s" title="Search">
</form>                        </div>
                        <!-- Begin wp_nav_menu -->
                                <div class="navbar navbar-nav float-md-right" id="navbarSupportedContent">
                                    <ul class="navbar-nav"><li id="menu-item-16" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-home current-menu-item page_item page-item-6 current_page_item active menu-item-16 nav-item"><a href="https://publifiedlabs.com/sandbox-theme/">Home</a></li>
    <li id="menu-item-15" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children dropdown menu-item-15 nav-item"><a href="https://publifiedlabs.com/sandbox-theme/about-us/" class="dropdown-toggle" data-toggle="dropdown">About <b class="caret"></b></a>
    <ul class="dropdown-menu depth_0 nav navbar-nav">
        <li id="menu-item-35" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-35 nav-item"><a href="#">Contact</a></li>
    </ul>
    </li>
    <li id="menu-item-32" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-32 nav-item"><a href="https://publifiedlabs.com/sandbox-theme/blog/">Blog</a></li>
    </ul>                    </div> <!-- /.container-fluid -->
                    </div></nav>
</code>```

Image of Menu Issue:

答:
Below is the answer to the problem from this post.

All I did was add the piece of code below in my functions.php file.

```<code>// This controls the <a></a> class
function add_menuclass($ulclass) {
    return preg_replace('/<a /', '<a class="nav-link"', $ulclass);
 }
 add_filter('wp_nav_menu','add_menuclass');
</code>```

Reference Link: How to add class to link in wp_nav_menu?

Title: Bootstrap issue with Wordpress Menu

Body:
I have integrated the bootstrap Navbar with my Wordpress theme I am developing. However my menu is squished together and there is no spacing or design within the ul & li tags. I have tried everything possible to make this work properly with bootstrap but I am lost.

Can anyone point me in the right direction to fix this issue or possibly give me a solution? Thank you for any help.

live site: https://publifiedlabs.com/sandbox-theme/

Here is my block of code

                    <a class="navbar-brand" href="<?php echo home_url( '/' ); ?>">
                    <img src="https://publifiedlabs.com/wp-content/uploads/2016/04/main-logo.png" alt="<?php //get alt tag for image ?>">

                    <?php get_search_form(); ?>

                        <?php   // This brings in the menu in the proper style with bootstrap
                                    wp_nav_menu( array(
                                        'theme_location'    =>'primary',
                                        //'depth'             => 2,
                                        'container'         => '',
                                        'fallback_cb'       => '',
                                        //'menu_class'        => 'navbar-nav mr-auto',
                                        'items_wrap'        => '
%3$s
',
                                        'walker'            => new pbf_walker_nav_primary(),
                                        'echo'              => true
                                        )
                                    ); ?>

Here is the outputed HTML:

                            <form role="search" method="get" action="https://publifiedlabs.com/sandbox-theme/">
    <input type="search" class="form-control" placeholder="Search" value="" name="s" title="Search">
</form>

Home

About

Contact

Blog

Image of Menu Issue:

Body:
Below is the answer to the problem from this post.

All I did was add the piece of code below in my functions.php file.

// This controls the <a></a> class
function add_menuclass($ulclass) {
    return preg_replace('/<a /', '<a class="nav-link"', $ulclass);
 }
 add_filter('wp_nav_menu','add_menuclass');

Reference Link: How to add class to link in wp_nav_menu?


问:
Aren't all errors caught during compilation regardless of typing (static vs. dynamic) in a compiled language?
Below is an answer explaining Dynamic vs. Static Typing.

I'm confused why this demonstrates Dynamic vs. Static typing as I thought all errors for compiled languages are caught during compilation anyway so it wouldn't matter whether it's statically or dynamically typed.

Maybe this is demonstrating that statically typed languages always raise errors before running and dynamic typing will always raise errors during execution regardless of it being compiled or interpreted?

Can someone explain this more in depth?

Here is an example contrasting how Python (dynamically typed) and Go
  (statically typed) handle a type error:

```<code>def silly(a):
    if a > 0:
        print 'Hi'
    else:
        print 5 + '3'
</code>```

Python does type checking at run time, and therefore:

```<code>silly(2)
</code>```

Runs perfectly fine, and produces the expected output Hi. Error is only raised if the problematic line is hit:

```<code>silly(-1)
</code>```

Produces

```<code>TypeError: unsupported operand type(s) for +: 'int' and 'str'
</code>```

because the relevant line was actually executed.

Go on the other hand does type-checking at compile time:

```<code>package main

import ("fmt"
)

func silly(a int) {
  if (a > 0) {
      fmt.Println("Hi")
  } else {
      fmt.Println("3" + 5)
  }
}

func main() {
  silly(2)
}
</code>```

The above will not compile, with the following error:

```<code>invalid operation: "3" + 5 (mismatched types string and int)
</code>```

答:
Compiled <-> interpreted scale is completely orthogonal to the dynamic <-> static typing scale. (and potentially another orthogonal scale of compile-time type checked and runtime type-checked)

For example, you can compile the Python script from the example using Cython to a native binary. It will work exactly the same way, but it's going to be compiled. The Python script can be also type-checked ahead of time using mypy and be run using CPython which provides runtime type exceptions.

On the other hand, you can install a language with static types and an interactive shell (interpreter) and try a similar expression - you'll get a type error before the code executes. This part is slightly confusing, since to get a type error, you need to compile the code to some extent (process into AST and type check), but I don't think it matches the common definition of "compiled".

In summary, you can have compiled dynamically typed, compiled statically, interpreted dynamically typed, and interpreted statically typed. (And the linked example from the repl can be argued it's about strong typing - feel free to provide a better one)

Body:
Below is an answer explaining Dynamic vs. Static Typing.

I'm confused why this demonstrates Dynamic vs. Static typing as I thought all errors for compiled languages are caught during compilation anyway so it wouldn't matter whether it's statically or dynamically typed.

Maybe this is demonstrating that statically typed languages always raise errors before running and dynamic typing will always raise errors during execution regardless of it being compiled or interpreted?

Can someone explain this more in depth?

Here is an example contrasting how Python (dynamically typed) and Go
  (statically typed) handle a type error:

def silly(a):
    if a > 0:
        print 'Hi'
    else:
        print 5 + '3'

Python does type checking at run time, and therefore:

silly(2)

Runs perfectly fine, and produces the expected output Hi. Error is only raised if the problematic line is hit:

silly(-1)

Produces

TypeError: unsupported operand type(s) for +: 'int' and 'str'

because the relevant line was actually executed.

Go on the other hand does type-checking at compile time:

package main

import ("fmt"
)

func silly(a int) {
  if (a > 0) {
      fmt.Println("Hi")
  } else {
      fmt.Println("3" + 5)
  }
}

func main() {
  silly(2)
}

The above will not compile, with the following error:

invalid operation: "3" + 5 (mismatched types string and int)


问:
Consuming OData v4 services in .NET Core
I'm looking for nice alternatives for consuming OData V4 services in .NET Core.

What are the alternatives? The Microsoft.OData.Client doesn't have support yet as far as I know.

答: Yes. OData client supports .Net core since the version 7.4.0-beta. </p>


问:
Data entered offline does not synchronize when going back online
Some users report that they create offline content and when they go online they lose their data. They just disappear.

I do not know where to start, in my tests this does not occur.

Is there an authentication problem? I use today the form E-mail and password.

I'm using minSdkVersion 16 and compile 'com.google.firebase: firebase-auth: 10.2.1'

I mentioned Auth, why it is not clear how the firebase behaves when the user loses authentication. Let's assume that it loses authentication and inserts new data (after losing authentication), what does firebase do?

1 - Block the insertion - if this is the behavior, my problem will not be the tightening, because the data is inserted and I can see it in the APP.

2 - Does not block the insertion, but when it is online this data will be lost (it is my suspicion)

3 - Does not block the insertion, puts the insert in the queue and updates the base (this is what I hope, because if the user for an unexpected reason lose the offline authentication I will not have to authenticate again until it goes online).

答:
From the Firebase docs  docs, it says:

Any transactions that are performed while the app is offline, are
  queued. Once the app regains network connectivity, the transactions
  are sent to the Realtime Database server.

But then immediately after that Firebase issues a warning:

Even with persistence enabled, transactions are not persisted across
  app restarts. So you cannot rely on transactions done offline being
  committed to your Firebase Realtime Database. To provide the best user
  experience, your app should show that a transaction has not been saved
  into your Firebase Realtime Database yet, or make sure your app
  remembers them manually and executes them again after an app restart.

Now I'm not too sure the exact scenario your users are going through, but I do have a couple of suggestions on how to deal with this issue.

Firstly, since the chances of transactions being persisted when the device is offline and the app goes to the background are very low, you could just as well check for network connectivity before allowing user updates in your app. This is an easy way out of course, but it does the trick.

Also, you could go with Firebase's advice and attach a listener to every upload and mark the offline content as "x" (not a good choice admittedly) or something to indicate that the content is not uploaded yet, in your UI. Something similar to the WhatsApp clock icon that shows on messages that haven't been sent. Then when your app resumes or restarts, let it check for all unsent content and re-upload them.

Thirdly, just like in the second case, you can just put an error message on that content, but this time tell your users to resend them on restart.

I basically just summarized all that the docs said, but at least this should put you on the right path to fixing this.


问:
R: "label" a row based on conditions from another data.table
I have a data.table (A) that is over 100,000 rows long. There are 3 columns.

         chrom     start      end
     1:  chr1   6484847   6484896
     2:  chr1   6484896   6484945
     3:  chr1   6484945   6484994
     4:  chr1   6484994   6485043
     5:  chr1   6485043   6485092
    ---

183569:  chrX 106893605 106893654
183570:  chrX 106893654 106893703
183571:  chrX 106893703 106893752
183572:  chrX 106893752 106893801
183573:  chrX 106893801 106894256

I'd like to generate a new column named "gene" that provides a label for each row based annotations from another data.table which has ~90 rows (B). Seen below:

    chrom     start       end     gene
 1:  chr1   6484847   6521004     ESPN
 2:  chr1  41249683  41306124     KCNQ4
 3:  chr1  55464616  55474465     BSND
42:  chrX  82763268  82764775     POU3F4
43:  chrX 100600643 100603957     TIMM8A
44:  chrX 106871653 106894256     PRPS1

If the row start value in data.table A is within the row start and end values of data.table B I need the row in A to be labeled with the correct gene accordingly.

For example the resulting complete data.table A would be

         chrom     start      end   gene
     1:  chr1   6484847   6484896   ESPN
     2:  chr1   6484896   6484945   ESPN
     3:  chr1   6484945   6484994   ESPN
     4:  chr1   6484994   6485043   ESPN
     5:  chr1   6485043   6485092   ESPN
    ---

183569:  chrX 106893605 106893654   TIMM8A
183570:  chrX 106893654 106893703   TIMM8A
183571:  chrX 106893703 106893752   TIMM8A
183572:  chrX 106893752 106893801   TIMM8A
183573:  chrX 106893801 106894256   TIMM8A

I've attempted some nested loops to do this but that seems like it would take WAY too long. I think there must be a way to do this with the data.table package but I can't seem to figure it out.

Any and all suggestions would be greatly appreciated.

答:
While it's certainly possible to do this in base R (or potentially using data.table), I would highly recommend using GenomicRanges; it's a very powerful and flexible R/Bioconductor library that's been designed for these kind of tasks.

Here is an example using GenomicRanges::findOverlaps:

```<code># Sample data
df1 <- read.table(text =
    "chrom     start      end
     chr1   6484847   6484896
     chr1   6484896   6484945
     chr1   6484945   6484994
     chr1   6484994   6485043
     chr1   6485043   6485092", sep = "", header = T, stringsAsFactors = F);

df2 <- read.table(text =
    "chrom     start       end     gene
     chr1   6484847   6521004     ESPN
     chr1  41249683  41306124     KCNQ4
     chr1  55464616  55474465     BSND
     chrX  82763268  82764775     POU3F4
     chrX 100600643 100603957     TIMM8A
     chrX 106871653 106894256     PRPS1", sep = "", header = TRUE, stringsAsFactors = F);

# Convert to GRanges objects
gr1 <- with(df1, GRanges(chrom, IRanges(start = start, end = end)));
gr2 <- with(df2, GRanges(chrom, IRanges(start = start, end = end), gene = gene));

# Find features from gr1 that overlap with gr2
m <- findOverlaps(gr1, gr2);

# Add gene annotation as metadata to gr1
mcols(gr1)$gene[queryHits(m)] <- mcols(gr2)$gene[subjectHits(m)];
gr1;
#GRanges object with 5 ranges and 1 metadata column:
#      seqnames             ranges strand |        gene
#         <Rle>          <IRanges>  <Rle> | <character>
#  [1]     chr1 [6484847, 6484896]      * |        ESPN
#  [2]     chr1 [6484896, 6484945]      * |        ESPN
#  [3]     chr1 [6484945, 6484994]      * |        ESPN
#  [4]     chr1 [6484994, 6485043]      * |        ESPN
#  [5]     chr1 [6485043, 6485092]      * |        ESPN
#  -------
#  seqinfo: 1 sequence from an unspecified genome; no seqlengths
</code>```

Body:
While it's certainly possible to do this in base R (or potentially using data.table), I would highly recommend using GenomicRanges; it's a very powerful and flexible R/Bioconductor library that's been designed for these kind of tasks.

Here is an example using GenomicRanges::findOverlaps:

# Sample data
df1 <- read.table(text =
    "chrom     start      end
     chr1   6484847   6484896
     chr1   6484896   6484945
     chr1   6484945   6484994
     chr1   6484994   6485043
     chr1   6485043   6485092", sep = "", header = T, stringsAsFactors = F);

df2 <- read.table(text =
    "chrom     start       end     gene
     chr1   6484847   6521004     ESPN
     chr1  41249683  41306124     KCNQ4
     chr1  55464616  55474465     BSND
     chrX  82763268  82764775     POU3F4
     chrX 100600643 100603957     TIMM8A
     chrX 106871653 106894256     PRPS1", sep = "", header = TRUE, stringsAsFactors = F);

# Convert to GRanges objects
gr1 <- with(df1, GRanges(chrom, IRanges(start = start, end = end)));
gr2 <- with(df2, GRanges(chrom, IRanges(start = start, end = end), gene = gene));

# Find features from gr1 that overlap with gr2
m <- findOverlaps(gr1, gr2);

# Add gene annotation as metadata to gr1
mcols(gr1)$gene[queryHits(m)] <- mcols(gr2)$gene[subjectHits(m)];
gr1;
#GRanges object with 5 ranges and 1 metadata column:
#      seqnames             ranges strand |        gene
#         <Rle>          <IRanges>  <Rle> | <character>
#  [1]     chr1 [6484847, 6484896]      * |        ESPN
#  [2]     chr1 [6484896, 6484945]      * |        ESPN
#  [3]     chr1 [6484945, 6484994]      * |        ESPN
#  [4]     chr1 [6484994, 6485043]      * |        ESPN
#  [5]     chr1 [6485043, 6485092]      * |        ESPN
#  -------
#  seqinfo: 1 sequence from an unspecified genome; no seqlengths


问:
Have JS APIs return a polyfilled DOM node
I am using the <data> element in HTML, which has decent support, but not sufficient for my purposes. The only extra functionality in HTMLDataElement is a getter for value, which returns the respective attribute.

Of course this is trivial to implement, just use the following code (after feature detection, of course)

```<code>class HTMLDataElement extends HTMLElement {
    constructor() {
        super();
    }

    get value() {
        return this.getAttribute(`value`);
    }
}
</code>```

This works great. Only one problem: when using native APIs such as getElementById, querySelector, etc., the returned Node is not of instance HTMLDataElement. How can I make it so, if this is even possible?

To be clear, I'd like to be able to do document.querySelector('foo').value, which would act the same with or without browser support for <data>.

(I'm well aware that I can just use .getAttribute('value') instead of .value. The point is I don't want to.)

答:
After reaching out to Jonathan Neal* on Twitter, he provided a great example of how this can be done.

if (!this.HTMLDataElement) {
    this.HTMLDataElement = this.HTMLUnknownElement;

    const valueDescriptor = Object.getOwnPropertyDescriptor(HTMLDataElement.prototype, 'value');

    Object.defineProperty(
        HTMLDataElement.prototype,
        'value',
        valueDescriptor || {
            get() {
                return 'DATA' === this.nodeName && this.getAttribute('value');
            }
        }
    );
}

console.log('data:', document.querySelector('data').value);

console.log('xdata:', document.querySelector('xdata').value);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><data value="this should work">
<xdata value="this should not work"></code>```

* For the unfamiliar, Jonathan Neal is large contributor of PostCSS plugins, and has created many JavaScript polyfills himself.

Body:
I am using the <data> element in HTML, which has decent support, but not sufficient for my purposes. The only extra functionality in HTMLDataElement is a getter for value, which returns the respective attribute.

Of course this is trivial to implement, just use the following code (after feature detection, of course)

class HTMLDataElement extends HTMLElement {
    constructor() {
        super();
    }

    get value() {
        return this.getAttribute(`value`);
    }
}

This works great. Only one problem: when using native APIs such as getElementById, querySelector, etc., the returned Node is not of instance HTMLDataElement. How can I make it so, if this is even possible?

To be clear, I'd like to be able to do document.querySelector('foo').value, which would act the same with or without browser support for <data>.

(I'm well aware that I can just use .getAttribute('value') instead of .value. The point is I don't want to.)

Body:
After reaching out to Jonathan Neal* on Twitter, he provided a great example of how this can be done.

if (!this.HTMLDataElement) {
    this.HTMLDataElement = this.HTMLUnknownElement;

    const valueDescriptor = Object.getOwnPropertyDescriptor(HTMLDataElement.prototype, 'value');

    Object.defineProperty(
        HTMLDataElement.prototype,
        'value',
        valueDescriptor || {
            get() {
                return 'DATA' === this.nodeName && this.getAttribute('value');
            }
        }
    );
}

console.log('data:', document.querySelector('data').value);

console.log('xdata:', document.querySelector('xdata').value);

<data value="this should work">
<xdata value="this should not work">

* For the unfamiliar, Jonathan Neal is large contributor of PostCSS plugins, and has created many JavaScript polyfills himself.


问:
Printing items from a list in Python
I am trying to write a function in Python where I am given a list, l = [[2,3],[5,6],[4,8]], which contains other lists. I am supposed to print the first item in every list on one line with three spaces in between and the second item in every list in another line with also three spaces in between. I have made the following code - however it seems to print everything on one line, and I am not sure what I am doing wrong.

```<code>l = [[2,3],[5,6],[4,8]]
for item in l:
    print(item[0], end = '  ')
for obj in l:
    print(obj[1], end = '  ')
</code>```

答:
Just put a print statement in between!</p>

```<code>l=[[2,3],[4,5],[6,7]]
for item in l:
    print(item[0], end = '  ')
print()
for obj in l:
    print(obj[1], end = '  ')
</code>```

Title: Printing items from a list in Python

Body:
I am trying to write a function in Python where I am given a list, l = [[2,3],[5,6],[4,8]], which contains other lists. I am supposed to print the first item in every list on one line with three spaces in between and the second item in every list in another line with also three spaces in between. I have made the following code - however it seems to print everything on one line, and I am not sure what I am doing wrong.

l = [[2,3],[5,6],[4,8]]
for item in l:
    print(item[0], end = '  ')
for obj in l:
    print(obj[1], end = '  ')

Body:
Just put a print statement in between!

l=[[2,3],[4,5],[6,7]]
for item in l:
    print(item[0], end = '  ')
print()
for obj in l:
    print(obj[1], end = '  ')


问:
C++ standard library - when should I use it and when shouldn't I?
I was wondering how often people actually use much of the standard c++ library, particularly the stuff in the <algorithm> and <numeric> headers.  The text books seem to recommend them, but I haven't seen any of them used at all in various projects I've sifted through (coincidence?) and personally it seems easier to just write appropriate simple algorithms myself each time rather than memorize or consult a reference to these headers each time. Am just being lazy or stubborn?  Is there actually performance gains etc when using these libraries?

Thanks,

R

答:
A lot of existing C++ projects don't use the standard library because they were started before you could rely on the standard library being available -- I'm talking code that's got a release history going back ten to fifteen years, here.  I have also heard that some modern environments (for instance Android) still don't give you a complete C++ runtime, so if you need to be portable to those environments you still can't use it.

Another reason is that some extremely large programs (I have personal experience with the guts of Firefox, and I have heard that this is also true of OpenOffice) are built with exception support disabled, because it is fervently believed to cause performance problems (this may actually be true for MSVC++'s ABI and/or for programs of ludicrous size, such as the above two) -- but you can't use most of the C++ runtime if you do that.

It's frustrating, but that's the industry for ya.

ContentLicense: CC BY-SA 2.5


问:
Why an action is not defined in action-creator function in react-redux?
While trying to make a simple appointment app using react-redux, I get an error where one item (lastname) in the action is not defined. The other two items (firstname and id) are properly defined. Why would this action item be not defined while others are defined? I feel i am missing a key concept in react-redux. Can you explain why the action is not defined and how to correct it?
action-creator:

```<code>import { ADD_BOOKING, DELETE_BOOKING } from "../constants";

const uid = () => Math.random().toString(34)

export const addBooking=function (firstname,lastname){

    const action={
        type:ADD_BOOKING,
        payload:{firstname,
                lastname,
                id:uid()

        }
    }
console.log('action in addBooking',action);
return action;
}

export const deleteBooking = (id) => {
    const action = {
        type: DELETE_BOOKING,
        id: id
    };
    console.log("deleting in actions", action);
    return action;
};
</code>```

reducer:

```<code>import { ADD_BOOKING, DELETE_BOOKING} from "../constants";

const booking = action => {
    return {
        firstname: action.payload.firstname,
        lastname: action.payload.lastname,
        id: action.payload.id
    };
};

const removeById = (state = [], id) => {
    //filter those not clicked
    const bookings = state.filter(booking => booking.id !==id);
    console.log("new reduced bookings", bookings);
    return bookings;
};

const bookings = (state = [], action) => {
    let bookings = null;
    switch (action.type) {
        case ADD_BOOKING:
            bookings = [...state, booking(action)];
            console.log("bookings as state", bookings);
            return bookings;
        case DELETE_BOOKING:
            bookings = removeById(state, action.id);
            return bookings;

        default:
            return state;
    }
};
export {bookings};
</code>```

Console log:

Component (App.jsx):

```<code>import React, { Component } from "react";
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { addBooking, deleteBooking } from "../actions";
import { Header } from "./NavigationBar";
import { connect } from "react-redux";

class App extends Component {
  //Initialize the Component
  constructor(props) {
    super(props);
    this.state = {
      firstname: "",
      lastname: "",
      duedate: ""
    };
  }
  //add Booking
  addBooking() {
    this.props.addBooking(this.state.firstname);
    this.props.addBooking(this.state.lastname);

  }

  //delete Booking
  deleteBooking(id) {
    this.props.deleteBooking(id);
  }
  //render the bookings
  renderBookings() {
    //access our bookings

   const {bookings} = this.props;

    return (
      <ul className="list-group col-sm-4">
        { bookings.map(booking => {
            return (<li key={ booking.id } className="list-group item">
                      <div className="list-item">
                        { booking.firstname }
                      </div>
                      <div className="list-item">
                        { booking.lastname }
                      </div>

                      <div className="btn btn-danger" onClick={ () => this.deleteBooking(booking.id) }>
                        Cancel Booking

                      </div>
                    </li>)
          }) }
      </ul>)
  }
  render() {
    return (
      <div className="App">
        <Header />
        <div className="form-inline booking-form">
          <div className="form-group">
            <input
              className="form-control"
              placeholder="Enter First Name"
              onChange={event =>
                this.setState({
                  firstname: event.target.value
                })
              }
            />
            <input
              className="form-control"
              placeholder="Enter Last Name"
              onChange={event =>
                this.setState({
                  lastname: event.target.value
                })
              }
            />
            <input
              className="form-control"
              type="datetime-local"
              onChange={event =>
                this.setState({
                  duedate: event.target.value
                })
              }
            />

            <button
              type="button"
              className="btn btn-success"
              onClick={() => this.addBooking()}
            >
              Add Booking
            </button>
          </div>
        </div>
        {this.renderBookings()}
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    bookings: state
  };
}

export default connect(mapStateToProps, {
  addBooking,
  deleteBooking
})(App);
</code>```

答: You call your addBooking function with only one parameter, but you call it twice. It returns two actions with each values assigned to firstname. Instead, do this: this.props.addBooking(this.state.firstname, this.state.lastname);. That will solve your issue.

Body:
While trying to make a simple appointment app using react-redux, I get an error where one item (lastname) in the action is not defined. The other two items (firstname and id) are properly defined. Why would this action item be not defined while others are defined? I feel i am missing a key concept in react-redux. Can you explain why the action is not defined and how to correct it?
action-creator:

import { ADD_BOOKING, DELETE_BOOKING } from "../constants";

const uid = () => Math.random().toString(34)

export const addBooking=function (firstname,lastname){

    const action={
        type:ADD_BOOKING,
        payload:{firstname,
                lastname,
                id:uid()

        }
    }
console.log('action in addBooking',action);
return action;
}

export const deleteBooking = (id) => {
    const action = {
        type: DELETE_BOOKING,
        id: id
    };
    console.log("deleting in actions", action);
    return action;
};

reducer:

import { ADD_BOOKING, DELETE_BOOKING} from "../constants";

const booking = action => {
    return {
        firstname: action.payload.firstname,
        lastname: action.payload.lastname,
        id: action.payload.id
    };
};

const removeById = (state = [], id) => {
    //filter those not clicked
    const bookings = state.filter(booking => booking.id !==id);
    console.log("new reduced bookings", bookings);
    return bookings;
};

const bookings = (state = [], action) => {
    let bookings = null;
    switch (action.type) {
        case ADD_BOOKING:
            bookings = [...state, booking(action)];
            console.log("bookings as state", bookings);
            return bookings;
        case DELETE_BOOKING:
            bookings = removeById(state, action.id);
            return bookings;

        default:
            return state;
    }
};
export {bookings};

Console log:

Component (App.jsx):

import React, { Component } from "react";
import "./App.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { addBooking, deleteBooking } from "../actions";
import { Header } from "./NavigationBar";
import { connect } from "react-redux";

class App extends Component {
  //Initialize the Component
  constructor(props) {
    super(props);
    this.state = {
      firstname: "",
      lastname: "",
      duedate: ""
    };
  }
  //add Booking
  addBooking() {
    this.props.addBooking(this.state.firstname);
    this.props.addBooking(this.state.lastname);

  }

  //delete Booking
  deleteBooking(id) {
    this.props.deleteBooking(id);
  }
  //render the bookings
  renderBookings() {
    //access our bookings

   const {bookings} = this.props;

    return (

        { bookings.map(booking => {
            return (

                        { booking.firstname }

                        { booking.lastname }

 this.deleteBooking(booking.id) }>
                        Cancel Booking

)
          }) }

)
  }
  render() {
    return (

            <input
              className="form-control"
              placeholder="Enter First Name"
              onChange={event =>
                this.setState({
                  firstname: event.target.value
                })
              }
            />
            <input
              className="form-control"
              placeholder="Enter Last Name"
              onChange={event =>
                this.setState({
                  lastname: event.target.value
                })
              }
            />
            <input
              className="form-control"
              type="datetime-local"
              onChange={event =>
                this.setState({
                  duedate: event.target.value
                })
              }
            />

            <button
              type="button"
              className="btn btn-success"
              onClick={() => this.addBooking()}
            >
              Add Booking
            </button>

        {this.renderBookings()}

    );
  }
}

function mapStateToProps(state) {
  return {
    bookings: state
  };
}

export default connect(mapStateToProps, {
  addBooking,
  deleteBooking
})(App);


问:
get all tuples with maximum second value
How to fix the number of occurrence in a list of tuples and return an item with max value.

```<code>        given = [('a',2),('b',3),('c',5),('a',3),('c',5)]

        expected = [('c',5),('a',3),('b',3)]
</code>```

How do you do this without doing anything to complex.

Body:
How to fix the number of occurrence in a list of tuples and return an item with max value.

        given = [('a',2),('b',3),('c',5),('a',3),('c',5)]

        expected = [('c',5),('a',3),('b',3)]

How do you do this without doing anything to complex.

Body:
        given = [('a',2),('b',3),('c',5),('a',3),('c',5)]
        expected = dict(given).items()
        dict_items([('a', 3), ('b', 3), ('c', 5)])


问:
Is there a way to pass in complex arguments into Mocked Dart Services using Mockito?
I was looking at the documentation at: https://pub.dartlang.org/packages/mockito and was trying to understand it more.  It seems that in the examples, the function stubs were accepting strings, but was kind of confused as to how I was going to implement my Mocked Services.

I was curious how I would do it.  The services I have is pretty simple and straight forward.

```<code>class Group{}
class GroupService {}
class MockGroupService extends Mock implements GroupService {}
final mockProviders = [new Provider(MockGroupService, useExisting: GroupService];
</code>```

So you can see I am using Angular dart.

I was creating a sample group in my Test file.

```<code>group("service tests", (){
  MockGroupService _mock;
  testBed.addProviders([mockProviders]);

  setUp(() async {
    fixture = await testBed.create();
    _mock = new MockGroupService();

    //This is where I was going to create some stubbs for the methods
    when(_mock.add()).thenReturn((){
      return null; //return the object.
    });

    //create additional when statements for edit, delete, etc.
  });
});
</code>```

So what i was thinking is that there would be an argument passed into add (or 2).... how would I properly code that in the when statement, and how do those 2 arguments reflect in the then statement?

Essentially, I was wanting to do a test with a complex class.. and pass it into add.  Then it would just process it accordingly and return it.

Do i pass into the arguments something akin to:  (using pseudocode)

```<code>when(_mock.add(argThat(hasType(Group)))).thenReturn((Group arg)=> arg);
</code>```

or something similar?  hasType isnt function, so im not 100% sure how to approach this design.  Ideally, Im trying create the Group in the test, and then pass it into the add function accordingly.  It just seems that the examples were showing Strings.

答:
Yes mockito allows objects to be passed you can see examples in the test.

It is a bit hard to follow but you can see here that it uses deep equality to check if arguments are equal if no matchers are specified.

The second part of your question is a bit more complex. If you want to use the values that were passed into your mock as part of your response then you need to use thenAnswer. It provides you with an Invocation of what was just called. From that object you can get and return any arguments that were used in the method call.

So for your add example if you know what is being passing in and have complete access to it I would write:

```<code>Group a = new Group();
when(_mock.add(a)).thenReturn(a);
</code>```

If the Group object is being created by something else I would write:

```<code>when(_mock.add(argThat(new isInstanceOf<Group>()))
  .thenAnswer((invocation)=>invocation.positionalArguments[0]);
</code>```

Or if you don't really care about checking for the type. Depending on what checks you are using for your test the type might already be checked for you.

```<code>when(_mock.add(any)).thenAnswer(
  (invocation)=>invocation.positionalArguments[0]);
</code>```

Or if you are using Dart 2.0:

```<code>when(_mock.add(typed(any))).thenAnswer(
  (invocation)=>invocation.positionalArguments[0]);
</code>```

Body:
I was looking at the documentation at: https://pub.dartlang.org/packages/mockito and was trying to understand it more.  It seems that in the examples, the function stubs were accepting strings, but was kind of confused as to how I was going to implement my Mocked Services.

I was curious how I would do it.  The services I have is pretty simple and straight forward.

class Group{}
class GroupService {}
class MockGroupService extends Mock implements GroupService {}
final mockProviders = [new Provider(MockGroupService, useExisting: GroupService];

So you can see I am using Angular dart.

I was creating a sample group in my Test file.

group("service tests", (){
  MockGroupService _mock;
  testBed.addProviders([mockProviders]);

  setUp(() async {
    fixture = await testBed.create();
    _mock = new MockGroupService();

    //This is where I was going to create some stubbs for the methods
    when(_mock.add()).thenReturn((){
      return null; //return the object.
    });

    //create additional when statements for edit, delete, etc.
  });
});

So what i was thinking is that there would be an argument passed into add (or 2).... how would I properly code that in the when statement, and how do those 2 arguments reflect in the then statement?

Essentially, I was wanting to do a test with a complex class.. and pass it into add.  Then it would just process it accordingly and return it.

Do i pass into the arguments something akin to:  (using pseudocode)

when(_mock.add(argThat(hasType(Group)))).thenReturn((Group arg)=> arg);

or something similar?  hasType isnt function, so im not 100% sure how to approach this design.  Ideally, Im trying create the Group in the test, and then pass it into the add function accordingly.  It just seems that the examples were showing Strings.

Body:
Yes mockito allows objects to be passed you can see examples in the test.

It is a bit hard to follow but you can see here that it uses deep equality to check if arguments are equal if no matchers are specified.

The second part of your question is a bit more complex. If you want to use the values that were passed into your mock as part of your response then you need to use thenAnswer. It provides you with an Invocation of what was just called. From that object you can get and return any arguments that were used in the method call.

So for your add example if you know what is being passing in and have complete access to it I would write:

Group a = new Group();
when(_mock.add(a)).thenReturn(a);

If the Group object is being created by something else I would write:

when(_mock.add(argThat(new isInstanceOf<Group>()))
  .thenAnswer((invocation)=>invocation.positionalArguments[0]);

Or if you don't really care about checking for the type. Depending on what checks you are using for your test the type might already be checked for you.

when(_mock.add(any)).thenAnswer(
  (invocation)=>invocation.positionalArguments[0]);

Or if you are using Dart 2.0:

when(_mock.add(typed(any))).thenAnswer(
  (invocation)=>invocation.positionalArguments[0]);


问:
Python Code Obfuscation
Do you know of any tool that could assist me in obfuscating python code?</p>

答: Python's standard library includes compileall.py. You can run this on a directory and it will generate .pyc files for all your source files. The .pyc files will only include bytecode and docstrings, and will strip out all comments. You could then copy this directory, and then run something like rm -rf $(find . -name .py) to remove the original source files.

OwnerDisplayName: vishal

LastEditorDisplayName: David Segonds

Title: Python Code Obfuscation


问:
UpperCasePipe for input in Angular 4
I want to use uppercase pipe for input box without ngModel, also I am using form builder. Any way to convert all value of form in uppercase.

<form [formGroup]="addTrackForm" (ngSubmit)="addTrack(addTrackForm.value)">
  <input type="text" formControlName="name" />
  <input type="text" formControlName="adminAdamGroup" class="inputTxt" />
  <button type="submit" class="btn btn-primary btn-sm" [disabled]="!addTrackForm.valid">Add</button>
</form>
```

答:
Solution. You can use the input as follows</p>

```<code>(input)="orderForm.patchValue({name: $event.target.value.toUpperCase()})"
</code>```

Title: UpperCasePipe for input in Angular 4

Body:
Solution. You can use the input as follows

(input)="orderForm.patchValue({name: $event.target.value.toUpperCase()})"


问:
Foreach loop with double condition in java8 using lambda
I have an exercise with this description:

```<code>1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit.
1111 produces 4 because each digit (all 1) matches the next.
1234 produces 0 because no digit matches the next.
91212129 produces 9 because the only digit that matches the next one is the last digit, 9.
</code>```

I have written the following code:

```<code>String inputString = "1111"; // taking this number as example

int sum = 0;
for (int i = 0; i < inputString.length() - 1; i++) {
    if (inputString.charAt(i) == inputString.charAt(i + 1)) {
        sum += Integer.parseInt(String.valueOf(inputString.charAt(i)));
    }
    if (i + 2 == inputString.length() - 1) {
        if (inputString.charAt(i + 2) == inputString.charAt(0)) {
            sum += Integer.parseInt(String.valueOf(inputString.charAt(i + 2)));
        }
    }
}
</code>```

The result of sum is 4, which is correct.

Now I'm trying to write the same one in Java8 using lambda but I can't figure out how to get the last condition inside my stream.

This is how far I got:

```<code>Integer sum = IntStream.range(0, (inputString.length() - 1)).boxed()
                .filter(j -> inputString.charAt(j) == inputString.charAt(j + 1))
                .mapToInt(i -> Integer.parseInt(String.valueOf(inputString.charAt(i)))).sum();
</code>```

答:
The last condition is actually like the others if you consider the loop variable modulo the length: ((length-1) + 1) % length == 0

```<code>int length = inputString.length();

IntStream.range(0, length)
  .filter(i -> inputString.charAt(i) == inputString.charAt((i + 1) % length))
  .map(i -> Integer.parseInt(String.valueOf(inputString.charAt(i))))
  .sum();
</code>```

Body:
I have an exercise with this description:

1122 produces a sum of 3 (1 + 2) because the first digit (1) matches the second digit and the third digit (2) matches the fourth digit.
1111 produces 4 because each digit (all 1) matches the next.
1234 produces 0 because no digit matches the next.
91212129 produces 9 because the only digit that matches the next one is the last digit, 9.

I have written the following code:

String inputString = "1111"; // taking this number as example

int sum = 0;
for (int i = 0; i < inputString.length() - 1; i++) {
    if (inputString.charAt(i) == inputString.charAt(i + 1)) {
        sum += Integer.parseInt(String.valueOf(inputString.charAt(i)));
    }
    if (i + 2 == inputString.length() - 1) {
        if (inputString.charAt(i + 2) == inputString.charAt(0)) {
            sum += Integer.parseInt(String.valueOf(inputString.charAt(i + 2)));
        }
    }
}

The result of sum is 4, which is correct.

Now I'm trying to write the same one in Java8 using lambda but I can't figure out how to get the last condition inside my stream.

This is how far I got:

Integer sum = IntStream.range(0, (inputString.length() - 1)).boxed()
                .filter(j -> inputString.charAt(j) == inputString.charAt(j + 1))
                .mapToInt(i -> Integer.parseInt(String.valueOf(inputString.charAt(i)))).sum();

Body:
The last condition is actually like the others if you consider the loop variable modulo the length: ((length-1) + 1) % length == 0

int length = inputString.length();

IntStream.range(0, length)
  .filter(i -> inputString.charAt(i) == inputString.charAt((i + 1) % length))
  .map(i -> Integer.parseInt(String.valueOf(inputString.charAt(i))))
  .sum();


问:
Not able to initialize constructor
I am creating a program which includes a parent class Account and a derived class BankAccount. Initially, I have to set the balance in account to be 5000. And when certain transactions are made, this balance should be updated. Also, whenever the program is closed, the program should return the latest balance. Below is my code. However, I am not able to initialize the constructor properly and hence, initial balance is never set correctly. Please tell me what I am doing wrong.</p>

```<code> class Account
{
public:

    void setCashBal(); //updates the cash balance in account whenever a transaction is made
    double getCashBal(); //retrieves recent cash balance

protected:
    double cash_balance;
};

void Account::setCashBal()
{

    double initial_bal;

    ifstream read_cash_file("cash_bal_file.txt", ios_base::in);

    int count = 0;

    if (read_cash_file.is_open()) //check whether the file could be openend
    {

        while (!(read_cash_file.eof())) //reading until the end of file
        {
            count = count + 1;
            break;
        }
        read_cash_file.close();

        if (count == 0)//if the file is opened the first time, initial cash balance is 5000
        {
            initial_bal = 5000;

            ofstream write_cash_file("cash_bal_file.txt", ios::out);

            write_cash_file << initial_bal; //writing the initial value of cash balance in cash_bal_file
            write_cash_file.close();

            read_cash_file.open("cash_bal_file.txt", ios_base::in);
            read_cash_file >> cash_balance;
            read_cash_file.close();
        }

        else //getting the latest cash balance
        {
            read_cash_file.open("cash_bal_file.txt", ios::in);
            read_cash_file >> cash_balance;
            read_cash_file.close();
        }
    }

    else //case when the file could not be openend
        cout << endl << "Sorry, cash_bal_file could not be opened." << endl;
}

double Account::getCashBal()
{
    return cash_balance;
}

    class BankAccount :public Account
    {
    public:
        BankAccount();
        void viewBalance();
    };

    BankAccount::BankAccount()

    {
        setCashBal();
        cash_balance = getCashBal();
    }

    void BankAccount::viewBalance()
    {

        double balance;
        ifstream view_bal("cash_bal_file.txt", ios_base::in); //getting the latest cash_balance from cash_bal_file.
        view_bal >> balance;

        cout << endl << "The balance in your bank account is " << balance << endl;
    }

    int main()
    {
        BankAccount bnkObj;
        bnkObj.viewBalance();

    return 0;
    }
</code>```

答:
```<code>class Account
{
  public:
    int n;

    Account(): n(5000)
    {}
};
</code>```

This is called "initializing a member variable in the constructor", or just "initializing". If you search an introductory C++ text for "initialize", you'll find something like this.

Title: Not able to initialize constructor

Body:
I am creating a program which includes a parent class Account and a derived class BankAccount. Initially, I have to set the balance in account to be 5000. And when certain transactions are made, this balance should be updated. Also, whenever the program is closed, the program should return the latest balance. Below is my code. However, I am not able to initialize the constructor properly and hence, initial balance is never set correctly. Please tell me what I am doing wrong.

 class Account
{
public:

    void setCashBal(); //updates the cash balance in account whenever a transaction is made
    double getCashBal(); //retrieves recent cash balance

protected:
    double cash_balance;
};

void Account::setCashBal()
{

    double initial_bal;

    ifstream read_cash_file("cash_bal_file.txt", ios_base::in);

    int count = 0;

    if (read_cash_file.is_open()) //check whether the file could be openend
    {

        while (!(read_cash_file.eof())) //reading until the end of file
        {
            count = count + 1;
            break;
        }
        read_cash_file.close();

        if (count == 0)//if the file is opened the first time, initial cash balance is 5000
        {
            initial_bal = 5000;

            ofstream write_cash_file("cash_bal_file.txt", ios::out);

            write_cash_file << initial_bal; //writing the initial value of cash balance in cash_bal_file
            write_cash_file.close();

            read_cash_file.open("cash_bal_file.txt", ios_base::in);
            read_cash_file >> cash_balance;
            read_cash_file.close();
        }

        else //getting the latest cash balance
        {
            read_cash_file.open("cash_bal_file.txt", ios::in);
            read_cash_file >> cash_balance;
            read_cash_file.close();
        }
    }

    else //case when the file could not be openend
        cout << endl << "Sorry, cash_bal_file could not be opened." << endl;
}

double Account::getCashBal()
{
    return cash_balance;
}

    class BankAccount :public Account
    {
    public:
        BankAccount();
        void viewBalance();
    };

    BankAccount::BankAccount()

    {
        setCashBal();
        cash_balance = getCashBal();
    }

    void BankAccount::viewBalance()
    {

        double balance;
        ifstream view_bal("cash_bal_file.txt", ios_base::in); //getting the latest cash_balance from cash_bal_file.
        view_bal >> balance;

        cout << endl << "The balance in your bank account is " << balance << endl;
    }

    int main()
    {
        BankAccount bnkObj;
        bnkObj.viewBalance();

    return 0;
    }

Body:
class Account
{
  public:
    int n;

    Account(): n(5000)
    {}
};

This is called "initializing a member variable in the constructor", or just "initializing". If you search an introductory C++ text for "initialize", you'll find something like this.


问:
Trouble with AWK'd command output and bash array
I am attempting to get a list of running VirtualBox VMs (the UUIDs) and put them into an array.  The command below produces the output below:

```<code>$ VBoxManage list runningvms | awk -F '[{}]' '{print $(NF-1)}'

f93c17ca-ab1b-4ba2-95e5-a1b0c8d70d2a
46b285c3-cabd-4fbb-92fe-c7940e0c6a3f
83f4789a-b55b-4a50-a52f-dbd929bdfe12
4d1589ba-9153-489a-947a-df3cf4f81c69
</code>```

I would like to take those UUIDs and put them into an array (possibly even an associative array for later use, but a simple array for now is sufficient)

If I do the following:

```<code>array1="( $(VBoxManage list runningvms | awk -F '[{}]' '{print $(NF-1)}') )"
</code>```

The commands

```<code>array1_len=${#array1[@]}
echo $array1_len
</code>```

Outputs "1" as in there's only 1 element.  If I print out the elements:

```<code>    echo ${array1[*]}
</code>```

I get a single line of all the UUIDs

```<code>( f93c17ca-ab1b-4ba2-95e5-a1b0c8d70d2a 46b285c3-cabd-4fbb-92fe-c7940e0c6a3f 83f4789a-b55b-4a50-a52f-dbd929bdfe12 4d1589ba-9153-489a-947a-df3cf4f81c69 )
</code>```

I did some research (Bash Guide/Arrays on how to tackle this and found this with command substitution and redirection, but it produces an empty array

```<code>while  read -r -d '\0'; do
        array2+=("$REPLY")
    done < <(VBoxManage list runningvms | awk -F '[{}]' '{print $(NF-1)}')
</code>```

I'm obviously missing something.  I've looked at several simiar questions on this site such as:

Reading output of command into array in Bash

AWK output to bash Array

Creating an Array in Bash with Quoted Entries from Command Output

Unfortunately, none have helped.  I would apprecaite any assistance in figuring out how to take the output and assign it to an array.

I am running this on macOS 10.11.6 (El Captain) and BASH version 3.2.57

答:
Since you're on a Mac:

```<code>brew install bash
</code>```

Then with this bash as your shell, pipe the output to:

```<code>readarray -t array1
</code>```

Of the -t option, the man page says:

```<code>-t     Remove a trailing delim (default newline) from each line read.
</code>```

If the bash4 solution is admissible, then the advice given
e.g. by gniourf_gniourf at reading-output-of-command-into-array-in-bash
 is still sound.

Body:
I am attempting to get a list of running VirtualBox VMs (the UUIDs) and put them into an array.  The command below produces the output below:

$ VBoxManage list runningvms | awk -F '[{}]' '{print $(NF-1)}'

f93c17ca-ab1b-4ba2-95e5-a1b0c8d70d2a
46b285c3-cabd-4fbb-92fe-c7940e0c6a3f
83f4789a-b55b-4a50-a52f-dbd929bdfe12
4d1589ba-9153-489a-947a-df3cf4f81c69

I would like to take those UUIDs and put them into an array (possibly even an associative array for later use, but a simple array for now is sufficient)

If I do the following:

array1="( $(VBoxManage list runningvms | awk -F '[{}]' '{print $(NF-1)}') )"

The commands

array1_len=${#array1[@]}
echo $array1_len

Outputs "1" as in there's only 1 element.  If I print out the elements:

    echo ${array1[*]}

I get a single line of all the UUIDs

( f93c17ca-ab1b-4ba2-95e5-a1b0c8d70d2a 46b285c3-cabd-4fbb-92fe-c7940e0c6a3f 83f4789a-b55b-4a50-a52f-dbd929bdfe12 4d1589ba-9153-489a-947a-df3cf4f81c69 )

I did some research (Bash Guide/Arrays on how to tackle this and found this with command substitution and redirection, but it produces an empty array

while  read -r -d '\0'; do
        array2+=("$REPLY")
    done < <(VBoxManage list runningvms | awk -F '[{}]' '{print $(NF-1)}')

I'm obviously missing something.  I've looked at several simiar questions on this site such as:

Reading output of command into array in Bash

AWK output to bash Array

Creating an Array in Bash with Quoted Entries from Command Output

Unfortunately, none have helped.  I would apprecaite any assistance in figuring out how to take the output and assign it to an array.

I am running this on macOS 10.11.6 (El Captain) and BASH version 3.2.57

Body:
Since you're on a Mac:

brew install bash

Then with this bash as your shell, pipe the output to:

readarray -t array1

Of the -t option, the man page says:

-t     Remove a trailing delim (default newline) from each line read.

If the bash4 solution is admissible, then the advice given
e.g. by gniourf_gniourf at reading-output-of-command-into-array-in-bash
 is still sound.


问:
Windows Service running but event logs not working
I have a windows service listening to messages from a queue but the messages are not read from the queue.I created an event log to check for logs during service startup and shutdown but the logs are not written. I do not want to debug the service since it is a painful process.Is there a way to solve this issue.The messages need to be read by the service and written to a database.</p>

答:
In my experience, the most common problem in writing to event logs is that the user does not have sufficient permission to write to the event log. Can you check the identity that the Windows service is running under, and verify that it has permission to write to the event log that you have created?

And, can you check the event log to see if any errors are being recorded when attempts are made to write to it?

OwnerDisplayName: kjayakum

LastEditorDisplayName: Ben Alpert

OwnerDisplayName: DOK

LastEditorDisplayName: DOK


问:
What's the difference between this and super keywords in java?
Check my coolMethod, babes:

```<code>package zoo;

public class Zoo {

    public String coolMethod() {
        return "Wow baby!";
    }

}
</code>```

My Moo Class, that extends my Zoo class, full of ways to do the same thing, which is calling my coolMethod.

```<code>package zoo;

public class Moo extends Zoo {

    public void useAZoo(){

        Zoo z = new Zoo();

        System.out.println("A Zoo says: "+ z.coolMethod());
    }

    public void useMyCoolMethod(){

        System.out.println("My cool method says: " + super.coolMethod());

    }

     public void useMyCoolMethodAgain(){

        System.out.println("My cool method says: " + this.coolMethod()+ " (again)");

    }

    public void inheritMyMethod(){
        System.out.println("My inhertied method says: " + coolMethod());
    }

}
</code>```

And my main, that calls my Moo class functionalities.

```<code>package javacert1;

import zoo.Moo;

public class Main {

    public static void main(String[] args) {

        Moo moo = new Moo();

        moo.useAZoo();

        moo.useMyCoolMethod();

        moo.useMyCoolMethodAgain();

        moo.inheritMyMethod();
    }

}
</code>```

As you can see, all those four calls get the same results. I'm learning Java and I practiced with an example that used the "this" but I had seen the use of "super" elsewhere so I tested it and the results where the same. Why is this? What's the major difference between a this and super keyword?

答:
Cool example, overmann :)

Here is another example ... has 2 source files - LevelSub.java which extends LevelSup.java

Save the 2 in some folder, compile using "javac LevelSub.java" (compiler will know from "extends" that it has to compile "LevelSup.java", too), and run "java LevelSub". The comments in the source code should tell you the difference.

this and super are used when there is a name clash for variables or methods (e.g., same name is used in super/sub classes or in a method body, or you want to call a method from the superclass that has been overridden). "this" refers to the current object instance and "super" refers to the one it is inheriting from. For no name clashes, the this or super prefix are redundant.

```<code>public class LevelSub extends LevelSup {
    protected String myName;

    public LevelSub (String myName) {
        super ("SuperClass");
        this.myName = myName;       // sets up instance variable
    }

    public void print () {
        System.out.println ("Hi, this is " + myName); // refers to this.myName
        System.out.println ("I am inherited from " + super.myName);
        System.out.println ("also known as " + defaultName); // gets from superclass
        super.print();           // overridden method of superclass
    }

    public static void main (String[] args) {
        new LevelSub("SubClass").print();
}}
</code>```

and the other source ...

```<code>public class LevelSup {
    // cannot be private if accessed by subclass
    protected String myName, defaultName = "TopLevel";

    public LevelSup (String name) {
        myName = name;      // this not required, no name clash
    }

    // cannot be private if accessed by subclass
    public void print () {
        System.out.println ("Hi, this is " + myName);
    }
}
</code>```

Body:
Check my coolMethod, babes:

package zoo;

public class Zoo {

    public String coolMethod() {
        return "Wow baby!";
    }

}

My Moo Class, that extends my Zoo class, full of ways to do the same thing, which is calling my coolMethod.

package zoo;

public class Moo extends Zoo {

    public void useAZoo(){

        Zoo z = new Zoo();

        System.out.println("A Zoo says: "+ z.coolMethod());
    }

    public void useMyCoolMethod(){

        System.out.println("My cool method says: " + super.coolMethod());

    }

     public void useMyCoolMethodAgain(){

        System.out.println("My cool method says: " + this.coolMethod()+ " (again)");

    }

    public void inheritMyMethod(){
        System.out.println("My inhertied method says: " + coolMethod());
    }

}

And my main, that calls my Moo class functionalities.

package javacert1;

import zoo.Moo;

public class Main {

    public static void main(String[] args) {

        Moo moo = new Moo();

        moo.useAZoo();

        moo.useMyCoolMethod();

        moo.useMyCoolMethodAgain();

        moo.inheritMyMethod();
    }

}

As you can see, all those four calls get the same results. I'm learning Java and I practiced with an example that used the "this" but I had seen the use of "super" elsewhere so I tested it and the results where the same. Why is this? What's the major difference between a this and super keyword?

Body:
Cool example, overmann :)

Here is another example ... has 2 source files - LevelSub.java which extends LevelSup.java

Save the 2 in some folder, compile using "javac LevelSub.java" (compiler will know from "extends" that it has to compile "LevelSup.java", too), and run "java LevelSub". The comments in the source code should tell you the difference.

this and super are used when there is a name clash for variables or methods (e.g., same name is used in super/sub classes or in a method body, or you want to call a method from the superclass that has been overridden). "this" refers to the current object instance and "super" refers to the one it is inheriting from. For no name clashes, the this or super prefix are redundant.

public class LevelSub extends LevelSup {
    protected String myName;

    public LevelSub (String myName) {
        super ("SuperClass");
        this.myName = myName;       // sets up instance variable
    }

    public void print () {
        System.out.println ("Hi, this is " + myName); // refers to this.myName
        System.out.println ("I am inherited from " + super.myName);
        System.out.println ("also known as " + defaultName); // gets from superclass
        super.print();           // overridden method of superclass
    }

    public static void main (String[] args) {
        new LevelSub("SubClass").print();
}}

and the other source ...

public class LevelSup {
    // cannot be private if accessed by subclass
    protected String myName, defaultName = "TopLevel";

    public LevelSup (String name) {
        myName = name;      // this not required, no name clash
    }

    // cannot be private if accessed by subclass
    public void print () {
        System.out.println ("Hi, this is " + myName);
    }
}


问:
Tensorflow processing with extremely big data
I have a large image file that I am trying to load and use with tensorflow (600000,20,64,64). I wanted to use feed_dict with a batch size but the array is too large to even load into a numpy array. Is there a method that I can use that will not require me to load the entire array in ?</p>

答:
The "feed_dict" method is good only for small data. For large data, there is a tfrecord or csv formats which may be read in a separate thread by chunks which populate a tensorflow input data queue. More info on data reading from HDD is here - how to read data in tensorflow.

There is also a nice blog where it is shown how to prepare tfrecords from raw data.


问:
Nativescript doesn't recognize Xcode (High Sierra)
I'm on High Sierra with Xcode Version 9.0.1 (9A1004).
When running tns doctor I get the following warning:

```<code>WARNING: Xcode is not installed or is not configured properly.
You will not be able to build your projects for iOS or run them in the iOS Simulator.
To be able to build for iOS and run apps in the native emulator, verify that you have installed Xcode.
</code>```

If I run the installation script, furthermore I get:

```<code>xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance
Xcode is not installed or not configured properly. Download, install, set it up and run this script again.
</code>```

As you might have guessed, I have Xcode installed from the app store and I've also installed cocoapods and xcodeproj. This is the only warning that I get.

Any suggestions?

答:
Run the following command:

```<code>sudo xcode-select --reset
</code>```

I found this answer here:

http://overengineer.net/fixing-nativescript-s-xcode-is-not-installed-or-is-not-configured-properly-on-macos

Body:
I'm on High Sierra with Xcode Version 9.0.1 (9A1004).
When running tns doctor I get the following warning:

WARNING: Xcode is not installed or is not configured properly.
You will not be able to build your projects for iOS or run them in the iOS Simulator.
To be able to build for iOS and run apps in the native emulator, verify that you have installed Xcode.

If I run the installation script, furthermore I get:

xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance
Xcode is not installed or not configured properly. Download, install, set it up and run this script again.

As you might have guessed, I have Xcode installed from the app store and I've also installed cocoapods and xcodeproj. This is the only warning that I get.

Any suggestions?

Body:
Run the following command:

sudo xcode-select --reset

I found this answer here:

http://overengineer.net/fixing-nativescript-s-xcode-is-not-installed-or-is-not-configured-properly-on-macos


问:
space winforms controls
I have a simple winforms app with a column of several buttons. What is the nicest way to enforce that they are equally spaced vertically?</p>

答: Change the location parameters in the properties windows to be proportionally aligned.</p>

Title: space winforms controls


问:
Which is a better time complexity?
I have to pick out which operations have a better worst case time complexity on an AVL tree than a BST. I have established that the time complexity for each operation is the same depending on the tree...

The worst case time complexity for an AVL tree is...

```<code>Insert - O(log(n))
Remove - O(log(n))
Search - O(log(n))
</code>```

The worst case time complexity for a BST is....

```<code>Insert - O(height)
Remove - O(height)
Search - O(height)
</code>```

So is O(log(n)) a better time complexity than O(height)?

答:
An AVL tree is basically a height balanced BST.
If you consider a full AVL tree, log n (AVL tree) > log n (BST).
-> where n is the number of nodes.

whereas when you consider O (height), it'll be the same in both the AVL and BST.

3

  \

    5

      (BST)

height = 2 , n = 2

```<code>  3
 / \
2   5
       (AVL)
</code>```

height = 2, n = 3

Title: Which is a better time complexity?

Body:
I have to pick out which operations have a better worst case time complexity on an AVL tree than a BST. I have established that the time complexity for each operation is the same depending on the tree...

The worst case time complexity for an AVL tree is...

Insert - O(log(n))
Remove - O(log(n))
Search - O(log(n))

The worst case time complexity for a BST is....

Insert - O(height)
Remove - O(height)
Search - O(height)

So is O(log(n)) a better time complexity than O(height)?

Body:
An AVL tree is basically a height balanced BST.
If you consider a full AVL tree, log n (AVL tree) > log n (BST).
-> where n is the number of nodes.

whereas when you consider O (height), it'll be the same in both the AVL and BST.

3

  \

    5

      (BST)

height = 2 , n = 2

  3
 / \
2   5
       (AVL)

height = 2, n = 3


问:
Opening local HTML file using Puppeteer
Is it possible to open a local HTML file with headless Chrome using Puppeteer (without a web server)? I could only get it to work against a local server.

I found setContent() and goto() in the Puppeteer API documentation, but:

page.goto: did not work with a local file or file://.

page.setContent: is for an HTML string

答:
I just did a test locally (you can see I did this on windows) and puppeteer happily opened my local html file using page.goto and a full file url, and saved it as a pdf:

```<code>'use strict';

const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('file://C:/Users/compoundeye/test.html');
await page.pdf({
  path: 'test.pdf',
  format: 'A4',
  margin: {
        top: "20px",
        left: "20px",
        right: "20px",
        bottom: "20px"
  }
});
await browser.close();
})();
</code>```

If you need to use a relative path might want to look at this question about the use of relative file paths: File Uri Scheme and Relative Files

Title: Opening local HTML file using Puppeteer

Body:
I just did a test locally (you can see I did this on windows) and puppeteer happily opened my local html file using page.goto and a full file url, and saved it as a pdf:

'use strict';

const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('file://C:/Users/compoundeye/test.html');
await page.pdf({
  path: 'test.pdf',
  format: 'A4',
  margin: {
        top: "20px",
        left: "20px",
        right: "20px",
        bottom: "20px"
  }
});
await browser.close();
})();

If you need to use a relative path might want to look at this question about the use of relative file paths: File Uri Scheme and Relative Files


问:
Silverstripe 4 - accessing core methods
In Silverstripe 3, eveything was autoloaded on demand. That meant that one could know the class and method that they wanted to use. Example:

```<code>Debug::dump('dump message');
</code>```

If I'm understanding the concepts of SS4 correctly, one needs to import the class to the file that you would like to use the method (or property). In the above example, one would need to do something as follows at the top of the file

```<code>use /name/space/to/Debug
Debug::dump('dump message');
</code>```

Is that understanding correct? If so, my real question is how does a developer effectively know the precise location of everything in core? Are they expected to know exactly where in system these core files reside on top of their names and the methods you wish to use? Are there tools or methods to assist in this?

答:
First, just a clarification -- what you're talking about is not autoloading, it's more like aliasing -- but the two are related.

Because the Debug class is no longer in the global namespace, its name is much more verbose (SilverStripe\Dev\Debug). This is known as a fully qualified class name, or "FQCN" for short. There's nothing short, however, about that new name. It's tedious to type, and if the class ever changes its name, you have a lot of updates to make.

To that end, you can use the use statement to "import" that class into the local scope of your file under an alias. By default, that alias is just the trailing part of the FQCN (Debug), but you're also allowed to use any custom alias you like. (use SilverStripe\Dev\Debug as MyDebugger).

SS4 now uses PSR-4 autoloading, for which namespacing is a critical piece. In very short terms, it dictates that the directory structure must match up with the FQCN, e.g. /framework/src/Dev/Debug.php. This makes the autoloading deterministic and predictable.

As for tooling, using a fully powered IDE like PHPStorm is invaluable for doing dev work in a framework with namespaced classes (which is far more the rule than the exception these days). A good IDE, like PHPStorm, will not only autocomplete as you inject a classname, but will also add the use statement for you, among many, many other wonderful time-saving features.

For a more manual approach, api.silverstripe.org is a good place to look up class mappings.

Title: Silverstripe 4 - accessing core methods

Body:
In Silverstripe 3, eveything was autoloaded on demand. That meant that one could know the class and method that they wanted to use. Example:

Debug::dump('dump message');

If I'm understanding the concepts of SS4 correctly, one needs to import the class to the file that you would like to use the method (or property). In the above example, one would need to do something as follows at the top of the file

use /name/space/to/Debug
Debug::dump('dump message');

Is that understanding correct? If so, my real question is how does a developer effectively know the precise location of everything in core? Are they expected to know exactly where in system these core files reside on top of their names and the methods you wish to use? Are there tools or methods to assist in this?