问:
Regex for numbers between 0-9 and 15 digits as limit
RegEx for only Numbers between 0-9 and 15 digits as limit</p>

答:
You can use the following using the pattern attribute:

```<code><input type="text" pattern="^[0-9]{0,15}$"/>
<input type="text" pattern="^[\d]{0,15}$"/>
</code>```

On the curly brackets {...} you can set the min and max length of the input ({minLength,maxLength}). To check this you have to make sure the whole value have to be valid. So you have to check completely from start (^) to end ($).

Body:
You can use the following using the pattern attribute:

<input type="text" pattern="^[0-9]{0,15}$"/>
<input type="text" pattern="^[\d]{0,15}$"/>

On the curly brackets {...} you can set the min and max length of the input ({minLength,maxLength}). To check this you have to make sure the whole value have to be valid. So you have to check completely from start (^) to end ($).


来源: stackexchange

问:
Function Not Working In My Program
My compiler says "too few arguments in the function". I can not figure out what is wrong. Does anyone have any idea on what I am doing wrong?</p>

```<code>#include<stdio.h>
#include<math.h>
int show(int a, int b, int c);

main( ){
int a, b = 10, c = 24;
printf("Enter a number\n");
scanf("%d\n", &a);
show(int a, int b, int c);
system("pause");
}

int show(int a, int b, int c){
if(a>c){
    printf("a is the largest number\n");
} else if(a>b){
    printf("a is smaller than c\n");
} else if(a<b){
    printf("a is bigger than b\n");
} else{
    printf("a is the smallest number \n");
}
return;
}
</code>```

答:
It should be</p>

```<code>#include<stdio.h>
#include<math.h>
int show(int a, int b, int c);

main( ){
int a, b = 10, c = 24;
printf("Enter a number\n");
scanf("%d\n", &a);
show(a,b,c);
system("pause");
}

int show(int a, int b, int c){
if(a>c){
    printf("a is the largest number\n");
} else if(a>b){
    printf("a is smaller than c\n");
} else if(a<b){
    printf("a is bigger than b\n");
} else{
    printf("a is the smallest number \n");
}
return;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Function Not Working In My Program

Body:
My compiler says "too few arguments in the function". I can not figure out what is wrong. Does anyone have any idea on what I am doing wrong?

#include<stdio.h>
#include<math.h>
int show(int a, int b, int c);

main( ){
int a, b = 10, c = 24;
printf("Enter a number\n");
scanf("%d\n", &a);
show(int a, int b, int c);
system("pause");
}

int show(int a, int b, int c){
if(a>c){
    printf("a is the largest number\n");
} else if(a>b){
    printf("a is smaller than c\n");
} else if(a<b){
    printf("a is bigger than b\n");
} else{
    printf("a is the smallest number \n");
}
return;
}

Body:
It should be

#include<stdio.h>
#include<math.h>
int show(int a, int b, int c);

main( ){
int a, b = 10, c = 24;
printf("Enter a number\n");
scanf("%d\n", &a);
show(a,b,c);
system("pause");
}

int show(int a, int b, int c){
if(a>c){
    printf("a is the largest number\n");
} else if(a>b){
    printf("a is smaller than c\n");
} else if(a<b){
    printf("a is bigger than b\n");
} else{
    printf("a is the smallest number \n");
}
return;
}


问:
When to call SetProcessWorkingSetSize? (Convincing the memory manager to release the memory)
In a previous post ( My program never releases the memory back. Why? ) I show that FastMM can cache (read as hold for itself) pretty large amounts of memory. If your application just loaded a large data set in RAM, after releasing the data, you will see that impressive amounts of RAM are not released back to the memory pool.

I looked around and it seems that calling the SetProcessWorkingSetSize API function will "flush" the cache to disk. However, I cannot decide when to call this function. I wanted to call it at the end of the OnClick event on the button that is performing the RAM intensive operation. However, some people are saying that this may cause AV.

If anybody used this function successfully, please let me (us) know.

Many thanks.

Edit:

1. After releasing the data set, the program still takes large amounts of RAM. After calling SetProcessWorkingSetSize the size returns to few MB. Some argue that nothing was released back. I agree. But the memory foot print is now small AND it is NOT increasing back after using the program normally (for example when performing normal operation that does not involves loading large data sets). Unfortunately, there is no way to demonstrate that the memory swapped to disk is ever loaded back into memory, but I think it is not.
2. I have already demonstrated (I hope) this is not a memory leak:

My program never releases the memory back. Why?

How to convince the memory manager to release unused memory

答: Are you sure there is a problem? Working sets might only decrease when there really is a memory shortage. </p>

ContentLicense: CC BY-SA 2.5


答:
You can use [0-9]{0,15} or [\d]{0,15} which will match all numbers up to fifteen digits in length as defined by the curly brackets.

To apply in html, use the pattern attribute in your input tag:

```<code><input type="text" pattern="[\d]{0,15}">
</code>```

Title: Regex for numbers between 0-9 and 15 digits as limit

Body: RegEx for only Numbers between 0-9 and 15 digits as limit

Body:
You can use [0-9]{0,15} or [\d]{0,15} which will match all numbers up to fifteen digits in length as defined by the curly brackets.

To apply in html, use the pattern attribute in your input tag:

<input type="text" pattern="[\d]{0,15}">


问:
How do you assign an action to a button in JScript?
just started learning Js for few days and i've been trying to make a button that when you click it, it would change the text of the 0 xp to 1, 2, 3,etc.. but im struggling to do so. Here is my code, any help would be appreciated.

var have = document.getElementsByClassName("earn");
var credits = document.getElementsByClassName("money");
var button = document.getElementsById("singlebutton");

credits.onclick = change() {
  document.getElementsByClassName("money").innerHTML = "i++" + " xp";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <title></title>
  <link rel="stylesheet" href="style.css">
  <!-- Latest compiled and minified CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <!-- Optional theme -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
</head>

<body>
  <header>
    <h1>Blank Page</h1>
  </header>
  <main>
    <form>
      <div class="col-md-4 text-center">
        <p><button id="singlebutton" name="singlebutton" class="btn btn-success">Click here</button></p>
      </div>
      <div class="credit text-center">
        <div class="earn">
          <p>You have earned: </p>
        </div>
        <div class="money">0 xp</div>
      </div>
    </form>
  </main>
  <script src="main.js"></script>
  <!-- Latest compiled and minified JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>

</html></code>```

答:
append [0] after calls to document.getElementsByClassName everywhere like this to get the first element that matches</p>

```<code>document.getElementsByClassName("earn")[0]
</code>```

Body:
just started learning Js for few days and i've been trying to make a button that when you click it, it would change the text of the 0 xp to 1, 2, 3,etc.. but im struggling to do so. Here is my code, any help would be appreciated.

var have = document.getElementsByClassName("earn");
var credits = document.getElementsByClassName("money");
var button = document.getElementsById("singlebutton");

credits.onclick = change() {
  document.getElementsByClassName("money").innerHTML = "i++" + " xp";
}

<!DOCTYPE html>

  <title></title>
  <link rel="stylesheet" href="style.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

Blank Page

    <form>

<button id="singlebutton" name="singlebutton" class="btn btn-success">Click here</button>

You have earned:

0 xp

    </form>

Body:
append [0] after calls to document.getElementsByClassName everywhere like this to get the first element that matches

document.getElementsByClassName("earn")[0]


问:
I got error in PHP preg_match. content constains [^>]*?
Nearly, when i write code with preg_match.Like this

```<code>    $string = <<<ETO
    <svg "[^>]*? width="480.24px" height="360px" viewBox="0 0 480.24 360" enable-background="new 0 0 480.24 360" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    ETO;

    preg_match('/<svg[^>]*?width=[\'|"]{1}(.*?)[\'|"]{1}[^>]*?>/is', $string, $svginfo);
</code>```

the $svginfo got null.

Sorry about this. I know [^>]*? should not be there in svg.
But when someone posts this I need to get the width info from this content.

Can anyone explain how to do this?

答:
Testing out on an online regex tester, it tells me:

```<code>\\ matches the character \ literally (case insensitive)
1 matches the character 1 literally (case insensitive)
</code>```

If instead I use \1 in the middle of the string, it says:

```<code>\1 matches the same text as most recently matched by the 1st capturing group
</code>```

This means that you will find the matching closing quote, which is what you seem to want to do.

Oh, and Zalgo.

UPDATE:

Ah, this is the Zalgo problem. The problem is that you want to ensure you don't skip over the whole <svg .... > tag, so that <svg>width="99" is rejected. A simple and valid HTML pattern would be:

```<code><svg name=">" width="42">
</code>```

A regex to catch this and similar variants will soon get out of hand; the proper way to do this is use an HTML parser; here is one article about how to do it.

Body:
Nearly, when i write code with preg_match.Like this

    $string = <<<ETO
    <svg "[^>]*? width="480.24px" height="360px" viewBox="0 0 480.24 360" enable-background="new 0 0 480.24 360" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    ETO;

    preg_match('/<svg[^>]*?width=[\'|"]{1}(.*?)[\'|"]{1}[^>]*?>/is', $string, $svginfo);

the $svginfo got null.

Sorry about this. I know [^>]*? should not be there in svg.
But when someone posts this I need to get the width info from this content.

Can anyone explain how to do this?

Body:
Testing out on an online regex tester, it tells me:

\\ matches the character \ literally (case insensitive)
1 matches the character 1 literally (case insensitive)

If instead I use \1 in the middle of the string, it says:

\1 matches the same text as most recently matched by the 1st capturing group

This means that you will find the matching closing quote, which is what you seem to want to do.

Oh, and Zalgo.

UPDATE:

Ah, this is the Zalgo problem. The problem is that you want to ensure you don't skip over the whole <svg .... > tag, so that <svg>width="99" is rejected. A simple and valid HTML pattern would be:

<svg name=">" width="42">

A regex to catch this and similar variants will soon get out of hand; the proper way to do this is use an HTML parser; here is one article about how to do it.


问:
How to build this query in postgresql

Supposing I have this data. How to query this in such a way that will result to this in an efficient way. It will sum the qty of all OUT less the IN per item.

答:
```<code>select desc, sum(case Type when 'out' then Qty else -Qty end) from test group by desc;
</code>```

this will be faster.

Title: How to build this query in postgresql

Body:
select desc, sum(case Type when 'out' then Qty else -Qty end) from test group by desc;

this will be faster.


问:
Editing excel file using vbscript but the edits are taking too long to complete
/* The reason why I am using vb scrips to edit the excel file is: the excel file will be different all the time but the format will be the same and the user does not want to save VBA macro on their workbook.

I am getting values from Column 3 and adding those values to Column 9 at the end of it.

*/

```<code>Set xlApp=CreateObject("Excel.Application")
Set xlBook=xlApp.Workbooks.Open("filepath", 0, true)
xlApp.visible=true

Set xlSheet=xlBook.Worksheets("Proposal Spreadsheet")
row=xlSheet.UsedRange.Rows.Count
col=xlSheet.UsedRange.Columns.Count

dim i

For i=15 to xlSheet.UsedRange.Rows.Count
cell=xlSheet.Cells(i,3).Value
celli=xlSheet.Cells(i,9).Value+"("+cell+")" //I am combining column 3 with column 9

xlSheet.Cells(i,9).Value=celli

Next

xlBook.Save
xlApp.Run "Submit_To_iDesk"
xlBook.Close

xlApp.Quit
Set xlApp=Nothing
Set xlBook=Nothing
WScript.Quit
</code>```

答:
The key to speeding up your procedure is reducing the number of write operations.

Here is how I would do it

Set a range variable (target) to the target cells in column 9

Create an array of values from the target range

Edit the elements of the values array Write the values array back over the original

target range in 1 operation

```<code>Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\Users\best buy\Desktop\Book1.xlsx", 0, True)

xlApp.Visible = True
xlApp.ScreenUpdating = False
Set xlSheet = xlBook.Worksheets("Proposal Spreadsheet")

Dim i, values, LastRow, target

With xlSheet
    LastRow = xlSheet.UsedRange.Rows.Count
    Set target = .Range(.Cells(15, 9), .Cells(LastRow, 9))
    values = target.Value

    For i = LBound(values, 1) To UBound(values, 1)
        values(i, 1) = values(i, 1) & "(" & .Cells(i + 15 - LBound(values, 1), 3) & ")"
    Next
    target.Value = values
End With

xlBook.Save
'xlApp.Run "Submit_To_iDesk"
xlBook.Close
xlApp.ScreenUpdating = True
xlApp.Quit
Set xlApp = Nothing
Set xlBook = Nothing
WScript.Quit
</code>```

Body:
/* The reason why I am using vb scrips to edit the excel file is: the excel file will be different all the time but the format will be the same and the user does not want to save VBA macro on their workbook.

I am getting values from Column 3 and adding those values to Column 9 at the end of it.

*/

Set xlApp=CreateObject("Excel.Application")
Set xlBook=xlApp.Workbooks.Open("filepath", 0, true)
xlApp.visible=true

Set xlSheet=xlBook.Worksheets("Proposal Spreadsheet")
row=xlSheet.UsedRange.Rows.Count
col=xlSheet.UsedRange.Columns.Count

dim i

For i=15 to xlSheet.UsedRange.Rows.Count
cell=xlSheet.Cells(i,3).Value
celli=xlSheet.Cells(i,9).Value+"("+cell+")" //I am combining column 3 with column 9

xlSheet.Cells(i,9).Value=celli

Next

xlBook.Save
xlApp.Run "Submit_To_iDesk"
xlBook.Close

xlApp.Quit
Set xlApp=Nothing
Set xlBook=Nothing
WScript.Quit

Body:
The key to speeding up your procedure is reducing the number of write operations.

Here is how I would do it

Set a range variable (target) to the target cells in column 9

Create an array of values from the target range

Edit the elements of the values array Write the values array back over the original

target range in 1 operation

Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\Users\best buy\Desktop\Book1.xlsx", 0, True)

xlApp.Visible = True
xlApp.ScreenUpdating = False
Set xlSheet = xlBook.Worksheets("Proposal Spreadsheet")

Dim i, values, LastRow, target

With xlSheet
    LastRow = xlSheet.UsedRange.Rows.Count
    Set target = .Range(.Cells(15, 9), .Cells(LastRow, 9))
    values = target.Value

    For i = LBound(values, 1) To UBound(values, 1)
        values(i, 1) = values(i, 1) & "(" & .Cells(i + 15 - LBound(values, 1), 3) & ")"
    Next
    target.Value = values
End With

xlBook.Save
'xlApp.Run "Submit_To_iDesk"
xlBook.Close
xlApp.ScreenUpdating = True
xlApp.Quit
Set xlApp = Nothing
Set xlBook = Nothing
WScript.Quit


问:
Dynamically Resizing UITableViewCell Heights in iOS Swift
I am trying to create a UITableView whose cell's heights are sized according to the amount of text being displayed. This seemed simple enough, as heightForRowAtIndexPath is available and I can get the required size needed for the UILabel using the code shown below. However, this method is called before cellForRowAtIndexPath so I cannot size based on the content in the cell, which seems a very strange choice to me. What is the "best practice" way to dynamically size the height of the cells based on content?

In addition, why did Apple not have the heightForRowAtIndexPath method be called after cellForRowAtIndexPath?

I am using the following in cellForRowAtIndexPath to determine the required height for my label, but I'm not sure how to move this to heightForRowAtIndexPath since dequeReusableCellWithIdentifier cannot be called in the method (as far as I know):

```<code>func getRequiredLabelHeight(label: UILabel, text: String, font: UIFont) -> CGFloat {
    label.numberOfLines = 0
    label.lineBreakMode = .ByWordWrapping
    label.font = font
    label.text = text
    label.sizeToFit()

    return label.frame.height

}
</code>```

I also know that I want the following to be my cell height, since I want the cell size to increase from the initial size (hinging on a 1 line label) based on the new label size (which can be any arbitrary length of lines)

```<code>self.cellHeight = getRequiredLabelHeight(commentCell.commentTextLabel, text: allComments![indexPath.row].text, font: UIFont(name: "Avenir", size: 16.0)!) + commentCell.bounds.height - commentCell.commentTextLabel.bounds.height
</code>```

Thanks!

EDIT
My question does NOT pertain to resizing the label. The code I have provided does that. The issue is that the cell height is not constant; it varies throughout the table based on the content, so I can't use a static tableview.rowHeight. Since I cannot resize the cell height from cellForRowAtIndexPath, my content will not fit in the cell. For example, here is my cellForRowAtIndexPath (in a nutshell):

```<code>func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let commentCell: CommentTableViewCell = tableView.dequeueReusableCellWithIdentifier("commentTableViewCell", forIndexPath: indexPath)
        as! CommentTableViewCell

    commentCell.commentTextLabel.textColor = Utils.hatchliTextDark
    commentCell.commentTextLabel.font = UIFont(name: "Avenir", size: 16)

    self.cellHeight = getRequiredLabelHeight(commentCell.commentTextLabel, text: allComments![indexPath.row].text, font: UIFont(name: "Avenir", size: 16.0)!) + commentCell.bounds.height - commentCell.commentTextLabel.bounds.height

    commentCell.commentTextLabel.frame = CGRectMake(commentCell.commentTextLabel.frame.origin.x, commentCell.commentTextLabel.frame.origin.y, commentCell.commentTextLabel.frame.width, self.cellHeight)
    commentCell.handleTextLabel.text = String(allComments![indexPath.row].creatorHandle)
    commentCell.votesTextLabel.text = String(allComments![indexPath.row].votes)
    commentCell.commentTextLabel.text = allComments![indexPath.row].text
    commentCell.setMargin()

    return commentCell

}
</code>```

So, if the frame of the UILabel becomes larger than tableview.rowHeight, it will not appear. Thus, the row height needs to be resized on a per cell basis from heightForRowAtIndexPath (I assume)

答:
Well I went through this tutorial and a single line of code helped me to resize the content of uitableview cell with the content of a label in it.

```<code>//=====
https://www.raywenderlich.com/129059/self-sizing-table-view-cells
//=====
</code>```

Add

```<code>tableView.rowHeight = UITableViewAutomaticDimension

tableView.estimatedRowHeight = 140
</code>```

in viewDidLoad() and make sure number of lines of label/textview is 0

Body:
I am trying to create a UITableView whose cell's heights are sized according to the amount of text being displayed. This seemed simple enough, as heightForRowAtIndexPath is available and I can get the required size needed for the UILabel using the code shown below. However, this method is called before cellForRowAtIndexPath so I cannot size based on the content in the cell, which seems a very strange choice to me. What is the "best practice" way to dynamically size the height of the cells based on content?

In addition, why did Apple not have the heightForRowAtIndexPath method be called after cellForRowAtIndexPath?

I am using the following in cellForRowAtIndexPath to determine the required height for my label, but I'm not sure how to move this to heightForRowAtIndexPath since dequeReusableCellWithIdentifier cannot be called in the method (as far as I know):

func getRequiredLabelHeight(label: UILabel, text: String, font: UIFont) -> CGFloat {
    label.numberOfLines = 0
    label.lineBreakMode = .ByWordWrapping
    label.font = font
    label.text = text
    label.sizeToFit()

    return label.frame.height

}

I also know that I want the following to be my cell height, since I want the cell size to increase from the initial size (hinging on a 1 line label) based on the new label size (which can be any arbitrary length of lines)

self.cellHeight = getRequiredLabelHeight(commentCell.commentTextLabel, text: allComments![indexPath.row].text, font: UIFont(name: "Avenir", size: 16.0)!) + commentCell.bounds.height - commentCell.commentTextLabel.bounds.height

Thanks!

EDIT
My question does NOT pertain to resizing the label. The code I have provided does that. The issue is that the cell height is not constant; it varies throughout the table based on the content, so I can't use a static tableview.rowHeight. Since I cannot resize the cell height from cellForRowAtIndexPath, my content will not fit in the cell. For example, here is my cellForRowAtIndexPath (in a nutshell):

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let commentCell: CommentTableViewCell = tableView.dequeueReusableCellWithIdentifier("commentTableViewCell", forIndexPath: indexPath)
        as! CommentTableViewCell

    commentCell.commentTextLabel.textColor = Utils.hatchliTextDark
    commentCell.commentTextLabel.font = UIFont(name: "Avenir", size: 16)

    self.cellHeight = getRequiredLabelHeight(commentCell.commentTextLabel, text: allComments![indexPath.row].text, font: UIFont(name: "Avenir", size: 16.0)!) + commentCell.bounds.height - commentCell.commentTextLabel.bounds.height

    commentCell.commentTextLabel.frame = CGRectMake(commentCell.commentTextLabel.frame.origin.x, commentCell.commentTextLabel.frame.origin.y, commentCell.commentTextLabel.frame.width, self.cellHeight)
    commentCell.handleTextLabel.text = String(allComments![indexPath.row].creatorHandle)
    commentCell.votesTextLabel.text = String(allComments![indexPath.row].votes)
    commentCell.commentTextLabel.text = allComments![indexPath.row].text
    commentCell.setMargin()

    return commentCell

}

So, if the frame of the UILabel becomes larger than tableview.rowHeight, it will not appear. Thus, the row height needs to be resized on a per cell basis from heightForRowAtIndexPath (I assume)

Body:
Well I went through this tutorial and a single line of code helped me to resize the content of uitableview cell with the content of a label in it.

//=====
https://www.raywenderlich.com/129059/self-sizing-table-view-cells
//=====

Add

tableView.rowHeight = UITableViewAutomaticDimension

tableView.estimatedRowHeight = 140

in viewDidLoad() and make sure number of lines of label/textview is 0


问:
What's the proper way to handle localized name-spaced routes in Rails 2.3.8?
I'm localizing my application and am struggling with how to handle routes for a specific portion of the app.

Initially I had routes that looked like this:

```<code>
    map.namespace :admin do |admin|
      admin.resources :people, :member => {:confirm_destroy => :get}, :collection => {:follow => :post, :sync_friends => :get, :upload => :post, :import => :get, :recommendations => :get, :mark_recommendations => :post, :batch_create => :post}
      admin.resources :jobs, :collection => {:remove => :post}
      admin.resources :users, :member => {:confirm_destroy => :get}
      admin.resources :sites, :member => {:update_design => :post, :design => :get, :update_links => :post, :links => :get, :content => :get, :update_content => :post, :add_admin => :post, :remove_admin => :post, :set_system_account => :get, :confirm_system_account => :get}, :collection => {:remove => :post, :upload => :post}
      admin.resources :subscriptions, :member => { :charge => :post, :migrate_plan => :post, :update_components => :post }
      admin.resources :accounts, :collection => {:remove => :post}
      admin.resources :subscription_plans, :as => 'plans'
      admin.resources :subscription_discounts, :as => 'discounts'
      admin.resources :twitter_lists, :collection => {:auto_generate_twitter_list => :post}
    end
</code>```

From what I've done successfully on other routes I need to add: :path_prefix => '/:locale/' to these routes.

The only example I've come across looks something like this:

```
  map.with_options(:path_prefix => '/:locale/admin') do |locale|
    locale.namespace :admin do |admin|
      admin.resources :people, :member => {:confirm_destroy => :get}, :collection => {:follow => :post, :sync_friends => :get, :upload => :post, :import => :get, :recommendations => :get, :mark_recommendations => :post, :batch_create => :post}
      admin.resources :subscriptions, :member => { :charge => :post, :migrate_plan => :post, :update_components => :post }
      admin.resources :accounts, :collection => {:remove => :post}
      etc etc etc
    end
  end
</code>```

This actually appears works great for the routes, however, it is screwing up some of my generated URLS.

For example previously I had something like = link_to(t('subscription'), edit_admin_subscription_path(subscription_id) which worked perfectly... after the above change this url no longer properly generates, giving the following error:

```
ActionController::RoutingError in Admin/base#index

Showing app/views/admin/shared/_menu.html.haml where line #13 raised:

edit_admin_subscription_url failed to generate from {:action=>"edit", :controller=>"admin/subscriptions", :locale=>BSON::ObjectId('4d0ecb6587adddc91c000014')}, expected: {:controller=>"admin/subscriptions", :action=>"edit"}, diff: {:locale=>BSON::ObjectId('4d0ecb6587adddc91c000014')}
```

I would sincerely appreciate any insight anyone can shed on the proper way to handle this type of thing and/or why this url doesn't like to generate any longer. THANKS!

答:
So as it turns out after the addition of the localization, I needed to be more specific with the the parameters passed into the URL helper:

= link_to(t('subscription'), edit_admin_subscription_path(:id => subscription_id) works just fine.

Still not sure not certain if the

```<code>
  map.with_options(:path_prefix => '/:locale/admin') do |locale|
    locale.namespace :admin do |admin|</code>```

is the best way to do that, but at least it's working for now.

Body:
I'm localizing my application and am struggling with how to handle routes for a specific portion of the app.

Initially I had routes that looked like this:

    map.namespace :admin do |admin|
      admin.resources :people, :member => {:confirm_destroy => :get}, :collection => {:follow => :post, :sync_friends => :get, :upload => :post, :import => :get, :recommendations => :get, :mark_recommendations => :post, :batch_create => :post}
      admin.resources :jobs, :collection => {:remove => :post}
      admin.resources :users, :member => {:confirm_destroy => :get}
      admin.resources :sites, :member => {:update_design => :post, :design => :get, :update_links => :post, :links => :get, :content => :get, :update_content => :post, :add_admin => :post, :remove_admin => :post, :set_system_account => :get, :confirm_system_account => :get}, :collection => {:remove => :post, :upload => :post}
      admin.resources :subscriptions, :member => { :charge => :post, :migrate_plan => :post, :update_components => :post }
      admin.resources :accounts, :collection => {:remove => :post}
      admin.resources :subscription_plans, :as => 'plans'
      admin.resources :subscription_discounts, :as => 'discounts'
      admin.resources :twitter_lists, :collection => {:auto_generate_twitter_list => :post}
    end

From what I've done successfully on other routes I need to add: :path_prefix => '/:locale/' to these routes.

The only example I've come across looks something like this:

  map.with_options(:path_prefix => '/:locale/admin') do |locale|
    locale.namespace :admin do |admin|
      admin.resources :people, :member => {:confirm_destroy => :get}, :collection => {:follow => :post, :sync_friends => :get, :upload => :post, :import => :get, :recommendations => :get, :mark_recommendations => :post, :batch_create => :post}
      admin.resources :subscriptions, :member => { :charge => :post, :migrate_plan => :post, :update_components => :post }
      admin.resources :accounts, :collection => {:remove => :post}
      etc etc etc
    end
  end

This actually appears works great for the routes, however, it is screwing up some of my generated URLS.

For example previously I had something like = link_to(t('subscription'), edit_admin_subscription_path(subscription_id) which worked perfectly... after the above change this url no longer properly generates, giving the following error:

ActionController::RoutingError in Admin/base#index

Showing app/views/admin/shared/_menu.html.haml where line #13 raised:

edit_admin_subscription_url failed to generate from {:action=>"edit", :controller=>"admin/subscriptions", :locale=>BSON::ObjectId('4d0ecb6587adddc91c000014')}, expected: {:controller=>"admin/subscriptions", :action=>"edit"}, diff: {:locale=>BSON::ObjectId('4d0ecb6587adddc91c000014')}

I would sincerely appreciate any insight anyone can shed on the proper way to handle this type of thing and/or why this url doesn't like to generate any longer. THANKS!

Body:
So as it turns out after the addition of the localization, I needed to be more specific with the the parameters passed into the URL helper:

= link_to(t('subscription'), edit_admin_subscription_path(:id => subscription_id) works just fine.

Still not sure not certain if the

  map.with_options(:path_prefix => '/:locale/admin') do |locale|
    locale.namespace :admin do |admin|

is the best way to do that, but at least it's working for now.


问:
how to setup the .htaccess for a subdomain on a shared hosting godaddy server
I want to upload my local Laravel project on godaddy but I'm having some error

error

```<code>[Wed Jul 05 21:16:44.858396 2017]
    [autoindex:error] [pid 21796:tid 139689709188864]
    [client 99.240.235.234:57754]
    AH01276:
        Cannot serve directory /home/bugsbunny/public_html/sto.com/:
            No matching DirectoryIndex (/home/bugsbunny/public_html/sto.com/public/index.php)
    found, and server-generated directory index forbidden by Options directive
</code>```

.htaccess

```<code>DirectoryIndex /home/bugsbunny/public_html/sto.com/public/index.php
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ /home/bugsbunny/public_html/sto.com/public/index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
</code>```

steps that I did

I edited the public/.htaccess file

by edited I mean changing the directory on the first line and the line starting by RewriteRule

I cut & paste this file into the root directory

I uploaded the project into godaddy

答: Why you are not using dedicated hosting for laravel. Get your server and [digitaloccean, etc] and do what you want... </p>

Body:
I want to upload my local Laravel project on godaddy but I'm having some error

error

[Wed Jul 05 21:16:44.858396 2017]
    [autoindex:error] [pid 21796:tid 139689709188864]
    [client 99.240.235.234:57754]
    AH01276:
        Cannot serve directory /home/bugsbunny/public_html/sto.com/:
            No matching DirectoryIndex (/home/bugsbunny/public_html/sto.com/public/index.php)
    found, and server-generated directory index forbidden by Options directive

.htaccess

DirectoryIndex /home/bugsbunny/public_html/sto.com/public/index.php
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ /home/bugsbunny/public_html/sto.com/public/index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

steps that I did

I edited the public/.htaccess file

by edited I mean changing the directory on the first line and the line starting by RewriteRule

I cut & paste this file into the root directory

I uploaded the project into godaddy


问:
Mule DB data retrieval into chunks
We are trying to extract approx. 40 GB data from database and want to generate multiple csv files. We used mule DB connector in streaming fashion, which is returning 'ResultSetIterator'

Q1) How to convert this ResultSetIterator to arraylist? or any readable format which we can use further to generate files

Q2) We tried using For-Each component to split this data in chunks, its working for limited set of data and for huge data giving SerializationException

In below input snippet we are making chunks of data using for-each and providing it to batch process for multiple files

```<code>  <batch:job name="testBatchWithDBOutside">
        <batch:input>
            <logger message="#[payload]" level="INFO" doc:name="Logger"/>
        </batch:input>
        <batch:process-records>
            <batch:step name="Batch_Step">
                <batch:commit size="10" doc:name="Batch Commit">
                    <object-to-string-transformer doc:name="Object to String"/>
                    <logger message="#[payload]" level="INFO" doc:name="Logger"/>
                    <file:outbound-endpoint path="C:\output" outputPattern="#[message.id].txt" responseTimeout="10000" doc:name="File"/>
                </batch:commit>
            </batch:step>
        </batch:process-records>
    </batch:job>
    <flow name="testBatchWithDBOutsideFlow" processingStrategy="synchronous">
        <file:inbound-endpoint path="C:\input" responseTimeout="10000" doc:name="File"/>
        <db:select config-ref="MySQL_Configuration" streaming="true" fetchSize="10" doc:name="Database">
            <db:parameterized-query><![CDATA[select * from classicmodels]]></db:parameterized-query>
        </db:select>
        <foreach batchSize="5" doc:name="For Each">
            <batch:execute name="testBatchWithDBOutside" doc:name="testBatchWithDBOutside"/>
        </foreach>
    </flow>
</code>```

答:
Q1. You don't want to convert the Iterator to a List, as this will defeat the purpose of streaming from the DB connector and load all records into memory. Mule handles Iterators and Lists in the same way anyway.

Q2. The batch module implies a for-each operation. The output of batch:input needs to be a List or an Iterator. You should be able to simplify this

```<code><batch:job name="testBatch">
    <batch:input>
        <db:select config-ref="MySQL_Configuration" streaming="true" fetchSize="10" doc:name="Database">
            <db:parameterized-query><![CDATA[select * from classicmodels]]></db:parameterized-query>
        </db:select>
    </batch:input>
    <batch:process-records>
        <batch:step name="Batch_Step">
            <object-to-string-transformer doc:name="Object to String"/>
            <file:outbound-endpoint path="C:\output" outputPattern="#[message.id].txt" responseTimeout="10000" doc:name="File"/>
        </batch:step>
    </batch:process-records>
</batch:job>
</code>```

You will also need to replace the object-to-string-transformer with a component that converts a database record (the payload at this point will be a map where the key is the column name, and the value is the record value) into a csv line.

You can find a decent example in the Mule blog here: https://blogs.mulesoft.com/dev/anypoint-platform-dev/batch-module-reloaded/

Another option would be to remove the batch processor and use DataWeave to generate csv output and stream it to the file. This might be helpful: https://docs.mulesoft.com/mule-user-guide/v/3.7/dataweave-streaming

Dataweave will call next on the ResultSetIterator as it processes each record, and that Iterator will handle selecting chunks of records from the underlying database, so there is no queueing in between steps, or loading the full dataset into memory.

```<code><flow name="batchtestFlow">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/batch" allowedMethods="GET" doc:name="HTTP"/>
    <db:select config-ref="Generic_Database_Configuration" streaming="true" doc:name="Database">
        <db:parameterized-query><![CDATA[select * from Employees]]></db:parameterized-query>
    </db:select>
    <dw:transform-message doc:name="Transform Message">
        <dw:set-payload><![CDATA[%dw 1.0
            %input payload application/java
            %output application/csv streaming=true, header=true, quoteValues=true
            ---
            payload map ((e, i) -> {
                surname: e.SURNAME,
                firstname: e.FIRST_NAME
            })]]></dw:set-payload>
    </dw:transform-message>
    <file:outbound-endpoint path="C:/tmp" outputPattern="testbatchfile.csv" connector-ref="File" responseTimeout="10000" doc:name="File"/>
</flow>
</code>```

Title: Mule DB data retrieval into chunks

Body:
We are trying to extract approx. 40 GB data from database and want to generate multiple csv files. We used mule DB connector in streaming fashion, which is returning 'ResultSetIterator'

Q1) How to convert this ResultSetIterator to arraylist? or any readable format which we can use further to generate files

Q2) We tried using For-Each component to split this data in chunks, its working for limited set of data and for huge data giving SerializationException

In below input snippet we are making chunks of data using for-each and providing it to batch process for multiple files

  <batch:job name="testBatchWithDBOutside">
        <batch:input>
            <logger message="#[payload]" level="INFO" doc:name="Logger"/>
        </batch:input>
        <batch:process-records>
            <batch:step name="Batch_Step">
                <batch:commit size="10" doc:name="Batch Commit">
                    <object-to-string-transformer doc:name="Object to String"/>
                    <logger message="#[payload]" level="INFO" doc:name="Logger"/>
                    <file:outbound-endpoint path="C:\output" outputPattern="#[message.id].txt" responseTimeout="10000" doc:name="File"/>
                </batch:commit>
            </batch:step>
        </batch:process-records>
    </batch:job>
    <flow name="testBatchWithDBOutsideFlow" processingStrategy="synchronous">
        <file:inbound-endpoint path="C:\input" responseTimeout="10000" doc:name="File"/>
        <db:select config-ref="MySQL_Configuration" streaming="true" fetchSize="10" doc:name="Database">
            <db:parameterized-query><![CDATA[select * from classicmodels]]></db:parameterized-query>
        </db:select>
        <foreach batchSize="5" doc:name="For Each">
            <batch:execute name="testBatchWithDBOutside" doc:name="testBatchWithDBOutside"/>
        </foreach>
    </flow>

Body:
Q1. You don't want to convert the Iterator to a List, as this will defeat the purpose of streaming from the DB connector and load all records into memory. Mule handles Iterators and Lists in the same way anyway.

Q2. The batch module implies a for-each operation. The output of batch:input needs to be a List or an Iterator. You should be able to simplify this

<batch:job name="testBatch">
    <batch:input>
        <db:select config-ref="MySQL_Configuration" streaming="true" fetchSize="10" doc:name="Database">
            <db:parameterized-query><![CDATA[select * from classicmodels]]></db:parameterized-query>
        </db:select>
    </batch:input>
    <batch:process-records>
        <batch:step name="Batch_Step">
            <object-to-string-transformer doc:name="Object to String"/>
            <file:outbound-endpoint path="C:\output" outputPattern="#[message.id].txt" responseTimeout="10000" doc:name="File"/>
        </batch:step>
    </batch:process-records>
</batch:job>

You will also need to replace the object-to-string-transformer with a component that converts a database record (the payload at this point will be a map where the key is the column name, and the value is the record value) into a csv line.

You can find a decent example in the Mule blog here: https://blogs.mulesoft.com/dev/anypoint-platform-dev/batch-module-reloaded/

Another option would be to remove the batch processor and use DataWeave to generate csv output and stream it to the file. This might be helpful: https://docs.mulesoft.com/mule-user-guide/v/3.7/dataweave-streaming

Dataweave will call next on the ResultSetIterator as it processes each record, and that Iterator will handle selecting chunks of records from the underlying database, so there is no queueing in between steps, or loading the full dataset into memory.

<flow name="batchtestFlow">
    <http:listener config-ref="HTTP_Listener_Configuration" path="/batch" allowedMethods="GET" doc:name="HTTP"/>
    <db:select config-ref="Generic_Database_Configuration" streaming="true" doc:name="Database">
        <db:parameterized-query><![CDATA[select * from Employees]]></db:parameterized-query>
    </db:select>
    <dw:transform-message doc:name="Transform Message">
        <dw:set-payload><![CDATA[%dw 1.0
            %input payload application/java
            %output application/csv streaming=true, header=true, quoteValues=true
            ---
            payload map ((e, i) -> {
                surname: e.SURNAME,
                firstname: e.FIRST_NAME
            })]]></dw:set-payload>
    </dw:transform-message>
    <file:outbound-endpoint path="C:/tmp" outputPattern="testbatchfile.csv" connector-ref="File" responseTimeout="10000" doc:name="File"/>
</flow>


问:
What is the use of SET type in MySQL? How to implement in Oracle?
I was reading on https://dev.mysql.com/doc/refman/5.7/en/set.html but I could not understand its use much. Why do we need it?
And how can we achieve this in Oracle?</p>

答:
Why do we need it? We don't. Anything that you think you can do with a set, you can do with a parent-child relationship. You can even cluster tables if you so desire, which I suppose could be a concern.

The closest concept in Oracle to a MySQL SET is what Oracle calls a nested table.

The biggest problem with nested tables is that you would be hard-pressed to index them.


问:
change bgcolor in html table depending on client input
I have seen a number of similar questions but none that appear to answer what I am trying to do.

In a form on page 1 the following three pieces of information will be entered for a measurement, (1)upper limit, (2)lower limit and (3)measured value.

The user will then click on a button taking them to page 2 where the entered information will be uploaded to a mysql data base, this all works well. On page 2 the entered information will be displayed confirming what has been uploaded to the data base. This information is displayed in a html table.

I wish to change the bgcolor of the cell where the measured value is displayed to RED if not a value that is between (1) upper limit or (2) lower limit .

The three pieces of information entered by the user can and will change every time.

Can this be done simply ?

答:
Below link can help you, listen for input value change and use jquery to set the appropriate BG. https://jsfiddle.net/fkacm5rz/5/

```<code>var input = document.querySelector('#number');
</code>```

var messages = document.querySelector('#text');

```<code>input.addEventListener('input', function()
{
    messages.textContent += 'input changed to: ' + input.value ;
    if(input.value === '1') {
    document.getElementById("text").style.color = "red";
    }
    else {
     document.getElementById("text").style.color = "green";
    }
});
</code>```

HTML:

```<code>    <input id="number" type="input">

    <div id="text">update </div>
</code>```

Body:
Below link can help you, listen for input value change and use jquery to set the appropriate BG. https://jsfiddle.net/fkacm5rz/5/

var input = document.querySelector('#number');

var messages = document.querySelector('#text');

input.addEventListener('input', function()
{
    messages.textContent += 'input changed to: ' + input.value ;
    if(input.value === '1') {
    document.getElementById("text").style.color = "red";
    }
    else {
     document.getElementById("text").style.color = "green";
    }
});

HTML:

    <input id="number" type="input">

    <div id="text">update </div>


问:
angular2 display message if field value is invalid
I have the following field in an angular2 page (I am not using forms).

```<code><input id="firstname" name="firstname" class="field-input field-validation-input" [(ngModel)]="firstname"
                    placeholder="First name" spellcheck="false" required #firstNameField>
</code>```

Now I want to display a message at the bottom of the field if it is invalid, in this scenario if it is empty.  What is the best way to do this, I can use firstNameField.className but as you can see there are a number of classes here and trying to filter for ng-invalid might be a problem

答:
Why not use a form and Angular's built in validation features?

Without forms, you could write some code in the setter for the firstname field that performs the validation and sets the message. You could then add the elements to display the message if the message is set.

In the component:

```<code>   message: string;
   _firstName: string;
   get firstName(): string {
      return this._firstName;
   }
   set firstName(value: string) {
      this._firstName = value;
      // Validation here
      // If validation does not pass
      {
         message = "Please enter a valid value";
      }
   }
</code>```

Body:
I have the following field in an angular2 page (I am not using forms).

<input id="firstname" name="firstname" class="field-input field-validation-input" [(ngModel)]="firstname"
                    placeholder="First name" spellcheck="false" required #firstNameField>

Now I want to display a message at the bottom of the field if it is invalid, in this scenario if it is empty.  What is the best way to do this, I can use firstNameField.className but as you can see there are a number of classes here and trying to filter for ng-invalid might be a problem

Body:
Why not use a form and Angular's built in validation features?

Without forms, you could write some code in the setter for the firstname field that performs the validation and sets the message. You could then add the elements to display the message if the message is set.

In the component:

   message: string;
   _firstName: string;
   get firstName(): string {
      return this._firstName;
   }
   set firstName(value: string) {
      this._firstName = value;
      // Validation here
      // If validation does not pass
      {
         message = "Please enter a valid value";
      }
   }


问:
parse string as conditions to filter pandas dataframe
Hi I have a pandas dataframe, I have a column A.

```<code>data = pandas.DataFrame()
data['A']= [numpy.random.choice([1,2,3,4,5,6]) for i in range(10)]
</code>```

I want to add a column B condition on A (when A =1 then B=0, when A>5 then B=1) instead of using:

```<code>data.loc[data['A']==1,'B']=0
data.loc[data['A']>5, 'B']=1
</code>```

Here I want to create a function to do this given the condition as a dict: {'A=1':0,'A>5':1} so I could use add_column({'A=1':0,'A>5':1}, 'B') to do the code above. I am thinking it is tricky to deal with the operators, any good idea?

```<code>def add_column(condition_dict, NewColumnName):
    pass
</code>```

答:
While there may be efficient ways to do it, one possible way might be to use eval function.

Creating input df:

```<code>import pandas as pd
import numpy as np

data = pd.DataFrame()
data['A']= [np.random.choice([1,2,3,4,5,6]) for i in range(10)]
print(data)
</code>```

Input df:

```<code>   A
0  4
1  3
2  3
3  1
4  1
5  2
6  3
7  6
8  2
9  1
</code>```

Now, a function is created such that it iterates through each row of dataframe and condition_dict and when row evaluation matches value is stored in list for corresponding row which is updated for new column. If none of the condition matches then with default it will None:

```<code>def add_column(df, condition_dict, NewColumnName):
    new_values = []
    for index, row in df.iterrows():
        # if none of the condition matches then put default value
        default_value = None
        # iterate through each condition to check if any matches
        for key, value in condition_dict.items():
            expression = 'row.' + key
            if(eval(expression)):
                default_value = value
        # add corresponding rows new value for new column
        new_values.append(default_value)

    df[NewColumnName] = new_values
</code>```

Now, to call the function:

```<code>add_column(data, {'A==1':0, 'A>5':1}, 'B')
print(data)
</code>```

Output:

```<code>   A    B
0  4  NaN
1  3  NaN
2  3  NaN
3  1  0.0
4  1  0.0
5  2  NaN
6  3  NaN
7  6  1.0
8  2  NaN
9  1  0.0
</code>```

Body:
Hi I have a pandas dataframe, I have a column A.

data = pandas.DataFrame()
data['A']= [numpy.random.choice([1,2,3,4,5,6]) for i in range(10)]

I want to add a column B condition on A (when A =1 then B=0, when A>5 then B=1) instead of using:

data.loc[data['A']==1,'B']=0
data.loc[data['A']>5, 'B']=1

Here I want to create a function to do this given the condition as a dict: {'A=1':0,'A>5':1} so I could use add_column({'A=1':0,'A>5':1}, 'B') to do the code above. I am thinking it is tricky to deal with the operators, any good idea?

def add_column(condition_dict, NewColumnName):
    pass

Body:
While there may be efficient ways to do it, one possible way might be to use eval function.

Creating input df:

import pandas as pd
import numpy as np

data = pd.DataFrame()
data['A']= [np.random.choice([1,2,3,4,5,6]) for i in range(10)]
print(data)

Input df:

   A
0  4
1  3
2  3
3  1
4  1
5  2
6  3
7  6
8  2
9  1

Now, a function is created such that it iterates through each row of dataframe and condition_dict and when row evaluation matches value is stored in list for corresponding row which is updated for new column. If none of the condition matches then with default it will None:

def add_column(df, condition_dict, NewColumnName):
    new_values = []
    for index, row in df.iterrows():
        # if none of the condition matches then put default value
        default_value = None
        # iterate through each condition to check if any matches
        for key, value in condition_dict.items():
            expression = 'row.' + key
            if(eval(expression)):
                default_value = value
        # add corresponding rows new value for new column
        new_values.append(default_value)

    df[NewColumnName] = new_values

Now, to call the function:

add_column(data, {'A==1':0, 'A>5':1}, 'B')
print(data)

Output:

   A    B
0  4  NaN
1  3  NaN
2  3  NaN
3  1  0.0
4  1  0.0
5  2  NaN
6  3  NaN
7  6  1.0
8  2  NaN
9  1  0.0


答:
Lot of typos

getElementsByClassName not getElementByClassName

getElementById not getElementsById

You can use onclick function for button

add type for button type="button"

Use index to get element from getElementsByClassName

Concatenation is wrong here  "i++" + " xp"; it should be (i++) + " xp";

You have not declared var i=0;

var i =0;
function change() {

document.getElementsByClassName("money")[0].innerHTML = (i++) + " xp";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <link rel="stylesheet" href="style.css">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

  </head>

    <header>
        <h1>Blank Page</h1>
    </header>
    <main>
        <form>
            <div class="col-md-4 text-center">
                <p><button id="singlebutton" name="singlebutton" class="btn btn-success" type="button" onclick ="change()">Click here</button></p>
            </div>

            <div class="credit text-center">
                <div class="earn"><p>You have earned: </p></div>
                <div class="money">0 xp</div>
            </div>
        </form>
    </main>
    <script src="main.js"></script>
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  </body>
</html></code>```

Title: How do you assign an action to a button in JScript?

Body:
just started learning Js for few days and i've been trying to make a button that when you click it, it would change the text of the 0 xp to 1, 2, 3,etc.. but im struggling to do so. Here is my code, any help would be appreciated.

var have = document.getElementsByClassName("earn");
var credits = document.getElementsByClassName("money");
var button = document.getElementsById("singlebutton");

credits.onclick = change() {
  document.getElementsByClassName("money").innerHTML = "i++" + " xp";
}

<!DOCTYPE html>

  <title></title>
  <link rel="stylesheet" href="style.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

Blank Page

    <form>

<button id="singlebutton" name="singlebutton" class="btn btn-success">Click here</button>

You have earned:

0 xp

    </form>

Body:
Lot of typos

getElementsByClassName not getElementByClassName

getElementById not getElementsById

You can use onclick function for button

add type for button type="button"

Use index to get element from getElementsByClassName

Concatenation is wrong here  "i++" + " xp"; it should be (i++) + " xp";

You have not declared var i=0;

var i =0;
function change() {

document.getElementsByClassName("money")[0].innerHTML = (i++) + " xp";
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <link rel="stylesheet" href="style.css">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

  </head>

    <header>
        <h1>Blank Page</h1>
    </header>
    <main>
        <form>
            <div class="col-md-4 text-center">
                <p><button id="singlebutton" name="singlebutton" class="btn btn-success" type="button" onclick ="change()">Click here</button></p>
            </div>

            <div class="credit text-center">
                <div class="earn"><p>You have earned: </p></div>
                <div class="money">0 xp</div>
            </div>
        </form>
    </main>
    <script src="main.js"></script>
    <!-- Latest compiled and minified JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  </body>
</html>


问:
How to open CoreData database file to see saved values
Right now i am using coredata to save my data.
Its all working fine but now i changed the logic to save values to the database. So i need to compare that the after logic change same values are getting saved in tables. So I need to compare tables.

I went through many links like
link 1
link 2

all the links shows that the database file that coredata create is of .sqlite extension. But the files create at that location are "persistentStore, persistentStore-shm, persistentStore-wal" as show in screenshot.

How should i suppose to open these files to see the saved data in tables.
Thanks in advance

```<code> - (void)setupDatabase:(void (^)(BOOL))completionHandler
{

    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"MainDataModel"];

    self.db = [[CWUIManagedDocument alloc] initWithFileURL:url];

    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                                  [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                                  [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

    self.db.persistentStoreOptions = options;

    if(![[NSFileManager defaultManager] fileExistsAtPath:[self.db.fileURL path]])
    {
        [self.db saveToURL:self.db.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            self.dataManager.db = self.db;
            completionHandler(success);
        }];
    } else if (self.db.documentState == UIDocumentStateClosed) {
        [self.db openWithCompletionHandler:^(BOOL success) {
            self.dataManager.db = self.db;
            completionHandler(success);
        }];
    }
}
</code>```

答:
Your sql file is the one without extension. The other 2 files are for journaling mode.

This has already been explained in this question. Apple changed the default journaling mode to WAL on iOS 7.

Body:
Right now i am using coredata to save my data.
Its all working fine but now i changed the logic to save values to the database. So i need to compare that the after logic change same values are getting saved in tables. So I need to compare tables.

I went through many links like
link 1
link 2

all the links shows that the database file that coredata create is of .sqlite extension. But the files create at that location are "persistentStore, persistentStore-shm, persistentStore-wal" as show in screenshot.

How should i suppose to open these files to see the saved data in tables.
Thanks in advance

 - (void)setupDatabase:(void (^)(BOOL))completionHandler
{

    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"MainDataModel"];

    self.db = [[CWUIManagedDocument alloc] initWithFileURL:url];

    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                                  [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                                                  [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];

    self.db.persistentStoreOptions = options;

    if(![[NSFileManager defaultManager] fileExistsAtPath:[self.db.fileURL path]])
    {
        [self.db saveToURL:self.db.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
            self.dataManager.db = self.db;
            completionHandler(success);
        }];
    } else if (self.db.documentState == UIDocumentStateClosed) {
        [self.db openWithCompletionHandler:^(BOOL success) {
            self.dataManager.db = self.db;
            completionHandler(success);
        }];
    }
}


问:
Very basic objective-c question-how do I make different views share information?
So, basically, I have four different views that are switched via a tab bar at the bottom of the screen. I have a view controller set up for each one, and they all work fine. The only problem is that I have no idea how to share information between the different views-for example, I have an IBAction on one that takes the output of a UISegmentedControl and stores the selection as an integer (1,2,3,4). The problem is, I don't know how to access that integer from the first view controller (the one that actually does stuff with that information). I'm sure this is a very basic problem but my google-fu doesn't seem to be working here. Thanks!</p>

答:
I use a general theme in all my apps where I have certain data that needs to be accessed practically in all main classes. I find it really easy to use and practically error free. (Thanks again to all the folks here in the forum for the super idea!)

I declare this variable in all the classes where I need it...

```<code>  @class WebiDataManager;

  @interface FirstViewController : UIViewController<MFMessageComposeViewControllerDelegate, SetupDelegate>  {
        WebiDataManager         *webiDataManager;
    ...
</code>```

In this code I get it from the AppDelegate...

```<code>#import "WebiAppDelegate.h"

 - (void)viewWillAppear:(BOOL)animated {
        //  D_IN;
        [super viewWillAppear:animated];

        //get the dataManager global Object, so we always have a structured accesss to the data!
        WebiAppDelegate *mainDelegate = (WebiAppDelegate *)[[UIApplication sharedApplication]delegate];
        self.webiDataManager = mainDelegate.webiDataManager;
</code>```

By the way, this also works great for coredata, since through this global variable I always have access to all the main coredata.

Hope I could explain it clearly enough...

Body:
I use a general theme in all my apps where I have certain data that needs to be accessed practically in all main classes. I find it really easy to use and practically error free. (Thanks again to all the folks here in the forum for the super idea!)

I declare this variable in all the classes where I need it...

  @class WebiDataManager;

  @interface FirstViewController : UIViewController<MFMessageComposeViewControllerDelegate, SetupDelegate>  {
        WebiDataManager         *webiDataManager;
    ...

In this code I get it from the AppDelegate...

#import "WebiAppDelegate.h"

 - (void)viewWillAppear:(BOOL)animated {
        //  D_IN;
        [super viewWillAppear:animated];

        //get the dataManager global Object, so we always have a structured accesss to the data!
        WebiAppDelegate *mainDelegate = (WebiAppDelegate *)[[UIApplication sharedApplication]delegate];
        self.webiDataManager = mainDelegate.webiDataManager;

By the way, this also works great for coredata, since through this global variable I always have access to all the main coredata.

Hope I could explain it clearly enough...


问:
How instance variable are related to class variable in python
```<code>class myclass(object):
    i=0
    def increase(self):
        self.i+=1
        print('increased value:', self.i)

if __name__=='__main__':
    m=myclass()
    m.increase()
</code>```

Here is a class variable and self.i is instance variable , on executing i get o/P as 1.

But if  comment class variable i I get an error

```<code>self.i+=1
AttributeError: 'myclass' object has no attribute 'i'
</code>```

what is the relation between class variable i and instance variable self.i here.

答:
You use the following statements to declare a constant inside your class. i is not supposed to be modified later.

```<code>class myclass(object):
     i=0
</code>```

You can access it with

```<code> value = myclass().i
</code>```

If you want a counter, you declare it in the constructor __init__, and increase it in a method

```<code>class myclass(object):
    def __init__(self):
        self.counter = 0
    def increase(self):
        self.counter += 1
</code>```

Body:
class myclass(object):
    i=0
    def increase(self):
        self.i+=1
        print('increased value:', self.i)

if __name__=='__main__':
    m=myclass()
    m.increase()

Here is a class variable and self.i is instance variable , on executing i get o/P as 1.

But if  comment class variable i I get an error

self.i+=1
AttributeError: 'myclass' object has no attribute 'i'

what is the relation between class variable i and instance variable self.i here.

Body:
You use the following statements to declare a constant inside your class. i is not supposed to be modified later.

class myclass(object):
     i=0

You can access it with

 value = myclass().i

If you want a counter, you declare it in the constructor __init__, and increase it in a method

class myclass(object):
    def __init__(self):
        self.counter = 0
    def increase(self):
        self.counter += 1


问:
back to back or gates with object comparisons. Confusion
To put it simply, i do not understand why they second if statement did not return false for the example (null, null)</p>

```<code>function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true
</code>```

答:
Comes from the definition of ===.

As referenced in the Mozilla docs this actually boils down to the definition from Ecma for ===, where it is stated for x === y:

...
  1. If Type(x) is different from Type(y), return false.

...
  3. If Type(x) is Null, return true.

...

If you call your function with (null, null), then:

Type(x) and Type(y) are the same

Type(x) is Null

∴ null === null ⇒ true

Body:
To put it simply, i do not understand why they second if statement did not return false for the example (null, null)

function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true


答:
Using an ECMA with a null value will always return true.

So - your function will never return false when you pass it a null value - beacuse it will always meet the first if condition , a === b, and return true;. The return statement stops its execution, and will never reach the 2nd if condition.

Title: back to back or gates with object comparisons. Confusion


问:
Unable to get iframe using Cheerio
Hi I am trying to get an iframe from wathfree.to.

Here is the code I am using for this purpose:

function getSecondBody(url2)
{
    url2 = 'http://www.watchfree.to/watch-366-Forrest-Gump-movie-online-free-putlocker.html';
    request(url2, function(err, resp, body)
{
 var $  = cheerio.load(body);

 var embedcode = $('.links_left_container');
  embedcodetext2 = embedcode.html();
 console.log(embedcodetext2);
 return embedcodetext2;
});
}```

But response returned doesn't contain the iframe that I need.

here is the response I am receiving:

while the actual page looks like this:

Only the iframe part is missing in my response.

答:
view-source:http://www.watchfree.to/watch-366-Forrest-Gump-movie-online-free-putlocker.html

Please take a look the source of the page. There is no iframe. It's generic content. So when you request it, it won't load to DOM.

You need to crawl probably this line if you want openload embed link:

```<code>var locations = ["http:\/\/streamin.to\/embed-k2msgp8yhhd8-580x326.html","http:\/\/streamin.to\/embed-cbp8zxw3yo3f-580x326.html","http:\/\/embed.nowvideo.sx\/embed.php?v=2729070a4365a","http:\/\/thevideo.me\/embed-wm815ejm5uvb-580x326.html","https:\/\/estream.to\/embed-6u49dntawgr0.html","http:\/\/thevideo.me\/embed-n14mh2bjj2nz-580x326.html","http:\/\/vidtodo.com\/embed-bmjw5u1e18js.html","http:\/\/vidtodo.com\/embed-z8614uxy1824.html","https:\/\/openload.co\/embed\/xTLPXjSGz7o\/","https:\/\/openload.co\/embed\/F8gJS5Y1o1o\/"];
</code>```

Title: Unable to get iframe using Cheerio

Body:
Hi I am trying to get an iframe from wathfree.to.

Here is the code I am using for this purpose:

function getSecondBody(url2)
{
    url2 = 'http://www.watchfree.to/watch-366-Forrest-Gump-movie-online-free-putlocker.html';
    request(url2, function(err, resp, body)
{
 var $  = cheerio.load(body);

 var embedcode = $('.links_left_container');
  embedcodetext2 = embedcode.html();
 console.log(embedcodetext2);
 return embedcodetext2;
});
}

But response returned doesn't contain the iframe that I need.

here is the response I am receiving:

while the actual page looks like this:

Only the iframe part is missing in my response.

Body:
view-source:http://www.watchfree.to/watch-366-Forrest-Gump-movie-online-free-putlocker.html

Please take a look the source of the page. There is no iframe. It's generic content. So when you request it, it won't load to DOM.

You need to crawl probably this line if you want openload embed link:

var locations = ["http:\/\/streamin.to\/embed-k2msgp8yhhd8-580x326.html","http:\/\/streamin.to\/embed-cbp8zxw3yo3f-580x326.html","http:\/\/embed.nowvideo.sx\/embed.php?v=2729070a4365a","http:\/\/thevideo.me\/embed-wm815ejm5uvb-580x326.html","https:\/\/estream.to\/embed-6u49dntawgr0.html","http:\/\/thevideo.me\/embed-n14mh2bjj2nz-580x326.html","http:\/\/vidtodo.com\/embed-bmjw5u1e18js.html","http:\/\/vidtodo.com\/embed-z8614uxy1824.html","https:\/\/openload.co\/embed\/xTLPXjSGz7o\/","https:\/\/openload.co\/embed\/F8gJS5Y1o1o\/"];


问:
Learning C# prior to learning ASP.NET MVC?
With only mild programming experience in the past, I was wondering about C# and ASP.NET MVC..

Do you guys think it's a better idea to learn C# before learning ASP.NET MVC?  I've already delved a little into both of these already, but I still need some help deciding.

I think I would be a much stronger MVC user if I had more knowledge of the C# language itself.

What do you guys think?

Thanks!

答: Learn C# first.  C# will be around for years to come; MVC may or may not be (Microsoft has a long history of handling web site code with flavor-of-the-month paradigms that don't age particularly well).</p>


问:
FileUpload.FileBytes get OutOfMemoryException
I use FileUpload component. I add file approximately 120mb. But when file size increase, FileBytes get error OutOfMemoryException

FileBytes returns byte[].

My code:

```<code>   byte[] byt = new byte[0];
    byt = FileUpload1.FileBytes;
</code>```

I need to get file and convert byte array or I can use js.
I must get file. But I take file path. Return value is c:/fakepath.... is wrong.

Any solutions?

答:
in your web.config, you have two parameters to deal with this:

```<code><system.web>
    <httpRuntime maxRequestLength="X" executionTimeout="Y"/>
</system.web>
</code>```

(X in kilobytes, Y in seconds)

and

```<code><system.webServer>
     <security>
          <requestFiltering>
             <requestLimits maxAllowedContentLength="Z" />
          </requestFiltering>
     </security>
</system.webServer>
</code>```

(Z in bytes)

Body:
I use FileUpload component. I add file approximately 120mb. But when file size increase, FileBytes get error OutOfMemoryException

FileBytes returns byte[].

My code:

   byte[] byt = new byte[0];
    byt = FileUpload1.FileBytes;

I need to get file and convert byte array or I can use js.
I must get file. But I take file path. Return value is c:/fakepath.... is wrong.

Any solutions?

Body:
in your web.config, you have two parameters to deal with this:

<system.web>
    <httpRuntime maxRequestLength="X" executionTimeout="Y"/>
</system.web>

(X in kilobytes, Y in seconds)

and

<system.webServer>
     <security>
          <requestFiltering>
             <requestLimits maxAllowedContentLength="Z" />
          </requestFiltering>
     </security>
</system.webServer>

(Z in bytes)


问:
Android outgoing Call Ringing Stage
I have trying to get ringing stage of the outgoing call. I have already try BroadcastReceiver with NEW_OUTGOING_CALL and PHONE_STATE action. But I am not getting the Ringing Stage of the reciever. I understand now that receiver does not tell you ringing stage. I have seen this same query:- Android - How to detect outgoing call is answered or received?
I have also apply this solution but still I am not getting any solution. I have declare the Service with action NotificationListenerService I need to do extra or something else...

I think to get the ringing stage of the outgoing call or to get pick up the call on other end this is possible..

Please help!

答:
In the manifest file you should have the following permissions to check the outgoing call:

```<code><uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
</code>```

and the code of broadcast receiver:

```<code>public class PhoneStateChecking extends BroadcastReceiver {
    boolean hasCallStateRinging = false;

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.d("Intent", intent.toString());
        if(intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
            Log.e("CAll-STATUS", "out going Call");
        }

        //        Checking for the call status
        try {
            // TELEPHONY MANAGER class object to register one listner
            TelephonyManager tmgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            //Create Listner
            MyPhoneStateListener PhoneListener = new MyPhoneStateListener();
            // Register listener for LISTEN_CALL_STATE
            tmgr.listen(PhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class MyPhoneStateListener extends PhoneStateListener {
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    if (hasCallStateRinging)
                        return;
                    else {
                        hasCallStateRinging = true;
                        Log.e("CAll-STATUS", "CALL_STATE_RINGING");
                    }
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    if(!hasCallStateRinging){
                        hasCallStateRinging = true;
                        Log.e("CAll-STATUS", "CALL_STATE_OFFHOOK");
                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    if (hasCallStateRinging) {
                        hasCallStateRinging = false;
                        Log.e("CAll-STATUS", "CALL_STATE_IDLE");
                    }
                    break;
            }
        }
    }

}
</code>```

Title: Android outgoing Call Ringing Stage

Body:
In the manifest file you should have the following permissions to check the outgoing call:

<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>

and the code of broadcast receiver:

public class PhoneStateChecking extends BroadcastReceiver {
    boolean hasCallStateRinging = false;

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.d("Intent", intent.toString());
        if(intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
            Log.e("CAll-STATUS", "out going Call");
        }

        //        Checking for the call status
        try {
            // TELEPHONY MANAGER class object to register one listner
            TelephonyManager tmgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            //Create Listner
            MyPhoneStateListener PhoneListener = new MyPhoneStateListener();
            // Register listener for LISTEN_CALL_STATE
            tmgr.listen(PhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class MyPhoneStateListener extends PhoneStateListener {
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    if (hasCallStateRinging)
                        return;
                    else {
                        hasCallStateRinging = true;
                        Log.e("CAll-STATUS", "CALL_STATE_RINGING");
                    }
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    if(!hasCallStateRinging){
                        hasCallStateRinging = true;
                        Log.e("CAll-STATUS", "CALL_STATE_OFFHOOK");
                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    if (hasCallStateRinging) {
                        hasCallStateRinging = false;
                        Log.e("CAll-STATUS", "CALL_STATE_IDLE");
                    }
                    break;
            }
        }
    }

}


问:
Android: Get the listview item from button clicked in custom listview
I have a custom ListView with two button and I when I click either button on any row I want to get the text label on the Listview and for now just popup a toast with it. So far nothing has worked I keep getting the last item in my array.

Here is a screen shot to give you a better idea of what i mean

Here is my Adapter subclass for my custom ListView

```<code>static final String[] Names =
           new String[] { "John", "Mike", "Maria", "Miguel"};

class MyArrayAdapter extends ArrayAdapter<String> {
    private final Context context;

    int which;

    public MyArrayAdapter(Context context, String[] pValues) {
        super(context, R.layout.main, pValues);
        this.context = context;
        values = pValues;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        rowView = inflater.inflate(R.layout.main, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.label);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
        Button call = (Button) rowView.findViewById(R.id.button1);
        Button chat = (Button) rowView.findViewById(R.id.button2);
        textView.setText(values[position]);

        // Change icon based on name
        s = values[position];
        which = position;
        call.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String name = values[which];
                Toast.makeText(CustomListView.this, name, Toast.LENGTH_SHORT).show();
            }
        });

        return rowView;
    }
}
</code>```

Edit:

```<code>String name = textView.getText().toString();
RelativeLayout ll = (RelativeLayout)v.getParent();
textView = (TextView)ll.findViewById(R.id.label);
Toast.makeText(CustomListView.this, name,
Toast.LENGTH_SHORT).show();
</code>```

答:
simply use getItem() and pass the  position
Ex:getItem(position).getID()
here getID() method is getter method

Body:
I have a custom ListView with two button and I when I click either button on any row I want to get the text label on the Listview and for now just popup a toast with it. So far nothing has worked I keep getting the last item in my array.

Here is a screen shot to give you a better idea of what i mean

Here is my Adapter subclass for my custom ListView

static final String[] Names =
           new String[] { "John", "Mike", "Maria", "Miguel"};

class MyArrayAdapter extends ArrayAdapter<String> {
    private final Context context;

    int which;

    public MyArrayAdapter(Context context, String[] pValues) {
        super(context, R.layout.main, pValues);
        this.context = context;
        values = pValues;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        rowView = inflater.inflate(R.layout.main, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.label);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
        Button call = (Button) rowView.findViewById(R.id.button1);
        Button chat = (Button) rowView.findViewById(R.id.button2);
        textView.setText(values[position]);

        // Change icon based on name
        s = values[position];
        which = position;
        call.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String name = values[which];
                Toast.makeText(CustomListView.this, name, Toast.LENGTH_SHORT).show();
            }
        });

        return rowView;
    }
}

Edit:

String name = textView.getText().toString();
RelativeLayout ll = (RelativeLayout)v.getParent();
textView = (TextView)ll.findViewById(R.id.label);
Toast.makeText(CustomListView.this, name,
Toast.LENGTH_SHORT).show();


问:
How to convert Observable<any> to array[]
I have following method in typescript, I need to bind to angular grid

CountryService

```<code>GetCountries()  {
  return this.http.get(`http://services.groupkt.com/country/get/all`)
    .map((res:Response) => <CountryData[]>res.json().RestResponse["result"]);
}
</code>```

GridComponent

```<code>  template: `
        <ag-grid-ng2 style="width: 100%" #agGrid class="ag-material"
                    rowHeight="50"
                    [gridOptions]="myGridOptions"
                     >
            </ag-grid-ng2>
        `,

  this.myGridOptions.rowData= this.CountryService.GetCountries();
</code>```

CountryData

```<code>export class CountryData{
  name: string;
  alpha2_code: string;
  alpha3_code: string;
}
</code>```

But GetCoutries will return Observable of any, unable to bind to rowData?

How to convert Observable to CountryData[] in typescript ?

you find JSON data here: http://services.groupkt.com/country/get/all

答:
You will need to subscribe to your observables:

```<code>this.CountryService.GetCountries()
    .subscribe(countries => {
        this.myGridOptions.rowData = countries as CountryData[]
    })
</code>```

And, in your html, wherever needed, you can pass the async pipe to it.

Body:
I have following method in typescript, I need to bind to angular grid

CountryService

GetCountries()  {
  return this.http.get(`http://services.groupkt.com/country/get/all`)
    .map((res:Response) => <CountryData[]>res.json().RestResponse["result"]);
}

GridComponent

  template: `
        <ag-grid-ng2 style="width: 100%" #agGrid class="ag-material"
                    rowHeight="50"
                    [gridOptions]="myGridOptions"
                     >
            </ag-grid-ng2>
        `,

  this.myGridOptions.rowData= this.CountryService.GetCountries();

CountryData

export class CountryData{
  name: string;
  alpha2_code: string;
  alpha3_code: string;
}

But GetCoutries will return Observable of any, unable to bind to rowData?

How to convert Observable to CountryData[] in typescript ?

you find JSON data here: http://services.groupkt.com/country/get/all

Body:
You will need to subscribe to your observables:

this.CountryService.GetCountries()
    .subscribe(countries => {
        this.myGridOptions.rowData = countries as CountryData[]
    })

And, in your html, wherever needed, you can pass the async pipe to it.