问:
JavaFX 8 Stacked Bar Chart numerical sorting issue
I'm developing an application that parses a text file and looks for times between certain sent actions, a simple visual aid in short.

My issue is that the sorting on the StackedBarCharts x-axis has gone awry, as shown by the image linked below;

Image of sorting issue

The relevant code for generating these charts;

```<code>public boolean updateBarChart(Tab t, DataHolder dock) {
    Node n = t.getContent();
    Node graph = n.lookup("#Graph");
    StackedBarChart bc = (StackedBarChart) graph;

    //Barchart
    NumberAxis xAxis = new NumberAxis();
    NumberAxis yAxis = new NumberAxis();
    bc.setTitle("Summary");
    bc.getData().clear();
    bc.setLegendVisible(true);
    bc.setCategoryGap(1);

    xAxis.setTickLabelRotation(90);

    ArrayList<String> tempArr = dock.getUniqueActionNumbers();

    for(String s : tempArr)
    {
        bc.getData().add(dock.calculateIntervalsBetweenActions(s));

    }

    bc.getXAxis().setAutoRanging(true);
    bc.getYAxis().setAutoRanging(true);

    return true;
}
</code>```

The code generating the series, where:

ConstantStrings are an ENUM of the constantly reocurring strings,

PairValue is a simple home brewed Pair made for a simple local caching system so I don't have search the entire data structure every time I want each instance of a specific value.

```<code>public XYChart.Series<String, Number> calculateIntervalsBetweenActions(String actionNumber)
{
    XYChart.Series returnValue = new XYChart.Series();
    returnValue.setName(actionNumber);
    LocalTime lastTime = null;
    TreeMap<Integer, Integer> listOfNumbers = new TreeMap<Integer, Integer>();
    int maxVal = 0;

    ArrayList<PairValue> temp = metaMap.get(ConstantStrings.RECIEVED_ACTION_NUMBER);

    if (temp != null)
    {
        for( PairValue p : temp)
        {
            String s = dp.get(p.getNodePlace()).getTokens().get(p.getPointPlace()).getValue();
            if (!s.equals(actionNumber))
                continue;

            if(lastTime != null)
            {
                LocalTime tempTime = LocalTime.parse(dp.get(p.getNodePlace()).getTimestamp());
                int seconds = (int) lastTime.until(tempTime, SECONDS);
                if(seconds > maxVal) maxVal = seconds;

                Integer count = listOfNumbers.get(seconds);
                listOfNumbers.put(seconds, (count == null) ? 1 : count + 1);
                lastTime = tempTime;

            }
            else lastTime = LocalTime.parse(dp.get(p.getNodePlace()).getTimestamp());

        }
        //todo add filter so the user can choose what to ignore and not.
        for(int i = 2; i <= maxVal; i++) {
            Integer find = listOfNumbers.get(i);
            if(find != null) {

                XYChart.Data toAdd = new XYChart.Data(Integer.valueOf(i).toString(), find);
                returnValue.getData().add(toAdd);

            }

        }

    }
    else Logger.getGlobal().warning("Could not find meta map for Recieved action numer, aborting");

    return returnValue;
}
</code>```

My suspicions lie in the order the Series are added, but that should not matter in my opinion, so my question stands; Is there any simple way to sort these values properly?

答:
Found the solution after an extensive amount of banging my head against the wall of not understanding:

First of all, don't programatically skip adding any values to the original series. Add all 0-values ranging between the values you want to keep. This is for sorting purposes.

Remove all 0-values when you've finalized the adding of new data.

This is the snippet of code I've used to remove the 0-values, modify for your own purposes as you wish.

```<code>    ObservableList<XYChart.Series> xys = bc.getData();
    for(XYChart.Series<String,Number> series : xys) {
        ArrayList<XYChart.Data> removelist = new ArrayList<>();

        for(XYChart.Data<String,Number> data: series.getData()) {
            if(data.getYValue().equals(0)) removelist.add(data);
        }

        series.getData().removeAll(removelist);
    }
</code>```

Body:
I'm developing an application that parses a text file and looks for times between certain sent actions, a simple visual aid in short.

My issue is that the sorting on the StackedBarCharts x-axis has gone awry, as shown by the image linked below;

Image of sorting issue

The relevant code for generating these charts;

public boolean updateBarChart(Tab t, DataHolder dock) {
    Node n = t.getContent();
    Node graph = n.lookup("#Graph");
    StackedBarChart bc = (StackedBarChart) graph;

    //Barchart
    NumberAxis xAxis = new NumberAxis();
    NumberAxis yAxis = new NumberAxis();
    bc.setTitle("Summary");
    bc.getData().clear();
    bc.setLegendVisible(true);
    bc.setCategoryGap(1);

    xAxis.setTickLabelRotation(90);

    ArrayList<String> tempArr = dock.getUniqueActionNumbers();

    for(String s : tempArr)
    {
        bc.getData().add(dock.calculateIntervalsBetweenActions(s));

    }

    bc.getXAxis().setAutoRanging(true);
    bc.getYAxis().setAutoRanging(true);

    return true;
}

The code generating the series, where:

ConstantStrings are an ENUM of the constantly reocurring strings,

PairValue is a simple home brewed Pair made for a simple local caching system so I don't have search the entire data structure every time I want each instance of a specific value.

public XYChart.Series<String, Number> calculateIntervalsBetweenActions(String actionNumber)
{
    XYChart.Series returnValue = new XYChart.Series();
    returnValue.setName(actionNumber);
    LocalTime lastTime = null;
    TreeMap<Integer, Integer> listOfNumbers = new TreeMap<Integer, Integer>();
    int maxVal = 0;

    ArrayList<PairValue> temp = metaMap.get(ConstantStrings.RECIEVED_ACTION_NUMBER);

    if (temp != null)
    {
        for( PairValue p : temp)
        {
            String s = dp.get(p.getNodePlace()).getTokens().get(p.getPointPlace()).getValue();
            if (!s.equals(actionNumber))
                continue;

            if(lastTime != null)
            {
                LocalTime tempTime = LocalTime.parse(dp.get(p.getNodePlace()).getTimestamp());
                int seconds = (int) lastTime.until(tempTime, SECONDS);
                if(seconds > maxVal) maxVal = seconds;

                Integer count = listOfNumbers.get(seconds);
                listOfNumbers.put(seconds, (count == null) ? 1 : count + 1);
                lastTime = tempTime;

            }
            else lastTime = LocalTime.parse(dp.get(p.getNodePlace()).getTimestamp());

        }
        //todo add filter so the user can choose what to ignore and not.
        for(int i = 2; i <= maxVal; i++) {
            Integer find = listOfNumbers.get(i);
            if(find != null) {

                XYChart.Data toAdd = new XYChart.Data(Integer.valueOf(i).toString(), find);
                returnValue.getData().add(toAdd);

            }

        }

    }
    else Logger.getGlobal().warning("Could not find meta map for Recieved action numer, aborting");

    return returnValue;
}

My suspicions lie in the order the Series are added, but that should not matter in my opinion, so my question stands; Is there any simple way to sort these values properly?

Body:
Found the solution after an extensive amount of banging my head against the wall of not understanding:

First of all, don't programatically skip adding any values to the original series. Add all 0-values ranging between the values you want to keep. This is for sorting purposes.

Remove all 0-values when you've finalized the adding of new data.

This is the snippet of code I've used to remove the 0-values, modify for your own purposes as you wish.

    ObservableList<XYChart.Series> xys = bc.getData();
    for(XYChart.Series<String,Number> series : xys) {
        ArrayList<XYChart.Data> removelist = new ArrayList<>();

        for(XYChart.Data<String,Number> data: series.getData()) {
            if(data.getYValue().equals(0)) removelist.add(data);
        }

        series.getData().removeAll(removelist);
    }


来源: stackexchange

问:
Using a WHERE NOT EXISTS
I am trying and failing miserably to create a simple WHERE NOT EXISTS Clause. Assume the following example,

```<code>CREATE TABLE #TempUser ( TempUserId INT, TempUserName VARCHAR(50) )

CREATE TABLE #TempData ( TempDataId INT, TempDesc VARCHAR(50) )

CREATE TABLE #TempUserData ( TempUserId INT, TempDataId INT )

INSERT #TempUser ( TempUserId, TempUserName )
VALUES  ( 1, 'Paul' ),
        ( 2, 'Franics' ),
        ( 3, 'Raj' )

INSERT #TempData ( TempDataId, TempDesc )
VALUES  ( 1, 'Test Exists'),
        ( 2, 'Test Not Exists')

INSERT #TempUserData ( TempUserId, TempDataId )
VALUES  ( 1, 1 ),
        ( 1, 2 ),
        ( 2, 1 )

SELECT TU.TempUserId
FROM
    #TempUser AS TU
    LEFT JOIN #TempUserData AS TUD ON TUD.TempUserId = TU.TempUserId
WHERE
    NOT EXISTS (SELECT * FROM #TempData AS TD WHERE TD.TempDataId = TUD.TempDataId AND TD.TempDesc LIKE '%Not%')
</code>```

All that I am trying to do is get the list of Users from the #TempUser table who does not have a specific data record, in this case Test Not Exists. The expected result set is UserId 2 and 3, as you can see executing the above will give 1, 2 and 3. So anyone out there who could help me out, please?

答:
I think this is what you want:

```<code>select TU.TempUserId
from #TempUser as TU
where not exists (
  select 1
  from #TempData as TD
    inner join #TempUserData as TUD
      on TD.TempDataId = TUD.TempDataId
  where TUD.TempUserId = TU.TempUserId
    and TD.TempDesc like '%Not%'
  )
</code>```

rextester demo: http://rextester.com/JJDTM34255

returns:

```<code>+------------+
| TempUserId |
+------------+
|          2 |
|          3 |
+------------+
</code>```

ContentLicense: CC BY-SA 3.0

Title: Using a WHERE NOT EXISTS

Body:
I am trying and failing miserably to create a simple WHERE NOT EXISTS Clause. Assume the following example,

CREATE TABLE #TempUser ( TempUserId INT, TempUserName VARCHAR(50) )

CREATE TABLE #TempData ( TempDataId INT, TempDesc VARCHAR(50) )

CREATE TABLE #TempUserData ( TempUserId INT, TempDataId INT )

INSERT #TempUser ( TempUserId, TempUserName )
VALUES  ( 1, 'Paul' ),
        ( 2, 'Franics' ),
        ( 3, 'Raj' )

INSERT #TempData ( TempDataId, TempDesc )
VALUES  ( 1, 'Test Exists'),
        ( 2, 'Test Not Exists')

INSERT #TempUserData ( TempUserId, TempDataId )
VALUES  ( 1, 1 ),
        ( 1, 2 ),
        ( 2, 1 )

SELECT TU.TempUserId
FROM
    #TempUser AS TU
    LEFT JOIN #TempUserData AS TUD ON TUD.TempUserId = TU.TempUserId
WHERE
    NOT EXISTS (SELECT * FROM #TempData AS TD WHERE TD.TempDataId = TUD.TempDataId AND TD.TempDesc LIKE '%Not%')

All that I am trying to do is get the list of Users from the #TempUser table who does not have a specific data record, in this case Test Not Exists. The expected result set is UserId 2 and 3, as you can see executing the above will give 1, 2 and 3. So anyone out there who could help me out, please?

Body:
I think this is what you want:

select TU.TempUserId
from #TempUser as TU
where not exists (
  select 1
  from #TempData as TD
    inner join #TempUserData as TUD
      on TD.TempDataId = TUD.TempDataId
  where TUD.TempUserId = TU.TempUserId
    and TD.TempDesc like '%Not%'
  )

rextester demo: http://rextester.com/JJDTM34255

returns:

+------------+
| TempUserId |
+------------+
|          2 |
|          3 |
+------------+


问:
passing an array to a function formal parameter
I have some doubts regarding pointers and arrays.Please correct me wherever i am wrong.

1)
i have read on the net that there are two ways of passing an array to a function.One in which,the formal parameter of the function is an array,like int a[]
and the second,in which the formal parameter is a pointer like int *a
But have a look here.In the below code,the first technique of passing arrays has been used.But I dont understand why we have passed balance as the actual parameter.I have read that for the array balance[],it's name,that is "balance" is a constant pointer to the first element.So,the value of  balance is the address of the first element(and *balance would be the first element of the array).

It would have been fine had the formal parameter been a pointer,because in that case,the address would have been assigned as the value of the formal parameter pointer.
I don't get why we have an array as a formal parameter and an address as an actual parameter (argument)?

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

/* function declaration */
double getAverage(int arr[], int size);

int main ()
{
    /* an int array with 5 elements */
  int balance[5] = {1000, 2, 3, 17, 50};
  double avg;

  /* pass pointer to the array as an argument */
  avg = getAverage( balance, 5 ) ;

 /* output the returned value */
  printf( "Average value is: %f ", avg );

 return 0;
}
</code>```

答:
```<code>#include<stdio.h>

double getAverage (int *arr, int size);

int main (void) {
    double avg;
    int balance [5]={1000, 2, 3, 17, 50};
    int *ptr;
    ptr = balance;
    avg= getAverage(ptr,5);
    printf("Average of the array is %f", avg);
    return 0;
}

double getAverage (int *arr, int size) {
    int i;
    double sum=0.0;
    double avg=0.0;
    for (i=0; i<size; i++) {
        sum += *arr;
        arr = arr+1;
    }
    avg = (sum/size);
    return avg;
}
</code>```

Body:
I have some doubts regarding pointers and arrays.Please correct me wherever i am wrong.

1)
i have read on the net that there are two ways of passing an array to a function.One in which,the formal parameter of the function is an array,like int a[]
and the second,in which the formal parameter is a pointer like int *a
But have a look here.In the below code,the first technique of passing arrays has been used.But I dont understand why we have passed balance as the actual parameter.I have read that for the array balance[],it's name,that is "balance" is a constant pointer to the first element.So,the value of  balance is the address of the first element(and *balance would be the first element of the array).

It would have been fine had the formal parameter been a pointer,because in that case,the address would have been assigned as the value of the formal parameter pointer.
I don't get why we have an array as a formal parameter and an address as an actual parameter (argument)?

 #include <stdio.h>

/* function declaration */
double getAverage(int arr[], int size);

int main ()
{
    /* an int array with 5 elements */
  int balance[5] = {1000, 2, 3, 17, 50};
  double avg;

  /* pass pointer to the array as an argument */
  avg = getAverage( balance, 5 ) ;

 /* output the returned value */
  printf( "Average value is: %f ", avg );

 return 0;
}


问:
Scala: short form of pattern matching that returns Boolean
I found myself writing something like this quite often:

```<code>a match {
  case `b` => // do stuff
  case _ => // do nothing
}
</code>```

Is there a shorter way to check if some value matches a pattern? I mean, in this case I could just write if (a == b) // do stuff, but what if the pattern is more complex? Like when matching against a list or any pattern of arbitrary complexity. I'd like to be able to write something like this:

```<code>if (a matches b) // do stuff
</code>```

I'm relatively new to Scala, so please pardon, if I'm missing something big :)

答:
This is exactly why I wrote these functions, which are apparently impressively obscure since nobody has mentioned them.</p>

```<code>scala> import PartialFunction._
import PartialFunction._

scala> cond("abc") { case "def" => true }
res0: Boolean = false

scala> condOpt("abc") { case x if x.length == 3 => x + x }
res1: Option[java.lang.String] = Some(abcabc)

scala> condOpt("abc") { case x if x.length == 4 => x + x }
res2: Option[java.lang.String] = None
</code>```

Body:
I found myself writing something like this quite often:

a match {
  case `b` => // do stuff
  case _ => // do nothing
}

Is there a shorter way to check if some value matches a pattern? I mean, in this case I could just write if (a == b) // do stuff, but what if the pattern is more complex? Like when matching against a list or any pattern of arbitrary complexity. I'd like to be able to write something like this:

if (a matches b) // do stuff

I'm relatively new to Scala, so please pardon, if I'm missing something big :)

Body:
This is exactly why I wrote these functions, which are apparently impressively obscure since nobody has mentioned them.

scala> import PartialFunction._
import PartialFunction._

scala> cond("abc") { case "def" => true }
res0: Boolean = false

scala> condOpt("abc") { case x if x.length == 3 => x + x }
res1: Option[java.lang.String] = Some(abcabc)

scala> condOpt("abc") { case x if x.length == 4 => x + x }
res2: Option[java.lang.String] = None

ContentLicense: CC BY-SA 2.5


问:
Form submission via AJAX query without allowing access to the PHP file on server
I have an ajax contact form on my page that sends data to a php file on the server (LAMP). I get flooded with spam messages that are not submitted from the website, but are sent by sending requests directly to the php file. How do I prevent that?</p>

答: Like Alex said, use captcha. Your server should ignore any requests that do not pass the captcha test. I.E. every request must read the validation from captcha in order to respond to any request. This way, you prevent bots from spamming you!</p>


问:
Not able to merge records in Oracle database using merge statement
```<code>SELECT * FROM DIM_TRANS_TYPE WHERE TRANSACTION_TYPE='ILAU';
</code>```

All I want to accomplish here is change ILAU to IFAU and Instant Loan Authorization Request to Instant Finance Authorization Request in the above-mentioned record.

Table Schema:

```<code>Name                  Null     Type
--------------------- -------- ------------------
TRANSACTION_TYPE      NOT NULL VARCHAR2(4 CHAR)   --> PRIMARY KEY
TRANSACTION_TYPE_DESC          VARCHAR2(256 CHAR)
</code>```

WORKS !!!

```<code>MERGE INTO DIM_TRANS_TYPE a
USING (SELECT 'ILAU' TRANSACTION_TYPE, 'Instant Loan Authorization Request' TRANSACTION_TYPE_DESC FROM DUAL) b
    ON (a.TRANSACTION_TYPE = b.TRANSACTION_TYPE)
WHEN MATCHED THEN UPDATE
    SET
      a.TRANSACTION_TYPE_DESC = 'Instant Finance Authorization Request'
WHEN NOT MATCHED THEN
    INSERT(a.TRANSACTION_TYPE, a.TRANSACTION_TYPE_DESC)
    VALUES(b.TRANSACTION_TYPE, b.TRANSACTION_TYPE_DESC);
</code>```

DOES NOT WORK !!! (Error shown below)

```<code>MERGE INTO DIM_TRANS_TYPE a
USING (SELECT 'ILAU' TRANSACTION_TYPE, 'Instant Loan Authorization Request' TRANSACTION_TYPE_DESC FROM DUAL) b
    ON (a.TRANSACTION_TYPE = b.TRANSACTION_TYPE)
WHEN MATCHED THEN UPDATE
    SET
      a.TRANSACTION_TYPE = 'IFAU',
      a.TRANSACTION_TYPE_DESC = 'Instant Finance Authorization Request'
WHEN NOT MATCHED THEN
    INSERT(a.TRANSACTION_TYPE, a.TRANSACTION_TYPE_DESC)
    VALUES(b.TRANSACTION_TYPE, b.TRANSACTION_TYPE_DESC);
</code>```

Error:

```<code>Error at Command Line : 5 Column : 9
Error report -
SQL Error: ORA-38104: Columns referenced in the ON Clause cannot be updated: "A"."TRANSACTION_TYPE"
38104. 00000 -  "Columns referenced in the ON Clause cannot be updated: %s"
*Cause:    LHS of UPDATE SET contains the columns referenced in the ON Clause
*Action:
</code>```

答:
As the error message indicates, it is not possible to update the fields that are used in the on clause.

You'll have to do this kind of update in a separate statement. Something like this:

```<code>UPDATE DIM_TRANS_TYPE
SET    TRANSACTION_TYPE = 'IFAU',
       TRANSACTION_TYPE_DESC = 'Instant Finance Authorization Request'
WHERE  TRANSACTION_TYPE IN (
            SELECT TRANSATION_TYPE
            FROM   (SELECT 'ILAU' TRANSACTION_TYPE,
                           'Instant Loan Authorization Request' TRANSACTION_TYPE_DESC
                    FROM DUAL)
       );

MERGE INTO DIM_TRANS_TYPE a
USING      (SELECT 'ILAU' TRANSACTION_TYPE,
                   'Instant Loan Authorization Request' TRANSACTION_TYPE_DESC
            FROM   DUAL) b
        ON (a.TRANSACTION_TYPE = b.TRANSACTION_TYPE)
WHEN NOT MATCHED THEN
    INSERT(TRANSACTION_TYPE, TRANSACTION_TYPE_DESC)
    VALUES(b.TRANSACTION_TYPE, b.TRANSACTION_TYPE_DESC);
</code>```

You may want to execute this in a transaction, so that the changes incurred by either both or neither of these statements are committed.

Of course, the IN clause looks a bit exaggerated as the value could simply be compared with ILAU, but I assume you simplified the question when in reality you have a bigger dataset to get the transaction_type values from.

Body:
SELECT * FROM DIM_TRANS_TYPE WHERE TRANSACTION_TYPE='ILAU';

All I want to accomplish here is change ILAU to IFAU and Instant Loan Authorization Request to Instant Finance Authorization Request in the above-mentioned record.

Table Schema:

Name                  Null     Type
--------------------- -------- ------------------
TRANSACTION_TYPE      NOT NULL VARCHAR2(4 CHAR)   --> PRIMARY KEY
TRANSACTION_TYPE_DESC          VARCHAR2(256 CHAR)

WORKS !!!

MERGE INTO DIM_TRANS_TYPE a
USING (SELECT 'ILAU' TRANSACTION_TYPE, 'Instant Loan Authorization Request' TRANSACTION_TYPE_DESC FROM DUAL) b
    ON (a.TRANSACTION_TYPE = b.TRANSACTION_TYPE)
WHEN MATCHED THEN UPDATE
    SET
      a.TRANSACTION_TYPE_DESC = 'Instant Finance Authorization Request'
WHEN NOT MATCHED THEN
    INSERT(a.TRANSACTION_TYPE, a.TRANSACTION_TYPE_DESC)
    VALUES(b.TRANSACTION_TYPE, b.TRANSACTION_TYPE_DESC);

DOES NOT WORK !!! (Error shown below)

MERGE INTO DIM_TRANS_TYPE a
USING (SELECT 'ILAU' TRANSACTION_TYPE, 'Instant Loan Authorization Request' TRANSACTION_TYPE_DESC FROM DUAL) b
    ON (a.TRANSACTION_TYPE = b.TRANSACTION_TYPE)
WHEN MATCHED THEN UPDATE
    SET
      a.TRANSACTION_TYPE = 'IFAU',
      a.TRANSACTION_TYPE_DESC = 'Instant Finance Authorization Request'
WHEN NOT MATCHED THEN
    INSERT(a.TRANSACTION_TYPE, a.TRANSACTION_TYPE_DESC)
    VALUES(b.TRANSACTION_TYPE, b.TRANSACTION_TYPE_DESC);

Error:

Error at Command Line : 5 Column : 9
Error report -
SQL Error: ORA-38104: Columns referenced in the ON Clause cannot be updated: "A"."TRANSACTION_TYPE"
38104. 00000 -  "Columns referenced in the ON Clause cannot be updated: %s"
*Cause:    LHS of UPDATE SET contains the columns referenced in the ON Clause
*Action:

Body:
As the error message indicates, it is not possible to update the fields that are used in the on clause.

You'll have to do this kind of update in a separate statement. Something like this:

UPDATE DIM_TRANS_TYPE
SET    TRANSACTION_TYPE = 'IFAU',
       TRANSACTION_TYPE_DESC = 'Instant Finance Authorization Request'
WHERE  TRANSACTION_TYPE IN (
            SELECT TRANSATION_TYPE
            FROM   (SELECT 'ILAU' TRANSACTION_TYPE,
                           'Instant Loan Authorization Request' TRANSACTION_TYPE_DESC
                    FROM DUAL)
       );

MERGE INTO DIM_TRANS_TYPE a
USING      (SELECT 'ILAU' TRANSACTION_TYPE,
                   'Instant Loan Authorization Request' TRANSACTION_TYPE_DESC
            FROM   DUAL) b
        ON (a.TRANSACTION_TYPE = b.TRANSACTION_TYPE)
WHEN NOT MATCHED THEN
    INSERT(TRANSACTION_TYPE, TRANSACTION_TYPE_DESC)
    VALUES(b.TRANSACTION_TYPE, b.TRANSACTION_TYPE_DESC);

You may want to execute this in a transaction, so that the changes incurred by either both or neither of these statements are committed.

Of course, the IN clause looks a bit exaggerated as the value could simply be compared with ILAU, but I assume you simplified the question when in reality you have a bigger dataset to get the transaction_type values from.


问:
Date picker and list picker (multiple time zones) to create a scheduled date string
On the UI side of this project, there is a date picker and list picker intended to allow users to select a future time and date for specific time zones to schedule an alert to be broadcasted by voice, SMS, email, etc. Unfortunately, though, the GMT offset does not correctly adjust. For instance, an alert scheduled for Berlin, Germany (GMT+0200) for June 7, 2017, 17:33 actually yields the next day at 02:30 Berlin time.

2017-06-08 00:33:00 +0200

1. Would anyone know what may cause this discrepancy and how to
    correct it for all time zones?

2. What steps are necessary to adjust all the scheduled
    times to Central Daylight Time?

Screenshot of New Alert View Controller

In the NewAlertTableViewController.m, this function updates the date picker label:

```<code>- (void) updateDateLabel {
    NSDate *now                  = [NSDate date];
    NSDate *scheduledDate        = self.datePicker.date;
    if ([scheduledDate isToday] && scheduledDate.hour <= now.hour && scheduledDate.minute <= now.minute) {
        self.dateLabel.text      = NSLocalizedString(@"Now", @"label for time an alert is scheduled to be sent");
        self.sendButton.title    = NSLocalizedString(@"Send Alert", @"button label for sending an alert");
        self.alert.sendNow       = YES;
    } else if ([scheduledDate isToday]) {
        self.dateLabel.text      = [NSString stringWithFormat: NSLocalizedString(@"Today, %@", @"label for time an alert is scheduled to be sent"), [scheduledDate stringWithDateStyle: NSDateFormatterNoStyle                                                                                timeStyle: NSDateFormatterShortStyle]];
        self.sendButton.title    = NSLocalizedString(@"Save Alert", @"button label for saving an alert");
        self.alert.sendNow       = NO;
    } else {
        self.dateLabel.text      = [scheduledDate stringWithDateStyle: NSDateFormatterShortStyle
                                                            timeStyle: NSDateFormatterShortStyle];
        self.sendButton.title    = NSLocalizedString(@"Save Alert", @"button label for saving an alert");
        self.alert.sendNow       = NO;
    }
    self.alert.scheduledDate     = scheduledDate;
    DDLogInfo(@"Date Picker: %@", scheduledDate);
}
</code>```

Also in the NewAlertTableViewController.m, we have this delegate to handle the time zone picker view:

```<code>- (void) pickerView: (UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent: (NSInteger)component {
    NSString *timeZone;
    NSString *timeZoneCity;
    NSDateFormatter *systemTimeZoneFormatter = [NSDateFormatter new];
    systemTimeZoneFormatter.timeZone         = [NSTimeZone localTimeZone];
    systemTimeZoneFormatter.dateFormat       = @"Z";
    NSString *systemTimeZoneOffset           = [systemTimeZoneFormatter stringFromDate: [NSDate date]];
    switch (row) {
        case 0:
            timeZone     = (@"GMT%@", systemTimeZoneOffset);
            timeZoneCity = @"Device Default";
            break;
        case 1:
            timeZone     = @"GMT+02:00";
            timeZoneCity = @"Berlin";
            break;
        case 2:
            timeZone     = @"GMT+01:00";
            timeZoneCity = @"London";
            break;
        case 3:
            timeZone     = @"GMT-04:00";
            timeZoneCity = @"New York";
            break;
        case 4:
            timeZone     = @"GMT-05:00";
            timeZoneCity = @"Chicago";
            break;
        case 5:
            timeZone     = @"GMT-06:00";
            timeZoneCity = @"Denver";
            break;
        case 6:
            timeZone     = @"GMT-07:00";
            timeZoneCity = @"Los Angeles";
            break;
        case 7:
            timeZone     = @"GMT-08:00";
            timeZoneCity = @"Anchorage";
            break;
        case 8:
            timeZone     = @"GMT-10:00";
            timeZoneCity = @"Honolulu";
            break;
        default:
            break;
    }
    [self updateTimeZone: timeZone];
    [[NSUserDefaults standardUserDefaults] setObject: timeZone forKey: @"timeZonePreference"];
    DDLogInfo(@"Time Zone Picker: %@, %@", timeZone, timeZoneCity);
    _timeZoneLabel.text = timeZoneCity;
}
</code>```

Yet again in the NewAlertTableViewController.m, this function updates the time zone:

```<code>- (void) updateTimeZone: (id)timeZone {
    self.now                     = [NSDate date];
    self.calendar                = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
    [self.calendar setTimeZone: [NSTimeZone timeZoneWithName: timeZone]];
    NSCalendarUnit units         = NSCalendarUnitHour;
    NSDateComponents *components = [self.calendar components: units fromDate: self.now];
    self.hours                   = (int)[components hour];
    self.alert.calendar          = self.calendar;
}
</code>```

In the Alert.m, we have this string that gets sent as a parameter to our CreateAlert.aspx endpoint. Ideally, we'd prefer all strings adjusted to Central Daylight Time (to match our server in Houston, TX) or at least Coordinated Universal Time (UTC).

```<code>- (NSString *)scheduledDateString { // This method solely uses the scheduledDate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat       = @"yyyy-MM-dd HH:mm:ss Z";
    dateFormatter.timeZone         = self.calendar.timeZone;
    NSString *dateString           = [dateFormatter stringFromDate: self.scheduledDate];
    DDLogInfo(@"Scheduled Date: %@", dateString);
    return dateString;
}
</code>```

答:
Here is some sample code to play with:

```<code>// User-selected Time Zone city
// using "Europe/Berlin" for this example
NSString *timeZoneName = @"Europe/Berlin";
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:timeZoneName];

// User-selected Date/Time (from the UIDatePicker)
NSDate *selDate = _datePicker.date;

// Current NSCalendar
NSCalendar *calendar = [NSCalendar currentCalendar];

// get all date components from the user-selected Date/Time
NSDateComponents *localComponents = [calendar components:-1 fromDate:selDate];

// set the Calendar to use the user-selected Time Zone
[calendar setTimeZone: timeZone];

// set the components with the values from localComponents
NSDateComponents *timeZoneComponents = [[NSDateComponents alloc] init];
[timeZoneComponents setYear:    [localComponents year]];
[timeZoneComponents setMonth:   [localComponents month]];
[timeZoneComponents setDay:     [localComponents day]];
[timeZoneComponents setHour:    [localComponents hour]];
[timeZoneComponents setMinute:  [localComponents minute]];
[timeZoneComponents setSecond:  [localComponents second]];

// get a NSDate object based on the user-selected Date/Time and Time Zone
// Note: if you print the default description of this date, it will show UTC value
NSDate *desiredDateTime = [calendar dateFromComponents:timeZoneComponents];
NSLog(@"%@", desiredDateTime);
</code>```

The key thing to remember is that a NSDate object is the same whether you are in London, New York, Houston, Honolulu, Tokyo, Berlin, etc, etc. The only difference is how it is displayed.

For example: Right now, it is almost 5:00 pm. But wait, when you read this, it is probably around 4:00 pm!!! How can that be? Well, I look at [NSDate date]; right now, I see "2017-06-07 20:55:56 +0000" - because that is the "absolute" date/time.

So, play with this code sample... try out different time zones (make sure you get the names right)... see if it all makes sense.

If I've done this right (it's possible I have a mistake or two here)... If you select Friday, June 16 at 10:00 am in your date picker (regardless of where in the world you are), and then run this code, the final NSLog() line should print:

```<code>2017-06-16 08:00:25 +0000
</code>```

Because UTC is 2-hours earlier than Berlin time.

Body:
On the UI side of this project, there is a date picker and list picker intended to allow users to select a future time and date for specific time zones to schedule an alert to be broadcasted by voice, SMS, email, etc. Unfortunately, though, the GMT offset does not correctly adjust. For instance, an alert scheduled for Berlin, Germany (GMT+0200) for June 7, 2017, 17:33 actually yields the next day at 02:30 Berlin time.

2017-06-08 00:33:00 +0200

1. Would anyone know what may cause this discrepancy and how to
    correct it for all time zones?

2. What steps are necessary to adjust all the scheduled
    times to Central Daylight Time?

Screenshot of New Alert View Controller

In the NewAlertTableViewController.m, this function updates the date picker label:

- (void) updateDateLabel {
    NSDate *now                  = [NSDate date];
    NSDate *scheduledDate        = self.datePicker.date;
    if ([scheduledDate isToday] && scheduledDate.hour <= now.hour && scheduledDate.minute <= now.minute) {
        self.dateLabel.text      = NSLocalizedString(@"Now", @"label for time an alert is scheduled to be sent");
        self.sendButton.title    = NSLocalizedString(@"Send Alert", @"button label for sending an alert");
        self.alert.sendNow       = YES;
    } else if ([scheduledDate isToday]) {
        self.dateLabel.text      = [NSString stringWithFormat: NSLocalizedString(@"Today, %@", @"label for time an alert is scheduled to be sent"), [scheduledDate stringWithDateStyle: NSDateFormatterNoStyle                                                                                timeStyle: NSDateFormatterShortStyle]];
        self.sendButton.title    = NSLocalizedString(@"Save Alert", @"button label for saving an alert");
        self.alert.sendNow       = NO;
    } else {
        self.dateLabel.text      = [scheduledDate stringWithDateStyle: NSDateFormatterShortStyle
                                                            timeStyle: NSDateFormatterShortStyle];
        self.sendButton.title    = NSLocalizedString(@"Save Alert", @"button label for saving an alert");
        self.alert.sendNow       = NO;
    }
    self.alert.scheduledDate     = scheduledDate;
    DDLogInfo(@"Date Picker: %@", scheduledDate);
}

Also in the NewAlertTableViewController.m, we have this delegate to handle the time zone picker view:

- (void) pickerView: (UIPickerView *)pickerView didSelectRow: (NSInteger)row inComponent: (NSInteger)component {
    NSString *timeZone;
    NSString *timeZoneCity;
    NSDateFormatter *systemTimeZoneFormatter = [NSDateFormatter new];
    systemTimeZoneFormatter.timeZone         = [NSTimeZone localTimeZone];
    systemTimeZoneFormatter.dateFormat       = @"Z";
    NSString *systemTimeZoneOffset           = [systemTimeZoneFormatter stringFromDate: [NSDate date]];
    switch (row) {
        case 0:
            timeZone     = (@"GMT%@", systemTimeZoneOffset);
            timeZoneCity = @"Device Default";
            break;
        case 1:
            timeZone     = @"GMT+02:00";
            timeZoneCity = @"Berlin";
            break;
        case 2:
            timeZone     = @"GMT+01:00";
            timeZoneCity = @"London";
            break;
        case 3:
            timeZone     = @"GMT-04:00";
            timeZoneCity = @"New York";
            break;
        case 4:
            timeZone     = @"GMT-05:00";
            timeZoneCity = @"Chicago";
            break;
        case 5:
            timeZone     = @"GMT-06:00";
            timeZoneCity = @"Denver";
            break;
        case 6:
            timeZone     = @"GMT-07:00";
            timeZoneCity = @"Los Angeles";
            break;
        case 7:
            timeZone     = @"GMT-08:00";
            timeZoneCity = @"Anchorage";
            break;
        case 8:
            timeZone     = @"GMT-10:00";
            timeZoneCity = @"Honolulu";
            break;
        default:
            break;
    }
    [self updateTimeZone: timeZone];
    [[NSUserDefaults standardUserDefaults] setObject: timeZone forKey: @"timeZonePreference"];
    DDLogInfo(@"Time Zone Picker: %@, %@", timeZone, timeZoneCity);
    _timeZoneLabel.text = timeZoneCity;
}

Yet again in the NewAlertTableViewController.m, this function updates the time zone:

- (void) updateTimeZone: (id)timeZone {
    self.now                     = [NSDate date];
    self.calendar                = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
    [self.calendar setTimeZone: [NSTimeZone timeZoneWithName: timeZone]];
    NSCalendarUnit units         = NSCalendarUnitHour;
    NSDateComponents *components = [self.calendar components: units fromDate: self.now];
    self.hours                   = (int)[components hour];
    self.alert.calendar          = self.calendar;
}

In the Alert.m, we have this string that gets sent as a parameter to our CreateAlert.aspx endpoint. Ideally, we'd prefer all strings adjusted to Central Daylight Time (to match our server in Houston, TX) or at least Coordinated Universal Time (UTC).

- (NSString *)scheduledDateString { // This method solely uses the scheduledDate
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat       = @"yyyy-MM-dd HH:mm:ss Z";
    dateFormatter.timeZone         = self.calendar.timeZone;
    NSString *dateString           = [dateFormatter stringFromDate: self.scheduledDate];
    DDLogInfo(@"Scheduled Date: %@", dateString);
    return dateString;
}

Body:
Here is some sample code to play with:

// User-selected Time Zone city
// using "Europe/Berlin" for this example
NSString *timeZoneName = @"Europe/Berlin";
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:timeZoneName];

// User-selected Date/Time (from the UIDatePicker)
NSDate *selDate = _datePicker.date;

// Current NSCalendar
NSCalendar *calendar = [NSCalendar currentCalendar];

// get all date components from the user-selected Date/Time
NSDateComponents *localComponents = [calendar components:-1 fromDate:selDate];

// set the Calendar to use the user-selected Time Zone
[calendar setTimeZone: timeZone];

// set the components with the values from localComponents
NSDateComponents *timeZoneComponents = [[NSDateComponents alloc] init];
[timeZoneComponents setYear:    [localComponents year]];
[timeZoneComponents setMonth:   [localComponents month]];
[timeZoneComponents setDay:     [localComponents day]];
[timeZoneComponents setHour:    [localComponents hour]];
[timeZoneComponents setMinute:  [localComponents minute]];
[timeZoneComponents setSecond:  [localComponents second]];

// get a NSDate object based on the user-selected Date/Time and Time Zone
// Note: if you print the default description of this date, it will show UTC value
NSDate *desiredDateTime = [calendar dateFromComponents:timeZoneComponents];
NSLog(@"%@", desiredDateTime);

The key thing to remember is that a NSDate object is the same whether you are in London, New York, Houston, Honolulu, Tokyo, Berlin, etc, etc. The only difference is how it is displayed.

For example: Right now, it is almost 5:00 pm. But wait, when you read this, it is probably around 4:00 pm!!! How can that be? Well, I look at [NSDate date]; right now, I see "2017-06-07 20:55:56 +0000" - because that is the "absolute" date/time.

So, play with this code sample... try out different time zones (make sure you get the names right)... see if it all makes sense.

If I've done this right (it's possible I have a mistake or two here)... If you select Friday, June 16 at 10:00 am in your date picker (regardless of where in the world you are), and then run this code, the final NSLog() line should print:

2017-06-16 08:00:25 +0000

Because UTC is 2-hours earlier than Berlin time.


答:
I would expect something like this:

```<code>SELECT TU.TempUserId
FROM  #TempUser TU
WHERE NOT EXISTS (SELECT 1
                  FROM #TempUserData TUD JOIN
                       #TempData TD
                       ON TD.TempDataId = TUD.TempDataId
                  WHERE TUD.TempUserId = TU.TempUserId AND
                        D.TempDesc LIKE '%Not%'
                 );
</code>```

I suspect your problem is that the first row for user 1 (the one with TempDataId = 1) meets the NOT EXISTS condition.

Title: Using a WHERE NOT EXISTS

Body:
I would expect something like this:

SELECT TU.TempUserId
FROM  #TempUser TU
WHERE NOT EXISTS (SELECT 1
                  FROM #TempUserData TUD JOIN
                       #TempData TD
                       ON TD.TempDataId = TUD.TempDataId
                  WHERE TUD.TempUserId = TU.TempUserId AND
                        D.TempDesc LIKE '%Not%'
                 );

I suspect your problem is that the first row for user 1 (the one with TempDataId = 1) meets the NOT EXISTS condition.


问:
JedisConnectionException: Unexpected end of stream error
I am trying to perform rpush operation and encountered the following error:

```<code>redis.clients.jedis.exceptions.JedisConnectionException: Unexpected end of stream.
    at redis.clients.util.RedisInputStream.ensureFill(RedisInputStream.java:199) ~[jedis-2.9.0.jar:na]
    at redis.clients.util.RedisInputStream.readByte(RedisInputStream.java:40) ~[jedis-2.9.0.jar:na]
    at redis.clients.jedis.Protocol.process(Protocol.java:151) ~[jedis-2.9.0.jar:na]
    at redis.clients.jedis.Protocol.read(Protocol.java:215) ~[jedis-2.9.0.jar:na]
    at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:340) ~[jedis-2.9.0.jar:na]
    at redis.clients.jedis.Connection.getIntegerReply(Connection.java:265) ~[jedis-2.9.0.jar:na]
    at redis.clients.jedis.Jedis.rpush(Jedis.java:865) ~[jedis-2.9.0.jar:na]
    at
</code>```

Any idea to resolve this error?

答:
Please provide code snipped and confirm Jedis version you are using (as I may guess it's 2.9.0).

Previously, Jedis had same issue (connected with timeout configuration).

More details here:

https://github.com/xetorthio/jedis/issues/1029

https://github.com/xetorthio/jedis/issues/932

ContentLicense: CC BY-SA 4.0

Body:
I am trying to perform rpush operation and encountered the following error:

redis.clients.jedis.exceptions.JedisConnectionException: Unexpected end of stream.
    at redis.clients.util.RedisInputStream.ensureFill(RedisInputStream.java:199) ~[jedis-2.9.0.jar:na]
    at redis.clients.util.RedisInputStream.readByte(RedisInputStream.java:40) ~[jedis-2.9.0.jar:na]
    at redis.clients.jedis.Protocol.process(Protocol.java:151) ~[jedis-2.9.0.jar:na]
    at redis.clients.jedis.Protocol.read(Protocol.java:215) ~[jedis-2.9.0.jar:na]
    at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:340) ~[jedis-2.9.0.jar:na]
    at redis.clients.jedis.Connection.getIntegerReply(Connection.java:265) ~[jedis-2.9.0.jar:na]
    at redis.clients.jedis.Jedis.rpush(Jedis.java:865) ~[jedis-2.9.0.jar:na]
    at

Any idea to resolve this error?


问:
can I use subquery in the inner join condition sql
table (Trips)

```<code>| Id | Client_Id | Driver_Id | City_Id |     Status      |Request_at|

| 1  |     1     |    10     |    1    |     completed      |2013-10-01|

| 2  |     2     |    10     |    1    |     completed      |2013-10-02|

| 3  |     3     |    11     |    6    |     completed      |2013-10-03|
</code>```

table ( users)

```<code>Users_Id    | Banned |  Role  |

|    1     |   No   | client |

|    2     |   Yes  | client |

|    3     |   No   | client |

|    4     |   No      | driver|
</code>```

How can I join these 2 tables (trips, users) on the condition that the user role needs to be client and these clients should be unbanned.
I am trying to use a subquery but I got "single-row subquery returns more than one row"error and not sure what went wrong.

```<code>SELECT * FROM Trips
INNER JOIN users
ON client_id = (SELECT users_id from users
                  where
                  role = 'Client' and  banned = 'No');
</code>```

答:
Try</p>

```<code>SELECT * FROM Trips
INNER JOIN users ON users.users_id = Trips.Client_ID
WHERE users.Banned = 'No' AND users.Role = 'client'
</code>```

Body:
table (Trips)

| Id | Client_Id | Driver_Id | City_Id |     Status      |Request_at|

| 1  |     1     |    10     |    1    |     completed      |2013-10-01|

| 2  |     2     |    10     |    1    |     completed      |2013-10-02|

| 3  |     3     |    11     |    6    |     completed      |2013-10-03|

table ( users)

Users_Id    | Banned |  Role  |

|    1     |   No   | client |

|    2     |   Yes  | client |

|    3     |   No   | client |

|    4     |   No      | driver|

How can I join these 2 tables (trips, users) on the condition that the user role needs to be client and these clients should be unbanned.
I am trying to use a subquery but I got "single-row subquery returns more than one row"error and not sure what went wrong.

SELECT * FROM Trips
INNER JOIN users
ON client_id = (SELECT users_id from users
                  where
                  role = 'Client' and  banned = 'No');

Body:
Try

SELECT * FROM Trips
INNER JOIN users ON users.users_id = Trips.Client_ID
WHERE users.Banned = 'No' AND users.Role = 'client'


问:
How do I open a dialog as soon as an application is initialized?
I'm trying to open a modal dialog as soon as a WPF application has started (using ShowDialog(this)). I tried the following methods, both of which throw an InvalidOperationException, presumably because the window hasn't been initialized yet:

```<code>public MainWindow()
{
    InitializeComponent();

    ShowMyDialogDammit();
}
</code>```

and:

```<code>public MainWindow()
{
    InitializeComponent();
}

protected override void OnInitialized(EventArgs e)
{
    base.OnInitialized(e);
    ShowMyDialogDammit();
}
</code>```

How do I do this?

答:
Add a handler for the FrameworkElement.Loaded event (which occurs "when the element is laid out, rendered, and ready for interaction"), and then open your dialog from within the event handler.

For example:

```<code>public MainWindow()
{
    InitializeComponent();

    // Adding the event handler
    Loaded += new RoutedEventHandler(IsLoaded);
}

private void Loaded(object sender, RoutedEventArgs e)
{
    ShowMyDialogDammit();
}
</code>```

Body:
I'm trying to open a modal dialog as soon as a WPF application has started (using ShowDialog(this)). I tried the following methods, both of which throw an InvalidOperationException, presumably because the window hasn't been initialized yet:

public MainWindow()
{
    InitializeComponent();

    ShowMyDialogDammit();
}

and:

public MainWindow()
{
    InitializeComponent();
}

protected override void OnInitialized(EventArgs e)
{
    base.OnInitialized(e);
    ShowMyDialogDammit();
}

How do I do this?

Body:
Add a handler for the FrameworkElement.Loaded event (which occurs "when the element is laid out, rendered, and ready for interaction"), and then open your dialog from within the event handler.

For example:

public MainWindow()
{
    InitializeComponent();

    // Adding the event handler
    Loaded += new RoutedEventHandler(IsLoaded);
}

private void Loaded(object sender, RoutedEventArgs e)
{
    ShowMyDialogDammit();
}


问:
Simple PIPE program does reads strange characters
I have created a straightforward program with processes that does one very basic thing: the child writes, the father reads.
Strangely, the father only read strange characters and I do not know why (I've been trying for past hour to deduct why, but no success.

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

// cp = Child -> Parent,  pc = Parent -> child
int cp[2], pc[2];
int main (){
    char str[13]="Hello World";
    char received[13];
    pid_t pid;
    pid = fork();
    if (pid == -1){
        printf("An error occured!\n");
        exit(1);
    }
    int res = pipe(cp);
    if (res == -1){
        printf("Error when creating pipe!..\n");
        exit(1);
    }
    //pipe(pc);
    if (pid==0){
        // Child process
        close(cp[0]);
        write(cp[1], str, 10);
        close(cp[1]);
        exit(0);
    }else{
        // Parent process
        close(cp[1]);
        read(cp[0], received, 10);
        close(cp[0]);
        printf("We received from child: %s\n", received);
        exit(1);
    }
    return 0;
}
</code>```

Examples of outputs:
1) We received from child: @
2) We received from child: �XCV�

答:
Your main problem is that you create your pipe after that you fork your process.

```<code>int cp[2];
int res = pipe(cp); // create the pipe before
if (res == -1) {
    perror("pipe()");
    return 1;
}
pid_t pid = fork(); // so child and parent share the same pipe
if (pid == -1) {
    perror("fork()");
    return 1;
}
</code>```

A tutorial about pipe grant by codekaizer.

read() is used to read bytes from a file descriptor. It will not add a nul byte at the end of the buffer.

You must put it yourself:

```<code>char received[42];
ssize_t n = read(cp[0], received, sizeof received - 1);
if (n == -1) {
    perror("read()");
    return 1;
}
received[n] = '\0';
printf("%s\n", received);
</code>```

Body:
I have created a straightforward program with processes that does one very basic thing: the child writes, the father reads.
Strangely, the father only read strange characters and I do not know why (I've been trying for past hour to deduct why, but no success.

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

// cp = Child -> Parent,  pc = Parent -> child
int cp[2], pc[2];
int main (){
    char str[13]="Hello World";
    char received[13];
    pid_t pid;
    pid = fork();
    if (pid == -1){
        printf("An error occured!\n");
        exit(1);
    }
    int res = pipe(cp);
    if (res == -1){
        printf("Error when creating pipe!..\n");
        exit(1);
    }
    //pipe(pc);
    if (pid==0){
        // Child process
        close(cp[0]);
        write(cp[1], str, 10);
        close(cp[1]);
        exit(0);
    }else{
        // Parent process
        close(cp[1]);
        read(cp[0], received, 10);
        close(cp[0]);
        printf("We received from child: %s\n", received);
        exit(1);
    }
    return 0;
}

Examples of outputs:
1) We received from child: @
2) We received from child: �XCV�

Body:
Your main problem is that you create your pipe after that you fork your process.

int cp[2];
int res = pipe(cp); // create the pipe before
if (res == -1) {
    perror("pipe()");
    return 1;
}
pid_t pid = fork(); // so child and parent share the same pipe
if (pid == -1) {
    perror("fork()");
    return 1;
}

A tutorial about pipe grant by codekaizer.

read() is used to read bytes from a file descriptor. It will not add a nul byte at the end of the buffer.

You must put it yourself:

char received[42];
ssize_t n = read(cp[0], received, sizeof received - 1);
if (n == -1) {
    perror("read()");
    return 1;
}
received[n] = '\0';
printf("%s\n", received);


问:
Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."
Important notice:

If you register for testing, go to your profile settings and to your interests add delete profile.

Trying to login with Facebook to my website:

I get the following error:

URL Blocked: This redirect failed because the redirect URI is not
  whitelisted in the app’s Client OAuth Settings. Make sure Client and
  Web OAuth Login are on and add all your app domains as Valid OAuth
  Redirect URIs.

My settings (Basics) in Facebook are:

App Domains: openstrategynetwork.com

Site URL for website: http://openstrategynetwork.com/

In the advanced tab, Valid OAuth redirect URIs is set to:

http://openstrategynetwork.com/_oauth/facebook?close

App is public.

More settings (Advanced) here:

App key and secret are correct. I'm using Meteor and its accounts packages.

答:
Login Helper of your site

$loginUrl       = $helper->getLoginUrl('xyz.com/user_by_facebook/', $permissions);

and in facebook application dashboard  (Under products tab  : Facebook Login )

Valid OAuth redirect URIs should also be same to xyz.com/user_by_facebook/

as mentioned earlier while making request from web


问:
PreparedStatement IN clause alternatives?
What are the best workarounds for using a SQL IN clause with instances of java.sql.PreparedStatement, which is not supported for multiple values due to SQL injection attack security issues: One ? placeholder represents one value, rather than a list of values.

Consider the following SQL statement:

```<code>SELECT my_column FROM my_table where search_column IN (?)
</code>```

Using preparedStatement.setString( 1, "'A', 'B', 'C'" ); is essentially a non-working attempt at a workaround of the reasons for using ? in the first place.

What workarounds are available?

答:
PreparedStatement doesn't provide any good way to deal with SQL IN clause. Per http://www.javaranch.com/journal/200510/Journal200510.jsp#a2 "You can't substitute things that are meant to become part of the SQL statement. This is necessary because if the SQL itself can change, the driver can't precompile the statement. It also has the nice side effect of preventing SQL injection attacks." I ended up using following approach:</p>

```<code>String query = "SELECT my_column FROM my_table where search_column IN ($searchColumns)";
query = query.replace("$searchColumns", "'A', 'B', 'C'");
Statement stmt = connection.createStatement();
boolean hasResults = stmt.execute(query);
do {
    if (hasResults)
        return stmt.getResultSet();

    hasResults = stmt.getMoreResults();

} while (hasResults || stmt.getUpdateCount() != -1);
</code>```

OwnerDisplayName: Chris Mazzola

Body:
What are the best workarounds for using a SQL IN clause with instances of java.sql.PreparedStatement, which is not supported for multiple values due to SQL injection attack security issues: One ? placeholder represents one value, rather than a list of values.

Consider the following SQL statement:

SELECT my_column FROM my_table where search_column IN (?)

Using preparedStatement.setString( 1, "'A', 'B', 'C'" ); is essentially a non-working attempt at a workaround of the reasons for using ? in the first place.

What workarounds are available?

LastEditorDisplayName: Chris Mazzola

Body:
PreparedStatement doesn't provide any good way to deal with SQL IN clause. Per http://www.javaranch.com/journal/200510/Journal200510.jsp#a2 "You can't substitute things that are meant to become part of the SQL statement. This is necessary because if the SQL itself can change, the driver can't precompile the statement. It also has the nice side effect of preventing SQL injection attacks." I ended up using following approach:

String query = "SELECT my_column FROM my_table where search_column IN ($searchColumns)";
query = query.replace("$searchColumns", "'A', 'B', 'C'");
Statement stmt = connection.createStatement();
boolean hasResults = stmt.execute(query);
do {
    if (hasResults)
        return stmt.getResultSet();

    hasResults = stmt.getMoreResults();

} while (hasResults || stmt.getUpdateCount() != -1);


问:
Counter in arrays c++
i have a really simple code right there that counts how much values you need in arrays.

```<code>for (int i = 0; i < dm; i++)
    {
        if (arr[i] == c)
        {
            counter++;
        }
    };
</code>```

But i need to make it a little bit tricky.I need to count number of same values. Imagine i have an array {4,4,4,3,3,2,2,1,1,0,0,0} and i need to find how much "twins" there. So 3,2,1 are twins because they have only 1 exact friend.
I tried something like 2 fors and 2 counters but still have troubles. Thanks. Hope you understand what i mean by "twin". x and x are twins and y,y,y are not ( just in case)

答:
I'd make a map that counts - for each individual number in the array - their occurrences. The code could look as follows:

```<code>#include <iostream>
#include <map>

int main()
{
    const int numberOfElements = 12;

    int array[numberOfElements] = { 4,4,4,3,3,2,2,1,1,0,0,0 };
    std::map<int,int> counts;
    for (int i=0; i < numberOfElements; i++) {
        counts[array[i]]++;
    }
    for (auto x : counts) {
        if (x.second == 2) {
            cout << "pair: " << x.first << endl;
        }
    }
    return 0;
}
</code>```

If  - for some reason - the range of the elements is limited, you could also use a "plain" array for counting the occurrences. If, for example, the elements are in the range of 0..4, you could use the following fragment:

```<code>const int numberOfElements = 12;
const int elementMax = 4;

int array[numberOfElements] = { 4,4,4,3,3,2,2,1,1,0,0,0 };
int counts[elementMax+1] = {};
for (int i=0; i<numberOfElements; i++) {
    counts[array[i]]++;
}
for (int i=0; i <= elementMax; i++) {
    if (counts[i] == 2) {
        cout << "pair: " << i << endl;
    }
}
</code>```

And if your array is sorted, than a solution without a counter-array could look as follows:

```<code>const int numberOfElements = 12;

int array[numberOfElements] = { 4,4,4,3,3,2,2,1,1,0,0,0 };
int prev = -1;
int count = 0;
for (int i=0; i<numberOfElements; i++) {
    if (array[i] == prev) {
      count++;
    }
    else {
        if (count == 2) {
            cout << "pair: " << prev << endl;
        }
        count=1;
        prev = array[i];
    }
}
if (prev >= 0 && count==2) {
    cout << "pair: " << prev << endl;
}
</code>```

Title: Counter in arrays c++

Body:
i have a really simple code right there that counts how much values you need in arrays.

for (int i = 0; i < dm; i++)
    {
        if (arr[i] == c)
        {
            counter++;
        }
    };

But i need to make it a little bit tricky.I need to count number of same values. Imagine i have an array {4,4,4,3,3,2,2,1,1,0,0,0} and i need to find how much "twins" there. So 3,2,1 are twins because they have only 1 exact friend.
I tried something like 2 fors and 2 counters but still have troubles. Thanks. Hope you understand what i mean by "twin". x and x are twins and y,y,y are not ( just in case)

Body:
I'd make a map that counts - for each individual number in the array - their occurrences. The code could look as follows:

#include <iostream>
#include <map>

int main()
{
    const int numberOfElements = 12;

    int array[numberOfElements] = { 4,4,4,3,3,2,2,1,1,0,0,0 };
    std::map<int,int> counts;
    for (int i=0; i < numberOfElements; i++) {
        counts[array[i]]++;
    }
    for (auto x : counts) {
        if (x.second == 2) {
            cout << "pair: " << x.first << endl;
        }
    }
    return 0;
}

If  - for some reason - the range of the elements is limited, you could also use a "plain" array for counting the occurrences. If, for example, the elements are in the range of 0..4, you could use the following fragment:

const int numberOfElements = 12;
const int elementMax = 4;

int array[numberOfElements] = { 4,4,4,3,3,2,2,1,1,0,0,0 };
int counts[elementMax+1] = {};
for (int i=0; i<numberOfElements; i++) {
    counts[array[i]]++;
}
for (int i=0; i <= elementMax; i++) {
    if (counts[i] == 2) {
        cout << "pair: " << i << endl;
    }
}

And if your array is sorted, than a solution without a counter-array could look as follows:

const int numberOfElements = 12;

int array[numberOfElements] = { 4,4,4,3,3,2,2,1,1,0,0,0 };
int prev = -1;
int count = 0;
for (int i=0; i<numberOfElements; i++) {
    if (array[i] == prev) {
      count++;
    }
    else {
        if (count == 2) {
            cout << "pair: " << prev << endl;
        }
        count=1;
        prev = array[i];
    }
}
if (prev >= 0 && count==2) {
    cout << "pair: " << prev << endl;
}


问:
Good reference + feature/syntax comparison matrix for SQL databases?
I am looking for a reference guide with possibility one or more comparison matrices for various SQL databases. The goal being to be able to see quickly what functions/operators/statements of the SQL standards (yes, plural would be good :) are supported by each and what syntax they use for them.

And then something similar for additional features as well, possibly matching them with equivalent features in other databases.

For instance, I'd like to be able to quickly see if database A, B, C support the LIKE operator and if they all support both the % and _ placeholders.

This Wikipedia comparison of several RDBMS mentioned in similar questions gives some interesting info but not to the extent of the syntactic features and operator support.

Preferably, I'm looking for a reference containing said info for at least the following tables:

Oracle,

PostgreSQL,

DB2,

HSQLDB,

MS SQL,

MySQL.

Haven't managed to find a good consolidated and usable reference for this over the past few days. Thanks.

答:
I have found this reference very useful:

Comparison of different SQL implementations


问:
Formatting a csv file
I have a csv file with no formatting. I need to format the csv file.

```<code>import pandas
df = pandas.read_csv('abc.csv')
df['speed'] = df['speed'].map('{:06,.2f}'.format)
df.to_csv("FINAL.csv")
</code>```

Error:

```<code>Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "C:\Python27\ArcGIS10.4\lib\site-packages\pandas\core\series.py", line 2009, in map
mapped = map_f(values, arg)
File "pandas\src\inference.pyx", line 1064, in pandas.lib.map_infer (pandas\lib.c:58525)
ValueError: Unknown format code 'f' for object of type 'str'
</code>```

For Example:

```<code>df['speed'] = [54,156,3]
</code>```

Expected output:

```<code>speed
054.00
156.00
003.00
</code>```

答:
Remove the comma in your string formatting and it should work.

```<code>import pandas as pd
df = pd.DataFrame([54,156,3])
df[0].map('{:06.2f}'.format)
</code>```

output:

```<code>054.00
156.00
003.00
</code>```

Here's a reasource for string formatting:

https://pyformat.info/

Edit:

It sounds like this is a problem of messy data. I suggest trying the following options when reading your csv file:

```<code>df = pandas.read_csv('abc.csv', dtype=object)
df['speed'] = df['speed'].apply(pd.to_numeric, errors='coerce')
df['speed'] = df['speed'].map('{:06.2f}'.format)
</code>```

errors='coerce' will try to convert to float, and return NaN if it fails to do so.

Title: Formatting a csv file

Body:
I have a csv file with no formatting. I need to format the csv file.

import pandas
df = pandas.read_csv('abc.csv')
df['speed'] = df['speed'].map('{:06,.2f}'.format)
df.to_csv("FINAL.csv")

Error:

Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "C:\Python27\ArcGIS10.4\lib\site-packages\pandas\core\series.py", line 2009, in map
mapped = map_f(values, arg)
File "pandas\src\inference.pyx", line 1064, in pandas.lib.map_infer (pandas\lib.c:58525)
ValueError: Unknown format code 'f' for object of type 'str'

For Example:

df['speed'] = [54,156,3]

Expected output:

speed
054.00
156.00
003.00

Body:
Remove the comma in your string formatting and it should work.

import pandas as pd
df = pd.DataFrame([54,156,3])
df[0].map('{:06.2f}'.format)

output:

054.00
156.00
003.00

Here's a reasource for string formatting:

https://pyformat.info/

Edit:

It sounds like this is a problem of messy data. I suggest trying the following options when reading your csv file:

df = pandas.read_csv('abc.csv', dtype=object)
df['speed'] = df['speed'].apply(pd.to_numeric, errors='coerce')
df['speed'] = df['speed'].map('{:06.2f}'.format)

errors='coerce' will try to convert to float, and return NaN if it fails to do so.


问:
Filter a list by pattern matching
How can I filter a list, keeping the items that match a pattern, removing ones that don't?

For example, if I have a list of lists, I would like a function...

```<code>singleItemLists :: [[Int]] -> [[Int]]
</code>```

... to remove all items that don't match the pattern [x].

Ideally, answers should be fairly straightforward to convert to other patterns.

答:
One way to do it is with a list comprehension

```<code>singleItemLists :: [[Int]] -> [[Int]]
singleItemLists xs = [[x] | [x] <- xs]
</code>```

It can be argued that this isn't clear, as it's not explicit that lists of length other than 1 are dropped.

Title: Filter a list by pattern matching

Body:
How can I filter a list, keeping the items that match a pattern, removing ones that don't?

For example, if I have a list of lists, I would like a function...

singleItemLists :: [[Int]] -> [[Int]]

... to remove all items that don't match the pattern [x].

Ideally, answers should be fairly straightforward to convert to other patterns.

Body:
One way to do it is with a list comprehension

singleItemLists :: [[Int]] -> [[Int]]
singleItemLists xs = [[x] | [x] <- xs]

It can be argued that this isn't clear, as it's not explicit that lists of length other than 1 are dropped.


问:
can't delete from specific row from generate table from mySQL
Hye, i'm working on a small project of Inventory system. Everything is okay until this last part. I have included a delete button at the end of each row for user to delete any item of choice, but when user press the delete button, it deleted the last row of the table, instead of the row/item of choices, where is my mistake in my coding?

Thank you!

<?php
 $result= mysql_query("SELECT * from Staff ORDER BY status");
 $count=1;

 while($row=mysql_fetch_array($result)){
?>

       <?php echo $count; ?>
    <?php echo $row['staffId']; ?>
    <?php echo $row['name']; ?>
    <?php echo $row['address'];?>
    <?php echo $row['pNum'];?>
    <?php echo $row['status'];?>
    <?php echo $row['type'];?>
                <input type="submit" name="deleteStaff" value="Delete" onClick="displayMessage()">
             <input type="hidden" name="staffId1" value="<?PHP echo $row['staffId']; ?>">

<?php
 $count++; }
 if(isset($_POST['deleteStaff'])){
  $id=$_POST['staffId1'];
  $result=mysql_query("DELETE from Staff WHERE staffId='$id' ");
  if($result){
   echo '';
   }
   else{
    ?>

                <?PHP
    }
  }
?>```

答:
If you include the same hidden field (StaffId1) for every record it will contain more then one value.

You are now listening to the pressed SUBMIT so you don't need the hidden field. You can just get the value if the pressed SUBMIT.

Button

```<code>type="submit" name="staffId" value="<?php echo $id ?>"
</code>```

Php

```<code>$id=$_POST['staffId'];
</code>```

Body:
If you include the same hidden field (StaffId1) for every record it will contain more then one value.

You are now listening to the pressed SUBMIT so you don't need the hidden field. You can just get the value if the pressed SUBMIT.

Button

type="submit" name="staffId" value="<?php echo $id ?>"

Php

$id=$_POST['staffId'];


问:
sending a packet to multiple client at a time from udp socket
I was trying to write a udp server who send an instance of a file to multiple clients.Now suppose any how I manage to know the address of those client statically(for the sake of simplicity) and now I want to send this packet to these addresses.So how exactly I need to fill the sockaddr structure to contain the address of these clients.I am taking an array of sockaddr structure(to contain client address) and trying to send at each one them at a time.Now problem is to fill the individual sockaddr structure to contain the client address.
I was trying to do something like that

```<code> sa[1].sin_family = AF_INET;
 sa[1].sin_addr.s_addr = htonl(INADDR_ANY);//should'nt I replace this INADDR_ANY with client ip??
 sa[1].sin_port = htons(50002);
</code>```

Correct me if this is not the correct way.
All your help in this regard will be highly appreciated.

With Thanks in advance,

Mawia

答:
As mentioned in a different answer, you're talking about multicast, but on the public Internet, that requires ISP support.

There is such a thing as an application level multicast infrastructure. This writeup, dating back to 2000, describes one such method.

Body:
I was trying to write a udp server who send an instance of a file to multiple clients.Now suppose any how I manage to know the address of those client statically(for the sake of simplicity) and now I want to send this packet to these addresses.So how exactly I need to fill the sockaddr structure to contain the address of these clients.I am taking an array of sockaddr structure(to contain client address) and trying to send at each one them at a time.Now problem is to fill the individual sockaddr structure to contain the client address.
I was trying to do something like that

 sa[1].sin_family = AF_INET;
 sa[1].sin_addr.s_addr = htonl(INADDR_ANY);//should'nt I replace this INADDR_ANY with client ip??
 sa[1].sin_port = htons(50002);

Correct me if this is not the correct way.
All your help in this regard will be highly appreciated.

With Thanks in advance,

Mawia


问:
Using a WHERE NOT EXISTS
I am trying and failing miserably to create a simple WHERE NOT EXISTS Clause. Assume the following example,

```<code>CREATE TABLE #TempUser ( TempUserId INT, TempUserName VARCHAR(50) )

CREATE TABLE #TempData ( TempDataId INT, TempDesc VARCHAR(50) )

CREATE TABLE #TempUserData ( TempUserId INT, TempDataId INT )

INSERT #TempUser ( TempUserId, TempUserName )
VALUES  ( 1, 'Paul' ),
        ( 2, 'Franics' ),
        ( 3, 'Raj' )

INSERT #TempData ( TempDataId, TempDesc )
VALUES  ( 1, 'Test Exists'),
        ( 2, 'Test Not Exists')

INSERT #TempUserData ( TempUserId, TempDataId )
VALUES  ( 1, 1 ),
        ( 1, 2 ),
        ( 2, 1 )

SELECT TU.TempUserId
FROM
    #TempUser AS TU
    LEFT JOIN #TempUserData AS TUD ON TUD.TempUserId = TU.TempUserId
WHERE
    NOT EXISTS (SELECT * FROM #TempData AS TD WHERE TD.TempDataId = TUD.TempDataId AND TD.TempDesc LIKE '%Not%')
</code>```

All that I am trying to do is get the list of Users from the #TempUser table who does not have a specific data record, in this case Test Not Exists. The expected result set is UserId 2 and 3, as you can see executing the above will give 1, 2 and 3. So anyone out there who could help me out, please?

答:
A slight modification to your existing query with one more left join and aggregation.

```<code>SELECT TU.TempUserId
FROM #TempUser AS TU
LEFT JOIN #TempUserData AS TUD ON TUD.TempUserId = TU.TempUserId
LEFT JOIN #TempData AS TD ON TD.TempDataId = TUD.TempDataId AND TD.TempDesc LIKE '%Not%'
GROUP BY TU.TempUserId
HAVING COUNT(TD.TempDesc) = 0
</code>```

Title: Using a WHERE NOT EXISTS

Body:
I am trying and failing miserably to create a simple WHERE NOT EXISTS Clause. Assume the following example,

CREATE TABLE #TempUser ( TempUserId INT, TempUserName VARCHAR(50) )

CREATE TABLE #TempData ( TempDataId INT, TempDesc VARCHAR(50) )

CREATE TABLE #TempUserData ( TempUserId INT, TempDataId INT )

INSERT #TempUser ( TempUserId, TempUserName )
VALUES  ( 1, 'Paul' ),
        ( 2, 'Franics' ),
        ( 3, 'Raj' )

INSERT #TempData ( TempDataId, TempDesc )
VALUES  ( 1, 'Test Exists'),
        ( 2, 'Test Not Exists')

INSERT #TempUserData ( TempUserId, TempDataId )
VALUES  ( 1, 1 ),
        ( 1, 2 ),
        ( 2, 1 )

SELECT TU.TempUserId
FROM
    #TempUser AS TU
    LEFT JOIN #TempUserData AS TUD ON TUD.TempUserId = TU.TempUserId
WHERE
    NOT EXISTS (SELECT * FROM #TempData AS TD WHERE TD.TempDataId = TUD.TempDataId AND TD.TempDesc LIKE '%Not%')

All that I am trying to do is get the list of Users from the #TempUser table who does not have a specific data record, in this case Test Not Exists. The expected result set is UserId 2 and 3, as you can see executing the above will give 1, 2 and 3. So anyone out there who could help me out, please?

Body:
A slight modification to your existing query with one more left join and aggregation.

SELECT TU.TempUserId
FROM #TempUser AS TU
LEFT JOIN #TempUserData AS TUD ON TUD.TempUserId = TU.TempUserId
LEFT JOIN #TempData AS TD ON TD.TempDataId = TUD.TempDataId AND TD.TempDesc LIKE '%Not%'
GROUP BY TU.TempUserId
HAVING COUNT(TD.TempDesc) = 0


问:
ember-simple-auth and torii firebase TypeError: Converting circular structure to JSON
I started out getting torri and emberfire to work for a login page but when I try to use that with ember simple auth I get the error:

```<code>TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
    at Class.persist (local-storage.js:45)
    at Class.persist (adaptive.js:163)
    at Class._callStoreAsync (internal-session.js:132)
    at Class._updateStore (internal-session.js:207)
    at Class._setup (internal-session.js:156)
    at internal-session.js:61
    at tryCatch (ember.debug.js:50180)
    at invokeCallback (ember.debug.js:50195)
    at publish (ember.debug.js:50163)
</code>```

Not sure if its a bug or I'm missing something that needs setting up. Made a quick repo which shows my problem https://github.com/tobias-g/ember-simple-auth-firebase where the diff https://github.com/tobias-g/ember-simple-auth-firebase/commit/02882f4db3a0320d4ac314d2e92192ac522470f8 shows what I added to try and get ember simple auth to work.

```<code>DEBUG: -------------------------------
DEBUG: Ember             : 2.13.3
DEBUG: Ember Data        : 2.13.1
DEBUG: Firebase          : 3.9.0
DEBUG: EmberFire         : 0.0.0
DEBUG: jQuery            : 3.2.1
DEBUG: Ember Simple Auth : 1.3.0
DEBUG: -------------------------------
</code>```

答:
The data.authenticated payload sent back by Emberfire is too complex and has circular references. Ember Simple Auth stores this payload to local storage to prevent log-in prompts when refreshing or opening the app on other tabs.

What seems to work for me now (I haven't tested much) is extending the session store. YMMV.

```<code>// app/session-stores/application.js

import AdaptiveStore from 'ember-simple-auth/session-stores/adaptive';

export default AdaptiveStore.extend({

  persist(data) {
    const a = data.authenticated;

    const subset = {
      authenticator: a.authenticator,
      email: a.email,
      provider: a.provider,
      refreshToken: a.refreshToken,
      uid: a.uid
    }

    return this._super({ authenticated: subset });
  }

});
</code>```

Body:
I started out getting torri and emberfire to work for a login page but when I try to use that with ember simple auth I get the error:

TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
    at Class.persist (local-storage.js:45)
    at Class.persist (adaptive.js:163)
    at Class._callStoreAsync (internal-session.js:132)
    at Class._updateStore (internal-session.js:207)
    at Class._setup (internal-session.js:156)
    at internal-session.js:61
    at tryCatch (ember.debug.js:50180)
    at invokeCallback (ember.debug.js:50195)
    at publish (ember.debug.js:50163)

Not sure if its a bug or I'm missing something that needs setting up. Made a quick repo which shows my problem https://github.com/tobias-g/ember-simple-auth-firebase where the diff https://github.com/tobias-g/ember-simple-auth-firebase/commit/02882f4db3a0320d4ac314d2e92192ac522470f8 shows what I added to try and get ember simple auth to work.

DEBUG: -------------------------------
DEBUG: Ember             : 2.13.3
DEBUG: Ember Data        : 2.13.1
DEBUG: Firebase          : 3.9.0
DEBUG: EmberFire         : 0.0.0
DEBUG: jQuery            : 3.2.1
DEBUG: Ember Simple Auth : 1.3.0
DEBUG: -------------------------------

Body:
The data.authenticated payload sent back by Emberfire is too complex and has circular references. Ember Simple Auth stores this payload to local storage to prevent log-in prompts when refreshing or opening the app on other tabs.

What seems to work for me now (I haven't tested much) is extending the session store. YMMV.

// app/session-stores/application.js

import AdaptiveStore from 'ember-simple-auth/session-stores/adaptive';

export default AdaptiveStore.extend({

  persist(data) {
    const a = data.authenticated;

    const subset = {
      authenticator: a.authenticator,
      email: a.email,
      provider: a.provider,
      refreshToken: a.refreshToken,
      uid: a.uid
    }

    return this._super({ authenticated: subset });
  }

});


问:
Send email async: An asynchronous module or handler completed while an asynchronous operation was still pending
I'm trying to send email from a Controller asynchronous and getting the following error:

I don't want to wait email be sent to complete the action.

An asynchronous module or handler completed while an asynchronous
  operation was still pending.

This is my implementation: I also tried using void instead async Task

```<code>public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    var user = await _userManager.FindByNameAsync(model.Email);
    if (user != null)
    {
        if (!await _userManager.IsEmailConfirmedAsync(user.Id))
        {

            //dont want to await result
            //just send email
            _mailService.SendAccountConfirmationEmailAsync(user);
            ...
        }
        ...
    }
    return View();
}
</code>```

.

```<code>public async Task SendAccountConfirmationEmailAsync(ApplicationUser user)
{
    dynamic email = GetAccountConfirmationEmailTemplate();

    email.Username = user.Email;
    email.Name = user.UserName;
    email.To = user.Email;
    email.AccountConfirmationUrl = await GetAccountConfirmationUrl(user);

    await _mailService.SendAsync(email);
}
</code>```

What am I missing?

答:
Since the runtime can recycle your appdomain when it knows there are no more pending requests, starting tasks that you don't wait for is specifically not recommended, hence that message.

In particular, without this check you would have no guarantee this email would ever be sent since the entire appdomain could be yanked down around that task after your controller action returns.

Now in your case you might say that the loss of the email is acceptable, but the runtime doesn't know that it is only an email, it could very well be your database call that you've forgotten to wait for that would be prematurely aborted. Hence it just informs you that this is bad form.

Instead you got two options:

Wait for that task to complete, which you have specifically said you don't want to do

Inform the runtime that you're firing off a task that you specifically don't want to wait for, but please oh please, don't yank out the appdomain before task has completed

This last part is what HostingEnvironment.QueueBackgroundWorkItem is for.

In your case you would call it like this:

```<code>HostingEnvironment.QueueBackgroundWorkItem(ct =>
    _mailService.SendAccountConfirmationEmailAsync(user));
</code>```

Additionally, the method provides a CancellationToken, you should check if there is an overload of SendAccountConfirmationEmailAsync that accepts it. If not, and if this is your API, you should consider adding support for such tokens.

Please be aware that this mechanism is not meant for long-running threads or tasks, for that there are other more appropriate trees to bark up, but in this case it should be enough.

Body:
I'm trying to send email from a Controller asynchronous and getting the following error:

I don't want to wait email be sent to complete the action.

An asynchronous module or handler completed while an asynchronous
  operation was still pending.

This is my implementation: I also tried using void instead async Task

public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    var user = await _userManager.FindByNameAsync(model.Email);
    if (user != null)
    {
        if (!await _userManager.IsEmailConfirmedAsync(user.Id))
        {

            //dont want to await result
            //just send email
            _mailService.SendAccountConfirmationEmailAsync(user);
            ...
        }
        ...
    }
    return View();
}

.

public async Task SendAccountConfirmationEmailAsync(ApplicationUser user)
{
    dynamic email = GetAccountConfirmationEmailTemplate();

    email.Username = user.Email;
    email.Name = user.UserName;
    email.To = user.Email;
    email.AccountConfirmationUrl = await GetAccountConfirmationUrl(user);

    await _mailService.SendAsync(email);
}

What am I missing?

Body:
Since the runtime can recycle your appdomain when it knows there are no more pending requests, starting tasks that you don't wait for is specifically not recommended, hence that message.

In particular, without this check you would have no guarantee this email would ever be sent since the entire appdomain could be yanked down around that task after your controller action returns.

Now in your case you might say that the loss of the email is acceptable, but the runtime doesn't know that it is only an email, it could very well be your database call that you've forgotten to wait for that would be prematurely aborted. Hence it just informs you that this is bad form.

Instead you got two options:

Wait for that task to complete, which you have specifically said you don't want to do

Inform the runtime that you're firing off a task that you specifically don't want to wait for, but please oh please, don't yank out the appdomain before task has completed

This last part is what HostingEnvironment.QueueBackgroundWorkItem is for.

In your case you would call it like this:

HostingEnvironment.QueueBackgroundWorkItem(ct =>
    _mailService.SendAccountConfirmationEmailAsync(user));

Additionally, the method provides a CancellationToken, you should check if there is an overload of SendAccountConfirmationEmailAsync that accepts it. If not, and if this is your API, you should consider adding support for such tokens.

Please be aware that this mechanism is not meant for long-running threads or tasks, for that there are other more appropriate trees to bark up, but in this case it should be enough.


问:
React Router sub-route call a different parent route
Version 4 of React Router

I have a sub-route setup:/profile/agree and on that sub-route I want a <Link> tag to go to /team.

It's setup right now so the parent page has:

```<code><Router>
  <Switch>
    <Route exact path="/" component={Home} />
    <Route path="/profile" component={Profile} />
    <Route path="/team" component={Team} />
  </Switch>
</Router>
</code>```

And the profile component has it's own routing:

```<code><Router>
  <Switch>
    <Route exact path="/profile" component={General} />
    <Route path="/profile/hotel" component={Hotel} />
    <Route path="/profile/release" component={Release} />
  </Switch>
</Router>
</code>```

Whether this is right or not, I'm not sure since none of the docs seem to explain this type of scenario, but it made sense to me.  Anyway when that "Release" component has a simple link, it doesn't seem to navigate properly and just shows a blank page:

```<code><a href="/team">Somehow</a> {/* << This works but refreshes the whole page */}
<Link to="/team">Of Course</Link> {/* << This just shows empty profile page /*}
</code>```

I thought maybe the sub-router can only look up as high as itself, so perhaps:

```<code><Link to="../team">Of Course</Link>
</code>```

But that did the same thing.  It seems to remain on the "profile" main route.  How does one navigate to a different parent route?

答:
So I eventually figured out the simple error I had.  The fact that Profile had <Router> in it!

Doing this worked in Profile (simply removed Router tag):

```<code>  <Switch>
   <Route exact path="/profile" component={General} />
   <Route path="/profile/hotel" component={Hotel} />
   <Route path="/profile/release" component={Release} />
 </Switch>
</code>```

This gives me what I think makes the most sense.  Each "scene" is responsible for it's own routing.  The only downside is it still needs /profile, although I could probably get crafty and send the "root" as a property to the scenes.

Body:
Version 4 of React Router

I have a sub-route setup:/profile/agree and on that sub-route I want a <Link> tag to go to /team.

It's setup right now so the parent page has:

<Router>
  <Switch>
    <Route exact path="/" component={Home} />
    <Route path="/profile" component={Profile} />
    <Route path="/team" component={Team} />
  </Switch>
</Router>

And the profile component has it's own routing:

<Router>
  <Switch>
    <Route exact path="/profile" component={General} />
    <Route path="/profile/hotel" component={Hotel} />
    <Route path="/profile/release" component={Release} />
  </Switch>
</Router>

Whether this is right or not, I'm not sure since none of the docs seem to explain this type of scenario, but it made sense to me.  Anyway when that "Release" component has a simple link, it doesn't seem to navigate properly and just shows a blank page:

Somehow {/* << This works but refreshes the whole page */}
<Link to="/team">Of Course</Link> {/* << This just shows empty profile page /*}

I thought maybe the sub-router can only look up as high as itself, so perhaps:

<Link to="../team">Of Course</Link>

But that did the same thing.  It seems to remain on the "profile" main route.  How does one navigate to a different parent route?

Body:
So I eventually figured out the simple error I had.  The fact that Profile had <Router> in it!

Doing this worked in Profile (simply removed Router tag):

  <Switch>
   <Route exact path="/profile" component={General} />
   <Route path="/profile/hotel" component={Hotel} />
   <Route path="/profile/release" component={Release} />
 </Switch>

This gives me what I think makes the most sense.  Each "scene" is responsible for it's own routing.  The only downside is it still needs /profile, although I could probably get crafty and send the "root" as a property to the scenes.


问:
Why is numpy slower than for loop
Update: this feature is now in sciPy.stats.qmc.discrepancy and was ported to Cython and also parallelised.

I have a function using some for loops and I wanted to improve the speed using numpy. But this seems not to do the trick as the bumpy version appears to be 2 times slower. Here is the code:

```<code>import numpy as np
import itertools
import timeit

def func():
    sample = np.random.random_sample((100, 2))

    disc1 = 0
    disc2 = 0
    n_sample = len(sample)
    dim = sample.shape[1]

    for i in range(n_sample):
        prod = 1
        for k in range(dim):
            sub = np.abs(sample[i, k] - 0.5)
            prod *= 1 + 0.5 * sub - 0.5 * sub ** 2

        disc1 += prod

    for i, j in itertools.product(range(n_sample), range(n_sample)):
        prod = 1
        for k in range(dim):
            a = 0.5 * np.abs(sample[i, k] - 0.5)
            b = 0.5 * np.abs(sample[j, k] - 0.5)
            c = 0.5 * np.abs(sample[i, k] - sample[j, k])
            prod *= 1 + a + b - c
        disc2 += prod

    c2 = (13 / 12) ** dim - 2 / n_sample * disc1 + 1 / (n_sample ** 2) * disc2

def func_numpy():
    sample = np.random.random_sample((100, 2))

    disc1 = 0
    disc2 = 0
    n_sample = len(sample)
    dim = sample.shape[1]

    disc1 = np.sum(np.prod(1 + 0.5 * np.abs(sample - 0.5) - 0.5 * np.abs(sample - 0.5) ** 2, axis=1))

    for i, j in itertools.product(range(n_sample), range(n_sample)):
        disc2 += np.prod(1 + 0.5 * np.abs(sample[i] - 0.5) + 0.5 * np.abs(sample[j] - 0.5) - 0.5 * np.abs(sample[i] - sample[j]))

    c2 = (13 / 12) ** dim - 2 / n_sample * disc1 + 1 / (n_sample ** 2) * disc2

print('Normal function time: ' , timeit.repeat('func()', number=20, repeat=5, setup="from __main__ import func"))
print('numpy function time: ', timeit.repeat('func_numpy()', number=20, repeat=5, setup="from __main__ import func_numpy"))
</code>```

The timing output is:

```<code>Normal function time:  [2.831496894999873, 2.832342429959681, 2.8009242500411347, 2.8075121529982425, 2.824807019031141]
numpy function time:  [5.154757721000351, 5.2011515340418555, 5.148996959964279, 5.095560318033677, 5.125199959962629]
</code>```

What am I missing here? I know that the bottleneck is the itertools part because I have a 100x100x2 loop instead of a 100x2 loop before.
Do you see another way to do that?

答:
With NumPy, one must look to vectorize things and we could certainly do  so here.

Taking a closer look at the loop portion, we are iterating along the first axis of the input data samples twice with that loop startup :

```<code>for i, j in itertools.product(range(n_sample), range(n_sample)):
</code>```

We could convert these iterations into vectorized operations, once we let broadcasting handle those.

Now, to have a fully vectorized solution, we would need a lot more memory space, specifically (N,N,M), where (N,M) is the shape of the input data.

Another noticeable aspect here is that at each iteration, we aren't doing a lot of work, as we are performing operation on each row and each row contains only 2 elements for the given sample. So, the idea that comes out is that we could run a loop along M, such that at each iteration, we would compute the prod and accumulate. Thus, for the given sample, its just two loop iterations.

Getting out of the loop, we would have the accumulated prod, that just needs summation for disc2 as the final output.

Here's an implementation to fulfil the above mentioned ideas -

```<code>prod_arr = 1
for i in range(sample.shape[1]):
    si = sample[:,i]
    prod_arr *= 1 + 0.5 * np.abs(si[:,None] - 0.5) + 0.5 * np.abs(si - 0.5) - \
                                    0.5 * np.abs(si[:,None] - si)
disc2 = prod_arr.sum()
</code>```

Runtime test

The stripped down version of the loopy portion from the original approach and the modified versions as approaches are listed below :

```<code>def org_app(sample):
    disc2 = 0
    n_sample = len(sample)
    for i, j in itertools.product(range(n_sample), range(n_sample)):
        disc2 += np.prod(1 + 0.5 * np.abs(sample[i] - 0.5) + 0.5 * \
            np.abs(sample[j] - 0.5) - 0.5 * np.abs(sample[i] - sample[j]))
    return disc2

def mod_app(sample):
    prod_arr = 1
    for i in range(sample.shape[1]):
        si = sample[:,i]
        prod_arr *= 1 + 0.5 * np.abs(si[:,None] - 0.5) + 0.5 * np.abs(si - 0.5) - \
                                        0.5 * np.abs(si[:,None] - si)
    disc2 = prod_arr.sum()
    return disc2
</code>```

Timings and verification -

```<code>In [10]: sample = np.random.random_sample((100, 2))

In [11]: org_app(sample)
Out[11]: 11934.878683659041

In [12]: mod_app(sample)
Out[12]: 11934.878683659068

In [14]: %timeit org_app(sample)
10 loops, best of 3: 84.4 ms per loop

In [15]: %timeit mod_app(sample)
10000 loops, best of 3: 94.6 µs per loop
</code>```

About 900x speedup! Well this should be motivating enough, hopefully to look to vectorize things whenever possible.

Title: Why is numpy slower than for loop

Body:
Update: this feature is now in sciPy.stats.qmc.discrepancy and was ported to Cython and also parallelised.

I have a function using some for loops and I wanted to improve the speed using numpy. But this seems not to do the trick as the bumpy version appears to be 2 times slower. Here is the code:

import numpy as np
import itertools
import timeit

def func():
    sample = np.random.random_sample((100, 2))

    disc1 = 0
    disc2 = 0
    n_sample = len(sample)
    dim = sample.shape[1]

    for i in range(n_sample):
        prod = 1
        for k in range(dim):
            sub = np.abs(sample[i, k] - 0.5)
            prod *= 1 + 0.5 * sub - 0.5 * sub ** 2

        disc1 += prod

    for i, j in itertools.product(range(n_sample), range(n_sample)):
        prod = 1
        for k in range(dim):
            a = 0.5 * np.abs(sample[i, k] - 0.5)
            b = 0.5 * np.abs(sample[j, k] - 0.5)
            c = 0.5 * np.abs(sample[i, k] - sample[j, k])
            prod *= 1 + a + b - c
        disc2 += prod

    c2 = (13 / 12) ** dim - 2 / n_sample * disc1 + 1 / (n_sample ** 2) * disc2

def func_numpy():
    sample = np.random.random_sample((100, 2))

    disc1 = 0
    disc2 = 0
    n_sample = len(sample)
    dim = sample.shape[1]

    disc1 = np.sum(np.prod(1 + 0.5 * np.abs(sample - 0.5) - 0.5 * np.abs(sample - 0.5) ** 2, axis=1))

    for i, j in itertools.product(range(n_sample), range(n_sample)):
        disc2 += np.prod(1 + 0.5 * np.abs(sample[i] - 0.5) + 0.5 * np.abs(sample[j] - 0.5) - 0.5 * np.abs(sample[i] - sample[j]))

    c2 = (13 / 12) ** dim - 2 / n_sample * disc1 + 1 / (n_sample ** 2) * disc2

print('Normal function time: ' , timeit.repeat('func()', number=20, repeat=5, setup="from __main__ import func"))
print('numpy function time: ', timeit.repeat('func_numpy()', number=20, repeat=5, setup="from __main__ import func_numpy"))

The timing output is:

Normal function time:  [2.831496894999873, 2.832342429959681, 2.8009242500411347, 2.8075121529982425, 2.824807019031141]
numpy function time:  [5.154757721000351, 5.2011515340418555, 5.148996959964279, 5.095560318033677, 5.125199959962629]

What am I missing here? I know that the bottleneck is the itertools part because I have a 100x100x2 loop instead of a 100x2 loop before.
Do you see another way to do that?

Body:
With NumPy, one must look to vectorize things and we could certainly do  so here.

Taking a closer look at the loop portion, we are iterating along the first axis of the input data samples twice with that loop startup :

for i, j in itertools.product(range(n_sample), range(n_sample)):

We could convert these iterations into vectorized operations, once we let broadcasting handle those.

Now, to have a fully vectorized solution, we would need a lot more memory space, specifically (N,N,M), where (N,M) is the shape of the input data.

Another noticeable aspect here is that at each iteration, we aren't doing a lot of work, as we are performing operation on each row and each row contains only 2 elements for the given sample. So, the idea that comes out is that we could run a loop along M, such that at each iteration, we would compute the prod and accumulate. Thus, for the given sample, its just two loop iterations.

Getting out of the loop, we would have the accumulated prod, that just needs summation for disc2 as the final output.

Here's an implementation to fulfil the above mentioned ideas -

prod_arr = 1
for i in range(sample.shape[1]):
    si = sample[:,i]
    prod_arr *= 1 + 0.5 * np.abs(si[:,None] - 0.5) + 0.5 * np.abs(si - 0.5) - \
                                    0.5 * np.abs(si[:,None] - si)
disc2 = prod_arr.sum()

Runtime test

The stripped down version of the loopy portion from the original approach and the modified versions as approaches are listed below :

def org_app(sample):
    disc2 = 0
    n_sample = len(sample)
    for i, j in itertools.product(range(n_sample), range(n_sample)):
        disc2 += np.prod(1 + 0.5 * np.abs(sample[i] - 0.5) + 0.5 * \
            np.abs(sample[j] - 0.5) - 0.5 * np.abs(sample[i] - sample[j]))
    return disc2

def mod_app(sample):
    prod_arr = 1
    for i in range(sample.shape[1]):
        si = sample[:,i]
        prod_arr *= 1 + 0.5 * np.abs(si[:,None] - 0.5) + 0.5 * np.abs(si - 0.5) - \
                                        0.5 * np.abs(si[:,None] - si)
    disc2 = prod_arr.sum()
    return disc2

Timings and verification -

In [10]: sample = np.random.random_sample((100, 2))

In [11]: org_app(sample)
Out[11]: 11934.878683659041

In [12]: mod_app(sample)
Out[12]: 11934.878683659068

In [14]: %timeit org_app(sample)
10 loops, best of 3: 84.4 ms per loop

In [15]: %timeit mod_app(sample)
10000 loops, best of 3: 94.6 µs per loop

About 900x speedup! Well this should be motivating enough, hopefully to look to vectorize things whenever possible.


问:
Is it possible to pass the elements of a list as arguments of one function call in C#?
I am writing a bot designed to interact with an online game. I am using a function called "Send" which is defined like so:

```<code>public void Send(string type, params object[] parameters);
</code>```

"Send" is a function which can have a variable number of arguments, thanks to the params keyword. If I am storing these arguments in a List<object>, can I pass this list of arguments to the function without having to write different code for each possible number of arguments?

I know that if that params keyword wasn't there I could just pass the whole list as one argument using List<T>.ToArray(), but the Send function is defined in a preprepared library which I can't alter.

答:
but the Send function is defined in a preprepared library which I can't alter.

You could define an extension method,

```<code>// Where Lib is the type that contains the Send method.
public static class MyExtensions
{
    public static void Send(this Lib lib, string type, int obj)
    {
        lib.Send(type, obj);
    }

    public static void Send(this Lib lib, string type, List<object> objs)
    {
        lib.Send(type, objs.ToArray());
    }

    // Other overloads
}
</code>```

Then you use it just like it was built into the library to being with,

```<code>var lib = new Lib();
lib.Send(type, 1) // Call Send(this Lib lib, string type, int obj)
</code>```

Body:
I am writing a bot designed to interact with an online game. I am using a function called "Send" which is defined like so:

public void Send(string type, params object[] parameters);

"Send" is a function which can have a variable number of arguments, thanks to the params keyword. If I am storing these arguments in a List<object>, can I pass this list of arguments to the function without having to write different code for each possible number of arguments?

I know that if that params keyword wasn't there I could just pass the whole list as one argument using List<T>.ToArray(), but the Send function is defined in a preprepared library which I can't alter.

Body:
but the Send function is defined in a preprepared library which I can't alter.

You could define an extension method,

// Where Lib is the type that contains the Send method.
public static class MyExtensions
{
    public static void Send(this Lib lib, string type, int obj)
    {
        lib.Send(type, obj);
    }

    public static void Send(this Lib lib, string type, List<object> objs)
    {
        lib.Send(type, objs.ToArray());
    }

    // Other overloads
}

Then you use it just like it was built into the library to being with,

var lib = new Lib();
lib.Send(type, 1) // Call Send(this Lib lib, string type, int obj)