问:
Verify a user's email address before confirming registration, with Flutter and Firebase
I've created a login and registration screen that works with my Flutter app, using Firebase as the backend authentication service. I'm able to switch between the login, registration and reset password screens well.

The Issue

At the moment, the registration screen accepts any email address that is entered, whether or not it is real. For example, if I were to type in gvevg@gverwbgw.com, it would allow the user to register. This is obviously an issue, when it comes to fake accounts and spam etc.

The Aim

I would basically like to be able to edit my code, to automatically generate an email address verification email, which prevents the user from signing in, before their email address has been verified. The code I have made uses a Future, FirebaseAuth and async/await to make this happen.

My Current Code

Firstly, I define an AuthBase abstract class, that creates the 'createUserWithEmailAndPassword' function (amongst others) as follows:

```<code>abstract class AuthBase {
  Stream<User> get onAuthStateChanged;
  Future<User> currentUser();
  Future<User> createUserWithEmailAndPassword(String email, String password);
}
</code>```

Then, I create an Auth function, that implements AuthBase, gets the current user from Firebase and creates the registration Future function, as follows:

```<code>class Auth implements AuthBase {
  final _firebaseAuth = FirebaseAuth.instance;

  // This creates the user ID token variable (if one doesn't already exist) which is then populated using one of the login methods.
  User _userFromFirebase(FirebaseUser user) {
    if (user == null) {
      return null;
    }
    return User(uid: user.uid);
  }

  // This helps to get the user from Google Firebase, noting if there is or isn't a user with those login details already.
  @override
  Stream<User> get onAuthStateChanged {
    return _firebaseAuth.onAuthStateChanged.map(_userFromFirebase);
  }

  // This identifies the current user, who is logged in at the time.
  @override
  Future<User> currentUser() async {
    final user = await _firebaseAuth.currentUser();
    return _userFromFirebase(user);
  }

  // This creates the user account for an email-and-password sign-in, with firebase, if it doesn't already exist.
  @override
  Future<User> createUserWithEmailAndPassword(
      String email, String password) async {
    final authResult = await _firebaseAuth.createUserWithEmailAndPassword(
        email: email, password: password);
    return _userFromFirebase(authResult.user);
  }
}
</code>```

My Question

How do I edit my code, so that it allows me to implement email verification automatically for any user that wants to sign in with email? I believe the sendEmailVerification() function must use FirebaseUser, although I am not sure how to implement it here. I would appreciate any help. Thanks!

答:
Email+password authentication requires nothing more than that the user knows the combination of email+password. It doesn't in itself require the email address to be verified to sign in. If you want the email address to be verified before allowing access to other data, you can do that by checking the user's token for the email_verified claim for example in the security rules of your database.

Also see:

How do I lock down Firebase Database to any user from a specific (email) domain?

Firebase email verification at SignUp

How to prevent user authentication in Firebase/Vue.js BEFORE email is verified

Only let pre-verified users log into Firebase

Body:
I've created a login and registration screen that works with my Flutter app, using Firebase as the backend authentication service. I'm able to switch between the login, registration and reset password screens well.

The Issue

At the moment, the registration screen accepts any email address that is entered, whether or not it is real. For example, if I were to type in gvevg@gverwbgw.com, it would allow the user to register. This is obviously an issue, when it comes to fake accounts and spam etc.

The Aim

I would basically like to be able to edit my code, to automatically generate an email address verification email, which prevents the user from signing in, before their email address has been verified. The code I have made uses a Future, FirebaseAuth and async/await to make this happen.

My Current Code

Firstly, I define an AuthBase abstract class, that creates the 'createUserWithEmailAndPassword' function (amongst others) as follows:

abstract class AuthBase {
  Stream<User> get onAuthStateChanged;
  Future<User> currentUser();
  Future<User> createUserWithEmailAndPassword(String email, String password);
}

Then, I create an Auth function, that implements AuthBase, gets the current user from Firebase and creates the registration Future function, as follows:

class Auth implements AuthBase {
  final _firebaseAuth = FirebaseAuth.instance;

  // This creates the user ID token variable (if one doesn't already exist) which is then populated using one of the login methods.
  User _userFromFirebase(FirebaseUser user) {
    if (user == null) {
      return null;
    }
    return User(uid: user.uid);
  }

  // This helps to get the user from Google Firebase, noting if there is or isn't a user with those login details already.
  @override
  Stream<User> get onAuthStateChanged {
    return _firebaseAuth.onAuthStateChanged.map(_userFromFirebase);
  }

  // This identifies the current user, who is logged in at the time.
  @override
  Future<User> currentUser() async {
    final user = await _firebaseAuth.currentUser();
    return _userFromFirebase(user);
  }

  // This creates the user account for an email-and-password sign-in, with firebase, if it doesn't already exist.
  @override
  Future<User> createUserWithEmailAndPassword(
      String email, String password) async {
    final authResult = await _firebaseAuth.createUserWithEmailAndPassword(
        email: email, password: password);
    return _userFromFirebase(authResult.user);
  }
}

My Question

How do I edit my code, so that it allows me to implement email verification automatically for any user that wants to sign in with email? I believe the sendEmailVerification() function must use FirebaseUser, although I am not sure how to implement it here. I would appreciate any help. Thanks!


来源: stackexchange

问:
building flink 1.10 encountered a package not found error
I am importing flink source code to IDEA as the official website guide

error:org.apache.flink.sql.parser.impl does not exist

description:the error resulted from an import in the interface
  org.apache.flink.sql.parser.utils.ParseResource

the import line is:

```<code>org.apache.flink.sql.impl.ParseException
</code>```

I looked up for the "impl" package in the path but did not found it actually, I am not sure if I did something wrong following the steps, tell me if you know?

答: Some parts are generated through maven plugins. Make sure you either run a full mvn install locally before importing, or use IntelliJ generate source feature

ContentLicense: CC BY-SA 4.0

Body:
I am importing flink source code to IDEA as the official website guide

error:org.apache.flink.sql.parser.impl does not exist

description:the error resulted from an import in the interface
  org.apache.flink.sql.parser.utils.ParseResource

the import line is:

org.apache.flink.sql.impl.ParseException

I looked up for the "impl" package in the path but did not found it actually, I am not sure if I did something wrong following the steps, tell me if you know?


问:
visual basic error with trying to calculate average
I am trying to create a macro that gathers both a flat # count, and an average of existing values in a sheet. I'm getting an error at the line where i try to calculate the avgScore variable by dividing my summed up vulnScore by the counter value. I'm getting a 'runtime 6 error' at the 'avgScore = vulnScore / counter' line. It's working with a data set thats 77 lines long. I've tried converting the variables to Long (the only real suggestion I've found) but that has not worked. the 'element' variable is for an array thats about 26 in size containing string variables.

```<code>Dim counter As Long
Dim vulnScore As Long
Dim avgScore As Long
vulnScore = 0
counter = 0
avgScore = 0

Dim rowNum As Integer
''''''''''''''''''''
For Each element In arr
vulnScore = 0
counter = 0
avgScore = 0
'get #'s for putting into Treg
'''''''''
For i = 2 To Cells(Rows.Count, 3).End(xlUp).Row
If Cells(i, 3).Value = element Then
'# of times that server is listed
counter = counter + 1
'combining vulnerability scores for that server
vulnScore = vulnScore + Cells(i, 7).Value
End If
Next i
avgScore = vulnScore / counter
'''''''''

'find Treg column/row
colNum = WorksheetFunction.Match("Findings Variance (4/15 vs Current)", ActiveWorkbook.TREG.Range("1:1"), 0)
rowNum = WorksheetFunction.Match(element, ActiveWorkbook.TREG.Range("1:1"), 0)
Cells(rowNum, colNum - 1).Value = avgScore
Cells(rowNum, colNum - 2).Value = counter
'''''''''
Next element
</code>```

Sample: it's pulling data from this sheet which would be the activeSheet when the macro is run

Sample: it's pasting the data into the two blank columns in this sheet (TREG)

答:
try adding this code:

debug.print("Vulnscore: " & vulnScore & " Counter: " & counter & " avgScore: " & vulnScore / counter)

right before your line

```<code>avgScore = vulnScore / counter
</code>```

And have a look at what get's printed

Body:
I am trying to create a macro that gathers both a flat # count, and an average of existing values in a sheet. I'm getting an error at the line where i try to calculate the avgScore variable by dividing my summed up vulnScore by the counter value. I'm getting a 'runtime 6 error' at the 'avgScore = vulnScore / counter' line. It's working with a data set thats 77 lines long. I've tried converting the variables to Long (the only real suggestion I've found) but that has not worked. the 'element' variable is for an array thats about 26 in size containing string variables.

Dim counter As Long
Dim vulnScore As Long
Dim avgScore As Long
vulnScore = 0
counter = 0
avgScore = 0

Dim rowNum As Integer
''''''''''''''''''''
For Each element In arr
vulnScore = 0
counter = 0
avgScore = 0
'get #'s for putting into Treg
'''''''''
For i = 2 To Cells(Rows.Count, 3).End(xlUp).Row
If Cells(i, 3).Value = element Then
'# of times that server is listed
counter = counter + 1
'combining vulnerability scores for that server
vulnScore = vulnScore + Cells(i, 7).Value
End If
Next i
avgScore = vulnScore / counter
'''''''''

'find Treg column/row
colNum = WorksheetFunction.Match("Findings Variance (4/15 vs Current)", ActiveWorkbook.TREG.Range("1:1"), 0)
rowNum = WorksheetFunction.Match(element, ActiveWorkbook.TREG.Range("1:1"), 0)
Cells(rowNum, colNum - 1).Value = avgScore
Cells(rowNum, colNum - 2).Value = counter
'''''''''
Next element

Sample: it's pulling data from this sheet which would be the activeSheet when the macro is run

Sample: it's pasting the data into the two blank columns in this sheet (TREG)

Body:
try adding this code:

debug.print("Vulnscore: " & vulnScore & " Counter: " & counter & " avgScore: " & vulnScore / counter)

right before your line

avgScore = vulnScore / counter

And have a look at what get's printed


问:
Not able to set SalesItemLineDetail tax code in Intuit quickbooks api C#
I am trying to add Tax Code for SalesItemLineDetail inside Invoice of Quickbooks online api, but it is not setting tax code correctly when checking it in Online Quickbooks.

Here is my C# Code, which I am using to create Line Item

```<code>                            Line = new Intuit.Ipp.Data.Line();
                            InvoiceLine = new Intuit.Ipp.Data.SalesItemLineDetail();

                            InvoiceLine.ItemRef = new Intuit.Ipp.Data.ReferenceType
                            {
                                Value = GetItem.Id, // this is inventory Item Id
                                name = GetItem.Name // inventory item name
                            };

                            Line.DetailTypeSpecified = true;
                            Line.DetailType = Intuit.Ipp.Data.LineDetailTypeEnum.SalesItemLineDetail;
                            Line.Description = inv.Description;

                            Line.Amount = (inv.Price == null || inv.Price == 0.0) ? (decimal)0.00 : (decimal)inv.Price;
                            Line.AmountSpecified = true;

                            InvoiceLine.Qty = decimal.Parse(inv.Quantity.Value.ToString());
                            InvoiceLine.QtySpecified = true;

                            InvoiceLine.AnyIntuitObject = (inv.Price == null || inv.Price == 0.0) ? (decimal)0.00 : (decimal)(Math.Round(inv.Price.Value, 2) / inv.Quantity.Value);
                            InvoiceLine.ItemElementName = Intuit.Ipp.Data.ItemChoiceType.UnitPrice;

                            // this line is not settings tax code properly
                            InvoiceLine.TaxCodeRef = new Intuit.Ipp.Data.ReferenceType
                            {
                                name = taxName,
                                Value = TaxId

                            };

                            //Line Sales Item Line Detail - ServiceDate
                            InvoiceLine.ServiceDate = DateTime.Now.Date;
                            InvoiceLine.ServiceDateSpecified = true;

                            //Assign Sales Item Line Detail to Line Item

                            Line.AnyIntuitObject = InvoiceLine;

                            lines.Add(Line);

                    Intuit.Ipp.Data.Invoice invoice = new Intuit.Ipp.Data.Invoice();

                   // SalesOrder is a database table object, and OrderNumber is auto generated number

                    invoice.DocNumber = SalesOrder.OrderNumber.ToString();

                    //TxnDate
                    invoice.TxnDate = DateTime.Now.Date;
                    invoice.TxnDateSpecified = true;

                    invoice.CustomerRef = new Intuit.Ipp.Data.ReferenceType
                    {
                        Value =  CompanyId
                    };

                    //convert list to array for Intuit Line
                    invoice.Line = lines.ToArray();

                    //TxnTaxDetail
                    Intuit.Ipp.Data.Line taxLine = new Intuit.Ipp.Data.Line();
                    Intuit.Ipp.Data.TxnTaxDetail txnTaxDetail = new Intuit.Ipp.Data.TxnTaxDetail();
                    Intuit.Ipp.Data.TaxLineDetail taxLineDetail = new Intuit.Ipp.Data.TaxLineDetail(); ;
                    //txnTaxDetail.TotalTaxSpecified = true;
                    //txnTaxDetail.TotalTax = decimal.Parse("2");
                    var MainTaxValue = "";
                    txnTaxDetail.TxnTaxCodeRef = new Intuit.Ipp.Data.ReferenceType()
                    {

                        Value = TaxId,
                        name = SalesOrder.TaxCode.TaxCodeName
                    };
                    foreach (var TAXName in TaxObject.TaxRateDetail)
                    {
                        if(TAXName.TaxRateRef.name.Contains(SalesOrder.TaxCode.TaxCodeName))
                        {
                            MainTaxValue = TAXName.TaxRateRef.value;
                        }
                    }
                    taxLineDetail.TaxRateRef = new Intuit.Ipp.Data.ReferenceType
                    {
                        Value = MainTaxValue

                    };
                    taxLine.AnyIntuitObject = taxLineDetail;
                    txnTaxDetail.TaxLine = new Intuit.Ipp.Data.Line[] { taxLine };

                    //DueDate
                    invoice.DueDate = SalesOrder.InvoiceDueDate != null ? SalesOrder.InvoiceDueDate.Value : DateTime.Now.AddDays(30).Date;
                    invoice.DueDateSpecified = true;

                    invoice.TxnTaxDetail = txnTaxDetail;
</code>```

I have tried these reference links, but it is not working for me

https://gist.github.com/IntuitDeveloperRelations/6500373

How to export Line items with Tax Code and Value in QBO Canada

https://developer.intuit.com/app/developer/qbo/docs/develop/tutorials/manage-sales-tax-for-non-us-locales

Using above links, I can see we can create Tax Code ref using this line of code, for Each Invoice Line item, but it is not setting value correctly.

```<code>                           InvoiceLine.TaxCodeRef = new Intuit.Ipp.Data.ReferenceType
                            {
                                name = taxName,
                                Value = TaxId

                            };
</code>```

But it is not working.
Note: this is non-US company, so I have to specify tax code ref for each Invoice Line.

Edit 1:
Attaching Image of Postman API request, which I sent to Quickbooks for creating invoice.

答:
try by removing the name field  I think it might not be required</p>

```<code>InvoiceLine.TaxCodeRef = new Intuit.Ipp.Data.ReferenceType()
                        {

                            Value = TaxId

                        };
</code>```

Body:
I am trying to add Tax Code for SalesItemLineDetail inside Invoice of Quickbooks online api, but it is not setting tax code correctly when checking it in Online Quickbooks.

Here is my C# Code, which I am using to create Line Item

                            Line = new Intuit.Ipp.Data.Line();
                            InvoiceLine = new Intuit.Ipp.Data.SalesItemLineDetail();

                            InvoiceLine.ItemRef = new Intuit.Ipp.Data.ReferenceType
                            {
                                Value = GetItem.Id, // this is inventory Item Id
                                name = GetItem.Name // inventory item name
                            };

                            Line.DetailTypeSpecified = true;
                            Line.DetailType = Intuit.Ipp.Data.LineDetailTypeEnum.SalesItemLineDetail;
                            Line.Description = inv.Description;

                            Line.Amount = (inv.Price == null || inv.Price == 0.0) ? (decimal)0.00 : (decimal)inv.Price;
                            Line.AmountSpecified = true;

                            InvoiceLine.Qty = decimal.Parse(inv.Quantity.Value.ToString());
                            InvoiceLine.QtySpecified = true;

                            InvoiceLine.AnyIntuitObject = (inv.Price == null || inv.Price == 0.0) ? (decimal)0.00 : (decimal)(Math.Round(inv.Price.Value, 2) / inv.Quantity.Value);
                            InvoiceLine.ItemElementName = Intuit.Ipp.Data.ItemChoiceType.UnitPrice;

                            // this line is not settings tax code properly
                            InvoiceLine.TaxCodeRef = new Intuit.Ipp.Data.ReferenceType
                            {
                                name = taxName,
                                Value = TaxId

                            };

                            //Line Sales Item Line Detail - ServiceDate
                            InvoiceLine.ServiceDate = DateTime.Now.Date;
                            InvoiceLine.ServiceDateSpecified = true;

                            //Assign Sales Item Line Detail to Line Item

                            Line.AnyIntuitObject = InvoiceLine;

                            lines.Add(Line);

                    Intuit.Ipp.Data.Invoice invoice = new Intuit.Ipp.Data.Invoice();

                   // SalesOrder is a database table object, and OrderNumber is auto generated number

                    invoice.DocNumber = SalesOrder.OrderNumber.ToString();

                    //TxnDate
                    invoice.TxnDate = DateTime.Now.Date;
                    invoice.TxnDateSpecified = true;

                    invoice.CustomerRef = new Intuit.Ipp.Data.ReferenceType
                    {
                        Value =  CompanyId
                    };

                    //convert list to array for Intuit Line
                    invoice.Line = lines.ToArray();

                    //TxnTaxDetail
                    Intuit.Ipp.Data.Line taxLine = new Intuit.Ipp.Data.Line();
                    Intuit.Ipp.Data.TxnTaxDetail txnTaxDetail = new Intuit.Ipp.Data.TxnTaxDetail();
                    Intuit.Ipp.Data.TaxLineDetail taxLineDetail = new Intuit.Ipp.Data.TaxLineDetail(); ;
                    //txnTaxDetail.TotalTaxSpecified = true;
                    //txnTaxDetail.TotalTax = decimal.Parse("2");
                    var MainTaxValue = "";
                    txnTaxDetail.TxnTaxCodeRef = new Intuit.Ipp.Data.ReferenceType()
                    {

                        Value = TaxId,
                        name = SalesOrder.TaxCode.TaxCodeName
                    };
                    foreach (var TAXName in TaxObject.TaxRateDetail)
                    {
                        if(TAXName.TaxRateRef.name.Contains(SalesOrder.TaxCode.TaxCodeName))
                        {
                            MainTaxValue = TAXName.TaxRateRef.value;
                        }
                    }
                    taxLineDetail.TaxRateRef = new Intuit.Ipp.Data.ReferenceType
                    {
                        Value = MainTaxValue

                    };
                    taxLine.AnyIntuitObject = taxLineDetail;
                    txnTaxDetail.TaxLine = new Intuit.Ipp.Data.Line[] { taxLine };

                    //DueDate
                    invoice.DueDate = SalesOrder.InvoiceDueDate != null ? SalesOrder.InvoiceDueDate.Value : DateTime.Now.AddDays(30).Date;
                    invoice.DueDateSpecified = true;

                    invoice.TxnTaxDetail = txnTaxDetail;

I have tried these reference links, but it is not working for me

https://gist.github.com/IntuitDeveloperRelations/6500373

How to export Line items with Tax Code and Value in QBO Canada

https://developer.intuit.com/app/developer/qbo/docs/develop/tutorials/manage-sales-tax-for-non-us-locales

Using above links, I can see we can create Tax Code ref using this line of code, for Each Invoice Line item, but it is not setting value correctly.

                           InvoiceLine.TaxCodeRef = new Intuit.Ipp.Data.ReferenceType
                            {
                                name = taxName,
                                Value = TaxId

                            };

But it is not working.
Note: this is non-US company, so I have to specify tax code ref for each Invoice Line.

Edit 1:
Attaching Image of Postman API request, which I sent to Quickbooks for creating invoice.

Body:
try by removing the name field  I think it might not be required

InvoiceLine.TaxCodeRef = new Intuit.Ipp.Data.ReferenceType()
                        {

                            Value = TaxId

                        };


问:
IBM Domino - delete shared view & convert NSF application to NTF (template)
I have a very simple IBM Domino database with an XPages Java application and nothing else inside, I want to export it  as a template (ntf) instead of a database. If I just rename the nsf file with ntf extension, I can see the template in the application list when trying to create a new application, but it's icon is still a database icon and not the green template one. I tried searching online and looking through designer/admin options but found nothing that would help me.

Another question is, in the nsf I have one blank view and it's being displayed every time I open the application, I want to get rid of this view but I'm getting an error that I cannot delete the last shared view. It's annoying me because when opening the application for the first time it's being shown together with my about page, despite the launch options in application configuration are set to only display the "about" page.

How can I achieve these two things in IBM Domino 10?

答: In order for your application to be recognized as a template you need to set a template name on the design tab:


问:
Bash regex that returns short alphanumeric operator name from AT command AT+COPS
I'm using a bash script with the AT command AT+COPS=? which returns the following string :

```<code>+COPS: (1,"Orange F","Orange","20801",2),(1,"Swisscom","Swisscom","22801",7),(1,"Swisscom","Swisscom","22801",2),(1,"Salt","Salt","22803",2),(1,"Sunrise","Sunrise","22802",2),(1,"Sunrise","Sunrise","22802",7),(1,"Sunrise","Sunrise","22802",0),(2,"Salt","Salt","22803",7),(1,"Free","Free","20815",2),(1,"F SFR","SFR","20810",7),(1,"F-Bouygues Telecom","BYTEL","20820",7),,(0-4),(0-2)
</code>```

And I'm trying to find a regular expression to match every short alphanumeric operator names. So here, it's :

```<code>Orange Swisscom Swisscom Salt Sunrise Sunrise Sunrise Salt Free SFR BYTEL
</code>```

For example, in the group

```<code>(1,"F-Bouygues Telecom","BYTEL","20820",7)
</code>```

It's the 'BYTEL' part that is interesting. 'BYTEL' could be also lower-case chars and numbers.

I tried multiple solution but they are all not 100% matching. For the moment, I'm using :

```<code> grep -oP '"([a-zA-z])\w+"'
</code>```

but it would not work in some special cases and is matching also the long alphanumeric operator names (first name between quotes).

答:
using a combination of sed and awk</p>

```<code>sed 's/(/\n/g' file | awk -F, '{print gensub(/\"/,"","g", $3)}'

Orange
Swisscom
Swisscom
Salt
Sunrise
Sunrise
Sunrise
Salt
Free
SFR
BYTEL
</code>```

Body:
I'm using a bash script with the AT command AT+COPS=? which returns the following string :

+COPS: (1,"Orange F","Orange","20801",2),(1,"Swisscom","Swisscom","22801",7),(1,"Swisscom","Swisscom","22801",2),(1,"Salt","Salt","22803",2),(1,"Sunrise","Sunrise","22802",2),(1,"Sunrise","Sunrise","22802",7),(1,"Sunrise","Sunrise","22802",0),(2,"Salt","Salt","22803",7),(1,"Free","Free","20815",2),(1,"F SFR","SFR","20810",7),(1,"F-Bouygues Telecom","BYTEL","20820",7),,(0-4),(0-2)

And I'm trying to find a regular expression to match every short alphanumeric operator names. So here, it's :

Orange Swisscom Swisscom Salt Sunrise Sunrise Sunrise Salt Free SFR BYTEL

For example, in the group

(1,"F-Bouygues Telecom","BYTEL","20820",7)

It's the 'BYTEL' part that is interesting. 'BYTEL' could be also lower-case chars and numbers.

I tried multiple solution but they are all not 100% matching. For the moment, I'm using :

 grep -oP '"([a-zA-z])\w+"'

but it would not work in some special cases and is matching also the long alphanumeric operator names (first name between quotes).

Body:
using a combination of sed and awk

sed 's/(/\n/g' file | awk -F, '{print gensub(/\"/,"","g", $3)}'

Orange
Swisscom
Swisscom
Salt
Sunrise
Sunrise
Sunrise
Salt
Free
SFR
BYTEL


问:
Data Preparation End OF Every Month - Moving Over 12 Months
I have data prep procedure in SQL. I want to have data preparation at the end of every month
 Say I want the procedure run on last day of month e.g. on 31 January 2020 it should prep data from 1 January to 31 January.

So it's kind of moving window over all months of the year. Because I need data for evaluation at the end of each month.

I tried this, however, this does not give automation. Its sort of manual running end of every month

```<code>select '2020-10-01' as beginDate_AnalysisWindow
, '2020 -01-31' as endDate_AnalysisWindow
   into #AnalysisWindow --create temporary table #AnalysisWindow
</code>```

I also tried the following, however, I’m not sure if it does for the whole month or just one day?

```<code>SELECT START_OF_MONTH_DATE AS beginDate_AnalysisWindow
,END_OF_MONTH_DATE AS endDate_AnalysisWindow
INTO #AnalysisWindow
FROM [dbo].[Date] WITH (NOLOCK)
WHERE DATE = DATEADD(dd, - 1,  CAST(GETDATE() AS DATE))
</code>```

Could someone pls help me/give me some suggestions.

Thanks in advance

答:
If you want the last day of the current month, use eomonth():

```<code>WHERE DATE = CONVERT(date, EOMONTH(GETDATE()))
</code>```

Note:  This assumes that the date column has no time component.  If that is the case:

```<code>WHERE CONVERT(date, DATE) = CONVERT(date, EOMONTH(GETDATE()))
</code>```

SQL Server will still use an index (if available) even for this type of conversion.

EDIT:

To get the current months data, one method is:

```<code>WHERE DATE <= CONVERT(date, EOMONTH(GETDATE())) AND
      DATE > CONVERT(date, EOMONTH(GETDATE(), -1))
</code>```

The second argument to EOMONTH() is a months offset.

Body:
I have data prep procedure in SQL. I want to have data preparation at the end of every month
 Say I want the procedure run on last day of month e.g. on 31 January 2020 it should prep data from 1 January to 31 January.

So it's kind of moving window over all months of the year. Because I need data for evaluation at the end of each month.

I tried this, however, this does not give automation. Its sort of manual running end of every month

select '2020-10-01' as beginDate_AnalysisWindow
, '2020 -01-31' as endDate_AnalysisWindow
   into #AnalysisWindow --create temporary table #AnalysisWindow

I also tried the following, however, I’m not sure if it does for the whole month or just one day?

SELECT START_OF_MONTH_DATE AS beginDate_AnalysisWindow
,END_OF_MONTH_DATE AS endDate_AnalysisWindow
INTO #AnalysisWindow
FROM [dbo].[Date] WITH (NOLOCK)
WHERE DATE = DATEADD(dd, - 1,  CAST(GETDATE() AS DATE))

Could someone pls help me/give me some suggestions.

Thanks in advance

Body:
If you want the last day of the current month, use eomonth():

WHERE DATE = CONVERT(date, EOMONTH(GETDATE()))

Note:  This assumes that the date column has no time component.  If that is the case:

WHERE CONVERT(date, DATE) = CONVERT(date, EOMONTH(GETDATE()))

SQL Server will still use an index (if available) even for this type of conversion.

EDIT:

To get the current months data, one method is:

WHERE DATE <= CONVERT(date, EOMONTH(GETDATE())) AND
      DATE > CONVERT(date, EOMONTH(GETDATE(), -1))

The second argument to EOMONTH() is a months offset.


问:
Is the WiX Toolset not designed for deploying C++ projects?
I have been referencing the following tutorial for creating a Setup Project for WiX v3, however, most WiX tutorials on the internet are targeting a C# application as its base project. I am currently building a Visual C++17 Win32 application that I want to deploy (i.e. create a setup *.msi installer) using WiX, given how powerful WiX is.

Unfortunately, adding a reference to my C++ project yields a yellow bang exclamation point:

Moreover, when trying to reference an icon file, for example, in the Product.wxs file using $(var.TimeTrack.ProjectDir)\TimeTrack.ico reports that it is an "undefined predecessor variable." I have tried unloading the WiX Setup Project and tried validating that the yellow banged Visual C++ project reference is referring to the correct path in the *.wixproj file. The include path appears to be correct:

```<code><ItemGroup>
    <ProjectReference Include="..\TimeTrack\TimeTrack.vcxproj">
    <Name>TimeTrack</Name>

    <!-- More not shown. -->
</ItemGroup>
</code>```

I did a bit of digging and I cam across this StackOverflow posting that indicated that WiX is dependent on .NET framework. In addition, there seems to be a lot of very old postings (e.g. example 1) on this topic and I just am not entirely sure if I am just misunderstanding something here. According to this post, the WiX project cannot refer to any C/C++ code, but this appears to be referring to "Custom Actions," which appear to be an entirely different topic (?).

All in all, am I doing something wrong or is WiX not capable of deploying C++ applications? Is WiX only meant for deploying C# applications?

答:
WiX has a development dependency on .NET but not an install time dependency.

Files are files.  WiX doesn't care if they are C, C++, VB, PowerBuilder, Delphi, .NET, NodeJS, Electron or whatever.

The main differences for .NET vs C/C++ is:

1) .NET typically requires you to check that .NET is installed or author a bootstrapper to install it.

2) .NET core can typically be packaged with the app privately without a system wide installation of .NET core.

3) C/C++ typically requires installing the VCRedist via a bootstrapper or statically linking the files into your application.

4) .NET is "AnyCPU" where as C/C++ is compiled for the platform.  MSI is compiled for the platoform. This means for .NET a single x86 MSI can deploy a .NET app that might run 32bit or 64bit depending on how it was built.  For C/C++ you might need to create a 32bit MSI and a 64bit MSI for your app.

I have a FOSS tool that helps with learning and authoring WiX.  You can read about it here:

http://www.github.com/iswix-llc/iswix-tutorials

The tutorials only hav C# examples but pull requests are welcome.  Create your C/C++ application  and use a postbuild copy command to stage the files to the Installer\Deploy folder and everything else is mostly the same.

Body:
I have been referencing the following tutorial for creating a Setup Project for WiX v3, however, most WiX tutorials on the internet are targeting a C# application as its base project. I am currently building a Visual C++17 Win32 application that I want to deploy (i.e. create a setup *.msi installer) using WiX, given how powerful WiX is.

Unfortunately, adding a reference to my C++ project yields a yellow bang exclamation point:

Moreover, when trying to reference an icon file, for example, in the Product.wxs file using $(var.TimeTrack.ProjectDir)\TimeTrack.ico reports that it is an "undefined predecessor variable." I have tried unloading the WiX Setup Project and tried validating that the yellow banged Visual C++ project reference is referring to the correct path in the *.wixproj file. The include path appears to be correct:

<ItemGroup>
    <ProjectReference Include="..\TimeTrack\TimeTrack.vcxproj">
    <Name>TimeTrack</Name>

</ItemGroup>

I did a bit of digging and I cam across this StackOverflow posting that indicated that WiX is dependent on .NET framework. In addition, there seems to be a lot of very old postings (e.g. example 1) on this topic and I just am not entirely sure if I am just misunderstanding something here. According to this post, the WiX project cannot refer to any C/C++ code, but this appears to be referring to "Custom Actions," which appear to be an entirely different topic (?).

All in all, am I doing something wrong or is WiX not capable of deploying C++ applications? Is WiX only meant for deploying C# applications?


问:
How to iterate over a nested Ruby hash to add a new key/value pair based on existing key/value data?

I have a nested hash of data:

```<code>munsters = {
  "Herman" => { "age" => 32, "gender" => "male" },
  "Lily" => { "age" => 30, "gender" => "female" },
  "Grandpa" => { "age" => 402, "gender" => "male" },
  "Eddie" => { "age" => 10, "gender" => "male" },
  "Marilyn" => { "age" => 23, "gender" => "female"}
}
</code>```

I want to loop through the hash for each member and look up their age in the nested hash.

For each member, I want to add a new key/value pair to the existing nested hash called "age_group".

The value of each member's "age_group" will be dependent on their age. For example, if the age is above 65 years I want to have their age_group read "senior", etc.

Problems I'm running into:

I'm confused how I would access just the "age" key_value pair of the nested hash when the first key is different for each member of the family. Meaning, I can't do something like munsters["age"] because that returns nil (assuming because "age" is nested).

If I had a simple (un-nested) hash it's pretty straightforward. Example of a non-nested hash:

```<code>ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 }
</code>```

I would then likely loop though like this:

```<code>age_group = {}

ages.each do |k, v|
  if v >= 65
    puts "#{k}'s age of #{v} makes them a senior!"
    age_group.merge!("age_group": "senior")
  elsif v > 17 && v < 65
    puts "#{k}'s age of #{v} makes them an adult"
    age_group.merge!("age_group": "adult")
  else
    puts "#{k}'s age of #{v} makes them a kid."
    age_group.merge!("age_group": "kid")
  end
end
</code>```

For the nested hash, I'm able to access the entire nested hash like this:

```<code>munsters.each do |k, v|
  v.each do |k2, v2|
    p "k2 is #{k2} and v2 is #{v2}"
  end
end
</code>```

But that still only returns the entire nested hash to the console instead of just the age:

k2 is age and v2 is 32
k2 is gender and v2 is male
```

答:
The v is a hash too. So you can do it like this:

```<code>ages.each do |k, v|
  if v["age"] > 60
    ages[k]["age_group"] = "adult"
  else
    ages[k]["age_group"] = "kid"
  end
end
</code>```

You add a age_group key with a string value to the k position of your age hash.

Body:
I have a nested hash of data:

munsters = {
  "Herman" => { "age" => 32, "gender" => "male" },
  "Lily" => { "age" => 30, "gender" => "female" },
  "Grandpa" => { "age" => 402, "gender" => "male" },
  "Eddie" => { "age" => 10, "gender" => "male" },
  "Marilyn" => { "age" => 23, "gender" => "female"}
}

I want to loop through the hash for each member and look up their age in the nested hash.

For each member, I want to add a new key/value pair to the existing nested hash called "age_group".

The value of each member's "age_group" will be dependent on their age. For example, if the age is above 65 years I want to have their age_group read "senior", etc.

Problems I'm running into:

I'm confused how I would access just the "age" key_value pair of the nested hash when the first key is different for each member of the family. Meaning, I can't do something like munsters["age"] because that returns nil (assuming because "age" is nested).

If I had a simple (un-nested) hash it's pretty straightforward. Example of a non-nested hash:

ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 }

I would then likely loop though like this:

age_group = {}

ages.each do |k, v|
  if v >= 65
    puts "#{k}'s age of #{v} makes them a senior!"
    age_group.merge!("age_group": "senior")
  elsif v > 17 && v < 65
    puts "#{k}'s age of #{v} makes them an adult"
    age_group.merge!("age_group": "adult")
  else
    puts "#{k}'s age of #{v} makes them a kid."
    age_group.merge!("age_group": "kid")
  end
end

For the nested hash, I'm able to access the entire nested hash like this:

munsters.each do |k, v|
  v.each do |k2, v2|
    p "k2 is #{k2} and v2 is #{v2}"
  end
end

But that still only returns the entire nested hash to the console instead of just the age:

k2 is age and v2 is 32
k2 is gender and v2 is male

Body:
The v is a hash too. So you can do it like this:

ages.each do |k, v|
  if v["age"] > 60
    ages[k]["age_group"] = "adult"
  else
    ages[k]["age_group"] = "kid"
  end
end

You add a age_group key with a string value to the k position of your age hash.


问:
Group Products by Brand then by Category - linq
There is three table:

```<code>Brand                               Category
-----------------------          --------------------------------
BrandID     BrandName             CategoryID        CategoryName
-----------------------          --------------------------------
1           Brand1                    1             cat1
2           Brand2                    2             cat2

Product
------------------------------------------------------------
ProductID       BrandID      CategoryID    ProductName
------------------------------------------------------------
1                 1             1          Product1
2                 1             1          Product2
3                 1             2          Product3
4                 2             1          Product4
</code>```

I want to write Llinq query to get output like below:

```<code>Brand1
|__ cat1
|   |__ Product1
|   |__ Product2
|
|__ Cat2
|   |__ Product3
|
|__ Brand2
|__ cat1
|   |__ Product4
</code>```

I Wrote this query to get Product group by Category:

```<code>    var query2 = db.Brands
        .GroupBy(x => new { x.BrandID, x.BrandName })
                    .Select(x => new
                    {
                        x.Key.BrandID,
                        x.Key.BrandName,
                        ProductsNames = db.Products
                                            .Where(p => p.BrandID == x.Key.BrandID)
                                            .Select(p => p.ProductName).ToList()
                    }).ToList();
</code>```

How can Group Products by Brand then by Category?

答:
You can do this in 2 steps

```<code>//Step 1 - Join 3 lists
var query = (from p in products
                join b in brands on p.BrandId equals b.Id
                join c in categories on p.CategoryId equals c.Id
                select new
                {
                    b.BrandName,
                    c.CategoryName,
                    p.ProductName
                }).ToList();

//Step 2 - query required results
var results = query
                .GroupBy(x => new { x.BrandName, x.CategoryName })
                .Select(x => new
                {
                    Brand = x.Key.BrandName,
                    Category = x.Key.CategoryName,
                    Product = x.Select(y=>y.ProductName).ToList()
                });

Console.WriteLine(JsonConvert.SerializeObject(results));
</code>```

OUTPUT

```<code>[
    {
        "Brand": "Brand1",
        "Category": "cat1",
        "Product": [
            "Product1",
            "Product2"
        ]
    },
    {
        "Brand": "Brand1",
        "Category": "cat2",
        "Product": [
            "Product3"
        ]
    },
    {
        "Brand": "Brand2",
        "Category": "cat1",
        "Product": [
            "Product4"
        ]
    }
]
</code>```

Body:
There is three table:

Brand                               Category
-----------------------          --------------------------------
BrandID     BrandName             CategoryID        CategoryName
-----------------------          --------------------------------
1           Brand1                    1             cat1
2           Brand2                    2             cat2

Product
------------------------------------------------------------
ProductID       BrandID      CategoryID    ProductName
------------------------------------------------------------
1                 1             1          Product1
2                 1             1          Product2
3                 1             2          Product3
4                 2             1          Product4

I want to write Llinq query to get output like below:

Brand1
|__ cat1
|   |__ Product1
|   |__ Product2
|
|__ Cat2
|   |__ Product3
|
|__ Brand2
|__ cat1
|   |__ Product4

I Wrote this query to get Product group by Category:

    var query2 = db.Brands
        .GroupBy(x => new { x.BrandID, x.BrandName })
                    .Select(x => new
                    {
                        x.Key.BrandID,
                        x.Key.BrandName,
                        ProductsNames = db.Products
                                            .Where(p => p.BrandID == x.Key.BrandID)
                                            .Select(p => p.ProductName).ToList()
                    }).ToList();

How can Group Products by Brand then by Category?

Body:
You can do this in 2 steps

//Step 1 - Join 3 lists
var query = (from p in products
                join b in brands on p.BrandId equals b.Id
                join c in categories on p.CategoryId equals c.Id
                select new
                {
                    b.BrandName,
                    c.CategoryName,
                    p.ProductName
                }).ToList();

//Step 2 - query required results
var results = query
                .GroupBy(x => new { x.BrandName, x.CategoryName })
                .Select(x => new
                {
                    Brand = x.Key.BrandName,
                    Category = x.Key.CategoryName,
                    Product = x.Select(y=>y.ProductName).ToList()
                });

Console.WriteLine(JsonConvert.SerializeObject(results));

OUTPUT

[
    {
        "Brand": "Brand1",
        "Category": "cat1",
        "Product": [
            "Product1",
            "Product2"
        ]
    },
    {
        "Brand": "Brand1",
        "Category": "cat2",
        "Product": [
            "Product3"
        ]
    },
    {
        "Brand": "Brand2",
        "Category": "cat1",
        "Product": [
            "Product4"
        ]
    }
]


问:
Find column name based on search criteria
I have the following Excel spreadsheet:

```<code>        A        B         C              D              E          F
1     MFC2      MFC1      QFC      Search Criteria:     CW14
2     CW11                         Column Name:         MFC1
3               CW13
4               CW14
5                        CW17
6                        CW18
7                        CW19
8
9
</code>```

In Cells A1:C8 I have different calender weeks. All of them are unique!

In Cell E2 I want that the column name is displayed based on the value that is put in Cell E1.

In this case the search criteria is CW14 so the result should be column name MFC1.

I tried to modify the formula from this question but could not make it work:

```<code>E1 = INDEX($A$1:$C$1,MATCH(E$1,$A$2:$C$30,0))
</code>```

This formula gives me #NV as result.

What do I need to change to get the desried result?

答:
Use AGGREGATE instead of MATCH:

```<code>=INDEX(1:1,AGGREGATE(15,7,COLUMN($A$2:$C$30)/($A$2:$C$30=$E$1),1))
</code>```

Body:
I have the following Excel spreadsheet:

        A        B         C              D              E          F
1     MFC2      MFC1      QFC      Search Criteria:     CW14
2     CW11                         Column Name:         MFC1
3               CW13
4               CW14
5                        CW17
6                        CW18
7                        CW19
8
9

In Cells A1:C8 I have different calender weeks. All of them are unique!

In Cell E2 I want that the column name is displayed based on the value that is put in Cell E1.

In this case the search criteria is CW14 so the result should be column name MFC1.

I tried to modify the formula from this question but could not make it work:

E1 = INDEX($A$1:$C$1,MATCH(E$1,$A$2:$C$30,0))

This formula gives me #NV as result.

What do I need to change to get the desried result?

Body:
Use AGGREGATE instead of MATCH:

=INDEX(1:1,AGGREGATE(15,7,COLUMN($A$2:$C$30)/($A$2:$C$30=$E$1),1))


问:
My android app crashes on Android 10 after upgrading the compileSdkVersion to 29
My android app crashes on Android 10 after upgrading the compileSdkVersion to 29

This is the crash message:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:163)
        at android.app.FragmentManagerImpl.getTargetSdk(FragmentManager.java:2975)
        at android.app.FragmentManagerImpl.attachController(FragmentManager.java:2964)
        at android.app.FragmentController.attachHost(FragmentController.java:88)
        at android.app.Activity.attach(Activity.java:7710)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3224)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.epicsyst.ibc/com.epicsyst.ibc.view.activities.Splash}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:163)
        at android.app.FragmentManagerImpl.getTargetSdk(FragmentManager.java:2975)
        at android.app.FragmentManagerImpl.attachController(FragmentManager.java:2964)
        at android.app.FragmentController.attachHost(FragmentController.java:88)
        at android.app.Activity.attach(Activity.java:7710)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3224)
</code>```

I searched the error message in Google and it gave me this on Github:
https://github.com/takahirom/DownloadableCalligraphy/pull/4/commits/3707383200749b385cc77adb2bb1aaf447420d62 but i couldn't relate!!

This is the activity xml file

```<code><androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.activities.Splash">

    <ImageView
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:src="@drawable/logo"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

The java file

```<code>package com.****.utils;

import android.content.Context;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.******.R;

import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;

    public class BaseActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            applyAppFont();
        }

        @Override
        protected void attachBaseContext(Context newBase) {
            super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
        }

        /**
         * This method to apply custom font in activity using third-party library.
         */
        private void applyAppFont() {
            CalligraphyConfig.initDefault(
                    new CalligraphyConfig.Builder().setDefaultFontPath("fonts/DroidKufi-Regular.ttf")
                            .setFontAttrId(R.attr.fontPath)
                            .build());
        }
    }
</code>```

答:
It seems that it's a knowed issue for the Calligraphy library : https://github.com/chrisjenx/Calligraphy/issues/475

Could you try to migrate to the Caliligraphy 3 : https://github.com/InflationX/Calligraphy ?

Body:
My android app crashes on Android 10 after upgrading the compileSdkVersion to 29

This is the crash message:

java.lang.RuntimeException: Unable to start activity ComponentInfo{...}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:163)
        at android.app.FragmentManagerImpl.getTargetSdk(FragmentManager.java:2975)
        at android.app.FragmentManagerImpl.attachController(FragmentManager.java:2964)
        at android.app.FragmentController.attachHost(FragmentController.java:88)
        at android.app.Activity.attach(Activity.java:7710)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3224)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.epicsyst.ibc/com.epicsyst.ibc.view.activities.Splash}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
        at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:163)
        at android.app.FragmentManagerImpl.getTargetSdk(FragmentManager.java:2975)
        at android.app.FragmentManagerImpl.attachController(FragmentManager.java:2964)
        at android.app.FragmentController.attachHost(FragmentController.java:88)
        at android.app.Activity.attach(Activity.java:7710)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3224)

I searched the error message in Google and it gave me this on Github:
https://github.com/takahirom/DownloadableCalligraphy/pull/4/commits/3707383200749b385cc77adb2bb1aaf447420d62 but i couldn't relate!!

This is the activity xml file

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".view.activities.Splash">

    <ImageView
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:src="@drawable/logo"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

The java file

package com.****.utils;

import android.content.Context;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.******.R;

import uk.co.chrisjenx.calligraphy.CalligraphyConfig;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;

    public class BaseActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            applyAppFont();
        }

        @Override
        protected void attachBaseContext(Context newBase) {
            super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
        }

        /**
         * This method to apply custom font in activity using third-party library.
         */
        private void applyAppFont() {
            CalligraphyConfig.initDefault(
                    new CalligraphyConfig.Builder().setDefaultFontPath("fonts/DroidKufi-Regular.ttf")
                            .setFontAttrId(R.attr.fontPath)
                            .build());
        }
    }


问:
What are the @tmp folders in a Jenkins workspace and how to clean them up
I have a Jenkins pipeline, for a PHP project in a Docker container. This is my Jenkinsfile:

```<code>pipeline {
  agent any
  stages {
    stage('Build') {
      agent any
      steps {
        sh 'docker-compose up -d'
        sh 'docker exec symfony composer install'
      }
    }
    stage('Test') {
      steps {
        sh 'docker exec symfony php ./bin/phpunit --coverage-clover=\'reports/coverage/coverage.xml\' --coverage-html=\'reports/coverage\' --coverage-crap4j=\'reports/crap4j.xml\''
      }
    }
    stage('Coverage') {
      steps {
        step([$class: 'CloverPublisher', cloverReportDir: '/reports/coverage', cloverReportFileName: 'coverage.xml'])
      }
    }
  }
  post {
    cleanup {
      sh 'docker-compose down -v'
      cleanWs()
    }
  }
}
</code>```

After running the pipeline, the var/lib/jenkins/workspace folder contains 4 folders (assuming my project name is Foo):

Foo

Foo@2

Foo@2@tmp

Foo@tmp

What are these, and how do I clean them up? cleanWs does not remove any except the first of them after the build.

EDIT: This is not a duplicate of this question because

That question does not answer my question: what are these files.

The answers to that question suggest using deleteDir, which is not recommended when using Docker containers.

答:
There is an opened Jenkins issue about deleteDir() not deleting the @tmp/@script/@... directories.

A workaround to delete those:

```<code>post {
  always {
    cleanWs()
    dir("${env.WORKSPACE}@tmp") {
      deleteDir()
    }
    dir("${env.WORKSPACE}@script") {
      deleteDir()
    }
    dir("${env.WORKSPACE}@script@tmp") {
      deleteDir()
    }
  }
}
</code>```

There is also a comment on the issue describing what @tmp is:

It [@tmp folder] contains the content of any library that was loaded at
  run time. Without a copy, Replay can't work reliably.

Body:
I have a Jenkins pipeline, for a PHP project in a Docker container. This is my Jenkinsfile:

pipeline {
  agent any
  stages {
    stage('Build') {
      agent any
      steps {
        sh 'docker-compose up -d'
        sh 'docker exec symfony composer install'
      }
    }
    stage('Test') {
      steps {
        sh 'docker exec symfony php ./bin/phpunit --coverage-clover=\'reports/coverage/coverage.xml\' --coverage-html=\'reports/coverage\' --coverage-crap4j=\'reports/crap4j.xml\''
      }
    }
    stage('Coverage') {
      steps {
        step([$class: 'CloverPublisher', cloverReportDir: '/reports/coverage', cloverReportFileName: 'coverage.xml'])
      }
    }
  }
  post {
    cleanup {
      sh 'docker-compose down -v'
      cleanWs()
    }
  }
}

After running the pipeline, the var/lib/jenkins/workspace folder contains 4 folders (assuming my project name is Foo):

Foo

Foo@2

Foo@2@tmp

Foo@tmp

What are these, and how do I clean them up? cleanWs does not remove any except the first of them after the build.

EDIT: This is not a duplicate of this question because

That question does not answer my question: what are these files.

The answers to that question suggest using deleteDir, which is not recommended when using Docker containers.

Body:
There is an opened Jenkins issue about deleteDir() not deleting the @tmp/@script/@... directories.

A workaround to delete those:

post {
  always {
    cleanWs()
    dir("${env.WORKSPACE}@tmp") {
      deleteDir()
    }
    dir("${env.WORKSPACE}@script") {
      deleteDir()
    }
    dir("${env.WORKSPACE}@script@tmp") {
      deleteDir()
    }
  }
}

There is also a comment on the issue describing what @tmp is:

It [@tmp folder] contains the content of any library that was loaded at
  run time. Without a copy, Replay can't work reliably.


问:
Sudoku Recursive Backtracking in Go
I am trying to solve a sudoku puzzle in Go using a recursive backtracking algorithm. I created helper functions that check if a certain row, column, or block are valid (i.e no repeated values), as well as a function to print out the current state. I have tested all of these many times so I don't think they are causing the issue. I created the following function to test if a potential game board would be possible.

```<code>func cellValid(gameBoard *[9][9]int, value int, y int, x int) bool {
    oldVal := gameBoard[y-1][x-1]
    gameBoard[y-1][x-1] = value
    row := getRow(gameBoard, y)
    col := getCol(gameBoard, x)
    block := getBlock(gameBoard, x, y)
    possible := unitValid(row) && unitValid(col) && unitValid(block)
    gameBoard[y-1][x-1] = oldVal
    return possible
}
</code>```

It makes a change to the gameboard, checks if it is possible and stores that bool in the variable possible. It changes the board back to what it was then returns the bool. This function is being called from the following solveBoard function.

```<code>func solveBoard(gameBoard *[9][9]int) {
    for row := 1; row <= 9; row++ {
        for col := 1; col <= 9; col++ {
            if gameBoard[row-1][col-1] == 0 {
                for value := 1; value <= 9; value++ {
                    if cellValid(gameBoard, value, row, col) {
                        gameBoard[row-1][col-1] = value
                        solveBoard(gameBoard)
                        gameBoard[row-1][col-1] = 0
                    }
                }
                return
            }
        }
    }
    printBoard(gameBoard)
    return
}
</code>```

Upon running the file I get no output.

```<code>func main() {
    var gameBoard = [9][9]int{
        {5, 3, 0, 0, 7, 0, 0, 0, 0},
        {6, 0, 0, 1, 9, 5, 0, 0, 0},
        {0, 9, 8, 0, 0, 0, 0, 6, 0},
        {8, 0, 0, 0, 6, 0, 0, 0, 3},
        {4, 0, 0, 8, 0, 3, 0, 0, 1},
        {7, 0, 0, 0, 2, 0, 0, 0, 6},
        {0, 6, 0, 0, 0, 0, 2, 8, 0},
        {0, 0, 0, 4, 1, 9, 0, 0, 5},
        {0, 0, 0, 0, 8, 0, 0, 7, 9}}

    solveBoard(&gameBoard)
}
</code>```

Here is a link to a go playground containing all my code.
Go Playground

The following video demonstrates what I am trying to accomplish in python.

Computerphile Video

Solution to puzzle:
Puzzle solution

答:
Your program works perfectly fine. Double check the second last line of your matrix:

You have:

```<code>{0, 0, 0, 4, 1, 7, 0, 0, 5},
</code>```

But it should be

```<code>{0, 0, 0, 4, 1, 9, 0, 0, 5},
</code>```

Title: Sudoku Recursive Backtracking in Go

Body:
I am trying to solve a sudoku puzzle in Go using a recursive backtracking algorithm. I created helper functions that check if a certain row, column, or block are valid (i.e no repeated values), as well as a function to print out the current state. I have tested all of these many times so I don't think they are causing the issue. I created the following function to test if a potential game board would be possible.

func cellValid(gameBoard *[9][9]int, value int, y int, x int) bool {
    oldVal := gameBoard[y-1][x-1]
    gameBoard[y-1][x-1] = value
    row := getRow(gameBoard, y)
    col := getCol(gameBoard, x)
    block := getBlock(gameBoard, x, y)
    possible := unitValid(row) && unitValid(col) && unitValid(block)
    gameBoard[y-1][x-1] = oldVal
    return possible
}

It makes a change to the gameboard, checks if it is possible and stores that bool in the variable possible. It changes the board back to what it was then returns the bool. This function is being called from the following solveBoard function.

func solveBoard(gameBoard *[9][9]int) {
    for row := 1; row <= 9; row++ {
        for col := 1; col <= 9; col++ {
            if gameBoard[row-1][col-1] == 0 {
                for value := 1; value <= 9; value++ {
                    if cellValid(gameBoard, value, row, col) {
                        gameBoard[row-1][col-1] = value
                        solveBoard(gameBoard)
                        gameBoard[row-1][col-1] = 0
                    }
                }
                return
            }
        }
    }
    printBoard(gameBoard)
    return
}

Upon running the file I get no output.

func main() {
    var gameBoard = [9][9]int{
        {5, 3, 0, 0, 7, 0, 0, 0, 0},
        {6, 0, 0, 1, 9, 5, 0, 0, 0},
        {0, 9, 8, 0, 0, 0, 0, 6, 0},
        {8, 0, 0, 0, 6, 0, 0, 0, 3},
        {4, 0, 0, 8, 0, 3, 0, 0, 1},
        {7, 0, 0, 0, 2, 0, 0, 0, 6},
        {0, 6, 0, 0, 0, 0, 2, 8, 0},
        {0, 0, 0, 4, 1, 9, 0, 0, 5},
        {0, 0, 0, 0, 8, 0, 0, 7, 9}}

    solveBoard(&gameBoard)
}

Here is a link to a go playground containing all my code.
Go Playground

The following video demonstrates what I am trying to accomplish in python.

Computerphile Video

Solution to puzzle:
Puzzle solution

Body:
Your program works perfectly fine. Double check the second last line of your matrix:

You have:

{0, 0, 0, 4, 1, 7, 0, 0, 5},

But it should be

{0, 0, 0, 4, 1, 9, 0, 0, 5},


问:
Extract image from resources within a java program packaged as a jar file
I have a java program that reads image resources from disk.

This works well while testing with mvn exec:java.

However, when program is packaged with mvn packaged, it throws the following error:

java.nio.file.FileSystemNotFoundException

Project structure

```<code>├── java
│   └── com
│       ├── aaa
│       │   ├── bbb
│       │   │   ├── AssemblingTags.java
│       │   │   ├── BatchLifeCycle.java
│       │   │   ├── config
│       │   │   │   ├── AssemblingTagsConfig.java
│       │   │   │   ├── Configuration.java
│       │   │   │   ├── DatabaseConfig.java
│       │   │   │   ├── ExecutionContext.java
│       │   │   │   ├── InjectionTagsConfig.java
│       │   │   │   ├── QualityConfig.java
│       │   │   │   └── TraceabilityContext.java
│       │   │   ├── Database.java
│       │   │   ├── DeviceLifeCycle.java
│       │   │   ├── Devices.java
│       │   │   ├── InjectionTags.java
│       │   │   ├── QRCode.java
│       │   │   ├── Quality.java
│       │   │   ├── Simulator.java
│       │   │   ├── ThreadManager.java
│       │   │   ├── TimeManager.java
│       │   │   └── Utils.java
│       │   └── traceability
│       │       └── Tracer.java
│       └── example
│           ├── AdminAPI.java
│           ├── ConfigAPI.java
│           ├── CORSFilter.java
│           ├── DeviceAPI.java
│           ├── Main.java
│           ├── QrCodeAPI.java
│           ├── ToggleAPI.java
│           └── TracerAPI.java
└── resources
    └── images
        └── strioscopy
            ├── v1-2.png
            ├── v1-3.png
            ├── v2-1.png
            └── v2-2.png
</code>```

The piece of code that reads the image

Note the prints.

```<code>try {
            System.out.println("images/" + type + "/" + name); <-- PRINT 1
            URL res = getClass().getClassLoader().getResource("images/" + type + "/" + name);
            System.out.println(res);                           <-- PRINT 2
            File file = Paths.get(res.toURI()).toFile();
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fis.read(data);
            fis.close();
            return Response.ok(data).build();
        } catch (Exception e) {
            e.printStackTrace();
            return Response.serverError().entity(e).build();
        }
</code>```

When using mvn exec:java, it works and print:

```<code>images/strioscopy/v1-3.png
file:/home/hduser/program/target/classes/images/strioscopy/v1-3.png
</code>```

When executing with the jar (java -jar myprogram-jar-with-dependencies.jar), it fails and prints:

```<code>images/strioscopy/v1-3.png

jar:file:/home/hduser/program/target/myprogram-jar-with-dependencies.jar!/images/strioscopy/v1-3.png
</code>```

From my understanding, it is not able to read the images from the jar (as it is "jared"). But how to fix this problem ?

Moreover, notice the exclamation mark here: (between chevrons) jar:file:/home/hduser/program/target/myprogram-jar-with-dependencies.jar>>!<</images/strioscopy/v1-3.png

Is it normal ?

答:
For whatever reason, it gives expected result with the following code:

```<code>try {
            System.out.println("images/" + type + "/" + name);
            InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("images/" + type + "/" + name);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int nRead;
            byte[] data = new byte[1024];
            while ((nRead = is.read(data,0,data.length)) != -1) {
                baos.write(data, 0, nRead);
            }
            baos.flush();
            byte[] ba = baos.toByteArray();
            return Response.ok(ba).build();
        } catch (Exception e) {
            e.printStackTrace();
            return Response.serverError().entity(e).build();
        }
</code>```

However, I am not able to explain why. (If someone can bring light on this, welcome !)

Body:
I have a java program that reads image resources from disk.

This works well while testing with mvn exec:java.

However, when program is packaged with mvn packaged, it throws the following error:

java.nio.file.FileSystemNotFoundException

Project structure

├── java
│   └── com
│       ├── aaa
│       │   ├── bbb
│       │   │   ├── AssemblingTags.java
│       │   │   ├── BatchLifeCycle.java
│       │   │   ├── config
│       │   │   │   ├── AssemblingTagsConfig.java
│       │   │   │   ├── Configuration.java
│       │   │   │   ├── DatabaseConfig.java
│       │   │   │   ├── ExecutionContext.java
│       │   │   │   ├── InjectionTagsConfig.java
│       │   │   │   ├── QualityConfig.java
│       │   │   │   └── TraceabilityContext.java
│       │   │   ├── Database.java
│       │   │   ├── DeviceLifeCycle.java
│       │   │   ├── Devices.java
│       │   │   ├── InjectionTags.java
│       │   │   ├── QRCode.java
│       │   │   ├── Quality.java
│       │   │   ├── Simulator.java
│       │   │   ├── ThreadManager.java
│       │   │   ├── TimeManager.java
│       │   │   └── Utils.java
│       │   └── traceability
│       │       └── Tracer.java
│       └── example
│           ├── AdminAPI.java
│           ├── ConfigAPI.java
│           ├── CORSFilter.java
│           ├── DeviceAPI.java
│           ├── Main.java
│           ├── QrCodeAPI.java
│           ├── ToggleAPI.java
│           └── TracerAPI.java
└── resources
    └── images
        └── strioscopy
            ├── v1-2.png
            ├── v1-3.png
            ├── v2-1.png
            └── v2-2.png

The piece of code that reads the image

Note the prints.

try {
            System.out.println("images/" + type + "/" + name); <-- PRINT 1
            URL res = getClass().getClassLoader().getResource("images/" + type + "/" + name);
            System.out.println(res);                           <-- PRINT 2
            File file = Paths.get(res.toURI()).toFile();
            FileInputStream fis = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fis.read(data);
            fis.close();
            return Response.ok(data).build();
        } catch (Exception e) {
            e.printStackTrace();
            return Response.serverError().entity(e).build();
        }

When using mvn exec:java, it works and print:

images/strioscopy/v1-3.png
file:/home/hduser/program/target/classes/images/strioscopy/v1-3.png

When executing with the jar (java -jar myprogram-jar-with-dependencies.jar), it fails and prints:

images/strioscopy/v1-3.png

jar:file:/home/hduser/program/target/myprogram-jar-with-dependencies.jar!/images/strioscopy/v1-3.png

From my understanding, it is not able to read the images from the jar (as it is "jared"). But how to fix this problem ?

Moreover, notice the exclamation mark here: (between chevrons) jar:file:/home/hduser/program/target/myprogram-jar-with-dependencies.jar>>!<</images/strioscopy/v1-3.png

Is it normal ?

Body:
For whatever reason, it gives expected result with the following code:

try {
            System.out.println("images/" + type + "/" + name);
            InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("images/" + type + "/" + name);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int nRead;
            byte[] data = new byte[1024];
            while ((nRead = is.read(data,0,data.length)) != -1) {
                baos.write(data, 0, nRead);
            }
            baos.flush();
            byte[] ba = baos.toByteArray();
            return Response.ok(ba).build();
        } catch (Exception e) {
            e.printStackTrace();
            return Response.serverError().entity(e).build();
        }

However, I am not able to explain why. (If someone can bring light on this, welcome !)


问:
Why is my OR operator not working in my WHERE clause?
I need to write a where statement that only returns names starting with A, B, C, or E. I have a WHERE clause with a less that D condition, and that seems to work fine. But my Equals E condition doesn't appear to be working.

```<code>SELECT vendor_name,
    CONCAT(vendor_contact_last_name, ', ', vendor_contact_first_name) AS full_name
FROM vendors
WHERE vendor_contact_last_name < 'D'
    OR vendor_contact_last_name = 'E'
ORDER BY vendor_contact_last_name, vendor_contact_first_name;
</code>```

It is only returning names that start with A, B, and C.

答:
You can use the following using LEFT:

```<code>SELECT vendor_name,
    CONCAT(vendor_contact_last_name, ', ', vendor_contact_first_name) AS full_name
FROM vendors
WHERE LEFT(vendor_contact_last_name, 1) IN ('A', 'B', 'C', 'E')
ORDER BY vendor_contact_last_name, vendor_contact_first_name;
</code>```

... or using RLIKE:

```<code>SELECT vendor_name,
    CONCAT(vendor_contact_last_name, ', ', vendor_contact_first_name) AS full_name
FROM vendors
WHERE vendor_contact_last_name RLIKE '^[A-CE]'
ORDER BY vendor_contact_last_name, vendor_contact_first_name;
</code>```

demo on dbfiddle.uk

Body:
I need to write a where statement that only returns names starting with A, B, C, or E. I have a WHERE clause with a less that D condition, and that seems to work fine. But my Equals E condition doesn't appear to be working.

SELECT vendor_name,
    CONCAT(vendor_contact_last_name, ', ', vendor_contact_first_name) AS full_name
FROM vendors
WHERE vendor_contact_last_name < 'D'
    OR vendor_contact_last_name = 'E'
ORDER BY vendor_contact_last_name, vendor_contact_first_name;

It is only returning names that start with A, B, and C.

Body:
You can use the following using LEFT:

SELECT vendor_name,
    CONCAT(vendor_contact_last_name, ', ', vendor_contact_first_name) AS full_name
FROM vendors
WHERE LEFT(vendor_contact_last_name, 1) IN ('A', 'B', 'C', 'E')
ORDER BY vendor_contact_last_name, vendor_contact_first_name;

... or using RLIKE:

SELECT vendor_name,
    CONCAT(vendor_contact_last_name, ', ', vendor_contact_first_name) AS full_name
FROM vendors
WHERE vendor_contact_last_name RLIKE '^[A-CE]'
ORDER BY vendor_contact_last_name, vendor_contact_first_name;

demo on dbfiddle.uk


问:
Parsing an unusual http response with Angular, RxJS in Facade pattern
I have a Back-End API that returns data in the following structure:

```<code>{
    "code": 200,
    "message": "Success",
    "data": // Can basically be anything.. object, array, string, etc...
}
</code>```

The thing is, I'm really confused about how all this is supposed to work with such a nested payload.

Would love a little more guidance regarding how to implement this abomination within my design pattern and how to do it right.

I have the following weapons in my arsenal:

APIResponse - Model

```<code>export default interface APIResponse {
    code: number;
    message: string;
    data?: any;
}
</code>```

NetworkService - Service

```<code>@Injectable({ providedIn: 'root' })
export class NetworkService {
    constructor(private http: HttpClient) { }

    private _formatErrors(error: any) {
        return throwError(error);
    }

    get(environment: string, path: string, params: HttpParams = new HttpParams()): Observable<APIResponse> {
        return this.http.get<APIResponse>(`${environment}${path}`, { params }).pipe(catchError(this._formatErrors));
    }
}
</code>```

PostsAPI

I'm stuck exactly here. How do I convert the APIResponse's data attribute to Post[] Observable?

```<code>@Injectable({ providedIn: 'root' })
export class PostsAPI {
    // Lifecycle
    constructor(private _network: NetworkService) { }

    // API Methods
    getAllPosts(page: number = 1, limit: number = 10): Observable<Post[]> {
        return this._network.get(GlobalAPI.baseURL, `${GlobalAPI.endpoints.posts.base}?page=${page}&limit=${limit}`); // Obviously I have a type mismatch here and I'm doing it all wrong.
    }
}
</code>```

PostsFacade

```<code>@Injectable({ providedIn: 'root' })
export class PostsFacade {
    posts$: Observable<Post[]>;

    // Lifecycle
    constructor(private _postsAPI: PostsAPI) {
        this._postsAPI.getAllPosts().subscribe(response => this.posts$ = response.data.posts); // Obviously I have a type mismatch here and I'm doing it all wrong.
    }
}
</code>```

HomeComponent - The page that displays the posts

```<code>@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
    posts$ = this._postsFacade.posts$;

    // Lifecycle
    constructor(private _postsFacade: PostsFacade) { }
    ngOnInit() {
        console.log(this.posts$); // Returns undefined
    }
}
</code>```

Thanks a lot!

答:
Your best bet is to unwrap the ApiResponse and handle errors (logging, showing a popup to the user, etc.) all within the NetworkService. Each business entity service can call the network service and benefit from that logic.

And as mentioned in a comment, this.posts$ in your PostsFacade should be an observable (or so you indicate with your '$'), so don't subscribe there. That would let you use an async pipe in a component template to subscribe/unsubscribe automatically. Otherwise...

posts: Post[];

ngOnInit() {
  this._postsApi.getAllPosts().subscribe(posts => this.posts = posts);
}
```

Body:
I have a Back-End API that returns data in the following structure:

{
    "code": 200,
    "message": "Success",
    "data": // Can basically be anything.. object, array, string, etc...
}

The thing is, I'm really confused about how all this is supposed to work with such a nested payload.

Would love a little more guidance regarding how to implement this abomination within my design pattern and how to do it right.

I have the following weapons in my arsenal:

APIResponse - Model

export default interface APIResponse {
    code: number;
    message: string;
    data?: any;
}

NetworkService - Service

@Injectable({ providedIn: 'root' })
export class NetworkService {
    constructor(private http: HttpClient) { }

    private _formatErrors(error: any) {
        return throwError(error);
    }

    get(environment: string, path: string, params: HttpParams = new HttpParams()): Observable<APIResponse> {
        return this.http.get<APIResponse>(`${environment}${path}`, { params }).pipe(catchError(this._formatErrors));
    }
}

PostsAPI

I'm stuck exactly here. How do I convert the APIResponse's data attribute to Post[] Observable?

@Injectable({ providedIn: 'root' })
export class PostsAPI {
    // Lifecycle
    constructor(private _network: NetworkService) { }

    // API Methods
    getAllPosts(page: number = 1, limit: number = 10): Observable<Post[]> {
        return this._network.get(GlobalAPI.baseURL, `${GlobalAPI.endpoints.posts.base}?page=${page}&limit=${limit}`); // Obviously I have a type mismatch here and I'm doing it all wrong.
    }
}

PostsFacade

@Injectable({ providedIn: 'root' })
export class PostsFacade {
    posts$: Observable<Post[]>;

    // Lifecycle
    constructor(private _postsAPI: PostsAPI) {
        this._postsAPI.getAllPosts().subscribe(response => this.posts$ = response.data.posts); // Obviously I have a type mismatch here and I'm doing it all wrong.
    }
}

HomeComponent - The page that displays the posts

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
    posts$ = this._postsFacade.posts$;

    // Lifecycle
    constructor(private _postsFacade: PostsFacade) { }
    ngOnInit() {
        console.log(this.posts$); // Returns undefined
    }
}

Thanks a lot!


问:
How to pad a number with leading zero in a SAS Macro loop counter?
So I have a range of datasets in a specific library. These datasets are named in the format DATASET_YYYYMM, with one dataset for each month. I am trying to append a range of these datasets based on user input for the date range. i.e. If start_date is 01NOV2019 and the end_date is 31JAN2020, I want to append the three datasets: LIBRARY.DATASET_201911, LIBRARY.DATASET_201912 and LIBRARY.DATASET_202001.

The range is obviously variable, so I can't simply name the datasets manually in a set function. Since I need to loop through the years and months in the date range, I believe a macro is the best way to do this. I'm using a loop within the SET statement to append all the datasets. I have copied my example code below. It does work in theory. But in practice, only if we are looping over the months of November and December. As the format of the dataset name has a two digit month, for Jan-Sept it will be 01-09. The month function returns 1-9 however, and of course a 'File DATASET_NAME does not exist' error is thrown.
Problem is I cannot figure out a way to get it to interpret the month with leading 0, without ruining functionality of another part of the loop/macro.

I have tried numerous approaches to format the number as z2, cannot get any to work.
i.e. Including PUTN functions in the DO line for quote_month as follows, it ignores the leading zero when generating the dataset name in the line below.

```<code>%DO quote_month = %SYSFUNC(IFN(&quote_year. = &start_year.,%SYSFUNC(PUTN(&start_month.,z2.)),1,.)) %TO %SYSFUNC(IFN(&quote_year. = &end_year.,%SYSFUNC(PUTN(&end_month.,z2.)),12,.));
</code>```

Below is example code (without any attempt to reformat it to z2) - it will throw an error because it cannot find 'dataset_20201' because it is actually called 'dataset_202001'. The dataset called dataset_combined_example produces the desired output of the code by manually referencing the dataset names which it will be unable to do in practice. Does anyone know how to go about this?

```<code>DATA _NULL_;
    FORMAT start_date end_date DATE9.;
    start_date = '01NOV2019'd;
    end_date = '31JAN2020'd;
    CALL symput('start_date',start_date);
    CALL symput('end_date',end_date);
RUN;

DATA dataset_201911;
   input name $;
   datalines;
Nov1
Nov2
;
RUN;
DATA dataset_201912;
   input name $;
   datalines;
Dec1
Dec2
;
RUN;
DATA dataset_202001;
   input name $;
   datalines;
Jan1
Jan2
;
RUN;

DATA dataset_combined_example;
    SET dataset_201911 dataset_201912 dataset_202001;
RUN;

%MACRO get_table(start_date, end_date);
    %LET start_year = %SYSFUNC(year(&start_date.));
    %LET end_year = %SYSFUNC(year(&end_date.));
    %LET start_month = %SYSFUNC(month(&start_date.));
    %LET end_month = %SYSFUNC(month(&end_date.));
    DATA dataset_combined;
        SET
            %DO quote_year = &start_year. %TO &end_year.;
                %DO quote_month = %SYSFUNC(IFN(&quote_year. = &start_year.,&start_month.,1,.)) %TO %SYSFUNC(IFN(&quote_year. = &end_year.,&end_month.,12,.));
                    dataset_&quote_year.&quote_month.
                %END;
            %END;
        ;
    RUN;
%MEND;
%get_table(&start_date.,&end_date.);
</code>```

答:
You could do this using putn and z2. format.

```<code>%DO quote_year = &start_year. %TO &end_year.;
     %DO quote_month = %SYSFUNC(IFN(&quote_year. = &start_year.,&start_month.,1,.)) %TO %SYSFUNC(IFN(&quote_year. = &end_year.,&end_month.,12,.));
            dataset_&quote_year.%sysfunc(putn(&quote_month.,z2.))
     %END;
%END;
</code>```

Body:
So I have a range of datasets in a specific library. These datasets are named in the format DATASET_YYYYMM, with one dataset for each month. I am trying to append a range of these datasets based on user input for the date range. i.e. If start_date is 01NOV2019 and the end_date is 31JAN2020, I want to append the three datasets: LIBRARY.DATASET_201911, LIBRARY.DATASET_201912 and LIBRARY.DATASET_202001.

The range is obviously variable, so I can't simply name the datasets manually in a set function. Since I need to loop through the years and months in the date range, I believe a macro is the best way to do this. I'm using a loop within the SET statement to append all the datasets. I have copied my example code below. It does work in theory. But in practice, only if we are looping over the months of November and December. As the format of the dataset name has a two digit month, for Jan-Sept it will be 01-09. The month function returns 1-9 however, and of course a 'File DATASET_NAME does not exist' error is thrown.
Problem is I cannot figure out a way to get it to interpret the month with leading 0, without ruining functionality of another part of the loop/macro.

I have tried numerous approaches to format the number as z2, cannot get any to work.
i.e. Including PUTN functions in the DO line for quote_month as follows, it ignores the leading zero when generating the dataset name in the line below.

%DO quote_month = %SYSFUNC(IFN(&quote_year. = &start_year.,%SYSFUNC(PUTN(&start_month.,z2.)),1,.)) %TO %SYSFUNC(IFN(&quote_year. = &end_year.,%SYSFUNC(PUTN(&end_month.,z2.)),12,.));

Below is example code (without any attempt to reformat it to z2) - it will throw an error because it cannot find 'dataset_20201' because it is actually called 'dataset_202001'. The dataset called dataset_combined_example produces the desired output of the code by manually referencing the dataset names which it will be unable to do in practice. Does anyone know how to go about this?

DATA _NULL_;
    FORMAT start_date end_date DATE9.;
    start_date = '01NOV2019'd;
    end_date = '31JAN2020'd;
    CALL symput('start_date',start_date);
    CALL symput('end_date',end_date);
RUN;

DATA dataset_201911;
   input name $;
   datalines;
Nov1
Nov2
;
RUN;
DATA dataset_201912;
   input name $;
   datalines;
Dec1
Dec2
;
RUN;
DATA dataset_202001;
   input name $;
   datalines;
Jan1
Jan2
;
RUN;

DATA dataset_combined_example;
    SET dataset_201911 dataset_201912 dataset_202001;
RUN;

%MACRO get_table(start_date, end_date);
    %LET start_year = %SYSFUNC(year(&start_date.));
    %LET end_year = %SYSFUNC(year(&end_date.));
    %LET start_month = %SYSFUNC(month(&start_date.));
    %LET end_month = %SYSFUNC(month(&end_date.));
    DATA dataset_combined;
        SET
            %DO quote_year = &start_year. %TO &end_year.;
                %DO quote_month = %SYSFUNC(IFN(&quote_year. = &start_year.,&start_month.,1,.)) %TO %SYSFUNC(IFN(&quote_year. = &end_year.,&end_month.,12,.));
                    dataset_&quote_year.&quote_month.
                %END;
            %END;
        ;
    RUN;
%MEND;
%get_table(&start_date.,&end_date.);

Body:
You could do this using putn and z2. format.

%DO quote_year = &start_year. %TO &end_year.;
     %DO quote_month = %SYSFUNC(IFN(&quote_year. = &start_year.,&start_month.,1,.)) %TO %SYSFUNC(IFN(&quote_year. = &end_year.,&end_month.,12,.));
            dataset_&quote_year.%sysfunc(putn(&quote_month.,z2.))
     %END;
%END;


问:
IndexError: list index out of range when no argument is supplied
I just want to know why this code is generating IndexError: list index out of range when no argument supplied to it?

script.py

```<code>import sys
a = sys.argv[1]
print(a)
</code>```

Sample output with argument/s

```<code>user@linux:~$ python3 script.py abc
abc
user@linux:~$ python3 script.py abc def
abc
user@linux:~$
</code>```

Sample output without argument/s

```<code>user@linux:~$ python3 script.py
Traceback (most recent call last):
  File "script.py", line 2, in <module>
    a = sys.argv[1]
IndexError: list index out of range
user@linux:~$
</code>```

My reference: https://www.pythonforbeginners.com/system/python-sys-argv

答:
List sys.argv contains your command line arguments (index 0 is command itself, rest are arguments). So, if you won't provide argument then list contains only one item (only sys.argv[0] is there).

Here's official Python documentation.

Body:
I just want to know why this code is generating IndexError: list index out of range when no argument supplied to it?

script.py

import sys
a = sys.argv[1]
print(a)

Sample output with argument/s

user@linux:~$ python3 script.py abc
abc
user@linux:~$ python3 script.py abc def
abc
user@linux:~$

Sample output without argument/s

user@linux:~$ python3 script.py
Traceback (most recent call last):
  File "script.py", line 2, in <module>
    a = sys.argv[1]
IndexError: list index out of range
user@linux:~$

My reference: https://www.pythonforbeginners.com/system/python-sys-argv


问:
Django pagination dependent on ordering
I have the following model (simplified):

```<code>class Post(models.Model):
    title = models.CharField(max_length=20)
    date_created = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('-date_created',) # note the "reverse" ordering here
</code>```

, then my custom DetailView based on generic.DetailView:

```<code>class PostDetailView(generic.DetailView):
    queryset = Post.objects.all()
</code>```

and, finally, the following template:

```<code>{% with object.get_previous_by_date_created as prev %}
    {% if prev %}
    <a class="nav-link-prev"
       href="{% url "blog:post_detail" pk=prev.id %}">Previous</a>
    {% endif %}
{% endwith %}

{% with object.get_next_by_date_created as next %}
    {% if next %}
    <a class="nav-link-next"
       href="{% url "blog:post_detail" pk=next.id %}">Next</a>
    {% endif %}
{% endwith %}
</code>```

My pagination implemented this way works, but due to the reverse ordering (i.e -date_created) field, its Previous/Next labels are misplaced. In other words my template outputs "Previous" where it should be "Next", and vice versa. If I remove a - sign in ordering = ('-date_created',) it will work fine, but that's not the ordering I would like to have on my website.

Is there an easy and idiomatic way of fixing this misbehavior? What am I missing?

答:
I went this route and was able to solve the issue:

```<code>class PostDetailView(generic.DetailView):
    model = Post

    def get_context_data(self, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)

        next = Post.objects.filter(pk__lt=self.object.pk).order_by('-pk')[:1]
        prev = Post.objects.filter(pk__gt=self.object.pk).order_by('pk')[:1]
        if prev:
            context['prev'] = prev[0]
        if next:
            context['next'] = next[0]

        return context
</code>```

now in template.html:

```<code>{% if prev %}
<a class="nav-link-prev"
   href="{% url "post_detail" pk=prev.id %}">Previous
</a>
{% endif %}

{% if next %}
    <a class="nav-link-next"
       href="{% url "post_detail" pk=next.id %}">Next
    </a>
{% endif %}
</code>```

What do you think of this approach?

Title: Django pagination dependent on ordering

Body:
I have the following model (simplified):

class Post(models.Model):
    title = models.CharField(max_length=20)
    date_created = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('-date_created',) # note the "reverse" ordering here

, then my custom DetailView based on generic.DetailView:

class PostDetailView(generic.DetailView):
    queryset = Post.objects.all()

and, finally, the following template:

{% with object.get_previous_by_date_created as prev %}
    {% if prev %}
    Previous
    {% endif %}
{% endwith %}

{% with object.get_next_by_date_created as next %}
    {% if next %}
    Next
    {% endif %}
{% endwith %}

My pagination implemented this way works, but due to the reverse ordering (i.e -date_created) field, its Previous/Next labels are misplaced. In other words my template outputs "Previous" where it should be "Next", and vice versa. If I remove a - sign in ordering = ('-date_created',) it will work fine, but that's not the ordering I would like to have on my website.

Is there an easy and idiomatic way of fixing this misbehavior? What am I missing?

Body:
I went this route and was able to solve the issue:

class PostDetailView(generic.DetailView):
    model = Post

    def get_context_data(self, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)

        next = Post.objects.filter(pk__lt=self.object.pk).order_by('-pk')[:1]
        prev = Post.objects.filter(pk__gt=self.object.pk).order_by('pk')[:1]
        if prev:
            context['prev'] = prev[0]
        if next:
            context['next'] = next[0]

        return context

now in template.html:

{% if prev %}
<a class="nav-link-prev"
   href="{% url "post_detail" pk=prev.id %}">Previous
</a>
{% endif %}

{% if next %}
    <a class="nav-link-next"
       href="{% url "post_detail" pk=next.id %}">Next
    </a>
{% endif %}

What do you think of this approach?