问:
Caffe: Converting CSV file to HDF5
I have learned a little about Caffe framework (which is used define and train deep learning models)

As my first program, I wanted to write a program for training and testing a "Face Emotion Recognition" task using fer2013 dataset

The dataset I have downloaded is in "CSV" format. As I know, for working with Caffe, dataset format has to be in either "lmdb" or "hdf5".

So it seems that the first thing I have to do is to convert my dataset into hdf5 or lmbd formats.

Here is a simple code I tried at first:

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

csvFile = pd.HDFStore('PrivateTest.csv')
PrivateTestHDF5 = csvFile.to_hdf(csvFile)

print len(PrivateTestHDF5)
</code>```

But it doesn't work, and I get this error:

" Unable to open/create file 'PrivateTest.csv "

I have searched alot, I found this link but I still can not understand how does it read from a CSV file.

Also I do not have installed Matlab.

I would be happy if anyone can help me on this. Also if any advice about writing caffe models for datasets that are on Kaggle website or any other dataset ( Those who are not on caffe website )

答:
A bit late, but wanted to point out that if the csv file is too big to load into memory you can use pandas "chunksize" to split the file and load the chunks one by one to HDF5:

```<code>import pandas as pd

csvfile = 'yourCSVfile.csv'
hdf5File = 'yourh5File.h5'

tp = pd.read_csv('CSVfile', chunksize=100000)

for chunk in tp:
   chunk.to_hdf(hdf5File,  key = 'data', mode ='a', format='table', append = True)
</code>```

Note that the append = True is for Table format.

Title: Caffe: Converting CSV file to HDF5

Body:
I have learned a little about Caffe framework (which is used define and train deep learning models)

As my first program, I wanted to write a program for training and testing a "Face Emotion Recognition" task using fer2013 dataset

The dataset I have downloaded is in "CSV" format. As I know, for working with Caffe, dataset format has to be in either "lmdb" or "hdf5".

So it seems that the first thing I have to do is to convert my dataset into hdf5 or lmbd formats.

Here is a simple code I tried at first:

import pandas as pd
import numpy as np
import csv

csvFile = pd.HDFStore('PrivateTest.csv')
PrivateTestHDF5 = csvFile.to_hdf(csvFile)

print len(PrivateTestHDF5)

But it doesn't work, and I get this error:

" Unable to open/create file 'PrivateTest.csv "

I have searched alot, I found this link but I still can not understand how does it read from a CSV file.

Also I do not have installed Matlab.

I would be happy if anyone can help me on this. Also if any advice about writing caffe models for datasets that are on Kaggle website or any other dataset ( Those who are not on caffe website )

Body:
A bit late, but wanted to point out that if the csv file is too big to load into memory you can use pandas "chunksize" to split the file and load the chunks one by one to HDF5:

import pandas as pd

csvfile = 'yourCSVfile.csv'
hdf5File = 'yourh5File.h5'

tp = pd.read_csv('CSVfile', chunksize=100000)

for chunk in tp:
   chunk.to_hdf(hdf5File,  key = 'data', mode ='a', format='table', append = True)

Note that the append = True is for Table format.


来源: stackexchange

问:
How to debug this Excel trouble?
```<code>Sub Macro3()
'
' Macro3 Macro
'

'
    Dim MyFile As String
MyFile = Application.GetOpenFilename(MultiSelect:=True)
Workbooks.Open (MyFile)
    Range("A2").Select
    Range(Selection, Selection.End(xlDown)).Select
    Application.DisplayAlerts = False
    Selection.Copy
    ActiveWorkbook.Close
    Application.DisplayAlerts = True
    Windows("Jane macro test.xlsx").Activate
    Sheets("Sheet2").Select
    Range("B2").Select
lMaxRows = Cells(Rows.Count, "B").End(xlUp).Row
Range("B" & lMaxRows + 1).Select
 ActiveSheet.Paste

End Sub
</code>```

<p>It keeps saying my code have runtime error 13 and mismatch. Anyone knows how to fix? I am able to use it if I change my MultiSelect to False, but I need it to run on multiple folders. How do I go about doing it? </p>

答:
Try it like this:

```<code>Option Explicit

Sub Macro3()

    Dim MyFile      As Variant
    Dim counter     As Long
    Dim wb          As Workbook

    MyFile = Application.GetOpenFilename(MultiSelect:=True)

    For counter = LBound(MyFile) To UBound(MyFile)
        Set wb = Workbooks.Open(MyFile(counter))
        MsgBox wb.Name

'    Range("A2").Select
'    Range(Selection, Selection.End(xlDown)).Select
'    Application.DisplayAlerts = False
'    Selection.Copy
'    ActiveWorkbook.Close
'    Application.DisplayAlerts = True
'
'    Windows("Jane macro test.xlsx").Activate
'    Sheets("Sheet2").Select
'    Range("B2").Select
'    lMaxRows = Cells(Rows.Count, "B").End(xlUp).Row
'    Range("B" & lMaxRows + 1).Select
'    ActiveSheet.Paste

    Next counter

End Sub
</code>```

It iterates through every workbook and then it displays its name in a MsgBox. Thus, you can do something with it in the loop, by accessing the wb object.
In general, make sure that you declare Option Explicit on the top so your compiler will check that every variable exists and avoid errors at runtime.

ContentLicense: CC BY-SA 3.0

Title: How to debug this Excel trouble?

Body:
Sub Macro3()
'
' Macro3 Macro
'

'
    Dim MyFile As String
MyFile = Application.GetOpenFilename(MultiSelect:=True)
Workbooks.Open (MyFile)
    Range("A2").Select
    Range(Selection, Selection.End(xlDown)).Select
    Application.DisplayAlerts = False
    Selection.Copy
    ActiveWorkbook.Close
    Application.DisplayAlerts = True
    Windows("Jane macro test.xlsx").Activate
    Sheets("Sheet2").Select
    Range("B2").Select
lMaxRows = Cells(Rows.Count, "B").End(xlUp).Row
Range("B" & lMaxRows + 1).Select
 ActiveSheet.Paste

End Sub

It keeps saying my code have runtime error 13 and mismatch. Anyone knows how to fix? I am able to use it if I change my MultiSelect to False, but I need it to run on multiple folders. How do I go about doing it?

Body:
Try it like this:

Option Explicit

Sub Macro3()

    Dim MyFile      As Variant
    Dim counter     As Long
    Dim wb          As Workbook

    MyFile = Application.GetOpenFilename(MultiSelect:=True)

    For counter = LBound(MyFile) To UBound(MyFile)
        Set wb = Workbooks.Open(MyFile(counter))
        MsgBox wb.Name

'    Range("A2").Select
'    Range(Selection, Selection.End(xlDown)).Select
'    Application.DisplayAlerts = False
'    Selection.Copy
'    ActiveWorkbook.Close
'    Application.DisplayAlerts = True
'
'    Windows("Jane macro test.xlsx").Activate
'    Sheets("Sheet2").Select
'    Range("B2").Select
'    lMaxRows = Cells(Rows.Count, "B").End(xlUp).Row
'    Range("B" & lMaxRows + 1).Select
'    ActiveSheet.Paste

    Next counter

End Sub

It iterates through every workbook and then it displays its name in a MsgBox. Thus, you can do something with it in the loop, by accessing the wb object.
In general, make sure that you declare Option Explicit on the top so your compiler will check that every variable exists and avoid errors at runtime.


问:
ElasticSearch using Angular JS
How can I implement Elastic Search Using Angular JS. For that I have created a sample page on angularjs in which it have 3 fields like Name,Address,Phone with submit button. Can any one suggest an approach to implementing elastic search using angular JS ? Thanks for all</p>

答:
u can try read this http://www.elasticui.com
but just for angular 1</p>

Title: ElasticSearch using Angular JS


问:
Split Values and Units using Jquery, Javascript
I have the values be like 10 #/mm3, and i want to split those as 10 and #/mm3 by value and unit respectively using jquery or Javascript, i tried to split it in java but i need it in client side.</p>

```<code>10|mm
</code>```

答:
try it now

var str = "51.400000000000006 % S*";
var val = str.search(/[%|X|-|+]/);
console.log(str.substr(0, val));
console.log(str.substr(val));

var str1 = "7.24X10^6";
var val = str1.search(/[%|X|-|+]/);
console.log(str1.substr(0, val));
console.log(str1.substr(val));```

Body:
I have the values be like 10 #/mm3, and i want to split those as 10 and #/mm3 by value and unit respectively using jquery or Javascript, i tried to split it in java but i need it in client side.

10|mm


问:
validate json payload in spring boot rest to throw error if unknown property or empty property has been sent as part of json payload
JSON Request:

```<code>{
    "notificationType" : "ISSUER_OTP1ee2asasa",
    "content" : "hi fff this is fff template content for SBI email good and mobile dfdfdfd and remaining balance is 333 and your name is hahaha.",
    "medium" : "EMAIL",
    "asa":"ddddd",
    "":""
}
</code>```

POJO:

```<code>package com.innoviti.notification.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@Document(collection = "NotificationTemplate")
@JsonIgnoreProperties(ignoreUnknown=false)

public class NotificationTemplate {
  @JsonCreator
  public NotificationTemplate(@JsonProperty(value="notificationType",required=true)String notificationType,
      @JsonProperty(value="content",required=true)String content, @JsonProperty(value="medium",required=true)String medium) {
    super();
    this.notificationType = notificationType;
    this.content = content;
    this.medium = medium;
  }

  @Override
  public String toString() {
    return "NotificationTemplate [id=" + id + ", templateId=" + templateId + ", notificationType="
        + notificationType + ", content=" + content + ", medium=" + medium + "]";
  }

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  @Id
  private String id;
  private String templateId;

  public String getTemplateId() {
    return templateId;
  }

  public void setTemplateId(String templateId) {
    this.templateId = templateId;
  }

  private String notificationType;
  private String content;
  private String medium;

  public String getMedium() {
    return medium;
  }

  public void setMedium(String medium) {
    this.medium = medium;
  }

  public String getNotificationType() {
    return notificationType;
  }

  public void setNotificationType(String notificationType) {
    this.notificationType = notificationType;
  }

  public String getContent() {
    return content;
  }

  public void setContent(String content) {
    this.content = content;
  }

}
</code>```

Controller where payload is posted.

```<code> @PostMapping(value = "/config", consumes = MediaType.APPLICATION_JSON_VALUE,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<NotificationTemplate> configureTemplate(
     @Valid @RequestBody NotificationTemplate notificationTemplate) {
    NotificationTemplate notificationTemplatePersisted = null;

    logger.info(
        "Printing payload of template on server side" + ">>>" + notificationTemplate.toString());
    try {
      validatePayLoad(notificationTemplate);
      notificationTemplatePersisted =
          notificationTemplateService.createNotificationTemplate(notificationTemplate);
    } catch (Exception de) {
      logger.info(String.format("Error in saving template", de.getMessage()));
      throw new RequestNotCompletedException(de.getLocalizedMessage());
    }
    return new ResponseEntity<NotificationTemplate>(notificationTemplatePersisted,
        HttpStatus.CREATED);
  }
</code>```

Question:How do I validate that an uknown property has been sent as part of payload.In Existing implementation,@RequestBody maps the json without any issue.I want to throw error or validate payload if incoming json is not confirming exactly to POJO.For e.g in payload example i gave,I want to be able to throw error saying that asa is not recognized property

答:
The Jackson property that controls this behaviour is FAIL_ON_UNKNOWN_PROPERTIES. This needs to be true in your case, to get the behaviour you describe.

It seems that since spring boot 1.2 this is set to false by default.

To set it to true add this line to your application.properties file:

```<code>spring.jackson.deserialization.fail-on-unknown-properties=true
</code>```

And then you will get a JsonMappingException when there are extraneous properties in a JSON payload

Body:
JSON Request:

{
    "notificationType" : "ISSUER_OTP1ee2asasa",
    "content" : "hi fff this is fff template content for SBI email good and mobile dfdfdfd and remaining balance is 333 and your name is hahaha.",
    "medium" : "EMAIL",
    "asa":"ddddd",
    "":""
}

POJO:

package com.innoviti.notification.model;

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;

@Document(collection = "NotificationTemplate")
@JsonIgnoreProperties(ignoreUnknown=false)

public class NotificationTemplate {
  @JsonCreator
  public NotificationTemplate(@JsonProperty(value="notificationType",required=true)String notificationType,
      @JsonProperty(value="content",required=true)String content, @JsonProperty(value="medium",required=true)String medium) {
    super();
    this.notificationType = notificationType;
    this.content = content;
    this.medium = medium;
  }

  @Override
  public String toString() {
    return "NotificationTemplate [id=" + id + ", templateId=" + templateId + ", notificationType="
        + notificationType + ", content=" + content + ", medium=" + medium + "]";
  }

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  @Id
  private String id;
  private String templateId;

  public String getTemplateId() {
    return templateId;
  }

  public void setTemplateId(String templateId) {
    this.templateId = templateId;
  }

  private String notificationType;
  private String content;
  private String medium;

  public String getMedium() {
    return medium;
  }

  public void setMedium(String medium) {
    this.medium = medium;
  }

  public String getNotificationType() {
    return notificationType;
  }

  public void setNotificationType(String notificationType) {
    this.notificationType = notificationType;
  }

  public String getContent() {
    return content;
  }

  public void setContent(String content) {
    this.content = content;
  }

}

Controller where payload is posted.

 @PostMapping(value = "/config", consumes = MediaType.APPLICATION_JSON_VALUE,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity<NotificationTemplate> configureTemplate(
     @Valid @RequestBody NotificationTemplate notificationTemplate) {
    NotificationTemplate notificationTemplatePersisted = null;

    logger.info(
        "Printing payload of template on server side" + ">>>" + notificationTemplate.toString());
    try {
      validatePayLoad(notificationTemplate);
      notificationTemplatePersisted =
          notificationTemplateService.createNotificationTemplate(notificationTemplate);
    } catch (Exception de) {
      logger.info(String.format("Error in saving template", de.getMessage()));
      throw new RequestNotCompletedException(de.getLocalizedMessage());
    }
    return new ResponseEntity<NotificationTemplate>(notificationTemplatePersisted,
        HttpStatus.CREATED);
  }

Question:How do I validate that an uknown property has been sent as part of payload.In Existing implementation,@RequestBody maps the json without any issue.I want to throw error or validate payload if incoming json is not confirming exactly to POJO.For e.g in payload example i gave,I want to be able to throw error saying that asa is not recognized property

Body:
The Jackson property that controls this behaviour is FAIL_ON_UNKNOWN_PROPERTIES. This needs to be true in your case, to get the behaviour you describe.

It seems that since spring boot 1.2 this is set to false by default.

To set it to true add this line to your application.properties file:

spring.jackson.deserialization.fail-on-unknown-properties=true

And then you will get a JsonMappingException when there are extraneous properties in a JSON payload


问:
How can I nullify css property?
Basically I have two external css in my page.

The first Main.css contains all style rules but I don't have access to it, and hence I cannot modify it. I have access to a second file Template.css , so I need to override the Main.css's values in template.css.

This is easy for which I have to change the value, but how do I remove a property entirely?

Like say a class .c1 has height: 40px;, how do I get rid of this height property?

答:
I had an issue that even when I did overwrite "height" to "unset" or "initial", it behaved differently from when I removed the previous setting.

It turned out I needed to remove the min-height property too!

```<code>height: unset;
min-height: none
</code>```

Edit: I tested on IE 7 and it doesn't recognize "unset", so "auto" works better".

Title: How can I nullify css property?

Body:
I had an issue that even when I did overwrite "height" to "unset" or "initial", it behaved differently from when I removed the previous setting.

It turned out I needed to remove the min-height property too!

height: unset;
min-height: none

Edit: I tested on IE 7 and it doesn't recognize "unset", so "auto" works better".


问:
Break a select statement inside a while loop and create multiple tables in a while loop
Is there a way force a statement to run a select only once inside a while loop,
For example:

```<code>WHILE(@NUMBERCOUNTER <@TOTALNUMBER)
BEGIN
Declare @Table2(
Id nvarchar(10)
);
Insert into @Table2
SELECT * FROM MainTable where Id in (select Id from Table1)

Insert into @Table2
SELECT * FROM MainTable where Id in (select Id from Table2)
END
</code>```

I only want to run this line

```<code>SELECT * FROM MainTable where Id in (select Id from TABLE1)
</code>```

once, then the other select to run continuous until it meets the While criteria.

Also, is there a way to separate data for each select in multiples table. I do not want the result from 2nd select get mixed with the first one.

The problem right now is that I cannot move the select statement outside the while loop, because it cannot select @Table2. And I cannot create @Table2 outside the while loop, the data will be mixed.

Note: TABLE 1 is created outside the loop

Thanks in advance!

答:
First question:
You can add flag e.g.:

```<code>DECLARE @flag bit = 0
WHILE(@NUMBERCOUNTER <@TOTALNUMBER)
BEGIN
Declare @Table2(
Id nvarchar(10)
);
IF @flag = 0
BEGIN
Insert into @Table2
SELECT * FROM MainTable where Id in (select Id from Table1)
SET @flag = 1;
END

Insert into @Table2
SELECT * FROM MainTable where Id in (select Id from Table2)

SET @NUMBERCOUNTER = @NUMBERCOUNTER + 1; --You had infinite loop
END
</code>```

Also, is there a way to separate data for each select in multiples table. I do not want the result from 2nd select get mixed with the first one.

Add flag to your table @Table2 from which table row comes and include it to your select statements.

Body:
Is there a way force a statement to run a select only once inside a while loop,
For example:

WHILE(@NUMBERCOUNTER <@TOTALNUMBER)
BEGIN
Declare @Table2(
Id nvarchar(10)
);
Insert into @Table2
SELECT * FROM MainTable where Id in (select Id from Table1)

Insert into @Table2
SELECT * FROM MainTable where Id in (select Id from Table2)
END

I only want to run this line

SELECT * FROM MainTable where Id in (select Id from TABLE1)

once, then the other select to run continuous until it meets the While criteria.

Also, is there a way to separate data for each select in multiples table. I do not want the result from 2nd select get mixed with the first one.

The problem right now is that I cannot move the select statement outside the while loop, because it cannot select @Table2. And I cannot create @Table2 outside the while loop, the data will be mixed.

Note: TABLE 1 is created outside the loop

Thanks in advance!

Body:
First question:
You can add flag e.g.:

DECLARE @flag bit = 0
WHILE(@NUMBERCOUNTER <@TOTALNUMBER)
BEGIN
Declare @Table2(
Id nvarchar(10)
);
IF @flag = 0
BEGIN
Insert into @Table2
SELECT * FROM MainTable where Id in (select Id from Table1)
SET @flag = 1;
END

Insert into @Table2
SELECT * FROM MainTable where Id in (select Id from Table2)

SET @NUMBERCOUNTER = @NUMBERCOUNTER + 1; --You had infinite loop
END

Also, is there a way to separate data for each select in multiples table. I do not want the result from 2nd select get mixed with the first one.

Add flag to your table @Table2 from which table row comes and include it to your select statements.


问:
How to hide sections in a table view using a radio button?
Here i am having four sections in a table view but in  the first section all the cells are having radio buttons. Whenever it is active, I need to show remaining three sections, if not I need to hide the remaining last three sections can anyone help me how to implement this ?

The image is as shown below ?

```<code> @IBAction func selectRadioButton(_ sender: KGRadioButton) {
        let chekIndex = self.checkIsRadioSelect.index(of: sender.tag)
        if sender.isSelected {

        } else{
            if(chekIndex == nil){
                self.checkIsRadioSelect.removeAll(keepingCapacity: false)
                self.checkIsRadioSelect.append(sender.tag)
                self.ProductTableView.reloadData()
            }
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int{
     return 4
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if (section == 0){
            return "PAYMENT INFORMATION"
        }
        else if (section == 1){
            return "ORDER REVIEW"
        }
        else if (section == 2){
            return "PRODUCT"
        }
        else{
            return ""
        }
    }
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
        let header = view as! UITableViewHeaderFooterView
        header.textLabel?.textColor = UIColor.gray
        header.textLabel?.textAlignment = NSTextAlignment.center
        header.textLabel?.font = UIFont(name: "Futura", size: 17)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if (section == 0){
            return paymentmethodsArray.count
        }
        else if (section == 2) {
            return productsDetails.count
        }
        else{
            return 1
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        if (indexPath.section == 0){
            return 44
        }
        else if (indexPath.section == 1){
            return 410
        }
        else if (indexPath.section == 2){
            return 120
        }
        else{
            return 230
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (indexPath.section == 0){
            let paymentcell = tableView.dequeueReusableCell(withIdentifier: "paymentcell",for:indexPath) as! paymentTableViewCell
            myActivityIndicator.stopAnimating()
            let arr = self.paymentmethodsArray[indexPath.row]
            paymentcell.paymentNameLabel.text = arr["name"]as? String
            paymentcell.radioButton.tag = indexPath.row
            let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row)
            if(checkIndex != nil){
                paymentcell.radioButton.isSelected = true
            }else{
                paymentcell.radioButton.isSelected = false
            }
            return paymentcell
        }
        else if (indexPath.section == 1){
            let shippingAddresscell = tableView.dequeueReusableCell(withIdentifier: "shippingaddresscell",for:indexPath) as! ShippingAddressTableViewCell
            shippingAddresscell.nameLabel.text = name
            shippingAddresscell.addressLabel.text = billingaddress
            shippingAddresscell.mobileNumberLabel.text = String(describing: phoneNumber)
            shippingAddresscell.shippingNameLabel.text = name
            shippingAddresscell.shippingAddressLabel.text = billingaddress
            shippingAddresscell.shippingMobileNumberLabel.text = String(describing: phoneNumber)
            shippingAddresscell.shippingMethodNameLabel.text = shippingMethod
            shippingAddresscell.paymentMethodNameLabel.text = paymentMethod
            return shippingAddresscell
        }
        else if (indexPath.section == 2){
            let productNamecell = tableView.dequeueReusableCell(withIdentifier: "productNamecell",for:indexPath) as! ProductNameTableViewCell
            let arr = productsDetails[indexPath.row]
            let array = arr["product name"] as! String
            productNamecell.productNameLabel.text = array
            productNamecell.priceLabel.text = arr["Price"] as! String
            productNamecell.QuantityLabel.text = String(describing: arr["Quantity"] as! Int)
            productNamecell.subTotalLabel.text = arr["SubTotal"] as! String
            return productNamecell
        }
        else{
            let ordercell = tableView.dequeueReusableCell(withIdentifier: "ordercell",for:indexPath) as! orderTableViewCell
            ordercell.subTotalLabel.text = subTotal
            ordercell.shippingLabel.text = shippingHandling
            ordercell.grandTotalLabel.text = total
            return ordercell
        }
    }
</code>```

答:
Keep the Bool variable to identify the radio button is selected or not based on that return the count of number of section.

```<code> var isRadioButtonSelected = false

 @IBAction func selectRadioButton(_ sender: KGRadioButton) {

  //Your remaining logic here.

  //Based on the selection action you have to update the flag value.
  if sender.isSelected {
     isRadioButtonSelected =  true
  } else {
     isRadioButtonSelected =  false
  }

    // Reload table
    self.ProductTableView.reloadData()
 }

 func numberOfSections(in tableView: UITableView) -> Int{
    if  isRadioButtonSelected ==  true {
      return 4
    } else {
      return 1
    }
  }
</code>```

Body:
Here i am having four sections in a table view but in  the first section all the cells are having radio buttons. Whenever it is active, I need to show remaining three sections, if not I need to hide the remaining last three sections can anyone help me how to implement this ?

The image is as shown below ?

 @IBAction func selectRadioButton(_ sender: KGRadioButton) {
        let chekIndex = self.checkIsRadioSelect.index(of: sender.tag)
        if sender.isSelected {

        } else{
            if(chekIndex == nil){
                self.checkIsRadioSelect.removeAll(keepingCapacity: false)
                self.checkIsRadioSelect.append(sender.tag)
                self.ProductTableView.reloadData()
            }
        }
    }

    func numberOfSections(in tableView: UITableView) -> Int{
     return 4
    }
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if (section == 0){
            return "PAYMENT INFORMATION"
        }
        else if (section == 1){
            return "ORDER REVIEW"
        }
        else if (section == 2){
            return "PRODUCT"
        }
        else{
            return ""
        }
    }
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){
        let header = view as! UITableViewHeaderFooterView
        header.textLabel?.textColor = UIColor.gray
        header.textLabel?.textAlignment = NSTextAlignment.center
        header.textLabel?.font = UIFont(name: "Futura", size: 17)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if (section == 0){
            return paymentmethodsArray.count
        }
        else if (section == 2) {
            return productsDetails.count
        }
        else{
            return 1
        }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        if (indexPath.section == 0){
            return 44
        }
        else if (indexPath.section == 1){
            return 410
        }
        else if (indexPath.section == 2){
            return 120
        }
        else{
            return 230
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (indexPath.section == 0){
            let paymentcell = tableView.dequeueReusableCell(withIdentifier: "paymentcell",for:indexPath) as! paymentTableViewCell
            myActivityIndicator.stopAnimating()
            let arr = self.paymentmethodsArray[indexPath.row]
            paymentcell.paymentNameLabel.text = arr["name"]as? String
            paymentcell.radioButton.tag = indexPath.row
            let checkIndex = self.checkIsRadioSelect.index(of: indexPath.row)
            if(checkIndex != nil){
                paymentcell.radioButton.isSelected = true
            }else{
                paymentcell.radioButton.isSelected = false
            }
            return paymentcell
        }
        else if (indexPath.section == 1){
            let shippingAddresscell = tableView.dequeueReusableCell(withIdentifier: "shippingaddresscell",for:indexPath) as! ShippingAddressTableViewCell
            shippingAddresscell.nameLabel.text = name
            shippingAddresscell.addressLabel.text = billingaddress
            shippingAddresscell.mobileNumberLabel.text = String(describing: phoneNumber)
            shippingAddresscell.shippingNameLabel.text = name
            shippingAddresscell.shippingAddressLabel.text = billingaddress
            shippingAddresscell.shippingMobileNumberLabel.text = String(describing: phoneNumber)
            shippingAddresscell.shippingMethodNameLabel.text = shippingMethod
            shippingAddresscell.paymentMethodNameLabel.text = paymentMethod
            return shippingAddresscell
        }
        else if (indexPath.section == 2){
            let productNamecell = tableView.dequeueReusableCell(withIdentifier: "productNamecell",for:indexPath) as! ProductNameTableViewCell
            let arr = productsDetails[indexPath.row]
            let array = arr["product name"] as! String
            productNamecell.productNameLabel.text = array
            productNamecell.priceLabel.text = arr["Price"] as! String
            productNamecell.QuantityLabel.text = String(describing: arr["Quantity"] as! Int)
            productNamecell.subTotalLabel.text = arr["SubTotal"] as! String
            return productNamecell
        }
        else{
            let ordercell = tableView.dequeueReusableCell(withIdentifier: "ordercell",for:indexPath) as! orderTableViewCell
            ordercell.subTotalLabel.text = subTotal
            ordercell.shippingLabel.text = shippingHandling
            ordercell.grandTotalLabel.text = total
            return ordercell
        }
    }

Body:
Keep the Bool variable to identify the radio button is selected or not based on that return the count of number of section.

 var isRadioButtonSelected = false

 @IBAction func selectRadioButton(_ sender: KGRadioButton) {

  //Your remaining logic here.

  //Based on the selection action you have to update the flag value.
  if sender.isSelected {
     isRadioButtonSelected =  true
  } else {
     isRadioButtonSelected =  false
  }

    // Reload table
    self.ProductTableView.reloadData()
 }

 func numberOfSections(in tableView: UITableView) -> Int{
    if  isRadioButtonSelected ==  true {
      return 4
    } else {
      return 1
    }
  }


问:
How to Download and install Coldfusion in Local Linux?
Am newbie to Coldfusion,Am tried to download and install coldfusion in my local using below link,

Download link

Once am filled form Got error like below image.

How to download and install coldfusion in linux?Is it possible to download and install in localhost?

答: @geetha-janarthanan , Error 403 might be coming from the broswer. Please try an alternate browser. I just tried the download link in IE/Chrome (latest version) and its downloading correctly.</p>


问:
Is there a way to index an array by enums in Rust?
I want to represent a table of data in the memory like the following:

     | USD | EUR |
-----+-----+-----+
John | 100 | 50  |
-----+-----+-----+
Tom  | 300 | 200 |
-----+-----+-----+
Nick | 200 | 0   |
-----+-----+-----+
```

<p>There is a known set of people, each of them owns some currency.</p>

<p>And I have the following enums:</p>

```enum Person {
    John,
    Tom,
    Nick
}

enum Currency {
    USD,
    EUR
}
```

<p>I'd like to encode this data as 2D array, and it would be cool to be able to index array elements not by <code>usize</code> but by <code>enum</code>. E.g.:</p>

```data[Person::John][Currency::USD] = 100;
```

Is it possible to do with arrays and enums in Rust? Or is there any other data structure that would serve for this?

I am aware of HashMap, but it's not exactly what I want because:

HashMap works on the heap (what makes it much slower than regular stack allocated array)

HashMap gives me no guarantee that item exist. E.g. every time I want to get something I have to unwrap it and handle None case, what is not very handy in comparison with usage of normal array.

This is different from How do I match enum values with an integer? because I am not interested in converting enum to usize; I just want a handy way to access array/map items by enum.

答:
If you need this to be implemented using arrays, this isn't as straightforward as it might seem.

In order to be able to contain both of these pieces of information in an array (to be able to index by them), you first need to combine them in a single type, e.g. in a struct:

```<code>struct Money([(Currency, usize); 2]);

struct PersonFinances {
    person: Person,
    money: Money
}
</code>```

Then, if you want to be able to index the table, you will need to wrap it in your own type so that you can implement the Index trait for it:

```<code>use std::ops::Index;

struct Table([PersonFinances; 3]);

impl Index<(Person, Currency)> for Table {
    type Output = usize;

    fn index(&self, idx: (Person, Currency)) -> &Self::Output {
        &self
        .0
        .iter()
        .find(|&pf| pf.person == idx.0) // find the given Person
        .expect("given Person not found!")
        .money
        .0
        .iter()
        .find(|&m| m.0 == idx.1)  // find the given Currency
        .expect("given Currency not found!")
        .1
    }
}
</code>```

Then you can index the Table by a Person, Currency pair:

```<code>table[(Tom, EUR)]
</code>```

Rust playground link to the whole code

Body:
I want to represent a table of data in the memory like the following:

     | USD | EUR |
-----+-----+-----+
John | 100 | 50  |
-----+-----+-----+
Tom  | 300 | 200 |
-----+-----+-----+
Nick | 200 | 0   |
-----+-----+-----+

There is a known set of people, each of them owns some currency.

And I have the following enums:

enum Person {
    John,
    Tom,
    Nick
}

enum Currency {
    USD,
    EUR
}

I'd like to encode this data as 2D array, and it would be cool to be able to index array elements not by usize but by enum. E.g.:

data[Person::John][Currency::USD] = 100;

Is it possible to do with arrays and enums in Rust? Or is there any other data structure that would serve for this?

I am aware of HashMap, but it's not exactly what I want because:

HashMap works on the heap (what makes it much slower than regular stack allocated array)

HashMap gives me no guarantee that item exist. E.g. every time I want to get something I have to unwrap it and handle None case, what is not very handy in comparison with usage of normal array.

This is different from How do I match enum values with an integer? because I am not interested in converting enum to usize; I just want a handy way to access array/map items by enum.

Body:
If you need this to be implemented using arrays, this isn't as straightforward as it might seem.

In order to be able to contain both of these pieces of information in an array (to be able to index by them), you first need to combine them in a single type, e.g. in a struct:

struct Money([(Currency, usize); 2]);

struct PersonFinances {
    person: Person,
    money: Money
}

Then, if you want to be able to index the table, you will need to wrap it in your own type so that you can implement the Index trait for it:

use std::ops::Index;

struct Table([PersonFinances; 3]);

impl Index<(Person, Currency)> for Table {
    type Output = usize;

    fn index(&self, idx: (Person, Currency)) -> &Self::Output {
        &self
        .0
        .iter()
        .find(|&pf| pf.person == idx.0) // find the given Person
        .expect("given Person not found!")
        .money
        .0
        .iter()
        .find(|&m| m.0 == idx.1)  // find the given Currency
        .expect("given Currency not found!")
        .1
    }
}

Then you can index the Table by a Person, Currency pair:

table[(Tom, EUR)]

Rust playground link to the whole code


问:
How to Drop a Duplicates Column in dataframe while retaining the Unique Column including the only one column among duplicates
I am trying to drop the duplicate column while retaining only the unique columns and only one column among the duplicates after joining.

For Example:
Duplicate DataFrame

```<code>root
|-- id: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)

After removing duplicates, the output should be

root
|-- id: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)
</code>```

Any help will be appreciated?

答:
I believe, if you go for generic approach, then below code may be help you. Here you no need to mention the duplicate column names.

First create a implicit class (Better design approach)

```<code>implicit class DataFrameOperations(df: DataFrame) {
  def dropDuplicateCols(rmvDF: DataFrame): DataFrame = {
    val cols = df.columns.groupBy(identity).mapValues(_.size).filter(_._2 > 1).keySet.toSeq

    @tailrec def deleteCol(df: DataFrame, cols: Seq[String]): DataFrame = {
      if (cols.size == 0) df else deleteCol(df.drop(rmvDF(cols.head)), cols.tail)
    }
    deleteCol(df, cols)
  }
}
</code>```

To call the method you can use below one

```<code>val dupDF = rdd1.join(rdd2,"id").dropDuplicateCols(rdd1)
</code>```

Body:
I am trying to drop the duplicate column while retaining only the unique columns and only one column among the duplicates after joining.

For Example:
Duplicate DataFrame

root
|-- id: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)

After removing duplicates, the output should be

root
|-- id: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)

Any help will be appreciated?

Body:
I believe, if you go for generic approach, then below code may be help you. Here you no need to mention the duplicate column names.

First create a implicit class (Better design approach)

implicit class DataFrameOperations(df: DataFrame) {
  def dropDuplicateCols(rmvDF: DataFrame): DataFrame = {
    val cols = df.columns.groupBy(identity).mapValues(_.size).filter(_._2 > 1).keySet.toSeq

    @tailrec def deleteCol(df: DataFrame, cols: Seq[String]): DataFrame = {
      if (cols.size == 0) df else deleteCol(df.drop(rmvDF(cols.head)), cols.tail)
    }
    deleteCol(df, cols)
  }
}

To call the method you can use below one

val dupDF = rdd1.join(rdd2,"id").dropDuplicateCols(rdd1)


问:
How LuisIntent attribute is overriden?
```<code>[LuisIntent(intentName: "Eligibility")]
private async Task Eligibility(IDialogContext context, LuisResult result)
{
   await context.PostAsync($"You have chosen the eligibility intent with no entities");
  context.Wait(MessageReceivedAsync);
}
</code>```

How to override LuisIntent attribute such that it takes both IntentName and EntityName??

答:
I believe that what you want to do can be done in a simpler way assuming that what you want to do is to execute a different logic depending if an entity (or more than one) was detected.

The LuisResult class that you get in the intent method contains an Entities property with the list of entities that LUIS detected based on your query.

If you still want to do the filtering overriding things, then I believe that you will have to start by overriding the DispatchToIntentHandler method of the LuisDialog. That method is the one responsible for looking in the intent handlers dictionary , based on the intent name,  which handler need storage be called.

However, that won't be likely enough and you will have to create a new EnumerateHandlers because as I mentioned before, the dictionary of handlers is being created just with the intent name as the key and it seems you want to incorporate entities.

Finally, you will have to update the LuisIntentAttribute to incorporate the Entity name you want to filter.

As you can see the overriding path is not the best way to go.

Title: How LuisIntent attribute is overriden?

Body:
[LuisIntent(intentName: "Eligibility")]
private async Task Eligibility(IDialogContext context, LuisResult result)
{
   await context.PostAsync($"You have chosen the eligibility intent with no entities");
  context.Wait(MessageReceivedAsync);
}

How to override LuisIntent attribute such that it takes both IntentName and EntityName??


问:
SQL - Insert form into a database
I have a php script to insert form input into a database called XXXX_comments into the Table called Comments that has Name and Comment as columns.When a user hits Save button the form should be inserted into the DB. I connect to the database using connect.php :

```<code><?php
$servername = "localhost";
$username = "XXXXX";
$password = "XXXXX";
$Dbconnect = "XXX_comments";

// Create connection
$conn = new mysqli($servername, $username, $password);
mysqli_select_db($conn,$Dbconnect);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
</code>```

in my index.php file i have the following form:

```<code><?php
    include ('connect.php');
?>

<?php
        if(isset($_POST['Save'])){
        $sql = $conn->prepare("INSERT INTO Comments (Name, Comment) VALUES (?, ?)");
        $stmt->bind_param("ss", $firstname, $comment);
        $firstname = $_POST['firstname'];
        $comment = $POST['comment'];
        $stmt->execute();
        Echo "Succefully inserted to table";
 }
 ?>
<div class="container">
  <div class="row" id="post-review-box" style="display:none;">
    <div class="col-md-12">
      <form id="form" accept-charset="UTF-8" action="index.php" method="post">
        <input type="text" class="form-control animated" id="firstname" type="hidden" placeholder="Enter your Name">
        <br>
        <input id="ratings-hidden" name="rating" type="hidden">
        <textarea class="form-control animated" cols="50" id="comment" placeholder="Enter your review here..." rows="5"></textarea>
        <br>
        <div class="text-right">
          <div class="stars starrr" data-rating="0"></div>
          <a class="btn btn-danger btn-sm" href="#" id="close-review-box" style="display:none; margin-right: 10px;">
            <span class="glyphicon glyphicon-remove"></span>Cancel</a>
          <button class="btn btn-success btn-lg" type="submit" name="Save">Save</button>
        </div>
      </form>

    </div>
  </div>

</div>
<div class="display"></div>
</div>
</div>
</div>
</code>```

The connection is successful but the data is not being inserted.

答:
For any one intrested I have solved the issue, It seemed like the submit button wasn't responding So i added a javascript onclick function to force submit the form.

```<code><input class="btn btn-default" onclick="myFunction()" value="Submit">
<script>
function myFunction() {
    document.getElementById("form").submit();
}
</script>
</code>```

Thanks for all the answers.

Title: SQL - Insert form into a database

Body:
I have a php script to insert form input into a database called XXXX_comments into the Table called Comments that has Name and Comment as columns.When a user hits Save button the form should be inserted into the DB. I connect to the database using connect.php :

<?php
$servername = "localhost";
$username = "XXXXX";
$password = "XXXXX";
$Dbconnect = "XXX_comments";

// Create connection
$conn = new mysqli($servername, $username, $password);
mysqli_select_db($conn,$Dbconnect);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

in my index.php file i have the following form:

<?php
    include ('connect.php');
?>

<?php
        if(isset($_POST['Save'])){
        $sql = $conn->prepare("INSERT INTO Comments (Name, Comment) VALUES (?, ?)");
        $stmt->bind_param("ss", $firstname, $comment);
        $firstname = $_POST['firstname'];
        $comment = $POST['comment'];
        $stmt->execute();
        Echo "Succefully inserted to table";
 }
 ?>

      <form id="form" accept-charset="UTF-8" action="index.php" method="post">
        <input type="text" class="form-control animated" id="firstname" type="hidden" placeholder="Enter your Name">

        <input id="ratings-hidden" name="rating" type="hidden">
        <textarea class="form-control animated" cols="50" id="comment" placeholder="Enter your review here..." rows="5"></textarea>

            Cancel
          <button class="btn btn-success btn-lg" type="submit" name="Save">Save</button>

      </form>

The connection is successful but the data is not being inserted.

Body:
For any one intrested I have solved the issue, It seemed like the submit button wasn't responding So i added a javascript onclick function to force submit the form.

<input class="btn btn-default" onclick="myFunction()" value="Submit">
<script>
function myFunction() {
    document.getElementById("form").submit();
}
</script>

Thanks for all the answers.


问:
Possible Unhandled Promise Rejection (id: 0): while using facebook sdk
screen shot of error React Native:

Possible unhandled promise rejection while using fbsdk

It displays a yellow screen with the above error. i tried lot to debug this but dint worked kindly Please help me to debug this error.

My code:

```<code>import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
} from 'react-native';

import FBSDK, { LoginManager } from 'react-native-fbsdk'

export default class fbappss extends Component {

   _fbAuth(){

        LoginManager.logInWithReadPermissions(['public_profile']).then(function(result){

          if (result.isCancelled) {

              console.log('Login was cancelled');
          } else {

              console.log('Login was a success' + result.grantedPermission.toString());
          }
        }, function(error) {

            console.log('an error occured:' +error);
        })

        }

  render() {
    return (
      <View>
        <TouchableOpacity onPress={this._fbAuth()}>
        <Text>facebook</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('fbappss', () => fbappss);
</code>```

答:
Can you post your error page

Try rebuilding your project after placing FDSDK in right place

Body:
screen shot of error React Native:

Possible unhandled promise rejection while using fbsdk

It displays a yellow screen with the above error. i tried lot to debug this but dint worked kindly Please help me to debug this error.

My code:

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
} from 'react-native';

import FBSDK, { LoginManager } from 'react-native-fbsdk'

export default class fbappss extends Component {

   _fbAuth(){

        LoginManager.logInWithReadPermissions(['public_profile']).then(function(result){

          if (result.isCancelled) {

              console.log('Login was cancelled');
          } else {

              console.log('Login was a success' + result.grantedPermission.toString());
          }
        }, function(error) {

            console.log('an error occured:' +error);
        })

        }

  render() {
    return (
      <View>
        <TouchableOpacity onPress={this._fbAuth()}>
        <Text>facebook</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('fbappss', () => fbappss);


问:
Is it a good idea, to use Google Oauth 2.0 for login and permission administration?
I'm currently working on a project, where the developer before me implemented the login into an intern tool via google Oauth 2.0

He does that, by just grabbing the user domain, after authenticating with google and checks if it is "ourCompany.com".

If yes, he renders the page, if not, he redirects the user to the login.
(So basically he does one oauth request per page view.)

I'm pretty new to Oauth 2.0 but as far as I understand it, this is not, how it should be used?

He wants to use Oauth, because his idea is to organize all our employees over google groups/organizations and thus have a central place to give and take permissions. (Which I have to implement now.)

He said I should "just also get the groups on each request" and that's it.
(Which I tried btw. as a "quick win" but couldn't manage to get them from google yet, not sure If it is even intended)

My understanding of how this should work is the following:

The user is redirected to the google Oauth 2.0 service with a scope to get his groups/organizations.

We get back an access Token, which I then would use to ask the google API for the users groups/organizations.

Based on these informations I would then set the users rights in our application itself. (For example The user is in a google group "author", then I would give him the author role in our application)

The user then gets logged in via a "normal" PHP session, which takes over for the rest of the application, instead of always asking the Oauth service.

Does this approach make sense or is my colleague right with his implementation? The only benefits I see in his solution is, that we get "real time" information, if the user still is in a group or not.

But from what I've read about Oauth 2.0 so far, his implementation does not feel right for me, on the other hand I don't feel secure enough at this topic to say it's wrong.

So any explanations/opinions would be very welcome.

Additional informations about the project:

We use Laravel 5.4

I thought about using the "socialite" plugin (https://github.com/laravel/socialite) and for permissions (https://github.com/spatie/laravel-permission)

答:
If the intended user groups in your application are the same as the Google groups configured for your domain, then I think it's OK to use the Google domain groups. If not, you could use new groups (possibly with some prefix like myApp-group1), but you could end up with many groups if multiple applications does it.

There is also a question who can modify the Google domain groups. Is it the same person/role who would have the right to modify permissions in your application?

I would consider creating a separate access management for the application if:

There is a chance of people outside of your company using the application.

You needed to modify existing Google groups (if there are some) just to make them fit your application.

It looks like you can read user's groups by Google Directory API with an access token containing scope https://www.googleapis.com/auth/admin.directory.group.member.readonly. But I have no experience with it.

I think it's common to use LDAP (or MS Active Directory) as an access management for in-company applications, so the idea of using Google groups is not strange.

The auth sequence you described looks correct.


问:
Is the query processing fast if I create an index on a column but make a query for multiple column out of which one is the indexed column?
For example, let's say I created index on 'id' but I make a query like this:

```<code>select id, class, name from student;
</code>```

Will the query processing be random or will it be optimised according to the id column?

答:
With exactly your query it's probable the index will not be used.  It could be different if you add

```<code>"WHERE ID = somevalue";
</code>```

or if your query is

```<code>SELECT ID FROM STUDENT;
</code>```

Try to give a read to How can I index these queries?

Body:
For example, let's say I created index on 'id' but I make a query like this:

select id, class, name from student;

Will the query processing be random or will it be optimised according to the id column?

Body:
With exactly your query it's probable the index will not be used.  It could be different if you add

"WHERE ID = somevalue";

or if your query is

SELECT ID FROM STUDENT;

Try to give a read to How can I index these queries?


问:
Angular 2 setTimeout e2e tests fails
I have a component which calculate properties in the "afterViewChecked" lifeCycle,  so I need to use setTimeout - for the changes to apply or else I get errors.  (Angular 4 Changes based on view)

I just found out that setTimeout, no matter where in my application causing protractor to throw timeout message. - which says

Failed: Timed out waitig for asynchronous angular tasks to finish..... - this may be because the current page is not angular application",

What should I do?  - sometimes you just need to use setTimeout...

答:
You need to replace $timeout with $interval and it will work.
"If your page uses $timeout for polling Protractor will not be able to tell when your page is ready. Consider using $interval instead of $timeout."

Their official docs: http://www.protractortest.org/#/system-setup
https://github.com/marcorinck/angular-growl/issues/43

Title: Angular 2 setTimeout e2e tests fails


问:
Count unique values based on criteria given in another column
I have a list of machines with respective batches and part number being manufactured.

I need a unique count of a batches running in a machine. This long list is updated daily. I have attached an example here.

I have this rough code.

```<code>last_row = ws.Cells(Rows.Count,1).End(xlUp).Row
For Each M_cCell in M_cRange
    Counter = 0
    For i = 2 to last_row
        If Cells(1, 1).Value = M_cCell Then
            Counter = Counter + (1/(WorksheetFunction.CountIF _
            (Range(Cells(2,2),Cells(Last_row,2),M_ccell.Value)))
        End If
    Next i
Next M_cCell
</code>```

This gives an undesired result in decimal figures.

答:
Another solution:

```<code>Sub Demo()
    Dim rng As Range

    For Each rng In Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row)
        Cells(rng.Row(), "E").Value = Evaluate(Replace("IFERROR(INDEX($A$2:$A$15,MATCH(0,INDEX(COUNTIF($E$1:E#,$A$2:$A$15),0,0),0)),"""")", "#", rng.Row()))
        If Cells(rng.Row(), "E").Value = "" Then Exit For
        Cells(rng.Row, "F").FormulaArray = Evaluate(Replace("SUM(IF($A$2:$A$15=E#, 1/(COUNTIFS($A$2:$A$15, E#, $B$2:$B$15, $B$2:$B$15)), 0))", "#", rng.Row()))
    Next rng
End Sub
</code>```

This displays the result in Column E-F, see image for reference.

ContentLicense: CC BY-SA 4.0

Body:
I have a list of machines with respective batches and part number being manufactured.

I need a unique count of a batches running in a machine. This long list is updated daily. I have attached an example here.

I have this rough code.

last_row = ws.Cells(Rows.Count,1).End(xlUp).Row
For Each M_cCell in M_cRange
    Counter = 0
    For i = 2 to last_row
        If Cells(1, 1).Value = M_cCell Then
            Counter = Counter + (1/(WorksheetFunction.CountIF _
            (Range(Cells(2,2),Cells(Last_row,2),M_ccell.Value)))
        End If
    Next i
Next M_cCell

This gives an undesired result in decimal figures.

Body:
Another solution:

Sub Demo()
    Dim rng As Range

    For Each rng In Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row)
        Cells(rng.Row(), "E").Value = Evaluate(Replace("IFERROR(INDEX($A$2:$A$15,MATCH(0,INDEX(COUNTIF($E$1:E#,$A$2:$A$15),0,0),0)),"""")", "#", rng.Row()))
        If Cells(rng.Row(), "E").Value = "" Then Exit For
        Cells(rng.Row, "F").FormulaArray = Evaluate(Replace("SUM(IF($A$2:$A$15=E#, 1/(COUNTIFS($A$2:$A$15, E#, $B$2:$B$15, $B$2:$B$15)), 0))", "#", rng.Row()))
    Next rng
End Sub

This displays the result in Column E-F, see image for reference.


答:
Take one flag (Bool I mean), It's initial value will be false. now on radio button's selection set it's value to true.

Now, change numberofSection method. It will conditionally returns 1 or 4. I mean if your flag was true then return 4 else 1! that's it!

Title: How to hide sections in a table view using a radio button?


问:
What is the use of SQL Server Integration Services Server in SQL Server 2016?
In SQL Server there is a separate Server we install for SSIS but when we deploy a project it goes to SQL Server Database engine (Integration Services Catalogs, SSISDB).

What is the use of this Integration Services here? I'm new to this and couldn't find any article talking about this Integration Services login.

答:
In SSIS, when you choose package deployment model and create a deployment utility ie Deployment manifest, at that time we have option of deploy it on integration services.

In SQL 2012+ By default we use project deployment which creates our .dtsx in SSISDB folder under Integration  Service Catalog.

As said in comments, it is just for compatibility purpose now.

Here is a short demonstration of how to use it :

then click next :

Now you will be able to see the package inside MSDB folder.
From here you can run the package as well as maintain it.


问:
How do I combine tf.absolute and tf.square to create the Huber loss function in Tensorflow?
To be precise, the loss function that I'm looking for is the squared error when the absolute error is lesser than 0.5, and it is the absolute error itself, when the absolute error is greater than 0.5. In this way, the gradient from the error function doesn't exceed 1 because once the gradient of the squared error function reaches 1, the absolute error function kicks in, and the gradient remains constant at 1. I've included my current implementation below. For some reason, it's giving me worse performance than just the squared error.

```<code>fn_choice_maker1 = (tf.to_int32(tf.sign(y - y_ + 0.5)) + 1)/2
fn_choice_maker2 = (tf.to_int32(tf.sign(y_ - y + 0.5)) + 1)/2
choice_maker_sqr = tf.to_float(tf.mul(fn_choice_maker1,   fn_choice_maker2))

sqr_contrib = tf.mul(choice_maker_sqr, tf.square(y - y_))
abs_contrib = tf.abs(y - y_)-0.25 - tf.mul(choice_maker_sqr, tf.abs(y - y_)-0.25)
loss = tf.reduce_mean(sqr_contrib + abs_contrib)
train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)
</code>```

choice_maker_sqr is a column tensor that is one whenever the error is between 0.5 and -0.5. The names are pretty self explanatory.

答:
```<code>err = tf.subtract(x,y)
huber_loss = tf.where(tf.less(x,y),
                       tf.sqrt(tf.square(err)),
                       tf.abs(err))
with tf.Session() as sess:
    print(sess.run(tf.reduce_mean(huber_loss)))
</code>```

Body:
To be precise, the loss function that I'm looking for is the squared error when the absolute error is lesser than 0.5, and it is the absolute error itself, when the absolute error is greater than 0.5. In this way, the gradient from the error function doesn't exceed 1 because once the gradient of the squared error function reaches 1, the absolute error function kicks in, and the gradient remains constant at 1. I've included my current implementation below. For some reason, it's giving me worse performance than just the squared error.

fn_choice_maker1 = (tf.to_int32(tf.sign(y - y_ + 0.5)) + 1)/2
fn_choice_maker2 = (tf.to_int32(tf.sign(y_ - y + 0.5)) + 1)/2
choice_maker_sqr = tf.to_float(tf.mul(fn_choice_maker1,   fn_choice_maker2))

sqr_contrib = tf.mul(choice_maker_sqr, tf.square(y - y_))
abs_contrib = tf.abs(y - y_)-0.25 - tf.mul(choice_maker_sqr, tf.abs(y - y_)-0.25)
loss = tf.reduce_mean(sqr_contrib + abs_contrib)
train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)

choice_maker_sqr is a column tensor that is one whenever the error is between 0.5 and -0.5. The names are pretty self explanatory.


问:
How to access values from Android "strings.xml" in Kotlin
How can I access values from the Android strings.xml using Kotlin?

```<code>class MainActivity : AppCompatActivity(), View.OnClickListener {
    override fun onClick(p0: View?) {
        getToastCalled("")
        TODO("not implemented")
    }

    private fun getToastCalled(message: String) {
        TODO("not implemented")
    }

    var btn: Button? = null;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var tv_name=findViewById(R.id.tv) as TextView
        btn=findViewById(R.id.button) as Button
        tv_name.setText(KtTest().name);
        (btn as Button).setOnClickListener(MainActivity@this)
    }
}
</code>```

答:
Accessing string values in Kotlin works exactly the same as it does in Java, just with Kotlin syntax:

```<code>val string: String = getString(R.string.your_string_id)
</code>```

(This assumes that your code is inside an Android Activity, or a similar class that inherits from Context. If not, you need to get a Context instance from somewhere, and change it to myContext.getString(...).)

Body:
How can I access values from the Android strings.xml using Kotlin?

class MainActivity : AppCompatActivity(), View.OnClickListener {
    override fun onClick(p0: View?) {
        getToastCalled("")
        TODO("not implemented")
    }

    private fun getToastCalled(message: String) {
        TODO("not implemented")
    }

    var btn: Button? = null;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        var tv_name=findViewById(R.id.tv) as TextView
        btn=findViewById(R.id.button) as Button
        tv_name.setText(KtTest().name);
        (btn as Button).setOnClickListener(MainActivity@this)
    }
}

Body:
Accessing string values in Kotlin works exactly the same as it does in Java, just with Kotlin syntax:

val string: String = getString(R.string.your_string_id)

(This assumes that your code is inside an Android Activity, or a similar class that inherits from Context. If not, you need to get a Context instance from somewhere, and change it to myContext.getString(...).)


问:
Split html by element and class
I have a Javascript HTML string as follows,

```<code>var stringCheck = 'Test<a href="http://testdomain.com?data=new" target="_blank">partial string data</a> Test Data<span class="spanClass">XYZ</span>';
</code>```

Now would like to split this string such that, in one variable I do have value as

```<code>var split1 = 'Test<a href="http://testdomain.com?data=new" target="_blank">partial string data</a> Test Data';
</code>```

and second variable would be as follows,

```<code>var split2 = '<span class="spanClass">XYZ</span>';
</code>```

I would like to split the span element which has class of spanClass. Does anyone has idea how I can make it by use of RegEx or another way?

答:
Some manipulation of DOM and jQuery should do it - much to be preferred over RegEx:

var stringCheck = 'Testpartial string data Test Data XYZ';

function splitText(html) {
  var $div = $("
").html(html),
  $span = $div.find("span").remove();

  return [$span[0].outerHTML,$div[0].innerHTML]; // you may want to add a trim too
}
console.log(splitText(stringCheck));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script></code>```

Title: Split html by element and class

Body:
I have a Javascript HTML string as follows,

var stringCheck = 'Testpartial string data Test DataXYZ';

Now would like to split this string such that, in one variable I do have value as

var split1 = 'Testpartial string data Test Data';

and second variable would be as follows,

var split2 = 'XYZ';

I would like to split the span element which has class of spanClass. Does anyone has idea how I can make it by use of RegEx or another way?

Body:
Some manipulation of DOM and jQuery should do it - much to be preferred over RegEx:

var stringCheck = 'Test<a href="http://testdomain.com?data=new" target="_blank">partial string data</a> Test Data <span class="spanClass">XYZ</span>';

function splitText(html) {
  var $div = $("<div/>").html(html),
  $span = $div.find("span").remove();

  return [$span[0].outerHTML,$div[0].innerHTML]; // you may want to add a trim too
}
console.log(splitText(stringCheck));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>


答:
You can create a jQuery object and extract the desired text.

var stringCheck = 'Testpartial string data Test Data XYZ';

//Create a jQuery object
var div = $('
').html(stringCheck);
//Extract span
var str1 = div.children('span.spanClass').prop('outerHTML');
//Remove it
div.children('span.spanClass').remove();
//Get rest of string
var str = div.html();

console.log(str);
console.log(str1);```
<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></code>```

Title: Split html by element and class

Body:
You can create a jQuery object and extract the desired text.

var stringCheck = 'Test<a href="http://testdomain.com?data=new" target="_blank">partial string data</a> Test Data <span class="spanClass">XYZ</span>';

//Create a jQuery object
var div = $('<div>').html(stringCheck);
//Extract span
var str1 = div.children('span.spanClass').prop('outerHTML');
//Remove it
div.children('span.spanClass').remove();
//Get rest of string
var str = div.html();

console.log(str);
console.log(str1);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
Delete image from database and from folder in php mysql
I try to delete an image from database and from folder, image path is saved in the database when we create a post, when  echo $res = $row['image']; i got this result
/bp_project/admin-bp/job/ad_images/Picture3.jpg , Every thing is fine and record gets deleted from the database but the image is still in 'ad_images' Folder.
if i try unlink("ad_images/"."Picture3.jpg"); its working but we didn't need this, we want to delete image by fetching image path from database.
Anybody can help me delete image by fetching image path from database Thanks.

```<code>$user_email=$_SESSION['session_email_id'];
$token=$_GET['id'];

$result = $con->prepare("SELECT * FROM bp_users WHERE email= '".$user_email."'");
$result->execute();
$row = $result->fetch();
$user_token = $row['token_id'];

if(isset($token)){
    $result = $con->prepare("SELECT * FROM job WHERE token_id = '".$token."'");
    $result->execute();
    $row = $result->fetch();

    echo $res = $row['image'];

    if(file_exists($res)){

        unlink($res);

        $result = $con->prepare("DELETE FROM job WHERE token_id= :memid");
        $result->bindParam(':memid', $token);
        $result->execute();

        echo "<script language='javascript' type='text/javascript'>alert('Ad Successfully Deleted!')</script>";
        echo "<script language='javascript' type='text/javascript'>window.open('all-ad.php?user_token=".$user_token."','_self')</script>";
    }
    else{
        echo "<script language='javascript' type='text/javascript'>alert('Ad not Deleted Please Try Again!')</script>";
        echo "<script language='javascript'
        type='text/javascript'>window.open('all-ad.php?
        user_token=".$user_token."','_self')</script>";
    }
}
</code>```

答: All you need Is to Delete the image from database so if you want to delete from database you can use "Delete" Key word Or what Please make it clear!</p>

Body:
I try to delete an image from database and from folder, image path is saved in the database when we create a post, when  echo $res = $row['image']; i got this result
/bp_project/admin-bp/job/ad_images/Picture3.jpg , Every thing is fine and record gets deleted from the database but the image is still in 'ad_images' Folder.
if i try unlink("ad_images/"."Picture3.jpg"); its working but we didn't need this, we want to delete image by fetching image path from database.
Anybody can help me delete image by fetching image path from database Thanks.

$user_email=$_SESSION['session_email_id'];
$token=$_GET['id'];

$result = $con->prepare("SELECT * FROM bp_users WHERE email= '".$user_email."'");
$result->execute();
$row = $result->fetch();
$user_token = $row['token_id'];

if(isset($token)){
    $result = $con->prepare("SELECT * FROM job WHERE token_id = '".$token."'");
    $result->execute();
    $row = $result->fetch();

    echo $res = $row['image'];

    if(file_exists($res)){

        unlink($res);

        $result = $con->prepare("DELETE FROM job WHERE token_id= :memid");
        $result->bindParam(':memid', $token);
        $result->execute();

        echo "";
        echo "";
    }
    else{
        echo "";
        echo "";
    }
}


问:
whose view is not in the windows heirarchy
I know this question has been asked before but none of the answers in the other questions worked for me. Here is my code:

```</p>

```var values = [String: AnyObject]()

func loginUserToFirebase(_ completion: () -> Void) {
    let accessToken = FBSDKAccessToken.current()
    guard let accessTokenString = accessToken?.tokenString else {fatalError()}
    let credentials = FIRFacebookAuthProvider.credential(withAccessToken: accessTokenString)
    FIRAuth.auth()?.signIn(with: credentials, completion: { (user, error) in
        if error != nil {
            print(error ?? "Something went wrong")
            return
        }
        self.fbGraphRequest()
    })
}

internal func fbGraphRequest(){
    FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start { (connection, result, error) in
        if error != nil {
            print(error ?? "error unknown")
            return
        } else {
            print(result ?? "no result")
            self.values = result as! [String: AnyObject]
            print(self.values)
            weak var rootViewModel = RootViewModel()
            rootViewModel?.values = self.values
            self.presentRootViewController()
        }
    }
}

internal func presentRootViewController() {
    let loginController = LoginController()
    let rootViewController = RootViewController()
        loginController.present(rootViewController, animated: true,
completion: nil)

}
```

<p>```

and here is my error:

Attempt to present <Art_Cache.RootViewController: 0x7fa6a1c2aab0> on <Art_Cache.LoginController: 0x7fa6a1c840b0> whose view is not in the window hierarchy!

This snippet worked when I had this in my LoginViewController and I used self.present(rootViewController, animation: true, completion: nil). Im trying to convert my project to MVVM and this is what's happening. The problem seems to be around the self.presentRootViewController(). These functions are fired upon pressing the facebook login button. Please help and cheers!

答:
This happens when you current view controller's is not the part of window, could you change </p>

```<code>func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {

        if let nav = base as? UINavigationController {
            return topViewController(nav.visibleViewController)
        }

        if let tab = base as? UITabBarController {
            let moreNavigationController = tab.moreNavigationController

            if let top = moreNavigationController.topViewController, top.view.window != nil {
                return topViewController(top)
            } else if let selected = tab.selectedViewController {
                return topViewController(selected)
            }
        }

        if let presented = base?.presentedViewController {
            return topViewController(presented)
        }

        return base
    }

    topViewController()?.present(rootViewController, animated: true,
    completion: nil)
</code>```

Body:
I know this question has been asked before but none of the answers in the other questions worked for me. Here is my code:

```</p>

<pre><code>var values = [String: AnyObject]()

func loginUserToFirebase(_ completion: () -> Void) {
    let accessToken = FBSDKAccessToken.current()
    guard let accessTokenString = accessToken?.tokenString else {fatalError()}
    let credentials = FIRFacebookAuthProvider.credential(withAccessToken: accessTokenString)
    FIRAuth.auth()?.signIn(with: credentials, completion: { (user, error) in
        if error != nil {
            print(error ?? "Something went wrong")
            return
        }
        self.fbGraphRequest()
    })
}

internal func fbGraphRequest(){
    FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start { (connection, result, error) in
        if error != nil {
            print(error ?? "error unknown")
            return
        } else {
            print(result ?? "no result")
            self.values = result as! [String: AnyObject]
            print(self.values)
            weak var rootViewModel = RootViewModel()
            rootViewModel?.values = self.values
            self.presentRootViewController()
        }
    }
}

internal func presentRootViewController() {
    let loginController = LoginController()
    let rootViewController = RootViewController()
        loginController.present(rootViewController, animated: true,
completion: nil)

}
</code></pre>

<p>```

and here is my error:

Attempt to present <Art_Cache.RootViewController: 0x7fa6a1c2aab0> on <Art_Cache.LoginController: 0x7fa6a1c840b0> whose view is not in the window hierarchy!

This snippet worked when I had this in my LoginViewController and I used self.present(rootViewController, animation: true, completion: nil). Im trying to convert my project to MVVM and this is what's happening. The problem seems to be around the self.presentRootViewController(). These functions are fired upon pressing the facebook login button. Please help and cheers!

Body:
This happens when you current view controller's is not the part of window, could you change

func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {

        if let nav = base as? UINavigationController {
            return topViewController(nav.visibleViewController)
        }

        if let tab = base as? UITabBarController {
            let moreNavigationController = tab.moreNavigationController

            if let top = moreNavigationController.topViewController, top.view.window != nil {
                return topViewController(top)
            } else if let selected = tab.selectedViewController {
                return topViewController(selected)
            }
        }

        if let presented = base?.presentedViewController {
            return topViewController(presented)
        }

        return base
    }

    topViewController()?.present(rootViewController, animated: true,
    completion: nil)


答:
Use something of this sort

var String = 'Testpartial string data Test Data XYZ';
String = String.replace(/\s(?=<span class="spanClass")/ig, "|||");
var arr = String.split("|||");
console.log(arr);```

**This will split on all your spans having class spanClass **

Title: Split html by element and class

Body:
Use something of this sort

var String = 'Test<a href="http://testdomain.com?data=new" target="_blank">partial string data</a> Test Data <span class="spanClass">XYZ</span>';
String = String.replace(/\s(?=<span class="spanClass")/ig, "|||");
var arr = String.split("|||");
console.log(arr);

**This will split on all your spans having class spanClass **


问:
stackoverflow exception was unhandled
In the code below it should multiply 2 numbers. It works for 3 and less than 3 digits numbers but when I give numbers with 4 digits or bigger it gives runtime error: stackoverflow exception was unhandled. I've commented where the problem is. I thought the problem is for defining variables in int and changed them in long but the problem still exists. Where is the mistake?

edited:
now,whats do you think about the problem?it doesnt do anything

```<code>        public long Prod2(long u, long v)
    {
        var numbers = textBox7.Text.Split(',').Select(p => long.Parse(p)).ToArray();
        int n = Math.Max((int)Math.Floor(Math.Log10(u) + 1),(int)Math.Floor(Math.Log10(v) + 1));
        int threshold = 3;

        if (u == 0 || v == 0)
        {
            return 0;
        }
        else if (n <= threshold)
        {
            return u * v;
        }
        else
        {
            int m = (int)Math.Ceiling(n / 2.0);

            int x = (int)(u / Math.Pow(10, m));
            int y = (int)(u % Math.Pow(10, m));
            int w = (int)(u / Math.Pow(10, m));
            int z = (int)(v % Math.Pow(10, m));

            long r = Prod2(x + y, w + z);
            long p = Prod2(x, w);
            long q = Prod2(y, z);

            return p * (long)Math.Pow(10, 2 * m) + (r - p - q) * (long)Math.Pow(10, m) + q;
            long result = Prod2(numbers[0], numbers[1]);
            textBox1.Text = result.ToString();
        }
    }
</code>```

答:
You are getting into an infinite recursive loop at this point

```<code> long result = bigzarb(x, w) * Math.Pow(10, m) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(10, m) + bigzarb(y, z);///here
    textBox1.Text = result.ToString();
</code>```

I notice this line is executed only when intn > 3, so perhaps you have a logic bug there?

Update: After reading your comments I can see that this test is intended to say "if the length of this string is <= 3 then..."  when in fact as written it is actually saying "if the VALUE of this converted string is <= 3 then..."

ContentLicense: CC BY-SA 2.5

Title: stackoverflow exception was unhandled

Body:
In the code below it should multiply 2 numbers. It works for 3 and less than 3 digits numbers but when I give numbers with 4 digits or bigger it gives runtime error: stackoverflow exception was unhandled. I've commented where the problem is. I thought the problem is for defining variables in int and changed them in long but the problem still exists. Where is the mistake?

edited:
now,whats do you think about the problem?it doesnt do anything

        public long Prod2(long u, long v)
    {
        var numbers = textBox7.Text.Split(',').Select(p => long.Parse(p)).ToArray();
        int n = Math.Max((int)Math.Floor(Math.Log10(u) + 1),(int)Math.Floor(Math.Log10(v) + 1));
        int threshold = 3;

        if (u == 0 || v == 0)
        {
            return 0;
        }
        else if (n <= threshold)
        {
            return u * v;
        }
        else
        {
            int m = (int)Math.Ceiling(n / 2.0);

            int x = (int)(u / Math.Pow(10, m));
            int y = (int)(u % Math.Pow(10, m));
            int w = (int)(u / Math.Pow(10, m));
            int z = (int)(v % Math.Pow(10, m));

            long r = Prod2(x + y, w + z);
            long p = Prod2(x, w);
            long q = Prod2(y, z);

            return p * (long)Math.Pow(10, 2 * m) + (r - p - q) * (long)Math.Pow(10, m) + q;
            long result = Prod2(numbers[0], numbers[1]);
            textBox1.Text = result.ToString();
        }
    }

Body:
You are getting into an infinite recursive loop at this point

 long result = bigzarb(x, w) * Math.Pow(10, m) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(10, m) + bigzarb(y, z);///here
    textBox1.Text = result.ToString();

I notice this line is executed only when intn > 3, so perhaps you have a logic bug there?

Update: After reading your comments I can see that this test is intended to say "if the length of this string is <= 3 then..."  when in fact as written it is actually saying "if the VALUE of this converted string is <= 3 then..."


问:
How to update the git dasho map files
After deleting a remote branch with the following command

```<code>git push origin --delete <remote_branch_name>
</code>```

I get the following using the command git branch -vv

```<code>...
local_branch_name SHA-1 [origin/remote_branch_name: gone] Update the dasho map files
...
</code>```

What does it means "Update the dasho map files"? How to do it?
I have tried with git fetch origin but it does not solve the problem.

答:
It's simply the message of the commit your branch local_branch_name is pointing to.

You don't have to do anything: there is no problem.

You can change your branch to stop tracking the "gone" remote branch origin/remote_branch_name with:

```<code>git branch --unset-upstream local_branch_name
</code>```

Then, the output of git branch -vv would be:

```<code>...
local_branch_name SHA-1 Update the dasho map files
...
</code>```

Title: How to update the git dasho map files

Body:
After deleting a remote branch with the following command

git push origin --delete <remote_branch_name>

I get the following using the command git branch -vv

...
local_branch_name SHA-1 [origin/remote_branch_name: gone] Update the dasho map files
...

What does it means "Update the dasho map files"? How to do it?
I have tried with git fetch origin but it does not solve the problem.

Body:
It's simply the message of the commit your branch local_branch_name is pointing to.

You don't have to do anything: there is no problem.

You can change your branch to stop tracking the "gone" remote branch origin/remote_branch_name with:

git branch --unset-upstream local_branch_name

Then, the output of git branch -vv would be:

...
local_branch_name SHA-1 Update the dasho map files
...


问:
There is no linked app associated with this client ID
I'm becoming crazy with this one. I just published a game on Google Play Store and the game uses the Google Play Games services.

Sign-in and leaderboards / achievements worked fined with the application signed with the debug key, but since I built and
published my app using my release key, Google+ sign-on is impossible. I always get the infamous error
"E/SignInIntentService(25004): There is no linked app associated with this client ID."

I double- and triple-checked everything : my app is published, the package name and SHA1 fingerprint are correct and match
what I extracted from the release APK, I unlinked and relinked the app in the Google Play Console multiple times, but nothing
works.

Ideas, anyone ?

Thanks

答:
I tried linking a new app and it didn't work and almost started the process of creating a new app again. However, I tried regenerating the API Key from the Google APIs Console and it worked!

Go to Credentials, select your API key and then click on "Regenerate Key".


问:
Laravel Eloquent ORM - Many to Many Delete Pivot Table Values left over
Using Laravel, I have the following code

```<code>$review = Review::find(1);
$review->delete();
</code>```

Review has a many to many relationship defined with a Product entity. When I delete a review, I'd expect it to be detached from the associated products in the pivot table, but this isn't the case. When I run the code above, I still see the linking row in the pivot table.

Have I missed something out here or is this the way Laravel works? I'm aware of the detach() method, but I thought that deleting an entity would also detach it from any related entities automatically.

Review is defined like this:

```<code><?php
class Review extends Eloquent
{
    public function products()
    {
        return $this->belongsToMany('Product');
    }
}
</code>```

Product is defined like this:

```<code><?php
class Product extends Eloquent
{
    public function reviews()
    {
        return $this->belongsToMany('Review');
    }
}
</code>```

Thanks in advance.

答:
$review->product()->sync([]) also works.

However $review->product()->detach() is much more explicit.

Body:
Using Laravel, I have the following code

$review = Review::find(1);
$review->delete();

Review has a many to many relationship defined with a Product entity. When I delete a review, I'd expect it to be detached from the associated products in the pivot table, but this isn't the case. When I run the code above, I still see the linking row in the pivot table.

Have I missed something out here or is this the way Laravel works? I'm aware of the detach() method, but I thought that deleting an entity would also detach it from any related entities automatically.

Review is defined like this:

<?php
class Review extends Eloquent
{
    public function products()
    {
        return $this->belongsToMany('Product');
    }
}

Product is defined like this:

<?php
class Product extends Eloquent
{
    public function reviews()
    {
        return $this->belongsToMany('Review');
    }
}

Thanks in advance.


问:
Why shouldn't I use a PoolingHttpClientConnectionManager with FutureRequestExecutionService?
I'm writing a service which needs to run many parallel http requests.  It will be deployed in an auto-scaling environment too but I'd like to get as much performance out of each service instance as I can.

I came across this post How to determine the maximum number of simultaneous connections for a given `HttpClient` instance and noticed the recommendation to not mix these two classes.

I'm curious as to why.  Basically, I'd like to submit http client jobs to an executor service and I want http connection pooling in place to reuse http connections.  Perhaps, I'm over-thinking this but I don't see why it's a bad idea to combine these two classes/concepts in one application.

Also, I noticed that example give in that response uses one http client instance per FutureRequestExecutionService. . . which makes me a bit nervous but CloseableHttpClient is thread safe so perhaps I'm worrying needlessly.

Also, for most of the client tasks my code submits, I don't care if the response is 200 and if it's not, I'm just planning to increment an error tracking metric and possibly log the exception, so I'm thinking of going the callback route.  On that note, it's not clear to me where the callback will run.  If my threadpool thread runs and completes i.e. doesn't block on the http request futures. . . then what thread runs the callback code?

答: The post in question advises against "... tight coupling of PoolingHttpClientConnectionManager and the FutureRequestExecutionService wiring code ...". There is no reason to NOT use FutureRequestExecutionService with PoolingHttpClientConnectionManager.


问:
How does the non executeable exploit work?
Hello the question is how works non executable exploit's, when i say non executable i mean those who don't have the file extension .exe, like word exploits .doc or other. How did they make some executable action if they are not compiled?</p>

答:
The other way is to exploit bugs in the code that handles those files. Often this will be a 'buffer overflow'. Perhaps the code is expecting a header of 100 bytes, but the malicious file has 120 bytes. That causes the program to overwrite some other data in its memory, and if you can smash the 'stack' with your extra bytes it's possible to redirect the processor to a 'payload' code embedded in your file.

google "buffer overflow exploit" for more.


问:
print all threads stack trace of a process in c/c++ on linux platform
What I want is to get stacktrace of all threads for running process using c/c++.

The different ways which I know to get stacktrace :

we have backtrace() api but problem with this is that it only gives stacktrace of current thread. Does any one know how to associate it with each running thread?

Second way I tried is using pstack command. pstack takes input as pid of running process shows all stack of all threads. But problem with this is that it is not a C/C++ api so we can't use it in our code. (When I study) pstack is a shell file which in turn used gdb's bt command.

Does anyone know different ways which will help me to get stacktrace of all threads for running process?

答:
Maybe you can use ptrace. Attach to all your threads (except for the thread that prints the stacktrace), and you can get register values with PTRACE_GETREGS. Then you can do stack unwinding (maybe you will need information stored in the .elf file to do this reliably). Note, that you have to take special care, if a thread is just creating/destroying its stack frame. And you may need debug information from the elf to do this reliably (you'd surely need that if your code compiled with omitted frame pointers).

Not an easy task to do this by hand, but surely can be done.


问:
PERL CTRL-D not stoping user input
Learning perl I found that in this case CTRL+D is not working to stop user input. Its working in others scripts so probably is something realted with the code itself.

I was reading on the internet about EOF but anything seems to work for me.

Thank you in advance and best Regards.

```<code>#!/usr/bin/perl

print "Dime tus numeros\n";

@numb =<STDIN>;

$cua = 0;
$count = 0;
$array = "@numb";

$max = @numb; #tamaño array
$joined = join('',@numb); #metemos array en sacalar juntandolo sin espacios
$joined = $original; #guardamos el num original

$diff = 999 - $joined;

for ($i=0; i<=$max;$i++){ #es <= por que el arraylenght no empieza en 0

    $sumatotal += $numb[$i]; #vamos sumando cada elemento del array
}

print "Has añadido los numeros $array. \n";
print "Combiandose en $joined que sumados entre si dan:$sumatotal \n";
print "La diferencia entre $joined y 999 es $cua\n";
</code>```

答:
Found the problem,
For loop never ends cause of bad declaration of the second i wich should be $i, this put the execution in an endless loop. </p>

```<code>for ($i=0; i<=$max;$i++)
</code>```

Title: PERL CTRL-D not stoping user input

Body:
Learning perl I found that in this case CTRL+D is not working to stop user input. Its working in others scripts so probably is something realted with the code itself.

I was reading on the internet about EOF but anything seems to work for me.

Thank you in advance and best Regards.

#!/usr/bin/perl

print "Dime tus numeros\n";

@numb =<STDIN>;

$cua = 0;
$count = 0;
$array = "@numb";

$max = @numb; #tamaño array
$joined = join('',@numb); #metemos array en sacalar juntandolo sin espacios
$joined = $original; #guardamos el num original

$diff = 999 - $joined;

for ($i=0; i<=$max;$i++){ #es <= por que el arraylenght no empieza en 0

    $sumatotal += $numb[$i]; #vamos sumando cada elemento del array
}

print "Has añadido los numeros $array. \n";
print "Combiandose en $joined que sumados entre si dan:$sumatotal \n";
print "La diferencia entre $joined y 999 es $cua\n";

Body:
Found the problem,
For loop never ends cause of bad declaration of the second i wich should be $i, this put the execution in an endless loop.

for ($i=0; i<=$max;$i++)


问:
Save compressed files into s3 and load in Athena
Hi I am writing some program that will write in some files (with more processes at the time) like:

```<code>with gzip.open('filename.gz', 'a') as f:
    f.write(json.dumps(some dictionary) + '\n')
    f.flush()
</code>```

After writing finishes I upload files with:

```<code>s3.meta.client(filename, bucket, destination, filename without .gz)
</code>```

Than I want to query data from Athena, after MSCK REPAIR everything seems fine but when I try to select data my rows are empty. Does anyone know what am I doing wrong?

EDIT: My mistake. I have forgot to add ContentType parameter to 'text/plain'

答:
I have fixed the problem by first saving bigger chunks of files locally and than gzip them. I repeat the process but with appending to gziped file. Read that it is better to add bigger chunks of text than just line by line

For the upload I used boto3.transfet.upload_file with extra_args={'ContentEncoding': 'gzip', 'ContentType': 'text/plain'}

I forgot to add ContetType first time so the s3 saved them differently and Athena gave me errors that said my JSON is not formatted right.

Body:
Hi I am writing some program that will write in some files (with more processes at the time) like:

with gzip.open('filename.gz', 'a') as f:
    f.write(json.dumps(some dictionary) + '\n')
    f.flush()

After writing finishes I upload files with:

s3.meta.client(filename, bucket, destination, filename without .gz)

Than I want to query data from Athena, after MSCK REPAIR everything seems fine but when I try to select data my rows are empty. Does anyone know what am I doing wrong?

EDIT: My mistake. I have forgot to add ContentType parameter to 'text/plain'