问:
How to prevent Popup closing after date selection?
I've a popup with a Datepicker inside:

```<code><materialDesign:PopupBox StaysOpen="True">
     <DatePicker Focusable="False"/>
</materialDesign:PopupBox>
</code>```

When I select a date the Datepicker will close automatically, and also the Popup. How can I prevent the Popup closing when I select a date from the Datepicker inside the Popup?

As you can see I tried the property StaysOpen to true, but not seems to working, almost, not in this circumstance.

答:
If I take Focusable="False" off the DatePicker, the PopupBox remains open when I select a date in the DatePicker.

```<code><materialDesign:PopupBox StaysOpen="True">
     <local:DatePicker2 />
</materialDesign:PopupBox>
</code>```

C#

```<code>public class DatePicker2 : DatePicker
{
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        if (GetTemplateChild("PART_TextBox") is TextBox textBox)
        {
            textBox.IsReadOnly = true;
        }
    }
}
</code>```

There you go, two answers for the price of one.

Body:
I've a popup with a Datepicker inside:

<materialDesign:PopupBox StaysOpen="True">
     <DatePicker Focusable="False"/>
</materialDesign:PopupBox>

When I select a date the Datepicker will close automatically, and also the Popup. How can I prevent the Popup closing when I select a date from the Datepicker inside the Popup?

As you can see I tried the property StaysOpen to true, but not seems to working, almost, not in this circumstance.

Body:
If I take Focusable="False" off the DatePicker, the PopupBox remains open when I select a date in the DatePicker.

<materialDesign:PopupBox StaysOpen="True">
     <local:DatePicker2 />
</materialDesign:PopupBox>

C#

public class DatePicker2 : DatePicker
{
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        if (GetTemplateChild("PART_TextBox") is TextBox textBox)
        {
            textBox.IsReadOnly = true;
        }
    }
}

There you go, two answers for the price of one.


来源: stackexchange

问:
How to convert string to uint8_t in C++?
How to convert string to uint8_t in C++?</p>

```<code>std::string str = "b2d";
static const uint8_t PublicKeyData[3] = ??? // it should be like 0x62 0x32 0x64}
</code>```

答:
You can copy all the string characters using the std::copy function:

```<code>#include <string>
#include <cstdint>
#include <algorithm>

int main() {
    std::string str = "b2d";
    uint8_t PublicKeyData[3];
    std::copy(str.begin(), str.end(), PublicKeyData);
}
</code>```

Your array will then hold the following values with the hexadecimal representation: 0x62, 0x32, 0x64 or the decimal equivalent: 98, 50, 100. Since the largest value is 100 which is less than 127 your array might have been a simple char instead:

```<code>char PublicKeyData[3];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to convert string to uint8_t in C++?

std::string str = "b2d";
static const uint8_t PublicKeyData[3] = ??? // it should be like 0x62 0x32 0x64}

Body:
You can copy all the string characters using the std::copy function:

#include <string>
#include <cstdint>
#include <algorithm>

int main() {
    std::string str = "b2d";
    uint8_t PublicKeyData[3];
    std::copy(str.begin(), str.end(), PublicKeyData);
}

Your array will then hold the following values with the hexadecimal representation: 0x62, 0x32, 0x64 or the decimal equivalent: 98, 50, 100. Since the largest value is 100 which is less than 127 your array might have been a simple char instead:

char PublicKeyData[3];


问:
Bubble sorting doesn't work to sort dynamic array of objects in C++
I have class City with following private data: name of city(type char), width(double),length(double) and height(double) of the city. I have to make dynamic array, which is inserted by constructor by default- City(),when the programs starts.Then the program uses method output() and prints inserted array of cities.mA is my object of cities.I should use bubble sort to sort the cities by their length.I have copy constructor, operator = and I have to convert double max(this is variable, used in bubble sort to store current max value) to type City and in this purpose I used contructor with one parameter: City(double max).The problem is that the sort doesn't work. I think that the problem is in my definition of constructor with one parameter(to convert type double to type city). </p>

```<code>#include "stdafx.h"
#include<iostream>
#include<math.h>
#include <algorithm>
using namespace std;

class City{
private: char *name;
         double width;
         double length;
         double height;
public:

    void Output();
    City();
    ~City();
    City(double max){
        name = "";
        width = 0;
        length = max;
        height = 0;
    }
    double GetLength()
    {
        return length;
    }
    double GetWidth(){ return width; }
    double GetHeight(){ return height; }
    char GetName(){ return *name; }
    City(const City& that)
    {
        name = new char[strlen(that.name) + 1];
        for (int i = 0; i <= strlen(that.name); i++)
            name[i] = that.name[i];
        //strcpy(name, that.name);
        width = that.width;
        length = that.length;
        height = that.height;
    }

    City& operator=(const City that)
    {
        name = that.name;
        width = that.width;
        length = that.length;
        height = that.height;
        return*this;
    }
};
City::City()
{
    char ime[20];
    cout << "Name= ";
    cin >> ime;
    name = new char[strlen(ime) + 1];
    for (int i = 0; i <= strlen(ime); i++)
        name[i] = ime[i];

    cout << "Width= ";
    cin >> width;
    cout << "Length= ";
    cin >> length;
    cout << "Height= ";
    cin >> height;
}

void City::Output()
{
    cout << "Name is: " << name << endl;
    cout << " Width is: " << width << " deg" << endl;;
    cout << " Length is: " << length << " deg" << endl;
    cout << " Height is: " << height << " m" << endl;
    return;
}
City::~City()
{
    cout << " " << endl;
    cout << "Destructor of City!" << endl;
    delete[] name;

}

int main()
{

    int n;
    City *mA;
    cout << "Input number of cities: " << endl;
    cin >> n;
    mA = new City[n];
    for (int j = 0; j < n; j++)
    {
        mA[j].Output();
    }
    cout << "Cities from west to east, sorted by their length" << endl;

    double max = mA[0].GetLength();
    for (int j = 1; j<n; j++)
    {
        if (mA[j - 1].GetLength()>mA[j].GetLength())
        {
            max = mA[j - 1].GetLength();

            mA[j - 1] = mA[j];
            mA[j] = max;
        }
    }
    for (int j = 0; j < n; j++)
    {
        mA[j].Output();
    }

    delete[]mA;
    return 0;

}
</code>```

答:
manually sorting requires comparing of resorted entries
------- comment ---------
for (int j = 1; jmA[j].GetLength()) {
            ... exchange elements
            ... j-=2; //index of
            ... if(j < 0) j=0; }
------- end comment ---------

if there will be used std::sort conditions are reliable checked by STL.
And there will only be checked compare conditions on callback function.

regards, Hubert Hermanutz

Body:
I have class City with following private data: name of city(type char), width(double),length(double) and height(double) of the city. I have to make dynamic array, which is inserted by constructor by default- City(),when the programs starts.Then the program uses method output() and prints inserted array of cities.mA is my object of cities.I should use bubble sort to sort the cities by their length.I have copy constructor, operator = and I have to convert double max(this is variable, used in bubble sort to store current max value) to type City and in this purpose I used contructor with one parameter: City(double max).The problem is that the sort doesn't work. I think that the problem is in my definition of constructor with one parameter(to convert type double to type city).

#include "stdafx.h"
#include<iostream>
#include<math.h>
#include <algorithm>
using namespace std;

class City{
private: char *name;
         double width;
         double length;
         double height;
public:

    void Output();
    City();
    ~City();
    City(double max){
        name = "";
        width = 0;
        length = max;
        height = 0;
    }
    double GetLength()
    {
        return length;
    }
    double GetWidth(){ return width; }
    double GetHeight(){ return height; }
    char GetName(){ return *name; }
    City(const City& that)
    {
        name = new char[strlen(that.name) + 1];
        for (int i = 0; i <= strlen(that.name); i++)
            name[i] = that.name[i];
        //strcpy(name, that.name);
        width = that.width;
        length = that.length;
        height = that.height;
    }

    City& operator=(const City that)
    {
        name = that.name;
        width = that.width;
        length = that.length;
        height = that.height;
        return*this;
    }
};
City::City()
{
    char ime[20];
    cout << "Name= ";
    cin >> ime;
    name = new char[strlen(ime) + 1];
    for (int i = 0; i <= strlen(ime); i++)
        name[i] = ime[i];

    cout << "Width= ";
    cin >> width;
    cout << "Length= ";
    cin >> length;
    cout << "Height= ";
    cin >> height;
}

void City::Output()
{
    cout << "Name is: " << name << endl;
    cout << " Width is: " << width << " deg" << endl;;
    cout << " Length is: " << length << " deg" << endl;
    cout << " Height is: " << height << " m" << endl;
    return;
}
City::~City()
{
    cout << " " << endl;
    cout << "Destructor of City!" << endl;
    delete[] name;

}

int main()
{

    int n;
    City *mA;
    cout << "Input number of cities: " << endl;
    cin >> n;
    mA = new City[n];
    for (int j = 0; j < n; j++)
    {
        mA[j].Output();
    }
    cout << "Cities from west to east, sorted by their length" << endl;

    double max = mA[0].GetLength();
    for (int j = 1; j<n; j++)
    {
        if (mA[j - 1].GetLength()>mA[j].GetLength())
        {
            max = mA[j - 1].GetLength();

            mA[j - 1] = mA[j];
            mA[j] = max;
        }
    }
    for (int j = 0; j < n; j++)
    {
        mA[j].Output();
    }

    delete[]mA;
    return 0;

}


问:
ES6 javascript Subclass not inheriting all variables?
So basically I have an es6 js class where constructor variables are created then assigned within a class method.  Later I create a sub class that extends the first and pass all variables I wish to use to the subclass constructor and subsequently to the super method. After this one variable is correct and the other is undefined, both are created passed and logged in the same manner. Why would it be undefined??</p>

```<code>class socket {
  constructor() {
    this.socket = {};
    this.base = '/*string*/';
    this.mainIndex;
    this.dashboard;
    this.user_id;
  }

  socket_start() {

    //do stuff here to start websocket

    self.socket.onmessage = function ( event ) {
      let stream = JSON.parse( event.data );
      this.mainIndex = stream.url.mainIndex;
      this.dashboard = stream.url.dashboard;
      this.user_id = stream.staffInfo.id;
      this.base = stream.base;

      console.log( this.user_id ); // "1"
      console.log( this.base); // "string"
    }
  }
}

class main extends socket {
  constructor( user_id, base, socket, mainIndex, dashboard ) {
  super( user_id, base, socket, mainIndex, dashboard );

  console.log( this.user_id ); // undefined   <--????
  console.log( this.base); // "string"
}
</code>```

答:
Your parent class ignores any arguments that it is passed. Compare the two versions below:

```<code>class A {
  constructor() {
    this.name;
  }
}

class B extends A {
  constructor(name) {
    super(name)
  }
}

> new B("Hunter");
B {}
</code>```

Now an example with the correct behavior:

```<code>class A {
  constructor(name) {
    this.name = name;
  }
}

class B extends A {
  constructor(name) {
    super(name)
  }
}

> new B("Hunter");
B { name: 'Hunter' }
</code>```

Body:
So basically I have an es6 js class where constructor variables are created then assigned within a class method.  Later I create a sub class that extends the first and pass all variables I wish to use to the subclass constructor and subsequently to the super method. After this one variable is correct and the other is undefined, both are created passed and logged in the same manner. Why would it be undefined??

class socket {
  constructor() {
    this.socket = {};
    this.base = '/*string*/';
    this.mainIndex;
    this.dashboard;
    this.user_id;
  }

  socket_start() {

    //do stuff here to start websocket

    self.socket.onmessage = function ( event ) {
      let stream = JSON.parse( event.data );
      this.mainIndex = stream.url.mainIndex;
      this.dashboard = stream.url.dashboard;
      this.user_id = stream.staffInfo.id;
      this.base = stream.base;

      console.log( this.user_id ); // "1"
      console.log( this.base); // "string"
    }
  }
}

class main extends socket {
  constructor( user_id, base, socket, mainIndex, dashboard ) {
  super( user_id, base, socket, mainIndex, dashboard );

  console.log( this.user_id ); // undefined   <--????
  console.log( this.base); // "string"
}

Body:
Your parent class ignores any arguments that it is passed. Compare the two versions below:

class A {
  constructor() {
    this.name;
  }
}

class B extends A {
  constructor(name) {
    super(name)
  }
}

> new B("Hunter");
B {}

Now an example with the correct behavior:

class A {
  constructor(name) {
    this.name = name;
  }
}

class B extends A {
  constructor(name) {
    super(name)
  }
}

> new B("Hunter");
B { name: 'Hunter' }


问:
Correlate start/stop dates and sum their duration
UPDATE: At the bottom I added expected output with the table I had envisioned

My goal is two correlate downtime events to show causation of one event and the downtime it caused.

I have an overall schema of:

```<code>DECLARE @EquipmentDownTime TABLE
(
ID INT IDENTITY(1,1),
Equipment varchar(5),
Time DATETIME,
StartStop NVARCHAR(15)
)
</code>```

so a record looks like this:

```<code> 1, Motor, '18/8/2017 12:00:00', Stop
 2, Motor, '18/8/2017 12:10:00', Start
</code>```

I'm currently using a matching pairs table function to sum the total duration of downtime between user entered date ranged but I want to expand the functionality to say how long an event caused another based on those durations.

What I'm trying to do is correlate when another piece of equipment "Stop" is in between the record above and then determine it's total time of being. Using the Sample data below:

```<code>INSERT INTO @EquipmentDownTime (Equipment, [Time], StartStop)
VALUES
  ('Motor', '20170812 12:00:00', 'Stop'), --ID 1
  ('Valve', '20170812 12:05:00', 'Stop'), --ID 2
  ('Motor', '20170812 12:30:00', 'Start'), --ID 3
  ('Valve', '20170812 13:05:00', 'Start'), --ID 4
  ('Motor', '20170812 14:00:00', 'Stop'), --ID 5
  ('Valve', '20170812 14:05:00', 'Stop'), --ID 6
  ('Motor', '20170812 15:30:00', 'Start'), --ID 7
  ('Valve', '20170812 15:05:00', 'Start'); --ID 8
</code>```

In this case I would say ID 1 Caused 1 hour of downtime for ID 2 since it's stop fell in between 1 and 3 which are a Stop/Start Pair.

I imagine the end result would look something like this:

```<code> DECLARE @Causation TABLE
(
ID INT                     IDENTITY(1,1),
CauationEquipment          varchar(5),
CauationEquipmentShutdown  DATETIME,
AffectedEquipment          varchar(5),
AffectedEquipmentShutdown  DATETIME,
DurationOfAffectedEquip    INT
)
</code>```

Records Result (Causation Id and Affected, comes from Identity Id in @EquipmentDowntime Table):

```<code> 1, Motor, '20170812 12:00:00', Valve, '20170812 12:05:00', 60
 2, Motor, '20170812 14:00:00', Valve, '20170812 14:05:00', 60
</code>```

The piece I am missing here is effectively linking the correlation I have thought to use a while loop going through all the downtime events and grab the stop and its next start and store it in temp tables but it is getting messy.

SQL Server 2014

答:
I expanded upon what Larnu provided and this matches the output I expected in my question:

```<code>DECLARE @EquipmentDownTime TABLE
(
ID INT IDENTITY(1,1),
Equipment varchar(5),
Time DATETIME,
StartStop NVARCHAR(15)
)

INSERT INTO @EquipmentDownTime (Equipment, [Time], StartStop)
VALUES
  ('Motor', '20170812 12:00:00', 'Stop'), --ID 1
  ('Valve', '20170812 12:05:00', 'Stop'), --ID 2
  ('Motor', '20170812 12:30:00', 'Start'), --ID 3
  ('Valve', '20170812 13:05:00', 'Start'), --ID 4
  ('Motor', '20170812 14:00:00', 'Stop'), --ID 5
  ('Valve', '20170812 14:05:00', 'Stop'), --ID 6 --
  ('Motor', '20170812 14:30:00', 'Start'), --ID 7
  ('Valve', '20170812 15:05:00', 'Start'); --ID 8

 ;WITH
    Causation AS (
        SELECT ID,
        LAG(Equipment) OVER (ORDER BY [Time] ASC) AS LastEquipment,
        LAG([Time]) OVER (ORDER BY [Time] ASC) AS PrevEquipDownTime
        FROM @EquipmentDownTime
        ),
    Downtime AS (
        SELECT *,
        (LEAD([Time]) OVER (PARTITION BY Equipment ORDER BY [Time] ASC)) AS NextStatus
        FROM @EquipmentDownTime
        )
SELECT Downtime.ID,
       LastEquipment AS [CauationEquipment],
       PrevEquipDownTime AS [CauationEquipmentShutdown],
       Equipment   AS [Affected Equipment],
       Time AS [AffectedEquipmentShutdown],
       NextStatus,
       DATEDIFF(MINUTE,[Time],NextStatus) AS Duration
FROM Downtime
JOIN Causation
ON   Downtime.ID = Causation.ID
WHERE StartStop = 'Stop'
AND Equipment = 'Valve'
</code>```

Output:

```<code>2,  Motor,  2017-08-12 12:00:00.000,    Valve,  2017-08-12 12:05:00.000,    2017-08-12 13:05:00.000,    60
6,  Motor,  2017-08-12 14:00:00.000,    Valve,  2017-08-12 14:05:00.000,    2017-08-12 15:05:00.000,    60
</code>```

Body:
UPDATE: At the bottom I added expected output with the table I had envisioned

My goal is two correlate downtime events to show causation of one event and the downtime it caused.

I have an overall schema of:

DECLARE @EquipmentDownTime TABLE
(
ID INT IDENTITY(1,1),
Equipment varchar(5),
Time DATETIME,
StartStop NVARCHAR(15)
)

so a record looks like this:

 1, Motor, '18/8/2017 12:00:00', Stop
 2, Motor, '18/8/2017 12:10:00', Start

I'm currently using a matching pairs table function to sum the total duration of downtime between user entered date ranged but I want to expand the functionality to say how long an event caused another based on those durations.

What I'm trying to do is correlate when another piece of equipment "Stop" is in between the record above and then determine it's total time of being. Using the Sample data below:

INSERT INTO @EquipmentDownTime (Equipment, [Time], StartStop)
VALUES
  ('Motor', '20170812 12:00:00', 'Stop'), --ID 1
  ('Valve', '20170812 12:05:00', 'Stop'), --ID 2
  ('Motor', '20170812 12:30:00', 'Start'), --ID 3
  ('Valve', '20170812 13:05:00', 'Start'), --ID 4
  ('Motor', '20170812 14:00:00', 'Stop'), --ID 5
  ('Valve', '20170812 14:05:00', 'Stop'), --ID 6
  ('Motor', '20170812 15:30:00', 'Start'), --ID 7
  ('Valve', '20170812 15:05:00', 'Start'); --ID 8

In this case I would say ID 1 Caused 1 hour of downtime for ID 2 since it's stop fell in between 1 and 3 which are a Stop/Start Pair.

I imagine the end result would look something like this:

 DECLARE @Causation TABLE
(
ID INT                     IDENTITY(1,1),
CauationEquipment          varchar(5),
CauationEquipmentShutdown  DATETIME,
AffectedEquipment          varchar(5),
AffectedEquipmentShutdown  DATETIME,
DurationOfAffectedEquip    INT
)

Records Result (Causation Id and Affected, comes from Identity Id in @EquipmentDowntime Table):

 1, Motor, '20170812 12:00:00', Valve, '20170812 12:05:00', 60
 2, Motor, '20170812 14:00:00', Valve, '20170812 14:05:00', 60

The piece I am missing here is effectively linking the correlation I have thought to use a while loop going through all the downtime events and grab the stop and its next start and store it in temp tables but it is getting messy.

SQL Server 2014

Body:
I expanded upon what Larnu provided and this matches the output I expected in my question:

DECLARE @EquipmentDownTime TABLE
(
ID INT IDENTITY(1,1),
Equipment varchar(5),
Time DATETIME,
StartStop NVARCHAR(15)
)

INSERT INTO @EquipmentDownTime (Equipment, [Time], StartStop)
VALUES
  ('Motor', '20170812 12:00:00', 'Stop'), --ID 1
  ('Valve', '20170812 12:05:00', 'Stop'), --ID 2
  ('Motor', '20170812 12:30:00', 'Start'), --ID 3
  ('Valve', '20170812 13:05:00', 'Start'), --ID 4
  ('Motor', '20170812 14:00:00', 'Stop'), --ID 5
  ('Valve', '20170812 14:05:00', 'Stop'), --ID 6 --
  ('Motor', '20170812 14:30:00', 'Start'), --ID 7
  ('Valve', '20170812 15:05:00', 'Start'); --ID 8

 ;WITH
    Causation AS (
        SELECT ID,
        LAG(Equipment) OVER (ORDER BY [Time] ASC) AS LastEquipment,
        LAG([Time]) OVER (ORDER BY [Time] ASC) AS PrevEquipDownTime
        FROM @EquipmentDownTime
        ),
    Downtime AS (
        SELECT *,
        (LEAD([Time]) OVER (PARTITION BY Equipment ORDER BY [Time] ASC)) AS NextStatus
        FROM @EquipmentDownTime
        )
SELECT Downtime.ID,
       LastEquipment AS [CauationEquipment],
       PrevEquipDownTime AS [CauationEquipmentShutdown],
       Equipment   AS [Affected Equipment],
       Time AS [AffectedEquipmentShutdown],
       NextStatus,
       DATEDIFF(MINUTE,[Time],NextStatus) AS Duration
FROM Downtime
JOIN Causation
ON   Downtime.ID = Causation.ID
WHERE StartStop = 'Stop'
AND Equipment = 'Valve'

Output:

2,  Motor,  2017-08-12 12:00:00.000,    Valve,  2017-08-12 12:05:00.000,    2017-08-12 13:05:00.000,    60
6,  Motor,  2017-08-12 14:00:00.000,    Valve,  2017-08-12 14:05:00.000,    2017-08-12 15:05:00.000,    60


问:
How to constraint a child view controller's view to the tab bar's top anchor?

In the picture above I am trying to create a feature that can search through the Yelp APIs for a specific business. This child view view controller has a table view inside of it.

I add the child view controller to its parent using the following code:

```<code>func addChildBusinessSearchController(){

        businessSearchResultController = storyboard?.instantiateViewController(withIdentifier: "BusinessSearchResultController") as! BusinessSearchResultController
        businessSearchResultController.delegate = self
        businessSearchResultController.managedObjectContext = managedObjectContext

        view.addSubview(businessSearchResultController.view)
        self.addChildViewController(businessSearchResultController)
        businessSearchResultController.didMove(toParentViewController: self)

        businessSearchResultController.view.translatesAutoresizingMaskIntoConstraints = false
        let heightConstraint = businessSearchResultController.view.heightAnchor.constraint(equalToConstant: self.view.bounds.height)
        let leadingConstraint = businessSearchResultController.view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor)
        let widthConstraint = businessSearchResultController.view.widthAnchor.constraint(equalToConstant: self.view.bounds.width)
        let topViewUpperConstraint = businessSearchResultController.view.topAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor, constant: -55)
        topViewUpperConstraint.identifier = ChildControllersUpperConstraints.businessSearchResultControllerTopConstraintIdentifier

        NSLayoutConstraint.activate([heightConstraint, leadingConstraint, widthConstraint, topViewUpperConstraint])

        let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(businessSearchResultControllerdidPan(_:)))

        businessSearchResultController.view.addGestureRecognizer(panGestureRecognizer)

 }
</code>```

Within the child controller I try to constraint the table view so that is shows up on the screen with the correct dimensions:

```<code>   func setUpTableView(){

        tableView.translatesAutoresizingMaskIntoConstraints = false
        let topConstraint = tableView.topAnchor.constraint(equalTo: headerView.bottomAnchor)
        let leadingConstraint = tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor)
        let trailingConstraint = tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
        let heightConstraint = tableView.heightAnchor.constraint(equalToConstant: 450)

        NSLayoutConstraint.activate([topConstraint, leadingConstraint, trailingConstraint, heightConstraint])
        tableView.clipsToBounds = true
        tableView.backgroundColor = UIColor.clear
 }
</code>```

However, I have one problem: I seem to be having trouble constraining the bottom of the table view in "BusinessSearchResultController" to the top of the tab bar so that it fills all the space intended for the this table view. I understand that this is because I am giving it a non-dynamic height of 450 in the following code:

let heightConstraint = tableView.heightAnchor.constraint(equalToConstant: 450)

But I have tried different ways to achieve the correct height for this table view including constraining its bottomAnchor to the topAnchor of its parent bottomLayoutGuide which of course results in an error because they don't have a common ancestor.

Any help in resolving this issue will be much appreciated...

答:
Your table view is a subview of your BusinessSearchResultController.

You don't want a height constraint on your table view, you want to constrain the bottom of the  table view to the bottom of its superview -- the same way you are setting its leading and trailing constraints.

Then, constrain the bottom of businessSearchResultController.view to the bottom of its superview, the same way your are setting its leading and trailing constraints.

Body:
In the picture above I am trying to create a feature that can search through the Yelp APIs for a specific business. This child view view controller has a table view inside of it.

I add the child view controller to its parent using the following code:

func addChildBusinessSearchController(){

        businessSearchResultController = storyboard?.instantiateViewController(withIdentifier: "BusinessSearchResultController") as! BusinessSearchResultController
        businessSearchResultController.delegate = self
        businessSearchResultController.managedObjectContext = managedObjectContext

        view.addSubview(businessSearchResultController.view)
        self.addChildViewController(businessSearchResultController)
        businessSearchResultController.didMove(toParentViewController: self)

        businessSearchResultController.view.translatesAutoresizingMaskIntoConstraints = false
        let heightConstraint = businessSearchResultController.view.heightAnchor.constraint(equalToConstant: self.view.bounds.height)
        let leadingConstraint = businessSearchResultController.view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor)
        let widthConstraint = businessSearchResultController.view.widthAnchor.constraint(equalToConstant: self.view.bounds.width)
        let topViewUpperConstraint = businessSearchResultController.view.topAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor, constant: -55)
        topViewUpperConstraint.identifier = ChildControllersUpperConstraints.businessSearchResultControllerTopConstraintIdentifier

        NSLayoutConstraint.activate([heightConstraint, leadingConstraint, widthConstraint, topViewUpperConstraint])

        let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(businessSearchResultControllerdidPan(_:)))

        businessSearchResultController.view.addGestureRecognizer(panGestureRecognizer)

 }

Within the child controller I try to constraint the table view so that is shows up on the screen with the correct dimensions:

   func setUpTableView(){

        tableView.translatesAutoresizingMaskIntoConstraints = false
        let topConstraint = tableView.topAnchor.constraint(equalTo: headerView.bottomAnchor)
        let leadingConstraint = tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor)
        let trailingConstraint = tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor)
        let heightConstraint = tableView.heightAnchor.constraint(equalToConstant: 450)

        NSLayoutConstraint.activate([topConstraint, leadingConstraint, trailingConstraint, heightConstraint])
        tableView.clipsToBounds = true
        tableView.backgroundColor = UIColor.clear
 }

However, I have one problem: I seem to be having trouble constraining the bottom of the table view in "BusinessSearchResultController" to the top of the tab bar so that it fills all the space intended for the this table view. I understand that this is because I am giving it a non-dynamic height of 450 in the following code:

let heightConstraint = tableView.heightAnchor.constraint(equalToConstant: 450)

But I have tried different ways to achieve the correct height for this table view including constraining its bottomAnchor to the topAnchor of its parent bottomLayoutGuide which of course results in an error because they don't have a common ancestor.

Any help in resolving this issue will be much appreciated...


问:
Python: Find all symetrics pairs in Dataframe

I have a dataframe with columns let's call them A and B, I want to find all symetrics pairs for example if :

```<code>pd.DataFrame({'A':[1, 2 , 3], 'B':[2, 1, 3]})
</code>```

I want to return all pairs like here I will get (I actually don't need both only (2,1) or (2,1) is enough)

```<code>(1,2) and (2,1)
</code>```

I have first tried an algorithm which works but is really slow in my dataframe of length 26325 after 10 minute it wasn't finished

```<code>listTuples = list()
for index, row in test.iterrows():
    listTuples.append((row["A"], row["B"])) # convert to a list of tuple

answer = [(x, y) for (x, y) in listTuples if (y, x) in listTuples]
</code>```

答:
In general you pretty much never have to iterate over rows in a pandas dataframe. In this case, you could speed things up with

```<code>listTuples = zip(df.A,df.B)
</code>```

If that's the part of your code that is running slowly, that should solve your problem.

Your list comprehension step looks efficient to me... your problem could be that you have many duplicate entries in the list that you continually check. Start by picking out only the unique ones, and then running your list comprehension.

Also see this stack overflow question about picking unique tuples from a list of tuples in python.

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe with columns let's call them A and B, I want to find all symetrics pairs for example if :

pd.DataFrame({'A':[1, 2 , 3], 'B':[2, 1, 3]})

I want to return all pairs like here I will get (I actually don't need both only (2,1) or (2,1) is enough)

(1,2) and (2,1)

I have first tried an algorithm which works but is really slow in my dataframe of length 26325 after 10 minute it wasn't finished

listTuples = list()
for index, row in test.iterrows():
    listTuples.append((row["A"], row["B"])) # convert to a list of tuple

answer = [(x, y) for (x, y) in listTuples if (y, x) in listTuples]

Body:
In general you pretty much never have to iterate over rows in a pandas dataframe. In this case, you could speed things up with

listTuples = zip(df.A,df.B)

If that's the part of your code that is running slowly, that should solve your problem.

Your list comprehension step looks efficient to me... your problem could be that you have many duplicate entries in the list that you continually check. Start by picking out only the unique ones, and then running your list comprehension.

Also see this stack overflow question about picking unique tuples from a list of tuples in python.


问:
How to use multiple input parameters in ASP.NET Web API and getting data from database by stored procedure
I am using multiple input parameters in my ASP.NET Web API application but I am not getting the output.

My code is here:

```<code>[HttpGet]
[Route("api/tblProducts/{Price1}/{Price2}/{CategoryId}/{Color}/{Size}")]
[ResponseType(typeof(IEnumerable<GetSimilarProducts_Result>))]
public IHttpActionResult GetSimlarProduct(Decimal Price1,Decimal Price2,string CategoryId, string Color, string Size)
{
    IEnumerable<GetSimilarProducts_Result> tblSmlrProduct = db.GetSimilarProducts(Price1, Price2,CategoryId, Color, Size ).AsEnumerable();

    if (tblSmlrProduct == null)
    {
        return NotFound();
    }

    return Ok(tblSmlrProduct);
}
</code>```

and I using given URI for accessing it

```<code>   http://localhost:54393/api/tblProducts/GetsimlarProduct?Price1=1000&Price2=10000&CategoryId=Cat102&Color=Black&Size=M
</code>```

Please help me how I can get data from database and my other stored procedure working well
My method code made by visual studio

```<code>public virtual ObjectResult<GetSimilarProducts_Result> GetSimilarProducts(Nullable<decimal> price1, Nullable<decimal> price2, string size, string categoryId, string color)
        {
            var price1Parameter = price1.HasValue ?
                new ObjectParameter("Price1", price1) :
                new ObjectParameter("Price1", typeof(decimal));

            var price2Parameter = price2.HasValue ?
                new ObjectParameter("Price2", price2) :
                new ObjectParameter("Price2", typeof(decimal));

            var sizeParameter = size != null ?
                new ObjectParameter("Size", size) :
                new ObjectParameter("Size", typeof(string));

            var categoryIdParameter = categoryId != null ?
                new ObjectParameter("CategoryId", categoryId) :
                new ObjectParameter("CategoryId", typeof(string));

            var colorParameter = color != null ?
                new ObjectParameter("Color", color) :
                new ObjectParameter("Color", typeof(string));

            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<GetSimilarProducts_Result>("GetSimilarProducts", price1Parameter, price2Parameter, sizeParameter, categoryIdParameter, colorParameter);
        }
</code>```

and this is my stored procedure code

```<code>USE [MakaAnOrderDB]
GO

/****** Object:  StoredProcedure [dbo].[GetSimilarProducts]    Script Date: 12/14/2017 12:44:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[GetSimilarProducts]
(@Price1 decimal(18,0),@Price2 decimal(18,0),@Size nvarchar(max),@CategoryId nvarchar(255),@Color nvarchar(20))

As
Begin
Select top(20)* from tblProduct where PrdPrice Between @Price1 And @Price2 And PrdSize=@Size And PrdColor=@Color
End

GO
</code>```

Update : my stored procedure which is working well

```<code>USE [MakaAnOrderDB]
GO

/****** Object:  StoredProcedure [dbo].[SingleProductDetails]    Script Date: 12/14/2017 12:44:24 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[SingleProductDetails]
@ProductId nvarchar(255)=''
As
Begin
Select* from tblProduct where ProductId=@ProductId

End

GO
</code>```

Update: this is c# code of fetching information from SingleProductDetails Procedure

```<code>[HttpGet]
        [Route("api/tblProducts/{productId}")]
        [ResponseType(typeof(IEnumerable<SingleProductDetails_Result>))]
        public IHttpActionResult Get(string productId)
        {
            IEnumerable<SingleProductDetails_Result> tblProduct = db.SingleProductDetails(productId).AsEnumerable();
            if (tblProduct == null)
            {
                return NotFound();
            }

            return Ok(tblProduct);
        }
</code>```

update:Code made by visual studio for procedure sigleProductDetails

```<code>public virtual ObjectResult<SingleProductDetails_Result> SingleProductDetails(string productId)
        {
            var productIdParameter = productId != null ?
                new ObjectParameter("ProductId", productId) :
                new ObjectParameter("ProductId", typeof(string));

            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<SingleProductDetails_Result>("SingleProductDetails", productIdParameter);
        }
</code>```

答:
You should follow your Route-Template:

```<code>[Route("api/tblProducts/{Price1}/{Price2}/{CategoryId}/{Color}/{Size}")]
</code>```

So instead of:

```<code>http://localhost:54393/api/tblProducts/GetsimlarProduct?Price1=1000&Price2=10000&CategoryId=Cat102&Color=Black&Size=M
</code>```

Use:

```<code>http://localhost:54393/api/tblProducts/1000/10000/Cat102/Black/M
</code>```

Update:
If you want to get not found in case of an empty result you also should change your if-Statement:
Replace:

```<code>if (tblSmlrProduct == null)
</code>```

With:

```<code>if (tblSmlrProduct == null || tblSmlrProduct.Count()==0)
</code>```

My method code made by visual studio

```<code>public virtual ObjectResult<GetSimilarProducts_Result> GetSimilarProducts(Nullable<decimal> price1, Nullable<decimal> price2, string size, string categoryId, string color)
        {
            var price1Parameter = price1.HasValue ?
                new ObjectParameter("Price1", price1) :
                new ObjectParameter("Price1", typeof(decimal));

            var price2Parameter = price2.HasValue ?
                new ObjectParameter("Price2", price2) :
                new ObjectParameter("Price2", typeof(decimal));

            var sizeParameter = size != null ?
                new ObjectParameter("Size", size) :
                new ObjectParameter("Size", typeof(string));

            var categoryIdParameter = categoryId != null ?
                new ObjectParameter("CategoryId", categoryId) :
                new ObjectParameter("CategoryId", typeof(string));

            var colorParameter = color != null ?
                new ObjectParameter("Color", color) :
                new ObjectParameter("Color", typeof(string));

            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<GetSimilarProducts_Result>("GetSimilarProducts", price1Parameter, price2Parameter, sizeParameter, categoryIdParameter, colorParameter);
        }
</code>```

and this is my stored procedure code

```<code>USE [MakaAnOrderDB]
GO

/****** Object:  StoredProcedure [dbo].[GetSimilarProducts]    Script Date: 12/14/2017 12:44:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[GetSimilarProducts]
(@Price1 decimal(18,0),@Price2 decimal(18,0),@Size nvarchar(max),@CategoryId nvarchar(255),@Color nvarchar(20))

As
Begin
Select top(20)* from tblProduct where PrdPrice Between @Price1 And @Price2 And PrdSize=@Size And PrdColor=@Color
End

GO
</code>```

Update: As you edited my answer I will add the solution at the end:
As stored procedure doesn't have a return value, you can see the result in the output-window when running in SSMS, but get nothing back into your application. Your stored procedure has to be changed to a stored function like this:

```<code>USE [MakaAnOrderDB]
GO

/****** Object:  StoredProcedure [dbo].[GetSimilarProducts]    Script Date: 12/14/2017 12:44:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE function [dbo].[GetSimilarProducts]
(@Price1 decimal(18,0),@Price2 decimal(18,0),@Size nvarchar(max),@CategoryId nvarchar(255),@Color nvarchar(20))

As
Begin
Return Select top(20)* from tblProduct where PrdPrice Between @Price1 And @Price2 And PrdSize=@Size And PrdColor=@Color
End

GO
</code>```

Body:
I am using multiple input parameters in my ASP.NET Web API application but I am not getting the output.

My code is here:

[HttpGet]
[Route("api/tblProducts/{Price1}/{Price2}/{CategoryId}/{Color}/{Size}")]
[ResponseType(typeof(IEnumerable<GetSimilarProducts_Result>))]
public IHttpActionResult GetSimlarProduct(Decimal Price1,Decimal Price2,string CategoryId, string Color, string Size)
{
    IEnumerable<GetSimilarProducts_Result> tblSmlrProduct = db.GetSimilarProducts(Price1, Price2,CategoryId, Color, Size ).AsEnumerable();

    if (tblSmlrProduct == null)
    {
        return NotFound();
    }

    return Ok(tblSmlrProduct);
}

and I using given URI for accessing it

   http://localhost:54393/api/tblProducts/GetsimlarProduct?Price1=1000&Price2=10000&CategoryId=Cat102&Color=Black&Size=M

Please help me how I can get data from database and my other stored procedure working well
My method code made by visual studio

public virtual ObjectResult<GetSimilarProducts_Result> GetSimilarProducts(Nullable<decimal> price1, Nullable<decimal> price2, string size, string categoryId, string color)
        {
            var price1Parameter = price1.HasValue ?
                new ObjectParameter("Price1", price1) :
                new ObjectParameter("Price1", typeof(decimal));

            var price2Parameter = price2.HasValue ?
                new ObjectParameter("Price2", price2) :
                new ObjectParameter("Price2", typeof(decimal));

            var sizeParameter = size != null ?
                new ObjectParameter("Size", size) :
                new ObjectParameter("Size", typeof(string));

            var categoryIdParameter = categoryId != null ?
                new ObjectParameter("CategoryId", categoryId) :
                new ObjectParameter("CategoryId", typeof(string));

            var colorParameter = color != null ?
                new ObjectParameter("Color", color) :
                new ObjectParameter("Color", typeof(string));

            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<GetSimilarProducts_Result>("GetSimilarProducts", price1Parameter, price2Parameter, sizeParameter, categoryIdParameter, colorParameter);
        }

and this is my stored procedure code

USE [MakaAnOrderDB]
GO

/****** Object:  StoredProcedure [dbo].[GetSimilarProducts]    Script Date: 12/14/2017 12:44:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[GetSimilarProducts]
(@Price1 decimal(18,0),@Price2 decimal(18,0),@Size nvarchar(max),@CategoryId nvarchar(255),@Color nvarchar(20))

As
Begin
Select top(20)* from tblProduct where PrdPrice Between @Price1 And @Price2 And PrdSize=@Size And PrdColor=@Color
End

GO

Update : my stored procedure which is working well

USE [MakaAnOrderDB]
GO

/****** Object:  StoredProcedure [dbo].[SingleProductDetails]    Script Date: 12/14/2017 12:44:24 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE Procedure [dbo].[SingleProductDetails]
@ProductId nvarchar(255)=''
As
Begin
Select* from tblProduct where ProductId=@ProductId

End

GO

Update: this is c# code of fetching information from SingleProductDetails Procedure

[HttpGet]
        [Route("api/tblProducts/{productId}")]
        [ResponseType(typeof(IEnumerable<SingleProductDetails_Result>))]
        public IHttpActionResult Get(string productId)
        {
            IEnumerable<SingleProductDetails_Result> tblProduct = db.SingleProductDetails(productId).AsEnumerable();
            if (tblProduct == null)
            {
                return NotFound();
            }

            return Ok(tblProduct);
        }

update:Code made by visual studio for procedure sigleProductDetails

public virtual ObjectResult<SingleProductDetails_Result> SingleProductDetails(string productId)
        {
            var productIdParameter = productId != null ?
                new ObjectParameter("ProductId", productId) :
                new ObjectParameter("ProductId", typeof(string));

            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<SingleProductDetails_Result>("SingleProductDetails", productIdParameter);
        }

Body:
You should follow your Route-Template:

[Route("api/tblProducts/{Price1}/{Price2}/{CategoryId}/{Color}/{Size}")]

So instead of:

http://localhost:54393/api/tblProducts/GetsimlarProduct?Price1=1000&Price2=10000&CategoryId=Cat102&Color=Black&Size=M

Use:

http://localhost:54393/api/tblProducts/1000/10000/Cat102/Black/M

Update:
If you want to get not found in case of an empty result you also should change your if-Statement:
Replace:

if (tblSmlrProduct == null)

With:

if (tblSmlrProduct == null || tblSmlrProduct.Count()==0)

My method code made by visual studio

public virtual ObjectResult<GetSimilarProducts_Result> GetSimilarProducts(Nullable<decimal> price1, Nullable<decimal> price2, string size, string categoryId, string color)
        {
            var price1Parameter = price1.HasValue ?
                new ObjectParameter("Price1", price1) :
                new ObjectParameter("Price1", typeof(decimal));

            var price2Parameter = price2.HasValue ?
                new ObjectParameter("Price2", price2) :
                new ObjectParameter("Price2", typeof(decimal));

            var sizeParameter = size != null ?
                new ObjectParameter("Size", size) :
                new ObjectParameter("Size", typeof(string));

            var categoryIdParameter = categoryId != null ?
                new ObjectParameter("CategoryId", categoryId) :
                new ObjectParameter("CategoryId", typeof(string));

            var colorParameter = color != null ?
                new ObjectParameter("Color", color) :
                new ObjectParameter("Color", typeof(string));

            return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<GetSimilarProducts_Result>("GetSimilarProducts", price1Parameter, price2Parameter, sizeParameter, categoryIdParameter, colorParameter);
        }

and this is my stored procedure code

USE [MakaAnOrderDB]
GO

/****** Object:  StoredProcedure [dbo].[GetSimilarProducts]    Script Date: 12/14/2017 12:44:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [dbo].[GetSimilarProducts]
(@Price1 decimal(18,0),@Price2 decimal(18,0),@Size nvarchar(max),@CategoryId nvarchar(255),@Color nvarchar(20))

As
Begin
Select top(20)* from tblProduct where PrdPrice Between @Price1 And @Price2 And PrdSize=@Size And PrdColor=@Color
End

GO

Update: As you edited my answer I will add the solution at the end:
As stored procedure doesn't have a return value, you can see the result in the output-window when running in SSMS, but get nothing back into your application. Your stored procedure has to be changed to a stored function like this:

USE [MakaAnOrderDB]
GO

/****** Object:  StoredProcedure [dbo].[GetSimilarProducts]    Script Date: 12/14/2017 12:44:09 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE function [dbo].[GetSimilarProducts]
(@Price1 decimal(18,0),@Price2 decimal(18,0),@Size nvarchar(max),@CategoryId nvarchar(255),@Color nvarchar(20))

As
Begin
Return Select top(20)* from tblProduct where PrdPrice Between @Price1 And @Price2 And PrdSize=@Size And PrdColor=@Color
End

GO


问:
How do I output content to a HttpServletResponse buffer?
I'm using Spring 4.3.8.RELEASE.  I want to set an error message for a particular Forbidden error.  I have this in my controller.  "response" is of the type "javax.servlet.HttpServletResponse".

```<code>        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentLength(errorMsg.length());
        byte[] buffer = new byte[10240];
        final OutputStream output = response.getOutputStream();
        output.write(buffer, 0, errorMsg.length());
        output.flush();
</code>```

However, the content doesn't seem to be getting returned, at least I can't see it in my unit test ...

```<code>    final MvcResult result = mockMvc.perform(get(contextPath + "/myurl")
                    .contextPath(contextPath)
                    .principal(auth)
                    .param("param1", param1)
                    .param("param2", param2))
        .andExpect(status().isForbidden())
        .andReturn();
    // Verify the error message is correct
    final String msgKey = "error.code";
    final String errorMsg = MessageFormat.format(resourceBundle.getString(msgKey), new Object[] {});
    Assert.assertEquals("Failed to return proper error message.", errorMsg, result.getResponse().getContentAsString());
</code>```

The assertion failed saying that the response string was empty.  What is teh proper way to write the response back to the HttpServletResponse buffer?

答:
you can use the response entity

```<code>@RequestMapping("/handle")
public ResponseEntity<String> handle() {

   HttpHeaders responseHeaders = new HttpHeaders();
   responseHeaders.setLocation(location);
   responseHeaders.set("MyResponseHeader", "MyValue");
   return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.FORBIDDEN);
 }
</code>```

Spring Response Entity

Body:
I'm using Spring 4.3.8.RELEASE.  I want to set an error message for a particular Forbidden error.  I have this in my controller.  "response" is of the type "javax.servlet.HttpServletResponse".

        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentLength(errorMsg.length());
        byte[] buffer = new byte[10240];
        final OutputStream output = response.getOutputStream();
        output.write(buffer, 0, errorMsg.length());
        output.flush();

However, the content doesn't seem to be getting returned, at least I can't see it in my unit test ...

    final MvcResult result = mockMvc.perform(get(contextPath + "/myurl")
                    .contextPath(contextPath)
                    .principal(auth)
                    .param("param1", param1)
                    .param("param2", param2))
        .andExpect(status().isForbidden())
        .andReturn();
    // Verify the error message is correct
    final String msgKey = "error.code";
    final String errorMsg = MessageFormat.format(resourceBundle.getString(msgKey), new Object[] {});
    Assert.assertEquals("Failed to return proper error message.", errorMsg, result.getResponse().getContentAsString());

The assertion failed saying that the response string was empty.  What is teh proper way to write the response back to the HttpServletResponse buffer?

Body:
you can use the response entity

@RequestMapping("/handle")
public ResponseEntity<String> handle() {

   HttpHeaders responseHeaders = new HttpHeaders();
   responseHeaders.setLocation(location);
   responseHeaders.set("MyResponseHeader", "MyValue");
   return new ResponseEntity<String>("Hello World", responseHeaders, HttpStatus.FORBIDDEN);
 }

Spring Response Entity


问:
set array to property of a structure
I'm using C#. Trying to do a structure with array property. It is my code:

```<code>namespace ConsoleApplication3

{
    struct Dummy
    {
        public bool one;
        public string two;
        public int[] three;

        public Dummy(bool o, string t, int[] th)
        {
            one = o; two=t; three=th;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
           int[] K = {5,2};
           Dummy d = new Dummy(true, "mnm", K);
            Console.WriteLine("{0} {1} {2}", d.one, d.two, d.three);

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}
</code>```

However d.three is System.Int32[] but not {5, 2}. How can I fix it?

答:
Because the Console.WriteLine will call the ToString() on object of int[] for the parameter d.three and it will return the type name actually, so you would need to convert the all array items in to a concatenated string, you can use String.Join here:

```<code>Console.WriteLine("{0} {1} {2}", d.one, d.two, String.Join(",",d.three));
</code>```

Now this will give the expected output which would be comma separated array items.

Title: set array to property of a structure

Body:
I'm using C#. Trying to do a structure with array property. It is my code:

namespace ConsoleApplication3

{
    struct Dummy
    {
        public bool one;
        public string two;
        public int[] three;

        public Dummy(bool o, string t, int[] th)
        {
            one = o; two=t; three=th;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
           int[] K = {5,2};
           Dummy d = new Dummy(true, "mnm", K);
            Console.WriteLine("{0} {1} {2}", d.one, d.two, d.three);

            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }
    }
}

However d.three is System.Int32[] but not {5, 2}. How can I fix it?

Body:
Because the Console.WriteLine will call the ToString() on object of int[] for the parameter d.three and it will return the type name actually, so you would need to convert the all array items in to a concatenated string, you can use String.Join here:

Console.WriteLine("{0} {1} {2}", d.one, d.two, String.Join(",",d.three));

Now this will give the expected output which would be comma separated array items.


问:
Error when evaluating the CDF of normal distribution with SymPy
I would like to use the SymPy normal distribution as I do some symbolic calculations with it.

```<code>from sympy.stats import Normal, cdf
from scipy.stats import norm

norm.cdf(10, 10, 0.1)

def survival(x):
    y = Normal("x", 10, 0.1)
    return cdf(y)(x)

survival(10)
</code>```

This code yields the following error:

```<code>UnboundLocalError: local variable 'reprec' referenced before assignment
</code>```

It is noted that with the following adjustment it seems to work:

```<code>return cdf(y, meijerg=False)(x)
</code>```

Can someone explain this behaviour?

答:
General points:

SymPy stats module has some room for improvement. In particular, the documentation acknowledges that the CDF returned for normal random variables "needs some help" from simplify to become usable.

Floating point numbers, especially those that are not represented precisely in binary system, are poison for SymPy. You think you are passing in 0.1, but it's really 3602879701896397/36028797018963968 and a symbolic integration routine is having a fit.

Concerning the first point; the following example shows that cdf(x)(t) is a risky proposition.

```<code>>>> x = Normal('x', 1, 1)
>>> cdf(x)(1)
nan
</code>```

The problem is that unsimplified cdf has division by _z-1. Better approach:

```<code>>>> simplify(cdf(x))(1)
1/2
</code>```

Concerning the second: since the CDF is computed by symbolic integration, passing floating point numbers as parameters can make the life of integrator hard enough that it hits some deeply hidden bug using Meijer G-functions for integration. Use Rational(1, 10) or S(1)/10 to create a rational number 1/10 instead of decimal 0.1.

```<code>>>> from sympy import S
>>> x = Normal("x", 10, S(1)/10)
>>> simplify(cdf(x))(10)
1/2
</code>```

Body:
I would like to use the SymPy normal distribution as I do some symbolic calculations with it.

from sympy.stats import Normal, cdf
from scipy.stats import norm

norm.cdf(10, 10, 0.1)

def survival(x):
    y = Normal("x", 10, 0.1)
    return cdf(y)(x)

survival(10)

This code yields the following error:

UnboundLocalError: local variable 'reprec' referenced before assignment

It is noted that with the following adjustment it seems to work:

return cdf(y, meijerg=False)(x)

Can someone explain this behaviour?

Body:
General points:

SymPy stats module has some room for improvement. In particular, the documentation acknowledges that the CDF returned for normal random variables "needs some help" from simplify to become usable.

Floating point numbers, especially those that are not represented precisely in binary system, are poison for SymPy. You think you are passing in 0.1, but it's really 3602879701896397/36028797018963968 and a symbolic integration routine is having a fit.

Concerning the first point; the following example shows that cdf(x)(t) is a risky proposition.

>>> x = Normal('x', 1, 1)
>>> cdf(x)(1)
nan

The problem is that unsimplified cdf has division by _z-1. Better approach:

>>> simplify(cdf(x))(1)
1/2

Concerning the second: since the CDF is computed by symbolic integration, passing floating point numbers as parameters can make the life of integrator hard enough that it hits some deeply hidden bug using Meijer G-functions for integration. Use Rational(1, 10) or S(1)/10 to create a rational number 1/10 instead of decimal 0.1.

>>> from sympy import S
>>> x = Normal("x", 10, S(1)/10)
>>> simplify(cdf(x))(10)
1/2


问:
How to reduce File IO on legacy app that writes to disk, and app that reads it in real time (.NET)
My situation is I have a legacy app which I don't have the code for which writes out data to disk every second or so. I have a C# program I wrote which every second reads what was written to disk and uses the data. The data is written to a few text files which I know the file name before its created.

The issue is I have lots of virtual machines running this legacy app and my program. They are not limited by ram or cpu but I can't add more than 10 VMs per machine due to file io bottleneck.

Is there an easy way I can make a file on disk that exists in ram or something else? I heard something about named pipes being an option?

Thanks!

答:
You can search for some kind of memory/temporary file systems.

RAM drive for compiling - is there such a thing?

http://256stuff.com/gray/docs/misc/linux_memory_tmp_filesystem_fs.shtml

I'm not sure if you can use pipes here since you legacy app is writing directly to the HDD.

ContentLicense: CC BY-SA 2.5


问:
Is there way to use interpolation inside *ngFor
```<code><div *ngFor="let t of {{randomName}}"></div>
</code>```

I want to pass the array name dynamically, i tried above code but i got error.

Thanks for answers but i have to update the question with my scenario

```<code><div formArrayName="{{obj.key}}">
 <div *ngFor="let t of formGrp.controls.{{obj.key}}.controls"></div>
</div>
</code>```

I am creating form array dynamically and it can have any name depending on schema. I   am able to bind that dynamic name to formArrayName as it supports interpolation but i need same behaviour on loop also

答:
It should be easy by using square brackets notation:

```<code><div *ngFor="let t of formGrp.controls[obj.key].controls"></div>
                                      ^^^^^^^^^
</code>```

Stackblitz Example

Body:
I want to pass the array name dynamically, i tried above code but i got error.

Thanks for answers but i have to update the question with my scenario

I am creating form array dynamically and it can have any name depending on schema. I   am able to bind that dynamic name to formArrayName as it supports interpolation but i need same behaviour on loop also

Body:
It should be easy by using square brackets notation:

<div *ngFor="let t of formGrp.controls[obj.key].controls"></div>
                                      ^^^^^^^^^

Stackblitz Example


问:
Nested if statement?
I'm trying to make a button that puts text that I need in TextView on specific EditText conditions, when EditText is empty, TextView is showing right text, but when I write numbers into the EditText field and press the button - program crashes.

```<code>    public void Guess(View view) {
    EditText Spejimas = (EditText) findViewById(R.id.guess);
    Tekstas = (TextView) findViewById(R.id.textView3);

    if (Spejimas.getText().length() == 0) {
        Tekstas.setText("Oops, you forgot to type your guess!");
    } else if (Spejimas.getText().length() != 0) {
        int Guessas = Integer.parseInt(Spejimas.toString());
        if (Guessas == number) {
            Tekstas.setText("Congratulations! You got it right!");
        } else if (Guessas > number) {
            Tekstas.setText("Your number is too high, try again!");
        } else if (Guessas < number) {
            Tekstas.setText("Your number is too low, try again!");
        }
    }
}
</code>```

I want TextView to say: "Congratulations! You got it right!", when Guessas is equal to number, "Your number is too high, try again!", when Guessas is higher than number and "Your number is too low, try again!", when Guessas is lower than number.

When I'm pressing the button that triggers this block of code when EditText has number(s) in it, program crashes.

答:
Change the code from

```<code>int Guessas = Integer.parseInt(Spejimas.toString());
</code>```

to

```<code>int Guessas = Integer.parseInt(Spejimas.getText().toString());
</code>```

Problem is Integer.parseInt() excepting string value containing only numbers. Here you are  trying to send the edittext as string. While converting edit text to string which contains characters other than numbers.

Title: Nested if statement?

Body:
I'm trying to make a button that puts text that I need in TextView on specific EditText conditions, when EditText is empty, TextView is showing right text, but when I write numbers into the EditText field and press the button - program crashes.

    public void Guess(View view) {
    EditText Spejimas = (EditText) findViewById(R.id.guess);
    Tekstas = (TextView) findViewById(R.id.textView3);

    if (Spejimas.getText().length() == 0) {
        Tekstas.setText("Oops, you forgot to type your guess!");
    } else if (Spejimas.getText().length() != 0) {
        int Guessas = Integer.parseInt(Spejimas.toString());
        if (Guessas == number) {
            Tekstas.setText("Congratulations! You got it right!");
        } else if (Guessas > number) {
            Tekstas.setText("Your number is too high, try again!");
        } else if (Guessas < number) {
            Tekstas.setText("Your number is too low, try again!");
        }
    }
}

I want TextView to say: "Congratulations! You got it right!", when Guessas is equal to number, "Your number is too high, try again!", when Guessas is higher than number and "Your number is too low, try again!", when Guessas is lower than number.

When I'm pressing the button that triggers this block of code when EditText has number(s) in it, program crashes.

Body:
Change the code from

int Guessas = Integer.parseInt(Spejimas.toString());

to

int Guessas = Integer.parseInt(Spejimas.getText().toString());

Problem is Integer.parseInt() excepting string value containing only numbers. Here you are  trying to send the edittext as string. While converting edit text to string which contains characters other than numbers.


问:
How to conduct iterative steps with multiple data frames in python ?
I collected some data in the lab and it is stored in multiple excel sheets. I loaded the excel sheets into data frames and now I want to perform the same function for each data frame but i am not sure how.</p>

```<code>df = pd.read_csv("TRSCE_5_1.csv")
df1 = pd.read_csv("TRSCE_5_2.csv")

def Function_plot() :
    X = df[["Frequency(Hz)"]].values
    y = df[" R(Ohm)-data"].values
    y1 = df[" X(Ohm)-data"].values
    plt.title("Resistance vs. Frequency")
    plt.plot(X, y, label = 'Resistance')
    plt.plot(X, y1, label= 'Reactance')
    plt.ylabel('ylabel')
    plt.xlabel('xlabel')
    plt.legend()

    plt.xlabel("Frequency", size=20)
    plt.ylabel("Resistance", size=20)
for each df in [df,df1,df2...,df8]
    Function_plot(df)
</code>```

答:
You can try the code below:

```<code>    import glob

    pattern = 'TRSCE*.csv'

    csv_files = glob.glob(pattern)

    df_list = []

    for csv in csv_files:
        df = pd.read_csv(csv)

        # Fill the data frame list
        df_list.append(df)

        # Plot the data frame using your user defined function
        Function_plot(df)
</code>```

Note that in the last line above your user function is modified to accept a single data frame argument. So the signature of your function needs to change to:

```<code>    def Function_plot(df)
        # then the function body
</code>```

I noticed that the syntax of your for loop in your code has a mistake. If you want to plot in a separate loop then use:

```<code>    for each in df_list:
        Function_plot(each)
</code>```

Body:
I collected some data in the lab and it is stored in multiple excel sheets. I loaded the excel sheets into data frames and now I want to perform the same function for each data frame but i am not sure how.

df = pd.read_csv("TRSCE_5_1.csv")
df1 = pd.read_csv("TRSCE_5_2.csv")

def Function_plot() :
    X = df[["Frequency(Hz)"]].values
    y = df[" R(Ohm)-data"].values
    y1 = df[" X(Ohm)-data"].values
    plt.title("Resistance vs. Frequency")
    plt.plot(X, y, label = 'Resistance')
    plt.plot(X, y1, label= 'Reactance')
    plt.ylabel('ylabel')
    plt.xlabel('xlabel')
    plt.legend()

    plt.xlabel("Frequency", size=20)
    plt.ylabel("Resistance", size=20)
for each df in [df,df1,df2...,df8]
    Function_plot(df)

Body:
You can try the code below:

    import glob

    pattern = 'TRSCE*.csv'

    csv_files = glob.glob(pattern)

    df_list = []

    for csv in csv_files:
        df = pd.read_csv(csv)

        # Fill the data frame list
        df_list.append(df)

        # Plot the data frame using your user defined function
        Function_plot(df)

Note that in the last line above your user function is modified to accept a single data frame argument. So the signature of your function needs to change to:

    def Function_plot(df)
        # then the function body

I noticed that the syntax of your for loop in your code has a mistake. If you want to plot in a separate loop then use:

    for each in df_list:
        Function_plot(each)


问:
How to close file upload dialogue after click on upload button in protractor
I want to upload an image file in protractor. the problem is i can not get "input[type = "file"]" element without clicking on upload button.

when I click upload button, file upload dialogue popup opens.

i have tried

browser.actions().sendKeys(protractor.Key.ESCAPE).perform(); but it does not work.

This is what I am doing:

```<code>var image = '../images/image1.png';
var absPathImg = path.resolve(__dirname, image);
element(by.id('uploadImage')).click();
browser.actions().sendKeys(protractor.Key.ESCAPE).perform();
element(by.css('input[type=file]')).sendKeys(absPathImg);
element(by.id('upload')).click();
</code>```

How can i close that file upload dialogue to upload an image?

答:
Try it like this. I used this for Protractor, but I think it's similar for Selenium.
I also have a problem for Windows File dialog not closing.
This is how I solved that:

element(by.css('elementForOpenDialog')).sendKeys(absPathImg);

Send Keys to the element which will open file dialog, not click on element to open file dialog. Just send to that element absolute path and it will upload without opening dialog.
It's worked for me. Good Luck!

Body:
I want to upload an image file in protractor. the problem is i can not get "input[type = "file"]" element without clicking on upload button.

when I click upload button, file upload dialogue popup opens.

i have tried

browser.actions().sendKeys(protractor.Key.ESCAPE).perform(); but it does not work.

This is what I am doing:

var image = '../images/image1.png';
var absPathImg = path.resolve(__dirname, image);
element(by.id('uploadImage')).click();
browser.actions().sendKeys(protractor.Key.ESCAPE).perform();
element(by.css('input[type=file]')).sendKeys(absPathImg);
element(by.id('upload')).click();

How can i close that file upload dialogue to upload an image?


问:
MySQL workbench SSH connection error [Bad authentication type(allowed_types=['publickey'])]
I have issue regarding SSH connection with my server. When i try to connect it results into error:"Bad authentication type(allowed_types=['publickey'])"
Thanks</p>

答:
FYI, my company uses a Yubikey and so the SSH part can be a bit mysterious. However, walking through a shell login with the yubikey yinit command, to ssh to IP (no password needed here), and finally to connecting mysql (still shell), I attempted to MySQL Workbench a few times with my different passwords to no avail.

Finally, I noticed the "SSH Key File" field and looked up where my .ssh file was -- /Users/myProfile/.ssh/
Set the "id_rsa.pub" file as it and voila!

Everything worked.


问:
How to read properties file in Unix script where key is in another user input variable
I have below property file in same directory.

cancellation.properties

Content:

```<code>TestData=My Name
</code>```

My unix script is abc.sh

Content:

```<code>#!/bin/ksh
. ./cancellation.properties

echo  "Please enter data to read"

read data

echo $data
</code>```

While running I give the value TestData.

I am getting output as "TestData".

But I want output as "My Name".  What changes needs to be done here because key will be entered by user.

答:
You could use awk to get this.

In place of your echo $data put:

```<code>awk -F"=" -v data=$data '$1==data{print $2}' cancellation.properties
</code>```

Which says "Split each record in your cancellation.properties file by an equal sign. If the first field is the value in variable $data (which is the variable data in your awk script set by that -v flag since you can't use shell variables directly in awk) then output the second field.

Also, now that read your question more thoroughly, it looks like you are including your .properties file at the top of the script. This may not be the best answer for you if you wish to proceed. See @cyrus comment to your question where it's noted to quote your variable assignment.

Body:
I have below property file in same directory.

cancellation.properties

Content:

TestData=My Name

My unix script is abc.sh

Content:

#!/bin/ksh
. ./cancellation.properties

echo  "Please enter data to read"

read data

echo $data

While running I give the value TestData.

I am getting output as "TestData".

But I want output as "My Name".  What changes needs to be done here because key will be entered by user.

Body:
You could use awk to get this.

In place of your echo $data put:

awk -F"=" -v data=$data '$1==data{print $2}' cancellation.properties

Which says "Split each record in your cancellation.properties file by an equal sign. If the first field is the value in variable $data (which is the variable data in your awk script set by that -v flag since you can't use shell variables directly in awk) then output the second field.

Also, now that read your question more thoroughly, it looks like you are including your .properties file at the top of the script. This may not be the best answer for you if you wish to proceed. See @cyrus comment to your question where it's noted to quote your variable assignment.


问:
Simple low-latency audio playback in iOS Swift
I'm a beginner in iOS and I'm trying to design a drum set app with Swift. I designed a view with a single button and wrote the code below, but it has some problems:

Some sounds are lost when I touch the button quickly like a drum roll.

Still in a 'drum roll', the sound is interrupted every time the button is touched, instead of letting the sample play till its ending. It's awful in cymbal roll, for instance. I'd like to hear every sample sounding completely, even if I touch the button again.

There is a latency between the touch and the sound. I know that AVAudioPlayer is not the best choice for low-latency audio, but as a beginner, it's hard to learn OpenAL, AudioUnit without code samples or tutorials in Swift. The problem is similar to this: Which framework should I use to play an audio file (WAV, MP3, AIFF) in iOS with low latency?.

The code:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    // Enable multiple touch for the button
    for v in view.subviews {
        if v.isKindOfClass(UIButton) {
            v.multipleTouchEnabled = true
        }
    }

    // Init audio
    audioURL = NSBundle.mainBundle().URLForResource("snareDrum", withExtension: "wav")!
    do {
        player = try AVAudioPlayer(contentsOfURL: audioURL)
        player?.prepareToPlay()
    } catch {
        print("AVAudioPlayer Error")
    }
}

override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(animated)

    player?.stop()
    player = nil
}

@IBAction func playSound(sender: UIButton) {
    player?.currentTime = 0
    player?.play()
}
</code>```

答:
I spent an afternoon trying to solve this issue by playing around with     AVAudioPlayer & AVAudioSession, but I couldn't get anywhere with it. (Setting the IO buffer duration as suggested by the accepted answer here didn't seem to help, unfortunately.) I also tried AudioToolbox, but I found that the resulting performance was pretty much the same - a clearly perceptible delay between the relevant user action and the audio.

After scouring the internet a bit more, I came across this:

www.rockhoppertech.com/blog/swift-avfoundation/

The section on AVAudioEngine turned out to be very useful. The code below is a slight reworking:

```<code>import UIKit
import AVFoundation

class ViewController: UIViewController {

var engine = AVAudioEngine()
var playerNode = AVAudioPlayerNode()
var mixerNode: AVAudioMixerNode?
var audioFile: AVAudioFile?

@IBOutlet var button: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    engine.attach(playerNode)
    mixerNode = engine.mainMixerNode

    engine.connect(playerNode, to: mixerNode!, format: mixerNode!.outputFormat(forBus: 0))

    do {
        try engine.start()
    }

    catch let error {
        print("Error starting engine: \(error.localizedDescription)")
    }

    let url = Bundle.main.url(forResource: "click_04", withExtension: ".wav")

    do {
        try audioFile = AVAudioFile(forReading: url!)
    }

    catch let error {
        print("Error opening audio file: \(error.localizedDescription)")
    }
}

@IBAction func playSound(_ sender: Any) {

    engine.connect(playerNode, to: engine.mainMixerNode, format: audioFile?.processingFormat)
    playerNode.scheduleFile(audioFile!, at: nil, completionHandler: nil)

    if engine.isRunning{
        playerNode.play()
    } else {
        print ("engine not running")
    }
}
</code>```

}

This might not be perfect as I'm a Swift newbie and haven't used AVAudioEngine before. It does seem to work, though!

Body:
I'm a beginner in iOS and I'm trying to design a drum set app with Swift. I designed a view with a single button and wrote the code below, but it has some problems:

Some sounds are lost when I touch the button quickly like a drum roll.

Still in a 'drum roll', the sound is interrupted every time the button is touched, instead of letting the sample play till its ending. It's awful in cymbal roll, for instance. I'd like to hear every sample sounding completely, even if I touch the button again.

There is a latency between the touch and the sound. I know that AVAudioPlayer is not the best choice for low-latency audio, but as a beginner, it's hard to learn OpenAL, AudioUnit without code samples or tutorials in Swift. The problem is similar to this: Which framework should I use to play an audio file (WAV, MP3, AIFF) in iOS with low latency?.

The code:

override func viewDidLoad() {
    super.viewDidLoad()

    // Enable multiple touch for the button
    for v in view.subviews {
        if v.isKindOfClass(UIButton) {
            v.multipleTouchEnabled = true
        }
    }

    // Init audio
    audioURL = NSBundle.mainBundle().URLForResource("snareDrum", withExtension: "wav")!
    do {
        player = try AVAudioPlayer(contentsOfURL: audioURL)
        player?.prepareToPlay()
    } catch {
        print("AVAudioPlayer Error")
    }
}

override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(animated)

    player?.stop()
    player = nil
}

@IBAction func playSound(sender: UIButton) {
    player?.currentTime = 0
    player?.play()
}

Body:
I spent an afternoon trying to solve this issue by playing around with     AVAudioPlayer & AVAudioSession, but I couldn't get anywhere with it. (Setting the IO buffer duration as suggested by the accepted answer here didn't seem to help, unfortunately.) I also tried AudioToolbox, but I found that the resulting performance was pretty much the same - a clearly perceptible delay between the relevant user action and the audio.

After scouring the internet a bit more, I came across this:

www.rockhoppertech.com/blog/swift-avfoundation/

The section on AVAudioEngine turned out to be very useful. The code below is a slight reworking:

import UIKit
import AVFoundation

class ViewController: UIViewController {

var engine = AVAudioEngine()
var playerNode = AVAudioPlayerNode()
var mixerNode: AVAudioMixerNode?
var audioFile: AVAudioFile?

@IBOutlet var button: UIButton!

override func viewDidLoad() {
    super.viewDidLoad()

    engine.attach(playerNode)
    mixerNode = engine.mainMixerNode

    engine.connect(playerNode, to: mixerNode!, format: mixerNode!.outputFormat(forBus: 0))

    do {
        try engine.start()
    }

    catch let error {
        print("Error starting engine: \(error.localizedDescription)")
    }

    let url = Bundle.main.url(forResource: "click_04", withExtension: ".wav")

    do {
        try audioFile = AVAudioFile(forReading: url!)
    }

    catch let error {
        print("Error opening audio file: \(error.localizedDescription)")
    }
}

@IBAction func playSound(_ sender: Any) {

    engine.connect(playerNode, to: engine.mainMixerNode, format: audioFile?.processingFormat)
    playerNode.scheduleFile(audioFile!, at: nil, completionHandler: nil)

    if engine.isRunning{
        playerNode.play()
    } else {
        print ("engine not running")
    }
}

}

This might not be perfect as I'm a Swift newbie and haven't used AVAudioEngine before. It does seem to work, though!


问:
No errors and always zero for result
I am trying to write a function that gets the average of a users number guesses. The table has the userID and tieBreakerPoints.

```<code>function getUserTBA($userID) {
    global $mysqli;

    // loop through user totals & calculate average for each user
    $sql = "SELECT u.userID, p.userID, AVG(p.tieBreakerPoints) AS 'avarage' ";
    $sql .= "FROM " . DB_PREFIX . "picksummary p";
    $sql .= "inner join " . DB_PREFIX . "users u on p.userID = u.userID ";
    $sql .= "WHERE p.userID = " . $user->userID . " ";
    $sql .= "GROUP BY p.userID";
    $query = $mysqli->query($sql);

    if ($query->num_rows > 0) {
        $row = $query->fetch_array();
        return (int)$row['average'];
    }

    return 0;
}
</code>```

When I call the function, I only seem to get zero values, but if I run the SQL query directly in SQL, I get the results. Am I missing something with this function?

答:
You need to configure PHP to emit errors.

Your query creates a virtual column called 'avarage', but your php code uses the spelling 'average'. Turning on errors would have made this very obvious.

Title: No errors and always zero for result

Body:
I am trying to write a function that gets the average of a users number guesses. The table has the userID and tieBreakerPoints.

function getUserTBA($userID) {
    global $mysqli;

    // loop through user totals & calculate average for each user
    $sql = "SELECT u.userID, p.userID, AVG(p.tieBreakerPoints) AS 'avarage' ";
    $sql .= "FROM " . DB_PREFIX . "picksummary p";
    $sql .= "inner join " . DB_PREFIX . "users u on p.userID = u.userID ";
    $sql .= "WHERE p.userID = " . $user->userID . " ";
    $sql .= "GROUP BY p.userID";
    $query = $mysqli->query($sql);

    if ($query->num_rows > 0) {
        $row = $query->fetch_array();
        return (int)$row['average'];
    }

    return 0;
}

When I call the function, I only seem to get zero values, but if I run the SQL query directly in SQL, I get the results. Am I missing something with this function?


问:
Piece back together numpy slices into original array
if you split a numpy array using slices like this:

Assuming data looked like this:
    [[ Y X X X....]
    [Y X X X....]]

```<code>X_test = data_test[:, 1:]
y_test = data_test[:, 0]
</code>```

I assumed this would work but I cannot find documentation in the process.

```<code>test_assembled = [:, y_test:X_test]
</code>```

Body:
if you split a numpy array using slices like this:

Assuming data looked like this:
    [[ Y X X X....]
    [Y X X X....]]

X_test = data_test[:, 1:]
y_test = data_test[:, 0]

I assumed this would work but I cannot find documentation in the process.

test_assembled = [:, y_test:X_test]

Body:
In this case you can use np.c_:

a = np.identity(4)
x, y = a[:,0], a[:,1:]
np.c_[x,y]
# array([[ 1.,  0.,  0.,  0.],
#        [ 0.,  1.,  0.,  0.],
#        [ 0.,  0.,  1.,  0.],
#        [ 0.,  0.,  0.,  1.]])

np.c_ conveniently handles the "missing dimension" in a[:,0] for you.


问:
How can I get my entire history with chrome.history.search?
I am building an extension that reads through the Chrome history and analyzes the link for keywords.

I am using the chrome.history.search method to retrieve the browser history like so:

```<code>chrome.history.search({
        'text': '',
        'maxResults': 500,
    }, function(historyItems){
    });
</code>```

At this point, I store the URLs retrieved in an array and begin reading through them.

But I am not getting everything. The number of URLs retrieved vary with different runs. I tried experimenting with the parameters in the search method, but I am not able to influence the number of links returned.

Can anyone help me understand this?

EDIT: When I say I am not getting everything, what I mean is compared to my browser history that I can see, the one pulled through the extension is much more limited.

答:
Interestingly, the Chromium bug that Justaman mentioned in his answer reveals that passing maxResults: 0 will actually return all history items.  So if you really wanted the entire history, you could do:

```<code>chrome.history.search({ text: "", startTime: 0, maxResults: 0 },
    items => console.log(items));
</code>```

I haven't tried that, as I expect that loading my tens (?) of thousands of history items into memory would take down Chrome.  But I did try it with a startTime of a few days ago, and that returned 645 items.

If you happen to be using the handy chrome-promise library, here's a version of Antony's answer that uses promises instead of callbacks to loop through the API calls until the desired number of history items is found:

```<code>import ChromePromise from 'chrome-promise';

const chromep = new ChromePromise();

function loop(fn)
{
    return fn().then(val => (val === true && loop(fn)) || val);
}

function getHistory(requestedCount)
{
    var history = [],
        ids = {};

    return loop(() => {
        var endTime = history.length &&
                history[history.length - 1].lastVisitTime || Date.now();

        return chromep.history.search({
            text: "",
            startTime: 0,
            endTime: endTime,
            maxResults: 1000
        })
            .then(historyItems => {
                var initialHistoryLength = history.length;

                historyItems.forEach(item => {
                    var id = item.id;

                        // history will often return duplicate items
                    if (!ids[id] && history.length < requestedCount) {
                        addURLs(item);
                        history.push(item);
                        ids[id] = true;
                    }
                });

                    // only loop if we found some new items in the last call
                    // and we haven't reached the limit yet
                if (history.length > initialHistoryLength &&
                        history.length < requestedCount) {
                    return true;
                } else {
                    return history;
                }
            });
    });
}
</code>```

You could use this function like this:

```<code>getHistory(2000).then(items => console.log(items));
</code>```

Body:
I am building an extension that reads through the Chrome history and analyzes the link for keywords.

I am using the chrome.history.search method to retrieve the browser history like so:

chrome.history.search({
        'text': '',
        'maxResults': 500,
    }, function(historyItems){
    });

At this point, I store the URLs retrieved in an array and begin reading through them.

But I am not getting everything. The number of URLs retrieved vary with different runs. I tried experimenting with the parameters in the search method, but I am not able to influence the number of links returned.

Can anyone help me understand this?

EDIT: When I say I am not getting everything, what I mean is compared to my browser history that I can see, the one pulled through the extension is much more limited.

Body:
Interestingly, the Chromium bug that Justaman mentioned in his answer reveals that passing maxResults: 0 will actually return all history items.  So if you really wanted the entire history, you could do:

chrome.history.search({ text: "", startTime: 0, maxResults: 0 },
    items => console.log(items));

I haven't tried that, as I expect that loading my tens (?) of thousands of history items into memory would take down Chrome.  But I did try it with a startTime of a few days ago, and that returned 645 items.

If you happen to be using the handy chrome-promise library, here's a version of Antony's answer that uses promises instead of callbacks to loop through the API calls until the desired number of history items is found:

import ChromePromise from 'chrome-promise';

const chromep = new ChromePromise();

function loop(fn)
{
    return fn().then(val => (val === true && loop(fn)) || val);
}

function getHistory(requestedCount)
{
    var history = [],
        ids = {};

    return loop(() => {
        var endTime = history.length &&
                history[history.length - 1].lastVisitTime || Date.now();

        return chromep.history.search({
            text: "",
            startTime: 0,
            endTime: endTime,
            maxResults: 1000
        })
            .then(historyItems => {
                var initialHistoryLength = history.length;

                historyItems.forEach(item => {
                    var id = item.id;

                        // history will often return duplicate items
                    if (!ids[id] && history.length < requestedCount) {
                        addURLs(item);
                        history.push(item);
                        ids[id] = true;
                    }
                });

                    // only loop if we found some new items in the last call
                    // and we haven't reached the limit yet
                if (history.length > initialHistoryLength &&
                        history.length < requestedCount) {
                    return true;
                } else {
                    return history;
                }
            });
    });
}

You could use this function like this:

getHistory(2000).then(items => console.log(items));


问:
Ionic - Search Results Under Searchbar
I am using Ionic and Angular to create a grocery list app. The design I was given calls for a searchbar with results to display after a button is clicked. These results are another list that is directly underneath the searchbar and overlays the content of the page.

Mockups

Before clicking button to show search

Desired look after clicking button to show search

So far, this is the code:

```<code><ion-content padding>

  <ion-grid>
    <ion-row>
      <ion-searchbar *ngIf="isOn"></ion-searchbar>
      <ion-list>
        <ion-item *ngFor="let searchresult of searchresults" (click)="selectresult(result)">
          {{ result.$value }}
        </ion-item>
      </ion-list>
      <ion-col>
      </ion-col>
      <ion-col>
      </ion-col>
      <ion-col>
        <ion-buttons end>
          <button *ngIf="!isOn" (click)="showsearch()" ion-button small color="nudgetprim" end>
            + Add Item
          </button>
        </ion-buttons>
      </ion-col>
    </ion-row>
  </ion-grid>

  <ion-item-group>
    <ion-item-divider color="light">Items</ion-item-divider>
    <ion-item *ngFor="let item of items | async" (click)="changestate(item)">{{item.$value}}</ion-item>
  </ion-item-group>

</ion-content>
</code>```

I assumed that I could make this happen with:

```<code>   <ion-list>
    <ion-item *ngFor="let searchresult of searchresults" (click)="selectresult(result)">
      {{ result.$value }}
    </ion-item>
  </ion-list>
</code>```

but no success.

Right now, the searchbar is displaying properly after the button is clicked, I just need to find a way to have the listed results underneath where it is overlaying the previously displayed contents. How do I achieve this look in Ionic?

答:
Initialize searchresults property in your class:

```<code>searchresults: any[] = [];
</code>```

It appears the property is undefined causing Angular to ignore bindings.

Please provide your .ts file for reference.

Title: Ionic - Search Results Under Searchbar

Body:
I am using Ionic and Angular to create a grocery list app. The design I was given calls for a searchbar with results to display after a button is clicked. These results are another list that is directly underneath the searchbar and overlays the content of the page.

Mockups

Before clicking button to show search

Desired look after clicking button to show search

So far, this is the code:

<ion-content padding>

  <ion-grid>
    <ion-row>
      <ion-searchbar *ngIf="isOn"></ion-searchbar>
      <ion-list>
        <ion-item *ngFor="let searchresult of searchresults" (click)="selectresult(result)">
          {{ result.$value }}
        </ion-item>
      </ion-list>
      <ion-col>
      </ion-col>
      <ion-col>
      </ion-col>
      <ion-col>
        <ion-buttons end>
          <button *ngIf="!isOn" (click)="showsearch()" ion-button small color="nudgetprim" end>
            + Add Item
          </button>
        </ion-buttons>
      </ion-col>
    </ion-row>
  </ion-grid>

  <ion-item-group>
    <ion-item-divider color="light">Items</ion-item-divider>
    <ion-item *ngFor="let item of items | async" (click)="changestate(item)">{{item.$value}}</ion-item>
  </ion-item-group>

</ion-content>

I assumed that I could make this happen with:

   <ion-list>
    <ion-item *ngFor="let searchresult of searchresults" (click)="selectresult(result)">
      {{ result.$value }}
    </ion-item>
  </ion-list>

but no success.

Right now, the searchbar is displaying properly after the button is clicked, I just need to find a way to have the listed results underneath where it is overlaying the previously displayed contents. How do I achieve this look in Ionic?

Body:
Initialize searchresults property in your class:

searchresults: any[] = [];

It appears the property is undefined causing Angular to ignore bindings.

Please provide your .ts file for reference.


问:
Deshuffle text with C
I wanted to get an opinion here. Would it be possible to write a C program that deshuffles a text file? What do I mean by that? Say I have the following data in a textfile:

```<code>1  X
4  T
3  Z
2  L
</code>```

And I wanted to deshuffle it and output another file as so:

```<code>1  X
2  L
3  Z
4  T
</code>```

Such that all of the data following the number is preserved with the actual index number. Do know that I have 40,500 shuffled entities, so that should probably be taken into account since that could take a long time if the program needs to loop through all of the entities for each entity...And I only used letters for representation. The actual data files don't have letters, but rather have floats. Sorry if this causes any confusion

So, bottom line, would this be possible with C? And if so, could I get a hint at where to start? I could obviously input all of the textfile data into an array dat[][], but how should I deshuffle it then?

Thanks!
Amit

答:
For those interested, I ended up using a series of loops to write this program, the code is show below. The only downside of it is that if my nrow variable is equal to 40,500, this program can take as long as 30 mins to run on a 3GHz dual core computer. I'm sure there are ways to optimize it, though at least it does what I want...for now.

Here's the code:

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

// Deshuffle the output files of the bond/swap mode

int main(int argc, char* argv[])
{
    if (argc < 4) {
        printf("\ndeshuffle usage: [number of chains] [number of atoms] [.dat file] \n");
        exit(1);
    }

    int i,j,k,l;
    int nch = atoi( argv[1] );
    int ns = atoi( argv[2] );
    double **in_dat, **s_dat, dm1;

    int nrow = ns*nch;

    in_dat = (double**) calloc(nrow, sizeof(double*));
    s_dat = (double**) calloc(nrow, sizeof(double*));
    for (i=0; i<nrow; i++) {
        in_dat[i] = (double*) calloc(6, sizeof(double));
        s_dat[i] = (double*) calloc(6, sizeof(double));
        for (j=0; j<6; j++)
            in_dat[i][j] = 0.0;
            s_dat[i][j] = 0.0;
    }

    // store input data into 2D array in_dat
    FILE *inp;
    inp = fopen( argv[3], "r" );

    for (i=0; i<nrow; i++) {
        for (j=0; j<6; j++) {
            fscanf(inp, "%lf", &dm1);
            in_dat[i][j] = dm1;
        }
    }

    fclose(inp);

    // Sort data in s_dat based on comparison with in_dat
    k=0;
    while (k < (nrow)) {
        for (i=0; i<nrow; i++) {
            for (l=0; l<nrow; l++) {
                if (in_dat[l][0] == (k+1)) {
                    for (j=0; j<6; j++) {
                        s_dat[i][j] = in_dat[l][j];
                    }
                    k++;
                    break;
                }
            }
        }
    }

    // Write sorted data to file

    FILE *otp;
    otp = fopen("results.out", "w");

    for (i=0; i<nrow; i++) {
        for (j=0; j<6; j++) {
            fprintf(otp, "%lf \t", s_dat[i][j]);
            if (j==5)
                fprintf(otp, "\n");
        }
    }

    fclose(otp);

    printf("\n Done. \n\n");

    return 0;
}
</code>```

Title: Deshuffle text with C

Body:
I wanted to get an opinion here. Would it be possible to write a C program that deshuffles a text file? What do I mean by that? Say I have the following data in a textfile:

1  X
4  T
3  Z
2  L

And I wanted to deshuffle it and output another file as so:

1  X
2  L
3  Z
4  T

Such that all of the data following the number is preserved with the actual index number. Do know that I have 40,500 shuffled entities, so that should probably be taken into account since that could take a long time if the program needs to loop through all of the entities for each entity...And I only used letters for representation. The actual data files don't have letters, but rather have floats. Sorry if this causes any confusion

So, bottom line, would this be possible with C? And if so, could I get a hint at where to start? I could obviously input all of the textfile data into an array dat[][], but how should I deshuffle it then?

Thanks!
Amit

Body:
For those interested, I ended up using a series of loops to write this program, the code is show below. The only downside of it is that if my nrow variable is equal to 40,500, this program can take as long as 30 mins to run on a 3GHz dual core computer. I'm sure there are ways to optimize it, though at least it does what I want...for now.

Here's the code:

#include "stdlib.h"
#include "stdio.h"

// Deshuffle the output files of the bond/swap mode

int main(int argc, char* argv[])
{
    if (argc < 4) {
        printf("\ndeshuffle usage: [number of chains] [number of atoms] [.dat file] \n");
        exit(1);
    }

    int i,j,k,l;
    int nch = atoi( argv[1] );
    int ns = atoi( argv[2] );
    double **in_dat, **s_dat, dm1;

    int nrow = ns*nch;

    in_dat = (double**) calloc(nrow, sizeof(double*));
    s_dat = (double**) calloc(nrow, sizeof(double*));
    for (i=0; i<nrow; i++) {
        in_dat[i] = (double*) calloc(6, sizeof(double));
        s_dat[i] = (double*) calloc(6, sizeof(double));
        for (j=0; j<6; j++)
            in_dat[i][j] = 0.0;
            s_dat[i][j] = 0.0;
    }

    // store input data into 2D array in_dat
    FILE *inp;
    inp = fopen( argv[3], "r" );

    for (i=0; i<nrow; i++) {
        for (j=0; j<6; j++) {
            fscanf(inp, "%lf", &dm1);
            in_dat[i][j] = dm1;
        }
    }

    fclose(inp);

    // Sort data in s_dat based on comparison with in_dat
    k=0;
    while (k < (nrow)) {
        for (i=0; i<nrow; i++) {
            for (l=0; l<nrow; l++) {
                if (in_dat[l][0] == (k+1)) {
                    for (j=0; j<6; j++) {
                        s_dat[i][j] = in_dat[l][j];
                    }
                    k++;
                    break;
                }
            }
        }
    }

    // Write sorted data to file

    FILE *otp;
    otp = fopen("results.out", "w");

    for (i=0; i<nrow; i++) {
        for (j=0; j<6; j++) {
            fprintf(otp, "%lf \t", s_dat[i][j]);
            if (j==5)
                fprintf(otp, "\n");
        }
    }

    fclose(otp);

    printf("\n Done. \n\n");

    return 0;
}


问:
Testing a function from a module with Jasmine
I have a module "test.js" which looks like this;

```<code>export default function main(){
   sub_main();
}

export function sub_main(){
 //Do something
}
</code>```

I would like to test the method sub_main in Jasmine. I have tried to import sub_main() function to test in Jasmine using import statement but Jasmine complies "Unexpected token import" then I used the require statement. It now complies about export keyword in test.js module.

答:
The syntax you're using is actually ES6 imports, which is not supported by your node version.

You'd either either to use Babel with Jasmine before loading transpiled files into Jasmine, or write your code using the way that @tehbeardedone said on his answer, which is CommonJS.

Body:
I have a module "test.js" which looks like this;

export default function main(){
   sub_main();
}

export function sub_main(){
 //Do something
}

I would like to test the method sub_main in Jasmine. I have tried to import sub_main() function to test in Jasmine using import statement but Jasmine complies "Unexpected token import" then I used the require statement. It now complies about export keyword in test.js module.