问:
Ruby on rails - unable to create comments. NoMethodError
I am creating one of my first RoR applications - a forum. I am try to add comments to the forum, but I am getting some errors. I have Googled for similar issues but none of the seem to solve my issue. Here is my code:

Comments Controller:

```<code>class CommentsController < ApplicationController
  def create
    @forum = Forum.find(params[:forum_id])

    if !@forum.nil?
        puts "Forum object is not nil"
    end

    @comment = @forum.comment.create(comment_params)

    redirect_to forum_path
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
  end
end
</code>```

The Forum controller is auto generated and I haven't changed in. (generated using rails generate scaffold Forum, if you still want to see it, let me know)

```<code>class Comment < ApplicationRecord
  belongs_to :forum
end

class Forum < ApplicationRecord
  has_many :comments
  validates :title, presence: true,
  length: {maximum: 50}
  validates :body, presence: true
end
</code>```

Below is the form for section from the show.html.erb for the forum page

```<code><h2>Comments</h2>

<% @forum.comments.each do |comment| %>
<p>
    <%= comment.body %>
</p>

<% end %>

<h2>Add a comment</h2>

<%= form_for([@forum, @forum.comments.build]) do |f| %>
<p>
    <%= f.label :body %><br/>
    <%= f.text_area :body %>
</p>
<p>
    <%= f.submit %>
</p>
<% end %>
</code>```

And this is the error from rails:

```<code>undefined method `comment' for #<Forum:0x444d518>
</code>```

with the following extract:

```<code>end
 @comment = @forum.comment.create(comment_params) #highlighted
 redirect_to forum_path
end
</code>```

答:
The problem is with this line @comment = @forum.comment.create(comment_params) in your CommentsController.
It should be @comment = @forum.comments.create(comment_params) . comments should be plural.

Your code should be:

```<code>class CommentsController < ApplicationController
  def create
    @forum = Forum.find(params[:forum_id])
    @comment = @forum.comments.create(comment_params)
    redirect_to forum_path
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
  end
end
</code>```

Body:
I am creating one of my first RoR applications - a forum. I am try to add comments to the forum, but I am getting some errors. I have Googled for similar issues but none of the seem to solve my issue. Here is my code:

Comments Controller:

class CommentsController < ApplicationController
  def create
    @forum = Forum.find(params[:forum_id])

    if !@forum.nil?
        puts "Forum object is not nil"
    end

    @comment = @forum.comment.create(comment_params)

    redirect_to forum_path
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
  end
end

The Forum controller is auto generated and I haven't changed in. (generated using rails generate scaffold Forum, if you still want to see it, let me know)

class Comment < ApplicationRecord
  belongs_to :forum
end

class Forum < ApplicationRecord
  has_many :comments
  validates :title, presence: true,
  length: {maximum: 50}
  validates :body, presence: true
end

Below is the form for section from the show.html.erb for the forum page

Comments

<% @forum.comments.each do |comment| %>

    <%= comment.body %>

<% end %>

Add a comment

<%= form_for([@forum, @forum.comments.build]) do |f| %>

    <%= f.label :body %>

    <%= f.text_area :body %>

    <%= f.submit %>

<% end %>

And this is the error from rails:

undefined method `comment' for #<Forum:0x444d518>

with the following extract:

end
 @comment = @forum.comment.create(comment_params) #highlighted
 redirect_to forum_path
end

Body:
The problem is with this line @comment = @forum.comment.create(comment_params) in your CommentsController.
It should be @comment = @forum.comments.create(comment_params) . comments should be plural.

Your code should be:

class CommentsController < ApplicationController
  def create
    @forum = Forum.find(params[:forum_id])
    @comment = @forum.comments.create(comment_params)
    redirect_to forum_path
  end

  private

  def comment_params
    params.require(:comment).permit(:body)
  end
end


来源: stackexchange

问:
PHP Timezone Name to Offset
How would I go about converting a timezone name ("Asia/Dubai", "Europe/Andorra", etc) to a GMT offset in hours (or even seconds, since I can convert it from there).

Most people ask for the reverse, but I need to get a timezone offset from the timezone name provided by GeoNames.

答:
Another option would be to use the available DateTimeZone::getOffset() method, which returns the offset in seconds for the time zone at the specified date/time.

```<code>$timezone = new DateTimeZone("Europe/Andorra");
$offset   = $timezone->getOffset(new DateTime);
</code>```

ContentLicense: CC BY-SA 2.5

Title: PHP Timezone Name to Offset

Body:
Another option would be to use the available DateTimeZone::getOffset() method, which returns the offset in seconds for the time zone at the specified date/time.

$timezone = new DateTimeZone("Europe/Andorra");
$offset   = $timezone->getOffset(new DateTime);


问:
Angular 4 cannot read property variable from app component
Thank you for any help, I understand this may be a newby question... but I can't see what I am missing and I have no compilation problems in my TypeScript.

I'm trying to do something quite simple, I want to have a variable that tells me which of my Main Menu Items is selected.

So I binded my HTML with several variables like this: (if you know how I could bind an enum value directly I will appreciate that).

```<code><div id ="menu_popular" class="{{menuClass}}" style=" left:90px; top:368px;">
  Menu Item
</div>
</code>```

Then I want to update my code declarations by invoking a function selectMenu like this:

```<code>import {Component} from '@angular/core';
import {MainMenuItem} from './domain';

@Component ({
          selector: 'app-root',
          templateUrl: './app.component.html',
          styleUrls: ['./app.component.css']
        })
export class AppComponent
{
  title = 'Angular App';
  menuClass = 'div.menu_text';

}

let selectedItem: any = MainMenuItem.POPULAR;

const selectMenu = function (item: MainMenuItem) {
  console.log ('Switching Selected Menu from: ' + selectedItem + ' to: ' + item);
  selectedItem = item;
  console.log('Asigned');
  console.log(this.AppComponent.menuClass);
  if (item === MainMenuItem.YEIIIII)
  {
 ...
 selectMenu (MainMenuItem.YEIIIII);
</code>```

But I will send me a runtime error stating Cannot read property 'AppComponent' of undefined

It seems I can't reach the AppComponent values any way I

```<code>console.log(this.AppComponent.menuClass);
</code>```

or

```<code>console.log(this.menuClass);
</code>```

What am I doing wrong :(

Thanks!

答:
Don't set the this if you want to got the component self.Your function scope is range your const , if you set arrorw function you would got windows scope(like golbal).

code

```<code>export class AppComponent implements AfterContentInit{

  constructor(
    private elementRef:ElementRef
  ) { }

  title = 'Angular App';
  menuClass = 'div.menu_text';
  public selectedItem: any = MainMenuItem.POPULAR;

  ngAfterContentInit(){
    this.selectMenu (MainMenuItem.YEIIIII);
  }

  selectMenu(item: MainMenuItem) {
    console.log('Switching Selected Menu from: ' + this.selectedItem + ' to: ' + item);
    this.selectedItem = item;
    console.log('Asigned');
    console.log(this.menuClass);
    if (item === MainMenuItem.YEIIIII) { }
  }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Thank you for any help, I understand this may be a newby question... but I can't see what I am missing and I have no compilation problems in my TypeScript.

I'm trying to do something quite simple, I want to have a variable that tells me which of my Main Menu Items is selected.

So I binded my HTML with several variables like this: (if you know how I could bind an enum value directly I will appreciate that).

  Menu Item

Then I want to update my code declarations by invoking a function selectMenu like this:

import {Component} from '@angular/core';
import {MainMenuItem} from './domain';

@Component ({
          selector: 'app-root',
          templateUrl: './app.component.html',
          styleUrls: ['./app.component.css']
        })
export class AppComponent
{
  title = 'Angular App';
  menuClass = 'div.menu_text';

}

let selectedItem: any = MainMenuItem.POPULAR;

const selectMenu = function (item: MainMenuItem) {
  console.log ('Switching Selected Menu from: ' + selectedItem + ' to: ' + item);
  selectedItem = item;
  console.log('Asigned');
  console.log(this.AppComponent.menuClass);
  if (item === MainMenuItem.YEIIIII)
  {
 ...
 selectMenu (MainMenuItem.YEIIIII);

But I will send me a runtime error stating Cannot read property 'AppComponent' of undefined

It seems I can't reach the AppComponent values any way I

console.log(this.AppComponent.menuClass);

or

console.log(this.menuClass);

What am I doing wrong :(

Thanks!

Body:
Don't set the this if you want to got the component self.Your function scope is range your const , if you set arrorw function you would got windows scope(like golbal).

code

export class AppComponent implements AfterContentInit{

  constructor(
    private elementRef:ElementRef
  ) { }

  title = 'Angular App';
  menuClass = 'div.menu_text';
  public selectedItem: any = MainMenuItem.POPULAR;

  ngAfterContentInit(){
    this.selectMenu (MainMenuItem.YEIIIII);
  }

  selectMenu(item: MainMenuItem) {
    console.log('Switching Selected Menu from: ' + this.selectedItem + ' to: ' + item);
    this.selectedItem = item;
    console.log('Asigned');
    console.log(this.menuClass);
    if (item === MainMenuItem.YEIIIII) { }
  }

}


问:
Corrupted google font inside swiper slider
I've got little problem with some words inside swiper slider (these with polish chars). I'm using google font's Montserrat. It happens only inside swiper slider. It looks like this:

Online version here: (section our perks [Co zyskujesz z Greenworks?])
http://greenworks.prexperting.com.pl#our-perks

I'm using https://developers.google.com/fonts/docs/webfont_loader for loading fonts.

I'd really appreciate your help :)

答:
Problem solved, thanks to w3c validator :)
C
I've copied text from pdf and some words were in different unicode standard. Retyped those words and all is working now.


问:
looping different php array to display different elements
I am printing content to an html page and the came content is being printed i'm trying to display the 5 different entries.

```<code><?php
       $sql2 = "SELECT * FROM $itemTable ORDER BY RAND() LIMIT 5";
       $selected = $db->query($sql2);
       ?>

                 <h3 class="like">Recommended</h3>
       <?php while($reccomendedItem = mysqli_fetch_assoc($selected)) :?>
         <p><?php echo $reccomendedItem['ProductName']; ?></p>
                 <ul id="example">

        <li><img src="images/pic11.jpg" class="img-responsive" /><div class="grid-flex"><a href="#"><?php echo $reccomendedItem['ProductName']; ?></a><p><?php echo $reccomendedItem['ProductPrice']; ?></p></div></li>
        <li><img src="images/pic10.jpg" class="img-responsive" /><div class="grid-flex"><a href="#"><?php echo $reccomendedItem['ProductName']; ?></a><p><?php echo $reccomendedItem['ProductPrice']; ?></p></div></li>
        <li><img src="images/pic9.jpg" class="img-responsive" /><div class="grid-flex"><a href="#"><?php echo $reccomendedItem['ProductName']; ?></a><p><?php echo $reccomendedItem['ProductPrice']; ?></p></div></li>
        <li><img src="images/pic8.jpg" class="img-responsive" /><div class="grid-flex"><a href="#"><?php echo $reccomendedItem['ProductName']; ?></a><p><?php echo $reccomendedItem['ProductPrice']; ?></p></div></li>
        <li><img src="images/pic7.jpg" class="img-responsive" /><div class="grid-flex"><a href="#"><?php echo $reccomendedItem['ProductName']; ?></a><p><?php echo $reccomendedItem['ProductPrice']; ?></p></div></li>

                 </ul>

         <?php endwhile; ?>
</code>```

This produces the same information in productName for each 5 items.

答:
See here: http://php.net/manual/en/function.mysql-fetch-assoc.php

You should only have 1
 tag inside the loop. If you put all 5 in the loop, it will make 5 copies of the same thing every time it goes through the loop. Also you
 tag should start and finish outside of the loop, otherwise it will be re-inserted every pass.

Try:

```<code><ul id="example">
  <?php while($reccomendedItem = mysqli_fetch_assoc($selected)) :?>
    <li><img src="images/pic11.jpg" class="img-responsive" /><div class="grid-flex"><a href="#"><?php echo $reccomendedItem['ProductName']; ?></a><p><?php echo $reccomendedItem['ProductPrice']; ?></p></div></li>
  <?php endwhile; ?>
</ul>
</code>```

Body:
I am printing content to an html page and the came content is being printed i'm trying to display the 5 different entries.

<?php
       $sql2 = "SELECT * FROM $itemTable ORDER BY RAND() LIMIT 5";
       $selected = $db->query($sql2);
       ?>

Recommended

       <?php while($reccomendedItem = mysqli_fetch_assoc($selected)) :?>

<?php echo $reccomendedItem['ProductName']; ?>

<?php echo $reccomendedItem['ProductName']; ?>
<?php echo $reccomendedItem['ProductPrice']; ?>

<?php echo $reccomendedItem['ProductName']; ?>
<?php echo $reccomendedItem['ProductPrice']; ?>

<?php echo $reccomendedItem['ProductName']; ?>
<?php echo $reccomendedItem['ProductPrice']; ?>

<?php echo $reccomendedItem['ProductName']; ?>
<?php echo $reccomendedItem['ProductPrice']; ?>

<?php echo $reccomendedItem['ProductName']; ?>
<?php echo $reccomendedItem['ProductPrice']; ?>

         <?php endwhile; ?>

This produces the same information in productName for each 5 items.

Body:
See here: http://php.net/manual/en/function.mysql-fetch-assoc.php

You should only have 1 <li> tag inside the loop. If you put all 5 in the loop, it will make 5 copies of the same thing every time it goes through the loop. Also you <ul> tag should start and finish outside of the loop, otherwise it will be re-inserted every pass.

Try:

<ul id="example">
  <?php while($reccomendedItem = mysqli_fetch_assoc($selected)) :?>
    <li><img src="images/pic11.jpg" class="img-responsive" /><div class="grid-flex"><a href="#"><?php echo $reccomendedItem['ProductName']; ?></a><p><?php echo $reccomendedItem['ProductPrice']; ?></p></div></li>
  <?php endwhile; ?>
</ul>


问:
How to fix warning with %ms in scanf
I need to do something like this:

```<code>scanf("%ms", ...)
</code>```

and compile it with

```<code>g++ -Wall -pedantic -std=c++11
</code>```

also with

```<code>gcc -Wall -pedantic -std=c99
</code>```

And it prints warning: ISO C does not support the 'm' scanf flag.
How can i fix it?

答:
Answer: Either drop -pedantic, or give up %ms. They don't come together.

AFAIK, there's nothing like %ms format specifier in ISO C standards. It's added as an extension by POSIX.

The command line argument -pedantic tells GCC to strictly follow the ISO C standards, so it won't accept %ms with that option.

If your program is targeting POSIX systems, it'd be fine if you drop -pedantic. Else if you want to make your code portable, don't use %ms in printf/scanf.

Title: How to fix warning with %ms in scanf

Body:
I need to do something like this:

scanf("%ms", ...)

and compile it with

g++ -Wall -pedantic -std=c++11

also with

gcc -Wall -pedantic -std=c99

And it prints warning: ISO C does not support the 'm' scanf flag.
How can i fix it?


问:
Finding the p-value of the pearson correlation between two non square matrices in R without rcorr() library
I have two non square matrices that i need to find the pearson correlation values and the associated p-values between each other. I'm aware of the rcorr() library, but the RAM memory usage with this library is huge - i have two enormous matrices and i'm unable to use rcorr().

Using the cor() library, i was able to obtain the correlation values. With this correlation array, is possible to make a function to obtain the p-values, without rcorr()??

ps. I also tried to look into Python to do this, but i was only able to found libraries that do not accept non-square matrices such as pearsonr and linegress from scipy.stat.

```<code> data1 <- matrix(runif(30),ncol=5)
 data2 <- matrix(runif(24),ncol=4)
 correlation <-cor(data1,data2,method='pearson')
 correlation
            [,1]       [,2]        [,3]         [,4]
[1,] -0.63451452  0.8311530 -0.18859842  0.004892728
[2,]  0.66676636 -0.8633116  0.02666929  0.010362925
[3,] -0.03299319 -0.4435478  0.06281622 -0.502668829
[4,] -0.79032734  0.7334099 -0.13531482  0.087650016
[5,] -0.02617180  0.5419900  0.67293404  0.112950907
</code>```

答:
Most tests assume for the null hypothesis that the inputs come from independent normally distributed data

They then test t = r * sqrt(n-2) / sqrt(1-r^2) as a t-statistic with n-2 degrees of freedom

So you could try something like this (no extra packages beyond base stats)

```<code>p <- function(t, d) { 1 - 2 * abs(pt(t, d) - 1/2) }
t <- function(r, n) { r * sqrt(n-2) / sqrt(1-r^2) }
rownum <- 6
set.seed(1)
data1 <- matrix(rnorm(5*rownum), nrow=rownum)
data2 <- matrix(rnorm(4*rownum), nrow=rownum)
correlation <- cor(data1, data2, method='pearson')
correlation
p(d(correlation, rownum), rownum-2)
</code>```

giving correlations of

```<code>            [,1]        [,2]       [,3]        [,4]
[1,] -0.52736212 -0.22015909  0.4017038 -0.09294361
[2,]  0.02056352  0.04304460  0.3434117  0.24733758
[3,]  0.40489453  0.73092841 -0.2950121 -0.83761011
[4,]  0.28672335 -0.07727180 -0.3430130 -0.02175433
[5,]  0.52745346  0.09179105 -0.7022999 -0.10932760
</code>```

and p-values of

```<code>    [,1]       [,2]      [,3]       [,4]
[1,] 0.2822894 0.67509693 0.4298549 0.86098603
[2,] 0.9691591 0.93547298 0.5051319 0.63655918
[3,] 0.4258473 0.09885895 0.5703196 0.03741457
[4,] 0.5817008 0.88432299 0.5056595 0.96737366
[5,] 0.2821905 0.86270012 0.1197462 0.83666197
</code>```

one of which is less than 0.05, hardly a surprise since you have 20 values.

Compare the numbers in the bottom right of these matrices with the results of

```<code>> cor.test(data1[,5], data2[,4])

        Pearson's product-moment correlation

data:  data1[, 5] and data2[, 4]
t = -0.21997, df = 4, p-value = 0.8367
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 -0.8458408  0.7706066
sample estimates:
       cor
-0.1093276
</code>```

so this method seems to produce the same answer for the correlation and p-value

Body:
I have two non square matrices that i need to find the pearson correlation values and the associated p-values between each other. I'm aware of the rcorr() library, but the RAM memory usage with this library is huge - i have two enormous matrices and i'm unable to use rcorr().

Using the cor() library, i was able to obtain the correlation values. With this correlation array, is possible to make a function to obtain the p-values, without rcorr()??

ps. I also tried to look into Python to do this, but i was only able to found libraries that do not accept non-square matrices such as pearsonr and linegress from scipy.stat.

 data1 <- matrix(runif(30),ncol=5)
 data2 <- matrix(runif(24),ncol=4)
 correlation <-cor(data1,data2,method='pearson')
 correlation
            [,1]       [,2]        [,3]         [,4]
[1,] -0.63451452  0.8311530 -0.18859842  0.004892728
[2,]  0.66676636 -0.8633116  0.02666929  0.010362925
[3,] -0.03299319 -0.4435478  0.06281622 -0.502668829
[4,] -0.79032734  0.7334099 -0.13531482  0.087650016
[5,] -0.02617180  0.5419900  0.67293404  0.112950907

Body:
Most tests assume for the null hypothesis that the inputs come from independent normally distributed data

They then test t = r * sqrt(n-2) / sqrt(1-r^2) as a t-statistic with n-2 degrees of freedom

So you could try something like this (no extra packages beyond base stats)

p <- function(t, d) { 1 - 2 * abs(pt(t, d) - 1/2) }
t <- function(r, n) { r * sqrt(n-2) / sqrt(1-r^2) }
rownum <- 6
set.seed(1)
data1 <- matrix(rnorm(5*rownum), nrow=rownum)
data2 <- matrix(rnorm(4*rownum), nrow=rownum)
correlation <- cor(data1, data2, method='pearson')
correlation
p(d(correlation, rownum), rownum-2)

giving correlations of

            [,1]        [,2]       [,3]        [,4]
[1,] -0.52736212 -0.22015909  0.4017038 -0.09294361
[2,]  0.02056352  0.04304460  0.3434117  0.24733758
[3,]  0.40489453  0.73092841 -0.2950121 -0.83761011
[4,]  0.28672335 -0.07727180 -0.3430130 -0.02175433
[5,]  0.52745346  0.09179105 -0.7022999 -0.10932760

and p-values of

    [,1]       [,2]      [,3]       [,4]
[1,] 0.2822894 0.67509693 0.4298549 0.86098603
[2,] 0.9691591 0.93547298 0.5051319 0.63655918
[3,] 0.4258473 0.09885895 0.5703196 0.03741457
[4,] 0.5817008 0.88432299 0.5056595 0.96737366
[5,] 0.2821905 0.86270012 0.1197462 0.83666197

one of which is less than 0.05, hardly a surprise since you have 20 values.

Compare the numbers in the bottom right of these matrices with the results of

> cor.test(data1[,5], data2[,4])

        Pearson's product-moment correlation

data:  data1[, 5] and data2[, 4]
t = -0.21997, df = 4, p-value = 0.8367
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 -0.8458408  0.7706066
sample estimates:
       cor
-0.1093276

so this method seems to produce the same answer for the correlation and p-value


问:
Understanding the delegates in UITableView and UITableViewController
I am learning how to use the UITableView and UITableViewController in the iOS and I think I may have confused myself. I have created a simple TableView and I have 2 sections.  Nothing complicated.

I have the following defined and it builds fine:

```<code>-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    // Section is going to be either 0 or 1, high or low
    if (section == 0) {
        return 1;
    }
    else {
        return 2;
    }
}
</code>```

However what I don't understand is the definitions of the methods.  Both methods have to return an integer so I understand the starting (NSInteger).  The numberOfRowsInSection starts with tableView:(UITableView *)tableView and I don't understand why?

I'm am new to programming the iOS so be gentle :-)  All help greatly appreciated.

Mike

答:
Check out the UITableViewController Class Reference

```<code>- (NSInteger)tableView:(UITableView *)tableView
</code>```

The first part, NSInteger lets you know that you need to return a number return 1;, the second part (UITableView *)tableView lets you know that you are dealing with the UITableView class.

Body:
I am learning how to use the UITableView and UITableViewController in the iOS and I think I may have confused myself. I have created a simple TableView and I have 2 sections.  Nothing complicated.

I have the following defined and it builds fine:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section
{
    // Section is going to be either 0 or 1, high or low
    if (section == 0) {
        return 1;
    }
    else {
        return 2;
    }
}

However what I don't understand is the definitions of the methods.  Both methods have to return an integer so I understand the starting (NSInteger).  The numberOfRowsInSection starts with tableView:(UITableView *)tableView and I don't understand why?

I'm am new to programming the iOS so be gentle :-)  All help greatly appreciated.

Mike

Body:
Check out the UITableViewController Class Reference

- (NSInteger)tableView:(UITableView *)tableView

The first part, NSInteger lets you know that you need to return a number return 1;, the second part (UITableView *)tableView lets you know that you are dealing with the UITableView class.


问:
Highly Available Bot in multiple regions using bot framework
We are planning to use Microsoft Bot framework to develop bot. We are having large user base in different countries which we want to cater through bot. Theoretically, We would like deploy bot service in different regions (so there there would be less latency) but still, there should be one single bot rather than having country specific bot.

Behind the scene, bot which I would be  writing,  will call API(services) of my web application.

As there is traffic manager is used for highly available systems deployed in different regions, will it be the same thing in case of bot service?

答:
@JasonSowers is right. Bot Framework SDK for C# is built with Web API, and Bot Framework SDK for Nodejs is built with restify. Both are all basically web applications. You can deploy your bot application on any web services who support cross regions. E.G. You can leverage Azure Web Apps for this requirement, please refer to Run a web application in multiple regions on Azure.

Hope it helps.


问:
How to convert a date format YYYY-MM-DD into integer YYYYMMDD in Presto/Hive?
How to CONVERT a date in format YYYY-MM-DD into integer YYYYMMDD in Presto/Hive?

I am trying to convert the below list into YYYYMMDD integers

```<code>WITH  all_dates  as (SELECT
    CAST(date_column AS DATE) date_column
FROM
    (VALUES
        (SEQUENCE(FROM_ISO8601_DATE('2017-07-01'),
                  FROM_ISO8601_DATE('2017-11-15'),
                  INTERVAL '1' DAY)
        )
    ) AS t1(date_array)
CROSS JOIN
    UNNEST(date_array) AS t2(date_column)
    )
</code>```

I tried something like this but it doesn't work

```<code>   SELECT
   CAST(
      CAST(year(date_column) AS VARCHAR(4)) +
      right('0' + CAST(month(date_column) AS VARCHAR(2)), 2) +
      right('0' + CAST(day(date_column) AS VARCHAR(2)), 2)
   AS DATETIME)
   FROM all_dates
</code>```

答:
Simply REPLACE the '-' with Empty string and CAST it into INT.

Try the following:

```<code>SELECT CAST(REPLACE(Date_Column,'-','') AS INT)
</code>```

Body:
How to CONVERT a date in format YYYY-MM-DD into integer YYYYMMDD in Presto/Hive?

I am trying to convert the below list into YYYYMMDD integers

WITH  all_dates  as (SELECT
    CAST(date_column AS DATE) date_column
FROM
    (VALUES
        (SEQUENCE(FROM_ISO8601_DATE('2017-07-01'),
                  FROM_ISO8601_DATE('2017-11-15'),
                  INTERVAL '1' DAY)
        )
    ) AS t1(date_array)
CROSS JOIN
    UNNEST(date_array) AS t2(date_column)
    )

I tried something like this but it doesn't work

   SELECT
   CAST(
      CAST(year(date_column) AS VARCHAR(4)) +
      right('0' + CAST(month(date_column) AS VARCHAR(2)), 2) +
      right('0' + CAST(day(date_column) AS VARCHAR(2)), 2)
   AS DATETIME)
   FROM all_dates

Body:
Simply REPLACE the '-' with Empty string and CAST it into INT.

Try the following:

SELECT CAST(REPLACE(Date_Column,'-','') AS INT)


问:
divs with vertical line
I need help about this image. How can I  set it up in css and in html thank you in advance if anyone will give time to help me.

答:
What I would recommend is to consider the image to be a background of one element. Then create a child of that element that only occupies the left-hand half of the image. In order to achieve this, the child needs the following styles:

```<code>#child {
  position: relative; /* To position the border in relation to the image parent */
  width: calc(50% - 2px); /* 2px correlates to the width of the border */
  height: 100%; /* To occupy the full height of the image */
}
</code>```

Now the the element is invisibly sitting on the left-hand half of the image, you can apply a border to the right-hand side of this element with border-right: 2px solid cyan.

This results in a line halfway through the image, as can be seen in the following:

#container {
  width: 300px;
  height: 200px;
  background: url(http://placehold.it/100);
}

#child {
  position: relative;
  width: calc(50% - 2px);
  height: 100%;
  border-right: 2px solid cyan;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <div id="child"></div>
</div></code>```

Hope this helps! :)

Title: divs with vertical line

Body:
What I would recommend is to consider the image to be a background of one element. Then create a child of that element that only occupies the left-hand half of the image. In order to achieve this, the child needs the following styles:

#child {
  position: relative; /* To position the border in relation to the image parent */
  width: calc(50% - 2px); /* 2px correlates to the width of the border */
  height: 100%; /* To occupy the full height of the image */
}

Now the the element is invisibly sitting on the left-hand half of the image, you can apply a border to the right-hand side of this element with border-right: 2px solid cyan.

This results in a line halfway through the image, as can be seen in the following:

#container {
  width: 300px;
  height: 200px;
  background: url(http://placehold.it/100);
}

#child {
  position: relative;
  width: calc(50% - 2px);
  height: 100%;
  border-right: 2px solid cyan;
}

<div id="container">
  <div id="child"></div>
</div>

Hope this helps! :)


问:
rhandsontable update in R Shiny App
I am trying to get an R shiny built with the following functionalities:

The user have two options to input their data that needs further processing in the app, upload csv file or fill in a table within the app.

I am able to get csv file upload working fine. The issue is with table portion. When user selects to input table, a 2 columns by 10 rows table appear. Once user updates it and saves the table, the table should be converted to data frame for further processing.

Below is my code so far. If I select table radiobutton, and update the table with values and hit save, it gives me error message. The error message indicate some issue with my calling of hot_to_r() function. Below is full error message:

```<code>Warning: Error in row.names<-.data.frame: invalid 'row.names' length
Stack trace (innermost first):
    71: row.names<-.data.frame
    70: row.names<-
    69: rownames<-
    68: <Anonymous>
    67: do.call
    66: hot_to_r
    65: observeEventHandler [C:\Users\kmehta\Documents\Projects\Enhanze\Test/server.R#46]
     1: runApp
</code>```

Thanks,
Krina

ui.R

```<code>library(shiny)
library(shinydashboard)
library(shinyBS)
library(dplyr)
library(gdata)
library(rhandsontable)

#Design sidebar
sidebar <- dashboardSidebar(width = 200, collapsed=F,
                            sidebarMenu(id="tabs",
                                        menuItem("TEST", tabName = "thick", icon = icon("puzzle-piece"))))

#Design body
body <- dashboardBody(
  tabItems(
    tabItem(tabName = "thick",
            box(collapsible=TRUE, width = 4, status = "success", solidHeader = T, title="Input",
                radioButtons(inputId="fileInput", "Choose data input method", choices = c("csv", "table"), selected = 'csv'),
                conditionalPanel(condition = "input.fileInput == 'csv'",
                                 fileInput(inputId="file", label = "Upload data in CSV file", accept = c(".csv"))),
                conditionalPanel(condition="input.fileInput == 'table'",
                                 rHandsontableOutput("hot"),
                                 actionButton("save", "Save table")),
                numericInput('Dose', 'mAB dose (mg)', value=0, min=0),
                actionButton('gothick','Run', class='btn btn-info', icon=icon('play-circle-o','fg-lg'))),
            box(collapsible=T, width=6, status = "success", solidHeader = T, title="Table", tableOutput('Table')))
  ))

#Show title and the page (includes sidebar and body)
dashboardPage(skin="blue",
              dashboardHeader(title = "TEST",
                              titleWidth = 800),
              sidebar,  body)
</code>```

Server.R

```<code>library(shiny)
library(shinydashboard)
library(shinyBS)
library(RxODE)
library(ggplot2)
library(dplyr)
library(gdata)
library(rhandsontable)

Concentration <- c(0,0,0,0,0,0,0,0,0,0)
Viscosity <- c(0,0,0,0,0,0,0,0,0,0)
DF <- data.frame(Concentration, Viscosity)

shinyServer(function(input, output, session){

#Handsontable

  output$hot <- renderRHandsontable({
    rhandsontable(DF, useTypes = F)
  })

  observeEvent(input$save, {
    DF1 = hot_to_r(input$hot)
    finalDF <- DF1
    })

  ThickFastFun <- eventReactive(input$gothick, {
    if (!is.null(input$file))
    {dat <- read.csv(inFile$datapath, header=T, stringsAsFactors = F)}
    else {dat <- finalDF}
    return(dat)
  })

  #Table
  ThickFast_Table <- reactiveValues(df = NULL)
  observeEvent(input$gothick, {
    ThickFast_Table$df <- ThickFastFun()})

  output$ThickFastTable <- renderTable({ThickFast_Table$df})

})
</code>```

答:
This seems to be a known issue with older version of rhandsontable that is available through CRAN.

The solution is to install rhandsontable package from github.

```<code>devtools::install_github("jrowen/rhandsontable", dependencies = T, upgrade_dependencies = T)
</code>```

Title: rhandsontable update in R Shiny App

Body:
I am trying to get an R shiny built with the following functionalities:

The user have two options to input their data that needs further processing in the app, upload csv file or fill in a table within the app.

I am able to get csv file upload working fine. The issue is with table portion. When user selects to input table, a 2 columns by 10 rows table appear. Once user updates it and saves the table, the table should be converted to data frame for further processing.

Below is my code so far. If I select table radiobutton, and update the table with values and hit save, it gives me error message. The error message indicate some issue with my calling of hot_to_r() function. Below is full error message:

Warning: Error in row.names<-.data.frame: invalid 'row.names' length
Stack trace (innermost first):
    71: row.names<-.data.frame
    70: row.names<-
    69: rownames<-
    68: <Anonymous>
    67: do.call
    66: hot_to_r
    65: observeEventHandler [C:\Users\kmehta\Documents\Projects\Enhanze\Test/server.R#46]
     1: runApp

Thanks,
Krina

ui.R

library(shiny)
library(shinydashboard)
library(shinyBS)
library(dplyr)
library(gdata)
library(rhandsontable)

#Design sidebar
sidebar <- dashboardSidebar(width = 200, collapsed=F,
                            sidebarMenu(id="tabs",
                                        menuItem("TEST", tabName = "thick", icon = icon("puzzle-piece"))))

#Design body
body <- dashboardBody(
  tabItems(
    tabItem(tabName = "thick",
            box(collapsible=TRUE, width = 4, status = "success", solidHeader = T, title="Input",
                radioButtons(inputId="fileInput", "Choose data input method", choices = c("csv", "table"), selected = 'csv'),
                conditionalPanel(condition = "input.fileInput == 'csv'",
                                 fileInput(inputId="file", label = "Upload data in CSV file", accept = c(".csv"))),
                conditionalPanel(condition="input.fileInput == 'table'",
                                 rHandsontableOutput("hot"),
                                 actionButton("save", "Save table")),
                numericInput('Dose', 'mAB dose (mg)', value=0, min=0),
                actionButton('gothick','Run', class='btn btn-info', icon=icon('play-circle-o','fg-lg'))),
            box(collapsible=T, width=6, status = "success", solidHeader = T, title="Table", tableOutput('Table')))
  ))

#Show title and the page (includes sidebar and body)
dashboardPage(skin="blue",
              dashboardHeader(title = "TEST",
                              titleWidth = 800),
              sidebar,  body)

Server.R

library(shiny)
library(shinydashboard)
library(shinyBS)
library(RxODE)
library(ggplot2)
library(dplyr)
library(gdata)
library(rhandsontable)

Concentration <- c(0,0,0,0,0,0,0,0,0,0)
Viscosity <- c(0,0,0,0,0,0,0,0,0,0)
DF <- data.frame(Concentration, Viscosity)

shinyServer(function(input, output, session){

#Handsontable

  output$hot <- renderRHandsontable({
    rhandsontable(DF, useTypes = F)
  })

  observeEvent(input$save, {
    DF1 = hot_to_r(input$hot)
    finalDF <- DF1
    })

  ThickFastFun <- eventReactive(input$gothick, {
    if (!is.null(input$file))
    {dat <- read.csv(inFile$datapath, header=T, stringsAsFactors = F)}
    else {dat <- finalDF}
    return(dat)
  })

  #Table
  ThickFast_Table <- reactiveValues(df = NULL)
  observeEvent(input$gothick, {
    ThickFast_Table$df <- ThickFastFun()})

  output$ThickFastTable <- renderTable({ThickFast_Table$df})

})

Body:
This seems to be a known issue with older version of rhandsontable that is available through CRAN.

The solution is to install rhandsontable package from github.

devtools::install_github("jrowen/rhandsontable", dependencies = T, upgrade_dependencies = T)


问:
C# Which Event should I use to display data in a textbox when I select an item in a listbox?
C# Which Event should I use to display data in a textbox when I select an item in a listbox?

I want to select an item in a list box (winforms) and then a textbox near by show some data related to that item but I don't know which event to use. I'll need to be able to click down the list and watch the textbox text update with each click.

Thanks

答:
Is the SelectedIndexChanged event not working for you?</p>

```<code>private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
    relatedTextbox.Text = listBox1.SelectedItem.ToString();
}
</code>```

OwnerDisplayName: Steve

Body:
Is the SelectedIndexChanged event not working for you?

private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
    relatedTextbox.Text = listBox1.SelectedItem.ToString();
}

OwnerDisplayName: Bob

LastEditorDisplayName: Bob


问:
basic wcf message contract soap header question
I have the following operation contract method:

```<code>[OperationContract]
MyOutputMessageType DeleteVRequest(DeleteVRequest type);

[MessageContract]
public class DeleteVRequest
   {

    [MessageHeader(Name = "UserId")]
    public Guid UserId;

    [MessageHeader(Name = "Password")]
    public String Password;

    [MessageHeader(Name = "Version")]
    public String Version;

    [MessageBodyMember]
    public Guid Id;
}

[MessageContract]
public class MyOutputMessageType
{
    [MessageBodyMember]
    public string Response;
}
</code>```

My question is how are the soap header values of the contract (userid,password,version) set for the call on the client side? If I write a header value using Add on the outgoingmessageheaders it does not seem to map to the value in the messagecontract. So for instance if I add a UserId value to the headers, it does not seem to see that within the DeleteVRequest method.

Thanks for any help, I've really been struggling with SOAP header reader/writing in SOAP.

答:
If the client side is using .NET, the service proxy will take in a message contract rather than the data contract, and you can set the header properties as you would any other properties.

Otherwise, you can using the OperationContextScope to set header values manually:

```<code>using(OperationContextScope context = new OperationContextScope(proxy.InnerChannel))
{
    OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("HeaderName", "HeaderNamespace", "SomeValue"));

    //Make your proxy calls here
}
</code>```

Body:
I have the following operation contract method:

[OperationContract]
MyOutputMessageType DeleteVRequest(DeleteVRequest type);

[MessageContract]
public class DeleteVRequest
   {

    [MessageHeader(Name = "UserId")]
    public Guid UserId;

    [MessageHeader(Name = "Password")]
    public String Password;

    [MessageHeader(Name = "Version")]
    public String Version;

    [MessageBodyMember]
    public Guid Id;
}

[MessageContract]
public class MyOutputMessageType
{
    [MessageBodyMember]
    public string Response;
}

My question is how are the soap header values of the contract (userid,password,version) set for the call on the client side? If I write a header value using Add on the outgoingmessageheaders it does not seem to map to the value in the messagecontract. So for instance if I add a UserId value to the headers, it does not seem to see that within the DeleteVRequest method.

Thanks for any help, I've really been struggling with SOAP header reader/writing in SOAP.

Body:
If the client side is using .NET, the service proxy will take in a message contract rather than the data contract, and you can set the header properties as you would any other properties.

Otherwise, you can using the OperationContextScope to set header values manually:

using(OperationContextScope context = new OperationContextScope(proxy.InnerChannel))
{
    OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("HeaderName", "HeaderNamespace", "SomeValue"));

    //Make your proxy calls here
}


问:
Compiling ffmpeg for Android on OSX
I'm trying to compile ffmpeg for Android, on OSX 10.12.4 .

Here are the steps I followed:

1°) Compile pkg-config

Download the sources from here . Extract && cd in the pkg-config folder.

```<code>export DST=/a/path/on/my/computer

./configure --with-internal-glib --prefix=$DST --exec-prefix=$DST
make -j2
make install

export PATH=$PATH:$DST/bin
</code>```

2°) Compile ffmpeg

Download the sources from here. Extract && cd in the ffmpeg folder.

```<code>export NDK=/path/to/android-ndk-r15c
export PLATFORM_VERSION=android-26
export ARCH=arm
export PLATFORM=$NDK/platforms/$PLATFORM_VERSION/arch-$ARCH
export TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64

export PREFIX=$(pwd)/android/$ARCH

export ADDI_CFLAGS="-Os -fpic -marm"
export ADDI_CONFIGURE_FLAG=""
export ADDI_LDFLAGS=""

./configure \
  --prefix=$PREFIX \
  --enable-shared \
  --disable-static \
  --disable-doc \
  --disable-ffmpeg \
  --disable-ffplay \
  --disable-ffprobe \
  --disable-ffserver \
  --disable-symver \
  --disable-avdevice \
  \
  --pkg-config=pkg-config \
  \
  --cross-prefix=$TOOLCHAIN/bin/arm-linux-androideabi- \
  --target-os=linux \
  --arch=$ARCH \
  --enable-cross-compile \
  --sysroot=$PLATFORM \
  --extra-cflags="$ADDI_CFLAGS" \
  --extra-ldflags="$ADDI_LDFLAGS" \
  \
  $ADDI_CONFIGURE_FLAG

make -j2
</code>```

Make fails with the following error:

```<code>AR  libavfilter/libavfilter.a
AR  libavformat/libavformat.a
CC  libavcodec/aaccoder.o
In file included from /Users/Tim/Library/Android/android-ndk-r15c/platforms/android-26/arch-arm/usr/include/asm/termbits.h:19:0,
from /Users/Tim/Library/Android/android-ndk-r15c/platforms/android-26/arch-arm/usr/include/asm-generic/termios.h:21,
from /Users/Tim/Library/Android/android-ndk-r15c/platforms/android-26/arch-arm/usr/include/asm/termios.h:19,
from /Users/Tim/Library/Android/android-ndk-r15c/platforms/android-26/arch-arm/usr/include/linux/termios.h:22,
from /Users/Tim/Library/Android/android-ndk-r15c/platforms/android-26/arch-arm/usr/include/sys/ioctl.h:37,
from ./libavutil/timer.h:36,
from ./libavutil/internal.h:42,
from ./libavutil/common.h:467,
from libavcodec/mathops.h:27,
from libavcodec/aaccoder.c:38:
libavcodec/aaccoder.c: In function 'search_for_ms':
libavcodec/aaccoder.c:803:25: error: expected identifier or '(' before numeric constant
int B0 = 0, B1 = 0;
^
libavcodec/aaccoder.c:865:28: error: lvalue required as left operand of assignment
B0 += b1+b2;
^
libavcodec/aaccoder.c:866:25: error: 'B1' undeclared (first use in this function)
B1 += b3+b4;
^
libavcodec/aaccoder.c:866:25: note: each undeclared identifier is reported only once for each function it appears in
make: *** [libavcodec/aaccoder.o] Error 1
make: *** Waiting for unfinished jobs....
</code>```

I'm able to fix that error by renaming B0 & B1 variables in the source to A0 & A1 (don't know why it fixes the problem), but then it fails somewhere else. I guess something is wrong in my config, and I'd prefer to avoid having to patch the source.

So the questions are:

does someone know what's wrong here? Do I need to give some args to gcc?

is the --target-os=linux correct, or should it be --target-os=darwin? Is target-os the OS where the compilation is done, or where ffmpeg will be executed? By using darwin, I can compile using --enable-static, but not --enable-shared (which I want).

Note: I need to compile it myself as I want only an arm version, with HTTPS support. Thus I can't use the existing built versions.

答:
I also met this problem when I tried to build the ffmpeg 3.4 the latest version.I wish you could try the 3.3 version.I built it successfully.
I doubt that latest version is unstable and with some bug.
By the way,You can take some answer By this article:
http://alientechlab.com/how-to-build-ffmpeg-for-android/</p>

Title: Compiling ffmpeg for Android on OSX

Body:
I'm trying to compile ffmpeg for Android, on OSX 10.12.4 .

Here are the steps I followed:

1°) Compile pkg-config

Download the sources from here . Extract && cd in the pkg-config folder.

export DST=/a/path/on/my/computer

./configure --with-internal-glib --prefix=$DST --exec-prefix=$DST
make -j2
make install

export PATH=$PATH:$DST/bin

2°) Compile ffmpeg

Download the sources from here. Extract && cd in the ffmpeg folder.

export NDK=/path/to/android-ndk-r15c
export PLATFORM_VERSION=android-26
export ARCH=arm
export PLATFORM=$NDK/platforms/$PLATFORM_VERSION/arch-$ARCH
export TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64

export PREFIX=$(pwd)/android/$ARCH

export ADDI_CFLAGS="-Os -fpic -marm"
export ADDI_CONFIGURE_FLAG=""
export ADDI_LDFLAGS=""

./configure \
  --prefix=$PREFIX \
  --enable-shared \
  --disable-static \
  --disable-doc \
  --disable-ffmpeg \
  --disable-ffplay \
  --disable-ffprobe \
  --disable-ffserver \
  --disable-symver \
  --disable-avdevice \
  \
  --pkg-config=pkg-config \
  \
  --cross-prefix=$TOOLCHAIN/bin/arm-linux-androideabi- \
  --target-os=linux \
  --arch=$ARCH \
  --enable-cross-compile \
  --sysroot=$PLATFORM \
  --extra-cflags="$ADDI_CFLAGS" \
  --extra-ldflags="$ADDI_LDFLAGS" \
  \
  $ADDI_CONFIGURE_FLAG

make -j2

Make fails with the following error:

AR  libavfilter/libavfilter.a
AR  libavformat/libavformat.a
CC  libavcodec/aaccoder.o
In file included from /Users/Tim/Library/Android/android-ndk-r15c/platforms/android-26/arch-arm/usr/include/asm/termbits.h:19:0,
from /Users/Tim/Library/Android/android-ndk-r15c/platforms/android-26/arch-arm/usr/include/asm-generic/termios.h:21,
from /Users/Tim/Library/Android/android-ndk-r15c/platforms/android-26/arch-arm/usr/include/asm/termios.h:19,
from /Users/Tim/Library/Android/android-ndk-r15c/platforms/android-26/arch-arm/usr/include/linux/termios.h:22,
from /Users/Tim/Library/Android/android-ndk-r15c/platforms/android-26/arch-arm/usr/include/sys/ioctl.h:37,
from ./libavutil/timer.h:36,
from ./libavutil/internal.h:42,
from ./libavutil/common.h:467,
from libavcodec/mathops.h:27,
from libavcodec/aaccoder.c:38:
libavcodec/aaccoder.c: In function 'search_for_ms':
libavcodec/aaccoder.c:803:25: error: expected identifier or '(' before numeric constant
int B0 = 0, B1 = 0;
^
libavcodec/aaccoder.c:865:28: error: lvalue required as left operand of assignment
B0 += b1+b2;
^
libavcodec/aaccoder.c:866:25: error: 'B1' undeclared (first use in this function)
B1 += b3+b4;
^
libavcodec/aaccoder.c:866:25: note: each undeclared identifier is reported only once for each function it appears in
make: *** [libavcodec/aaccoder.o] Error 1
make: *** Waiting for unfinished jobs....

I'm able to fix that error by renaming B0 & B1 variables in the source to A0 & A1 (don't know why it fixes the problem), but then it fails somewhere else. I guess something is wrong in my config, and I'd prefer to avoid having to patch the source.

So the questions are:

does someone know what's wrong here? Do I need to give some args to gcc?

is the --target-os=linux correct, or should it be --target-os=darwin? Is target-os the OS where the compilation is done, or where ffmpeg will be executed? By using darwin, I can compile using --enable-static, but not --enable-shared (which I want).

Note: I need to compile it myself as I want only an arm version, with HTTPS support. Thus I can't use the existing built versions.


问:
Function arguments inheriting defaults from other function
Let's say there's a function in a Python library (let's call it mymodule):

```<code>def some_func(a,b='myDefaultValue'):
    return some_computation
</code>```

and then there's another function in another module that calls it,

```<code>import mymodule
def wrapper(a,b):
    return some_transform(mymodule.some_func(a,b))
</code>```

How do I make it such that wrapper inherits some_func's default value for the b parameter? I could do something like:

```<code>def wrapper(a,b=None):
    if b:
        return some_transform(some_func(a,b))
    else:
        return some_transform(some_func(a))
</code>```

but that seems needlessly cumbersome, leads to a combinatorial explosion of possibilities with multiple optional arguments, and makes it so I can't explicitly pass in None to wrapper.

Is there a way of getting the default args for a function, or is common practice to simply pull that value out into a shared constant that both function declarations can make use of?

答:
You can use argument unpacking to accomplish this:

```<code>In [1]: def some_func(a,b='myDefaultValue'):
   ...:     print a, b
   ...:

In [2]: def wrapper(a, *args, **kwargs):
   ...:     some_func(a, *args, **kwargs)
   ...:

In [3]: some_func('foo', 'bar')
foo bar

In [4]: some_func('baz')
baz myDefaultValue

In [5]: wrapper('foo', 'bar')
foo bar

In [6]: wrapper('baz')
baz myDefaultValue
</code>```

If you plan to wrap multiple functions in this way, you might consider making wrapper a decorator:

```<code>In [1]: from functools import wraps

In [2]: def wrapper(func):
   ...:     @wraps(func)
   ...:     def decorated(a, *args, **kwargs):
   ...:         print 'wrapper invoked with a = {}'.format(a)
   ...:         return func(a, *args, **kwargs)
   ...:     return decorated
   ...:

In [3]: @wrapper
   ...: def some_func(a, b='myDefaultValue'):
   ...:     print a, b
   ...:

In [4]: some_func('foo', 'bar')
wrapper invoked with a = foo
foo bar

In [5]: some_func('baz')
wrapper invoked with a = baz
baz myDefaultValue
</code>```

Body:
Let's say there's a function in a Python library (let's call it mymodule):

def some_func(a,b='myDefaultValue'):
    return some_computation

and then there's another function in another module that calls it,

import mymodule
def wrapper(a,b):
    return some_transform(mymodule.some_func(a,b))

How do I make it such that wrapper inherits some_func's default value for the b parameter? I could do something like:

def wrapper(a,b=None):
    if b:
        return some_transform(some_func(a,b))
    else:
        return some_transform(some_func(a))

but that seems needlessly cumbersome, leads to a combinatorial explosion of possibilities with multiple optional arguments, and makes it so I can't explicitly pass in None to wrapper.

Is there a way of getting the default args for a function, or is common practice to simply pull that value out into a shared constant that both function declarations can make use of?

Body:
You can use argument unpacking to accomplish this:

In [1]: def some_func(a,b='myDefaultValue'):
   ...:     print a, b
   ...:

In [2]: def wrapper(a, *args, **kwargs):
   ...:     some_func(a, *args, **kwargs)
   ...:

In [3]: some_func('foo', 'bar')
foo bar

In [4]: some_func('baz')
baz myDefaultValue

In [5]: wrapper('foo', 'bar')
foo bar

In [6]: wrapper('baz')
baz myDefaultValue

If you plan to wrap multiple functions in this way, you might consider making wrapper a decorator:

In [1]: from functools import wraps

In [2]: def wrapper(func):
   ...:     @wraps(func)
   ...:     def decorated(a, *args, **kwargs):
   ...:         print 'wrapper invoked with a = {}'.format(a)
   ...:         return func(a, *args, **kwargs)
   ...:     return decorated
   ...:

In [3]: @wrapper
   ...: def some_func(a, b='myDefaultValue'):
   ...:     print a, b
   ...:

In [4]: some_func('foo', 'bar')
wrapper invoked with a = foo
foo bar

In [5]: some_func('baz')
wrapper invoked with a = baz
baz myDefaultValue


问:
How to access elements in the table cell
I have an HTML table to traverse using DOM.
I begin accessing using my table id and then I am able to access a particular cell.

```<code>'<td><a onclick=send_symbol_2(\"'+comp+'\")>'+comp+'</a></td>'
</code>```

I am confused on how to access the data contained within anchor tags. I had earlier constructed the table by adding strings.
eg: '
	'+arr[4]+'
'
I understand toString() would been called.
I am unsure how to proceed further.
I used

```<code>rows[i].getElementsByTagName("td")[0]
</code>```

to access the cell data.

答:
Let's say we have such a table

```<code><table id="table">
  <tr><td>11</td><td>12</td></tr>
  <tr><td>21</td><td>22</td></tr>
</table>
</code>```

Then to access some specific cell content I would use the following approach:

```<code>  function getCellContent(x, y) {
    x = parseInt(x, 10);
    y = parseInt(y, 10);
    if(isNaN(x) || --x < 0 || isNaN(y) || --y < 0) {
      return;
    }
    var tE = document.getElementById('table');
    var rows = tE.getElementsByTagName('tr');
    if(!rows || y >= rows.length) {
      return;
    }
    var row = rows[y];
    var cells = row.getElementsByTagName('td');
    if(!cells || x >= cells.length) {
      return;
    }
    var cell = cells[x];
    return cell.innerHTML;
  }

  console.log(getCellContent(1, 2)); // "12"
</code>```

Note, that x, y arguments are being started from "1". That's why I decrementing arguments. Three return statements are for bad params and out-of-range protections. So you'll get just undefined if something's not ok.

I also created a Plunker demo.

Body:
I have an HTML table to traverse using DOM.
I begin accessing using my table id and then I am able to access a particular cell.

''+comp+'	'

I am confused on how to access the data contained within anchor tags. I had earlier constructed the table by adding strings.
eg: '
	'+arr[4]+'
'
I understand toString() would been called.
I am unsure how to proceed further.
I used

rows[i].getElementsByTagName("td")[0]

to access the cell data.

Body:
Let's say we have such a table

<table id="table">
  <tr><td>11</td><td>12</td></tr>
  <tr><td>21</td><td>22</td></tr>
</table>

Then to access some specific cell content I would use the following approach:

  function getCellContent(x, y) {
    x = parseInt(x, 10);
    y = parseInt(y, 10);
    if(isNaN(x) || --x < 0 || isNaN(y) || --y < 0) {
      return;
    }
    var tE = document.getElementById('table');
    var rows = tE.getElementsByTagName('tr');
    if(!rows || y >= rows.length) {
      return;
    }
    var row = rows[y];
    var cells = row.getElementsByTagName('td');
    if(!cells || x >= cells.length) {
      return;
    }
    var cell = cells[x];
    return cell.innerHTML;
  }

  console.log(getCellContent(1, 2)); // "12"

Note, that x, y arguments are being started from "1". That's why I decrementing arguments. Three return statements are for bad params and out-of-range protections. So you'll get just undefined if something's not ok.

I also created a Plunker demo.


问:
Reading port numbers of a switch configured with V1
SNMP agent on switch is configured with V1. I am using lextm snmp library VersionCode.V2 to fetch port numbers which is not working. Should the versions match to fetch the info?</p>

答:
According to SNMPv1 & SNMPv2c interoperability, it appears they do:

```<code>As presently specified, SNMPv2c is incompatible with SNMPv1 in two key
areas: message formats and protocol operations. SNMPv2c messages use
different header and protocol data unit (PDU) formats from SNMPv1 messages.
SNMPv2c also uses two protocol operations that are not specified in SNMPv1.
Furthermore, RFC 2576 defines two possible SNMPv1/v2c coexistence
strategies: proxy agents and bilingual network-management systems.
</code>```

Any reason why you have chosen to implement the client in v2 when targeting a v1 agent?

Body:
According to SNMPv1 & SNMPv2c interoperability, it appears they do:

As presently specified, SNMPv2c is incompatible with SNMPv1 in two key
areas: message formats and protocol operations. SNMPv2c messages use
different header and protocol data unit (PDU) formats from SNMPv1 messages.
SNMPv2c also uses two protocol operations that are not specified in SNMPv1.
Furthermore, RFC 2576 defines two possible SNMPv1/v2c coexistence
strategies: proxy agents and bilingual network-management systems.

Any reason why you have chosen to implement the client in v2 when targeting a v1 agent?


问:
"cannot load such file -- rubygems/defaults/operating_system" when installing Ruby 2.0.0
I have need of Ruby 2.0.0, so I turned to RVM to help manage my ruby installations.

However, when I do rvm install ruby-2.0.0, the installation ends up bombing out.

```<code>$ rvm install ruby-2.0.0
Searching for binary rubies, this might take some time.
No binary rubies available for: osx/10.12/x86_64/ruby-2.0.0-p648.
Continuing with compilation. Please read 'rvm help mount' to get more information on binary rubies.
Checking requirements for osx.
Certificates bundle '/usr/local/etc/openssl/cert.pem' is already up to date.
Requirements installation successful.
Installing Ruby from source to: /Users/nick/.rvm/rubies/ruby-2.0.0-p648, this may take a while depending on your cpu(s)...
ruby-2.0.0-p648 - #downloading ruby-2.0.0-p648, this may take a while depending on your connection...
ruby-2.0.0-p648 - #extracting ruby-2.0.0-p648 to /Users/nick/.rvm/src/ruby-2.0.0-p648....
ruby-2.0.0-p648 - #applying patch /Users/nick/.rvm/patches/ruby/2.0.0/openssl3.patch.
ruby-2.0.0-p648 - #applying patch /Users/nick/.rvm/patches/ruby/2.0.0/update-autoconf.patch.
ruby-2.0.0-p648 - #configuring.................................................
ruby-2.0.0-p648 - #post-configuration.
ruby-2.0.0-p648 - #compiling...................................................|
ruby-2.0.0-p648 - #installing..............
ruby-2.0.0-p648 - #making binaries executable..
ruby-2.0.0-p648 - #downloading rubygems-2.7.2
ruby-2.0.0-p648 - #extracting rubygems-2.7.2.....
ruby-2.0.0-p648 - #removing old rubygems........
ruby-2.0.0-p648 - #installing rubygems-2.7.2.
Error running 'env GEM_HOME=/Users/nick/.rvm/gems/ruby-2.0.0-p648@global GEM_PATH= /Users/nick/.rvm/rubies/ruby-2.0.0-p648/bin/ruby -d /Users/nick/.rvm/src/rubygems-2.7.2/setup.rb --no-document',
please read /Users/nick/.rvm/log/1510703598_ruby-2.0.0-p648/rubygems.install.log
</code>```

So, I check out the log file as instructed, and this is what I see:

```<code>[2017-11-14 15:55:25] /Users/nick/.rvm/rubies/ruby-2.0.0-p648/bin/ruby
current path: /Users/nick/.rvm/src/rubygems-2.7.2
PATH=/usr/local/opt/coreutils/bin:/usr/local/opt/pkg-config/bin:/usr/local/opt/libtool/bin:/usr/local/opt/automake/bin:/usr/local/opt/autoconf/bin:/Users/nick/.nvm/versions/node/v8.4.0/bin:/usr/local/sbin:/usr/local/bin:/Users/nick/.gvm/vertx/current/bin:/Users/nick/.gvm/springboot/current/bin:/Users/nick/.gvm/lazybones/current/bin:/Users/nick/.gvm/jbake/current/bin:/Users/nick/.gvm/groovyserv/current/bin:/Users/nick/.gvm/groovy/current/bin:/Users/nick/.gvm/griffon/current/bin:/Users/nick/.gvm/grails/current/bin:/Users/nick/.gvm/gradle/current/bin:/Users/nick/.gvm/glide/current/bin:/Users/nick/.gvm/gaiden/current/bin:/Users/nick/.gvm/crash/current/bin:/usr/local/mongodb_2.4.5/bin:/Users/nick/.gvm/grails/current/bin:/usr/local/mysql/bin:/Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home/bin:/usr/local/mongodb_2.4.5/bin:/Users/nick/.gvm/grails/current/bin:/usr/local/scala-2.12.1/bin:/usr/local/mysql/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/share/dotnet:/usr/local/git/bin:/Library/Frameworks/Mono.framework/Versions/Current/Commands:/Users/nick/.rvm/bin
command(7): env GEM_HOME=/Users/nick/.rvm/gems/ruby-2.0.0-p648@global GEM_PATH= /Users/nick/.rvm/rubies/ruby-2.0.0-p648/bin/ruby -d /Users/nick/.rvm/src/rubygems-2.7.2/setup.rb --no-document
Exception `LoadError' at /Users/nick/.rvm/rubies/ruby-2.0.0-p648/lib/ruby/2.0.0/rubygems.rb:1087 - cannot load such file -- rubygems/defaults/operating_system
Exception `LoadError' at /Users/nick/.rvm/rubies/ruby-2.0.0-p648/lib/ruby/2.0.0/rubygems.rb:1096 - cannot load such file -- rubygems/defaults/ruby
YAML safe loading is not available. Please upgrade psych to a version that supports safe loading (>= 2.0).
Bundler 1.16.0 installed
RubyGems 2.7.2 installed
Regenerating binstubs
</code>```

I'm not really sure what to make of this error. I've tried uninstalling 2.0.0 and installing it again, imploding & reinstalling rvm, even reinstalling ruby with homebrew and doing everything from scratch, but this error persists. Any ideas?

答:
Try installing Ruby using the --rubygems ignore option:

$ rvm install ruby-2.0.0 --rubygems ignore

Body:
I have need of Ruby 2.0.0, so I turned to RVM to help manage my ruby installations.

However, when I do rvm install ruby-2.0.0, the installation ends up bombing out.

$ rvm install ruby-2.0.0
Searching for binary rubies, this might take some time.
No binary rubies available for: osx/10.12/x86_64/ruby-2.0.0-p648.
Continuing with compilation. Please read 'rvm help mount' to get more information on binary rubies.
Checking requirements for osx.
Certificates bundle '/usr/local/etc/openssl/cert.pem' is already up to date.
Requirements installation successful.
Installing Ruby from source to: /Users/nick/.rvm/rubies/ruby-2.0.0-p648, this may take a while depending on your cpu(s)...
ruby-2.0.0-p648 - #downloading ruby-2.0.0-p648, this may take a while depending on your connection...
ruby-2.0.0-p648 - #extracting ruby-2.0.0-p648 to /Users/nick/.rvm/src/ruby-2.0.0-p648....
ruby-2.0.0-p648 - #applying patch /Users/nick/.rvm/patches/ruby/2.0.0/openssl3.patch.
ruby-2.0.0-p648 - #applying patch /Users/nick/.rvm/patches/ruby/2.0.0/update-autoconf.patch.
ruby-2.0.0-p648 - #configuring.................................................
ruby-2.0.0-p648 - #post-configuration.
ruby-2.0.0-p648 - #compiling...................................................|
ruby-2.0.0-p648 - #installing..............
ruby-2.0.0-p648 - #making binaries executable..
ruby-2.0.0-p648 - #downloading rubygems-2.7.2
ruby-2.0.0-p648 - #extracting rubygems-2.7.2.....
ruby-2.0.0-p648 - #removing old rubygems........
ruby-2.0.0-p648 - #installing rubygems-2.7.2.
Error running 'env GEM_HOME=/Users/nick/.rvm/gems/ruby-2.0.0-p648@global GEM_PATH= /Users/nick/.rvm/rubies/ruby-2.0.0-p648/bin/ruby -d /Users/nick/.rvm/src/rubygems-2.7.2/setup.rb --no-document',
please read /Users/nick/.rvm/log/1510703598_ruby-2.0.0-p648/rubygems.install.log

So, I check out the log file as instructed, and this is what I see:

[2017-11-14 15:55:25] /Users/nick/.rvm/rubies/ruby-2.0.0-p648/bin/ruby
current path: /Users/nick/.rvm/src/rubygems-2.7.2
PATH=/usr/local/opt/coreutils/bin:/usr/local/opt/pkg-config/bin:/usr/local/opt/libtool/bin:/usr/local/opt/automake/bin:/usr/local/opt/autoconf/bin:/Users/nick/.nvm/versions/node/v8.4.0/bin:/usr/local/sbin:/usr/local/bin:/Users/nick/.gvm/vertx/current/bin:/Users/nick/.gvm/springboot/current/bin:/Users/nick/.gvm/lazybones/current/bin:/Users/nick/.gvm/jbake/current/bin:/Users/nick/.gvm/groovyserv/current/bin:/Users/nick/.gvm/groovy/current/bin:/Users/nick/.gvm/griffon/current/bin:/Users/nick/.gvm/grails/current/bin:/Users/nick/.gvm/gradle/current/bin:/Users/nick/.gvm/glide/current/bin:/Users/nick/.gvm/gaiden/current/bin:/Users/nick/.gvm/crash/current/bin:/usr/local/mongodb_2.4.5/bin:/Users/nick/.gvm/grails/current/bin:/usr/local/mysql/bin:/Library/Java/JavaVirtualMachines/jdk1.7.0_80.jdk/Contents/Home/bin:/usr/local/mongodb_2.4.5/bin:/Users/nick/.gvm/grails/current/bin:/usr/local/scala-2.12.1/bin:/usr/local/mysql/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin:/usr/local/share/dotnet:/usr/local/git/bin:/Library/Frameworks/Mono.framework/Versions/Current/Commands:/Users/nick/.rvm/bin
command(7): env GEM_HOME=/Users/nick/.rvm/gems/ruby-2.0.0-p648@global GEM_PATH= /Users/nick/.rvm/rubies/ruby-2.0.0-p648/bin/ruby -d /Users/nick/.rvm/src/rubygems-2.7.2/setup.rb --no-document
Exception `LoadError' at /Users/nick/.rvm/rubies/ruby-2.0.0-p648/lib/ruby/2.0.0/rubygems.rb:1087 - cannot load such file -- rubygems/defaults/operating_system
Exception `LoadError' at /Users/nick/.rvm/rubies/ruby-2.0.0-p648/lib/ruby/2.0.0/rubygems.rb:1096 - cannot load such file -- rubygems/defaults/ruby
YAML safe loading is not available. Please upgrade psych to a version that supports safe loading (>= 2.0).
Bundler 1.16.0 installed
RubyGems 2.7.2 installed
Regenerating binstubs

I'm not really sure what to make of this error. I've tried uninstalling 2.0.0 and installing it again, imploding & reinstalling rvm, even reinstalling ruby with homebrew and doing everything from scratch, but this error persists. Any ideas?


问:
When to call thread.join in a GUI application
```<code>import wx
import json
import queue
from collections import namedtuple
import threading

class MyDialog(wx.Frame):

    def __init__(self, parent, title):
        self.no_resize = wx.DEFAULT_FRAME_STYLE & ~ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)
        wx.Frame.__init__(self, parent, title=title, size=(500, 450),style = self.no_resize)

        self.panel = wx.Panel(self, size=(250, 270))
        self.emp_selection = wx.ComboBox(self.panel, -1, pos=(40, 50), size=(200,100))
        self.start_read_thread()

        #code to load other GUI components

        self.Centre()
        self.Show(True)

    def read_employees(self, read_file):
        list_of_emails = queue.Queue()
        with open(read_file) as f_obj:
            employees = json.load(f_obj)
        list_of_emails = [empEmail for empEmail in employees.keys()]
        wx.CallAfter(self.emp_selection.Append, list_of_emails)

    def start_read_thread(self):
        filename = 'employee.json'
        empThread = threading.Thread(target=self.read_employees, args=(filename,))
        empThread.start()
</code>```

I have a GUI application that loads a combobox, and starts a thread to read some data and load it into the combobox. I don't want the read to block, so that the other GUI components can load.

After calling thread.start() when is it appropriate to call thread.join()? From my understanding, join() waits for the thread to complete, I don't want that, I want to start the thread and allow all the other components to load. Is it bad practice not to call join()

答:
It is perfectly ok to not call join() if you don't need its functionality to wait for the thread to finish.

By the way: In the main thread of a GUI application (the thread automatically created at start in which all GUI things happen) it is bad practice to call any function that sleeps or waits for anything as the GUI doesn't react (freezes) while waiting.

Body:
import wx
import json
import queue
from collections import namedtuple
import threading

class MyDialog(wx.Frame):

    def __init__(self, parent, title):
        self.no_resize = wx.DEFAULT_FRAME_STYLE & ~ (wx.RESIZE_BORDER | wx.MAXIMIZE_BOX)
        wx.Frame.__init__(self, parent, title=title, size=(500, 450),style = self.no_resize)

        self.panel = wx.Panel(self, size=(250, 270))
        self.emp_selection = wx.ComboBox(self.panel, -1, pos=(40, 50), size=(200,100))
        self.start_read_thread()

        #code to load other GUI components

        self.Centre()
        self.Show(True)

    def read_employees(self, read_file):
        list_of_emails = queue.Queue()
        with open(read_file) as f_obj:
            employees = json.load(f_obj)
        list_of_emails = [empEmail for empEmail in employees.keys()]
        wx.CallAfter(self.emp_selection.Append, list_of_emails)

    def start_read_thread(self):
        filename = 'employee.json'
        empThread = threading.Thread(target=self.read_employees, args=(filename,))
        empThread.start()

I have a GUI application that loads a combobox, and starts a thread to read some data and load it into the combobox. I don't want the read to block, so that the other GUI components can load.

After calling thread.start() when is it appropriate to call thread.join()? From my understanding, join() waits for the thread to complete, I don't want that, I want to start the thread and allow all the other components to load. Is it bad practice not to call join()


问:
How do I remove the bouncing effect on appbar?
Appbar used to have an issue when flinging. It was not scrolling smoothly.

Please refer to these:

http://stackoverflow.com/questions/30923889/flinging-with-recyclerview-appbarlayout

https://code.google.com/p/android/issues/detail?id=177729&q=appbarlayout&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars

https://github.com/henrytao-me/smooth-app-bar-layout

But it has been fixed in support library version 26.

```<code>compile 'com.android.support:design:26.0.0'
</code>```

However, appbar is now bouncing back even if fling is not hard.

How do I remove this behavior?

答:
This is only happening when AppBar is scrolled/flung while the NestedScrollView(or RecyclerView) has not yet finish flinging.

Solution: Extend AppBar's default Behavior and block the call for AppBar.Behavior's onNestedPreScroll() and onNestedScroll() when AppBar is touched while NestedScroll hasn't stopped yet.

```<code> @Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed, int type) {
    if (type == TYPE_FLING) {
        isFlinging = true;
    }
    if (!shouldBlockNestedScroll) {
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
    }
}

@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) {
    if (!shouldBlockNestedScroll) {
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type);
    }
}
</code>```

then use it on the layout:

```<code><android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    ...
    app:layout_behavior="com.mypackage.NoBounceBehavior"/>
</code>```

Reference for full code of the custom behavior can be found here: https://gist.github.com/ampatron/9d56ea401094f67196f407f82f14551a

Body:
Appbar used to have an issue when flinging. It was not scrolling smoothly.

Please refer to these:

http://stackoverflow.com/questions/30923889/flinging-with-recyclerview-appbarlayout

https://code.google.com/p/android/issues/detail?id=177729&q=appbarlayout&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars

https://github.com/henrytao-me/smooth-app-bar-layout

But it has been fixed in support library version 26.

compile 'com.android.support:design:26.0.0'

However, appbar is now bouncing back even if fling is not hard.

How do I remove this behavior?

Body:
This is only happening when AppBar is scrolled/flung while the NestedScrollView(or RecyclerView) has not yet finish flinging.

Solution: Extend AppBar's default Behavior and block the call for AppBar.Behavior's onNestedPreScroll() and onNestedScroll() when AppBar is touched while NestedScroll hasn't stopped yet.

 @Override
public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed, int type) {
    if (type == TYPE_FLING) {
        isFlinging = true;
    }
    if (!shouldBlockNestedScroll) {
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
    }
}

@Override
public void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int type) {
    if (!shouldBlockNestedScroll) {
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type);
    }
}

then use it on the layout:

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar"
    ...
    app:layout_behavior="com.mypackage.NoBounceBehavior"/>

Reference for full code of the custom behavior can be found here: https://gist.github.com/ampatron/9d56ea401094f67196f407f82f14551a


问:
Text File Formatting a Dictionary-like Line to Individual Lines
I have a text file that is tab separated with at least two columns in each line. The first column is an unique ID and every column after is an identifier of a fasta sequence (DNA Sequence Identifier). My question is how to reshape this structure to a two column matrix.

This means I want to go from this data format:

```<code>1040713 91
969805  47
862949  502 485
798097  671 593
939058  575
721526  400 523 76  610
</code>```

To this data format:

```<code>1040713 91
969805  47
862949  502
862949  485
798097  671
798097  593
939058  575
721526  400
721526  523
721526  76
721526  610
</code>```

I am trying to use awk -F '\t' '{print $3}' | to a sed with a new line character and the first column. However, I am unsure how to access the first column after the pipe. Any suggestions to achieve my desired formatting would be greatly appreciated.

答:
awk to the rescue!

```<code>awk '{for(i=2;i<=NF;i++) print $1 "\t" $i}'
</code>```

Body:
I have a text file that is tab separated with at least two columns in each line. The first column is an unique ID and every column after is an identifier of a fasta sequence (DNA Sequence Identifier). My question is how to reshape this structure to a two column matrix.

This means I want to go from this data format:

1040713 91
969805  47
862949  502 485
798097  671 593
939058  575
721526  400 523 76  610

To this data format:

1040713 91
969805  47
862949  502
862949  485
798097  671
798097  593
939058  575
721526  400
721526  523
721526  76
721526  610

I am trying to use awk -F '\t' '{print $3}' | to a sed with a new line character and the first column. However, I am unsure how to access the first column after the pipe. Any suggestions to achieve my desired formatting would be greatly appreciated.

Body:
awk to the rescue!

awk '{for(i=2;i<=NF;i++) print $1 "\t" $i}'


问:
namespaces and using scope resolution
I have run across something I find odd in C# .NET Core 2.0 and I am wondering what is going on here.

I have a file called FooBar.cs and it looks like this

```<code>namespace Foo
{
    public class FooClass
    {

    }

    namespace Bar
    {
        enum BarEnums
        {
             Bar1
            ,Bar2
            ,Bar3
        }
    }
}
</code>```

And I have a simple program that looks like this

```<code>using System;

using Foo;

namespace Using
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            FooClass fooClass = new FooClass();

            Console.WriteLine(Bar.BarEnums.Bar1);
        }
    }
}
</code>```

This gives me the following error:

```<code>Program.cs(16,22): error CS0103: The name 'Bar' does not exist in the current context
</code>```

I am confused as to why the using statement exposes the class within the name space but it does not expose the namespace also found at the same level? If I put in using Foo.Bar it still gives the same error.. so the using statement can see the namespace but it does not help it find the references below.

Now if I put in Foo.Bar.BarEnums.Bar1 it will work just fine.. But why do I not have to put in Foo.FooClass following the same nomenclature as with the reference to the enums? Is this just a difference between accessing enums vs classes from within a namespace?

答:
That happens because using Foo only imports the types contained in the given namespace, but it does not specifically import the nested namespaces. So that´s why when you reference your enum you have to do it with the full namespace reference.

This is a C# language specification.

Here is an explanation from a guy from the C# team:

In C#, when you specify a “using” clause, such as

using System.Text;

the compiler only imports the types in System.Text into the global
  namespace – it doesn’t do the same with any namespaces inside of
  System.Text. So, while that using allows me to write:

StringBuilder s = new StringBuilder();

it does not allow me to write:

RegularExpressions.Regex r = new RegularExpressions.Regex();

Why?

Well, an early version of the C# compiler had that behavior, but we
  found that it had a few issues:

First, it made the code harder to follow. In the above example,
  RegularExpressions.Regex() could be a global name, or a name based on
  any of my using clauses. Having to look at the top of your code to
  figure out what a name is is something we’d like to avoid.

The second problem had to do with collisions between namespace names,
  which occurred much more often with this behavior. If there was
  another namespace with a RegularExpressions namespace inside of it,
  the user wouldn’t be able to have a “using” statement for both – even
  if they didn’t actually care about that namespace.

We therefore decided to change the behavior.

https://blogs.msdn.microsoft.com/csharpfaq/2004/03/07/why-dont-namespace-using-directives-import-nested-namespaces/

And here is the C# spec: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/namespaces

Title: namespaces and using scope resolution

Body:
I have run across something I find odd in C# .NET Core 2.0 and I am wondering what is going on here.

I have a file called FooBar.cs and it looks like this

namespace Foo
{
    public class FooClass
    {

    }

    namespace Bar
    {
        enum BarEnums
        {
             Bar1
            ,Bar2
            ,Bar3
        }
    }
}

And I have a simple program that looks like this

using System;

using Foo;

namespace Using
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            FooClass fooClass = new FooClass();

            Console.WriteLine(Bar.BarEnums.Bar1);
        }
    }
}

This gives me the following error:

Program.cs(16,22): error CS0103: The name 'Bar' does not exist in the current context

I am confused as to why the using statement exposes the class within the name space but it does not expose the namespace also found at the same level? If I put in using Foo.Bar it still gives the same error.. so the using statement can see the namespace but it does not help it find the references below.

Now if I put in Foo.Bar.BarEnums.Bar1 it will work just fine.. But why do I not have to put in Foo.FooClass following the same nomenclature as with the reference to the enums? Is this just a difference between accessing enums vs classes from within a namespace?


问:
C Buffer Overflow - how many bytes to input
I made a simple C program to try understand buffer overflows. I am trying to overflow the input buffer so that flag gets changed to true and the program outputs "got here". The program is here (assume you have password.txt with hey in it):

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv){
  int flag = 0;

  char pwd[5];
  char input[5];

  FILE *f = fopen("password.txt", "r");

  fscanf(f, "%s", pwd);
  fclose(f);

  strcpy(input, argv[1]);

  if(strcmp(input, pwd)){
    printf("wrong password!\n");
  }
  else{
    flag = 1;
    printf("correct password!\n");
  }
  if(flag){
    printf("you got into the secret place\n");
  }
  return 0;
}
</code>```

So on the stack we have something like this I guess:

```<code>[high addresses]
flag   ---> 4 bytes
pwd    ---> 8 bytes
input  ---> 8 bytes
[low addresses]
</code>```

So I think I just need to give the program just 17 bytes to overwrite the flag variable. So i gave it aaaaaaaaaaaaaaaaa but that didn't work. I had to give it a 23 times, so 23 bytes. Why is 17 bytes not enough?

答:
You can run into multiple problems when trying this.

The order of the local variable on the stack isn't necessarily in the same order as the one in the code. The compiler is free to rearrange them as he wish.

The compiler often aligns data to boundary for faster execution. This means the space between the different local variable can be much bigger than what you think. It's not uncommon to see stack variable aligned on a 8 or 16 bytes boundary even if it's content is much smaller.

You can get the disassembly of your program with objdump -D or debug it with gdb. This will give you a much better idea of the stack alignment in your program.

Body:
I made a simple C program to try understand buffer overflows. I am trying to overflow the input buffer so that flag gets changed to true and the program outputs "got here". The program is here (assume you have password.txt with hey in it):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv){
  int flag = 0;

  char pwd[5];
  char input[5];

  FILE *f = fopen("password.txt", "r");

  fscanf(f, "%s", pwd);
  fclose(f);

  strcpy(input, argv[1]);

  if(strcmp(input, pwd)){
    printf("wrong password!\n");
  }
  else{
    flag = 1;
    printf("correct password!\n");
  }
  if(flag){
    printf("you got into the secret place\n");
  }
  return 0;
}

So on the stack we have something like this I guess:

[high addresses]
flag   ---> 4 bytes
pwd    ---> 8 bytes
input  ---> 8 bytes
[low addresses]

So I think I just need to give the program just 17 bytes to overwrite the flag variable. So i gave it aaaaaaaaaaaaaaaaa but that didn't work. I had to give it a 23 times, so 23 bytes. Why is 17 bytes not enough?


问:
Unclear errorreport from RRDTool graphing script
When one version of a set of scripts runs, which apply RRDTool, you try more of the same .....

Made a version of the lua-script, which now collects power/energy-info, and the related file create_pipower1A_graph.sh is a direct derivative of the errorfree running sh-file described in RRDTool, How to get png-files by means of os-execute-call from lua-script?

The derivative sh-file should produce a graph with the output of 3 inverters and the parallel consumption.
That sh-file for graphic output is below.

```<code>#!/bin/bash
rrdtool graph /home/pi/pipower1.png \
  DEF:Pwr_MAC=/home/pi/pipower1.rrd:Power0430:AVERAGE \
  DEF:Pwr_SAJ=/home/pi/pipower1.rrd:Power1530:AVERAGE \
  DEF:Pwr_STECA=/home/pi/pipower1.rrd:Power2950:AVERAGE \
  DEF:Pwr_Cons=/home/pi/pipower1.rrd:Power_Cons:AVERAGE \
  LINE1:Pwr_MAC#ff0000:Output Involar \
  LINE1:Pwr_SAJ#0000ff:Output SAJ1.5 \
  LINE1:Pwr_STECA#5fd00b:Output STECA \
  LINE1:Pwr_Cons#00ffff:Consumption \
  COMMENT:"\t\t\t\t\t\t\l" \
  COMMENT:"\t\t\t\t\t\t\l" \
  GPRINT:Pwr_MAC:LAST:"Output_Involar   Latest\: %2.1lf" \
  GPRINT:Pwr_MAC:MAX:"  Max.\: %2.1lf" \
  GPRINT:Pwr_MAC:MIN:"  Min.\: %2.1lf" \
  COMMENT:"\t\t\t\t\t\t\l" \
  GPRINT:Pwr_SAJ:LAST:"Output SAJ1.5k   Latest\: %2.1lf" \
  GPRINT:Pwr_SAJ:MAX:"  Max.\: %2.1lf" \
  GPRINT:Pwr_SAJ:MIN:"  Min.\: %2.1lf" \
  COMMENT:"\t\t\t\t\t\t\l" \
  GPRINT:Pwr_STECA:LAST:"Output STECA   Latest\: %2.1lf" \
  GPRINT:Pwr_STECA:MAX:"  Max.\: %2.1lf" \
  GPRINT:Pwr_STECA:MIN:"  Min.\: %2.1lf" \
  COMMENT:"\t\t\t\t\t\t\l" \
  GPRINT:Pwr_Cons:LAST:"Consumption    Latest\: %2.1lf" \
  GPRINT:Pwr_Cons:MAX:"  Max.\: %2.1lf" \
  GPRINT:Pwr_Cons:MIN:"  Min.\: %2.1lf" \
  COMMENT:"\t\t\t\t\t\t\l" \
  --width 700 --height 400 \
  --title="Graph B: Power Production & Consumption for last 24 hour" \
  --vertical-label="Power(W)" \
  --watermark "`date`"
</code>```

The lua-script again runs without errors and as result the rrd-file is periodically updated, the graphic output is generated,but no graph appears! Tested on 2 different Raspberries, but no difference in reactions.
Running the sh-file create_pipower1A_graph from the commandline produces the following errors.

```<code>pi@raspberrypi:~$ sudo /home/pi/create_pipower1A_graph.sh
ERROR: 'I' is not a valid function name
pi@raspberrypi:~$ ./create_pipower1A_graph.sh
ERROR: 'I' is not a valid function name
</code>```

Question: Puzzled, because nowhere in the sh-file an I is applied as function command. Explanation? Hint for remedy of this error?

答:
Your problem is here:

```<code>LINE1:Pwr_MAC#ff0000:Output Involar \
LINE1:Pwr_SAJ#0000ff:Output SAJ1.5 \
LINE1:Pwr_STECA#5fd00b:Output STECA \
LINE1:Pwr_Cons#00ffff:Consumption \
</code>```

These lines need to be quoted as they contain spaces and hash symbols.

```<code>LINE1:"Pwr_MAC#ff0000:Output Involar" \
LINE1:"Pwr_SAJ#0000ff:Output SAJ1.5" \
LINE1:"Pwr_STECA#5fd00b:Output STECA" \
LINE1:"Pwr_Cons#00ffff:Consumption" \
</code>```

Body:
When one version of a set of scripts runs, which apply RRDTool, you try more of the same .....

Made a version of the lua-script, which now collects power/energy-info, and the related file create_pipower1A_graph.sh is a direct derivative of the errorfree running sh-file described in RRDTool, How to get png-files by means of os-execute-call from lua-script?

The derivative sh-file should produce a graph with the output of 3 inverters and the parallel consumption.
That sh-file for graphic output is below.

#!/bin/bash
rrdtool graph /home/pi/pipower1.png \
  DEF:Pwr_MAC=/home/pi/pipower1.rrd:Power0430:AVERAGE \
  DEF:Pwr_SAJ=/home/pi/pipower1.rrd:Power1530:AVERAGE \
  DEF:Pwr_STECA=/home/pi/pipower1.rrd:Power2950:AVERAGE \
  DEF:Pwr_Cons=/home/pi/pipower1.rrd:Power_Cons:AVERAGE \
  LINE1:Pwr_MAC#ff0000:Output Involar \
  LINE1:Pwr_SAJ#0000ff:Output SAJ1.5 \
  LINE1:Pwr_STECA#5fd00b:Output STECA \
  LINE1:Pwr_Cons#00ffff:Consumption \
  COMMENT:"\t\t\t\t\t\t\l" \
  COMMENT:"\t\t\t\t\t\t\l" \
  GPRINT:Pwr_MAC:LAST:"Output_Involar   Latest\: %2.1lf" \
  GPRINT:Pwr_MAC:MAX:"  Max.\: %2.1lf" \
  GPRINT:Pwr_MAC:MIN:"  Min.\: %2.1lf" \
  COMMENT:"\t\t\t\t\t\t\l" \
  GPRINT:Pwr_SAJ:LAST:"Output SAJ1.5k   Latest\: %2.1lf" \
  GPRINT:Pwr_SAJ:MAX:"  Max.\: %2.1lf" \
  GPRINT:Pwr_SAJ:MIN:"  Min.\: %2.1lf" \
  COMMENT:"\t\t\t\t\t\t\l" \
  GPRINT:Pwr_STECA:LAST:"Output STECA   Latest\: %2.1lf" \
  GPRINT:Pwr_STECA:MAX:"  Max.\: %2.1lf" \
  GPRINT:Pwr_STECA:MIN:"  Min.\: %2.1lf" \
  COMMENT:"\t\t\t\t\t\t\l" \
  GPRINT:Pwr_Cons:LAST:"Consumption    Latest\: %2.1lf" \
  GPRINT:Pwr_Cons:MAX:"  Max.\: %2.1lf" \
  GPRINT:Pwr_Cons:MIN:"  Min.\: %2.1lf" \
  COMMENT:"\t\t\t\t\t\t\l" \
  --width 700 --height 400 \
  --title="Graph B: Power Production & Consumption for last 24 hour" \
  --vertical-label="Power(W)" \
  --watermark "`date`"

The lua-script again runs without errors and as result the rrd-file is periodically updated, the graphic output is generated,but no graph appears! Tested on 2 different Raspberries, but no difference in reactions.
Running the sh-file create_pipower1A_graph from the commandline produces the following errors.

pi@raspberrypi:~$ sudo /home/pi/create_pipower1A_graph.sh
ERROR: 'I' is not a valid function name
pi@raspberrypi:~$ ./create_pipower1A_graph.sh
ERROR: 'I' is not a valid function name

Question: Puzzled, because nowhere in the sh-file an I is applied as function command. Explanation? Hint for remedy of this error?

Body:
Your problem is here:

LINE1:Pwr_MAC#ff0000:Output Involar \
LINE1:Pwr_SAJ#0000ff:Output SAJ1.5 \
LINE1:Pwr_STECA#5fd00b:Output STECA \
LINE1:Pwr_Cons#00ffff:Consumption \

These lines need to be quoted as they contain spaces and hash symbols.

LINE1:"Pwr_MAC#ff0000:Output Involar" \
LINE1:"Pwr_SAJ#0000ff:Output SAJ1.5" \
LINE1:"Pwr_STECA#5fd00b:Output STECA" \
LINE1:"Pwr_Cons#00ffff:Consumption" \


问:
Error al correr laravel
Help with the following error in laravel </p>

```<code> Fatal Error: Class 'lluminate\Foundation\Application' no found in boostrap/app.php on line 14
</code>```

答:
Add in your file composer.json

```<code>en "config":{"preferred-install": "dist", "secure-http:false" }
</code>```

and run   composer update

Title: Error al correr laravel

Body:
Help with the following error in laravel

 Fatal Error: Class 'lluminate\Foundation\Application' no found in boostrap/app.php on line 14

Body:
Add in your file composer.json

en "config":{"preferred-install": "dist", "secure-http:false" }

and run   composer update


问:
Best way to archive an Azure VM?
I want to archive a Azure VM. It's currently deallocated, so we're not incurring compute charges, but we're still paying for the storage, even if it's not online. We want to move the storage to BLOB storage since it's cheaper, as we don't want to lose the data, but don't want to pay a premium to have it sit idle, either.

I tried to create an image, which then deleted the VM instance, but left the disks in-tact without a reference to them.

What's the best way to archive a VM?

答:
If your Disk is managed, you can take following steps.
Now, Azure can let you change your Managed Disk type easily.

Steps:Go to Azure Portal> Stop (deallocate) your VM> Go to Your Disk> Account type > Choose standard (HDD)> Click Save

Then your disk will be successfully updated!

After deleting the VM, you can also use the disk to create VM from the disk. Also, you can  generate a URI for the disk to copy it to another storage account or export it.

If your Disk is unmanaged, you cannot convert the disk from Premium to standard directly. You need to  create a new storage account (or use an existing storage account) and copy the blobs holding the disks from Premium account to Standard account. The best way is that you can use Azcopy to do this.

Title: Best way to archive an Azure VM?


问:
Rails 3: validates :presence => true vs validates_presence_of
What is the difference between validates :presence and validates_presence_of? Looking through ActiveModel it looks like they setup the validation the same way. However, given the following model definition:

```<code>class Account < ActiveRecord::Base
  has_one :owner_permission, :class_name => 'AccountPermission', :conditions => { :owner => true, :admin => true }
  has_one :owner, :class_name => 'User', :through => :owner_permission, :source => :user

  validate :owner, :presence => true
  validates_associated :owner
end
</code>```

Calling save on an instance of Account does not validate the presence of owner. Though, if I use validates_presence_of it will.

答:
I would have thought that it is appropriate to use validates :foo presence: true when you want to include other validations of :foo such as length or uniqueness. But if you know the only validation you'll need for an attribute is presence, then validates_presence_of appears to be more efficient.

So:

```<code>validates :foo, length: {maximum: 50}, uniqueness: true,
                format: {with: /bar/},
                presence: true # lots of validations needed
</code>```

But:

```<code>validates_presence_of :foo # only presence validation needed
</code>```

Body:
What is the difference between validates :presence and validates_presence_of? Looking through ActiveModel it looks like they setup the validation the same way. However, given the following model definition:

class Account < ActiveRecord::Base
  has_one :owner_permission, :class_name => 'AccountPermission', :conditions => { :owner => true, :admin => true }
  has_one :owner, :class_name => 'User', :through => :owner_permission, :source => :user

  validate :owner, :presence => true
  validates_associated :owner
end

Calling save on an instance of Account does not validate the presence of owner. Though, if I use validates_presence_of it will.

Body:
I would have thought that it is appropriate to use validates :foo presence: true when you want to include other validations of :foo such as length or uniqueness. But if you know the only validation you'll need for an attribute is presence, then validates_presence_of appears to be more efficient.

So:

validates :foo, length: {maximum: 50}, uniqueness: true,
                format: {with: /bar/},
                presence: true # lots of validations needed

But:

validates_presence_of :foo # only presence validation needed


问:
Laravel attach object to many objects in many-to-many relationship without loop
I have a many-to-many relationship on a User model and Notification model.

To create a Notification and attach to many Users, I am currently doing:

```<code>$users = User::all();
$notification = new Notification(['title'=>'some title', 'body'=>'notification body']);
$notification->save();
foreach ($users as $user) {
   $user->notifications()->attach([$notification->id]);
}
</code>```

The foreach implementation won't be ideal if $users->count() becomes a very large number;
Please is there a better way to get this done without so many loops?

Thanks

答:
No there isn't, not using Eloquent.

There exists the ability to attach multiple records simultaneously, but this internally uses a loop itself, so you're not making any saving there.

```<code>$notification->users()->attach([
    1 => [],
    2 => [],
    // ...
]);
</code>```

When dealing with large result sets, Eloquent is not necessarily the ideal solution. You might consider using the Database query builder or even raw SQL to handle mass insert operations.

Body:
I have a many-to-many relationship on a User model and Notification model.

To create a Notification and attach to many Users, I am currently doing:

$users = User::all();
$notification = new Notification(['title'=>'some title', 'body'=>'notification body']);
$notification->save();
foreach ($users as $user) {
   $user->notifications()->attach([$notification->id]);
}

The foreach implementation won't be ideal if $users->count() becomes a very large number;
Please is there a better way to get this done without so many loops?

Thanks

Body:
No there isn't, not using Eloquent.

There exists the ability to attach multiple records simultaneously, but this internally uses a loop itself, so you're not making any saving there.

$notification->users()->attach([
    1 => [],
    2 => [],
    // ...
]);

When dealing with large result sets, Eloquent is not necessarily the ideal solution. You might consider using the Database query builder or even raw SQL to handle mass insert operations.


问:
Binding property to control in Winforms
What is the best way to bind a property to a control so that when the property value is changed, the control's bound property changes with it.

So if I have a property FirstName which I want to bind to a textbox's txtFirstName text value. So if I change FirstName to value "Stack" then the property txtFirstName.Text also changes to value "Stack".

I know this may sound a stupid question but I'll appreciate the help.

答:
A simplified version of the accepted answer that does NOT require you to type names of properties manually in every property setter like OnPropertyChanged("some-property-name"). Instead you just call OnPropertyChanged() without parameters:

You need .NET 4.5 minimum.
  CallerMemberName is in the System.Runtime.CompilerServices namespace

```<code>public class Sample : INotifyPropertyChanged
{
    private string _propString;
    private int _propInt;

    //======================================
    // Actual implementation
    //======================================
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    //======================================
    // END: actual implementation
    //======================================

    public string PropString
    {
        get { return _propString; }
        set
        {
            // do not trigger change event if values are the same
            if (Equals(value, _propString)) return;
            _propString = value;

            //===================
            // Usage in the Source
            //===================
            OnPropertyChanged();

        }
    }

    public int PropInt
    {
        get { return _propInt; }
        set
        {
            // do not allow negative numbers, but always trigger a change event
            _propInt = value < 0 ? 0 : value;
            OnPropertyChanged();
        }
    }
}
</code>```

Usage stays the same:

```<code>var source = new Sample();
textbox.DataBindings.Add("Text", source, "PropString");
source.PropString = "Some new string";
</code>```

Hope this helps someone.

Title: Binding property to control in Winforms

Body:
A simplified version of the accepted answer that does NOT require you to type names of properties manually in every property setter like OnPropertyChanged("some-property-name"). Instead you just call OnPropertyChanged() without parameters:

You need .NET 4.5 minimum.
  CallerMemberName is in the System.Runtime.CompilerServices namespace

public class Sample : INotifyPropertyChanged
{
    private string _propString;
    private int _propInt;

    //======================================
    // Actual implementation
    //======================================
    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
    //======================================
    // END: actual implementation
    //======================================

    public string PropString
    {
        get { return _propString; }
        set
        {
            // do not trigger change event if values are the same
            if (Equals(value, _propString)) return;
            _propString = value;

            //===================
            // Usage in the Source
            //===================
            OnPropertyChanged();

        }
    }

    public int PropInt
    {
        get { return _propInt; }
        set
        {
            // do not allow negative numbers, but always trigger a change event
            _propInt = value < 0 ? 0 : value;
            OnPropertyChanged();
        }
    }
}

Usage stays the same:

var source = new Sample();
textbox.DataBindings.Add("Text", source, "PropString");
source.PropString = "Some new string";

Hope this helps someone.

ContentLicense: CC BY-SA 4.0


问:
Is there a way to get the key for Classic Azure Storage Account using powershell?
I think Get-AzureRmStorageAccountKey doesn't work with Classic Azure Storage Account. Get-AzureStorageAccount can return classic storage account, but it won't return the key.

thanks.
Lidong

答:
You can use cmdlet : Get-AzureStorageKey</p>

```<code>Get-AzureStorageKey -StorageAccountName "ContosoStore01"
</code>```

Body:
You can use cmdlet : Get-AzureStorageKey

Get-AzureStorageKey -StorageAccountName "ContosoStore01"