问:
Get only unique data from array of objects in JavaScript
So I have the following structure:

```<code>[{
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Monday",
    "periods": [{
        "openDay": "Monday",
        "openTime": "12:00",
        "closeDay": "Monday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Monday",
        "openTime": "19:00",
        "closeDay": "Monday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Monday",
        "openTime": "23:00",
        "closeDay": "Monday",
        "closeTime": "23:30"
      }
    ]
  },
  {
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Tuesday",
    "periods": [{
        "openDay": "Tuesday",
        "openTime": "12:00",
        "closeDay": "Tuesday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Tuesday",
        "openTime": "19:00",
        "closeDay": "Tuesday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Tuesday",
        "openTime": "23:00",
        "closeDay": "Tuesday",
        "closeTime": "23:30"
      }
    ]
  }
]
</code>```

What I want to do, is if all periods for a given day are the same as any other day(matching by their openTime and closeTime) in the array to merge them (or just delete the second occurrence). If the periods are of a different length no action will occur. Also if just one of the openTime or closeTime is different, again no action will occur.
So far I have tried looping through all days and comparing one with the following after it. Got stuck in comparing the periods. Tried following the explanation here - https://gomakethings.com/check-if-two-arrays-or-objects-are-equal-with-javascript/, but again got lost.
The desired output will be:

```<code>[{
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Monday, Tuesday",
    "periods": [{
        "openDay": "Monday",
        "openTime": "12:00",
        "closeDay": "Monday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Monday",
        "openTime": "19:00",
        "closeDay": "Monday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Monday",
        "openTime": "23:00",
        "closeDay": "Monday",
        "closeTime": "23:30"
      }
    ]
  },
</code>```

As I don't care about changing the openDay/closeDay in the periods. I want to do this check for all days in the array.

答:
You can sum up the entire process inside reduce method:

var data = [{ "isOpen":1, "weekday":1, "humanDay":"Monday", "periods": [ { "openDay":"Monday", "openTime":"12:00", "closeDay":"Monday", "closeTime":"14:30" }, { "openDay":"Monday", "openTime":"19:00", "closeDay":"Monday", "closeTime":"22:30" }, { "openDay":"Monday", "openTime":"23:00", "closeDay":"Monday", "closeTime":"23:30" } ]},{ "isOpen":1, "weekday":1, "humanDay":"Tuesday", "periods": [ { "openDay":"Tuesday", "openTime":"12:00", "closeDay":"Tuesday", "closeTime":"14:30" }, { "openDay":"Tuesday", "openTime":"19:00", "closeDay":"Tuesday", "closeTime":"22:30" }, { "openDay":"Tuesday", "openTime":"23:00", "closeDay":"Tuesday", "closeTime":"23:30" } ]}];

var result = Object.values(data.reduce((acc, elem, i, self)=>{
   otherDays = self.filter(k=>k.periods.every((d,j)=>d.openTime == elem.periods[j].openTime && d.closeTime == elem.periods[j].closeTime));
   key = otherDays.map(({humanDay})=>humanDay).join(',');
   acc[key] = acc[key] || {...elem, humanDay:key};
   return acc;
},{}));

console.log(result);```

Body:
So I have the following structure:

[{
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Monday",
    "periods": [{
        "openDay": "Monday",
        "openTime": "12:00",
        "closeDay": "Monday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Monday",
        "openTime": "19:00",
        "closeDay": "Monday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Monday",
        "openTime": "23:00",
        "closeDay": "Monday",
        "closeTime": "23:30"
      }
    ]
  },
  {
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Tuesday",
    "periods": [{
        "openDay": "Tuesday",
        "openTime": "12:00",
        "closeDay": "Tuesday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Tuesday",
        "openTime": "19:00",
        "closeDay": "Tuesday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Tuesday",
        "openTime": "23:00",
        "closeDay": "Tuesday",
        "closeTime": "23:30"
      }
    ]
  }
]

What I want to do, is if all periods for a given day are the same as any other day(matching by their openTime and closeTime) in the array to merge them (or just delete the second occurrence). If the periods are of a different length no action will occur. Also if just one of the openTime or closeTime is different, again no action will occur.
So far I have tried looping through all days and comparing one with the following after it. Got stuck in comparing the periods. Tried following the explanation here - https://gomakethings.com/check-if-two-arrays-or-objects-are-equal-with-javascript/, but again got lost.
The desired output will be:

[{
    "isOpen": 1,
    "weekday": 1,
    "humanDay": "Monday, Tuesday",
    "periods": [{
        "openDay": "Monday",
        "openTime": "12:00",
        "closeDay": "Monday",
        "closeTime": "14:30"
      },
      {
        "openDay": "Monday",
        "openTime": "19:00",
        "closeDay": "Monday",
        "closeTime": "22:30"
      },
      {
        "openDay": "Monday",
        "openTime": "23:00",
        "closeDay": "Monday",
        "closeTime": "23:30"
      }
    ]
  },

As I don't care about changing the openDay/closeDay in the periods. I want to do this check for all days in the array.


来源: stackexchange

问:
Text widget must not be null
I pass argument through a pushNamedandRemoveUntil but it shows text widget must not be null when I try to access the passed parameter.

```<code>CustomButton(
                    buttonText: 'Go',
                    buttonClick: () {Navigator.pushNamedAndRemoveUntil(context, Next.id, (route) => false, arguments: "123456789");},
                  ),

class Next extends StatefulWidget {

  const Next({this.number});
  static const id = "next";
  final String number;
  @override
  _NextState createState() => _NextState();
}

class _NextState extends State<Next> {
 @override
  Widget build(BuildContext context) {
       return Scaffold(
body: Container(child: Center(child: Text(widget.number)))
)
}
}
</code>```

Error is
Failed assertion: line 298 pos 10: 'data != null'

答:
You can't access like that. Use ModalRoute in your next screen and fetch the data.

```<code>Widget build(BuildContext context) {
      final number = ModalRoute.of(context).settings.arguments as String;
//....
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Text widget must not be null

Body:
I pass argument through a pushNamedandRemoveUntil but it shows text widget must not be null when I try to access the passed parameter.

CustomButton(
                    buttonText: 'Go',
                    buttonClick: () {Navigator.pushNamedAndRemoveUntil(context, Next.id, (route) => false, arguments: "123456789");},
                  ),

class Next extends StatefulWidget {

  const Next({this.number});
  static const id = "next";
  final String number;
  @override
  _NextState createState() => _NextState();
}

class _NextState extends State<Next> {
 @override
  Widget build(BuildContext context) {
       return Scaffold(
body: Container(child: Center(child: Text(widget.number)))
)
}
}

Error is
Failed assertion: line 298 pos 10: 'data != null'

Body:
You can't access like that. Use ModalRoute in your next screen and fetch the data.

Widget build(BuildContext context) {
      final number = ModalRoute.of(context).settings.arguments as String;
//....
}


问:
Set Discounted Price for Related Product on Product Page
I am trying to set the price of all related products on the products page to 10% less = 0.9

The goal is to provide a discount of all related products on the product page but when viewed as a product, give the normal price.

Overall, the idea is to provide incentive that generates up-selling of related products.

I am asking for two things here. ONE: change the product price for related products on the product page (10% off) and TWO: carry that discounted price into the cart and checkout when the related discounted product is added to cart from the product page.

I almost got the first part down, but the code I'm trying to get working is giving me an error saying:

```<code>Warning: A non-numeric value encountered
</code>```

My code so far:

```<code>add_filter( 'woocommerce_get_price_html', 'related_product_price_discount', 100, 2 );
function related_product_price_discount( $price, $product ) {
    global $woocommerce_loop;

    // make sure this is a related product on product page
    if( is_product() && $woocommerce_loop['name'] == 'related' ){
        $price = $price * 0.9;
    }
    // return related product price with discount
    return apply_filters( 'woocommerce_get_price', $price );
}
</code>```

答:
The rule in StackOverFlow is one question at the time, so I will answer only your first question, which is related to your code issue...

Note that the hook woocommerce_get_price_html is related to the displayed formatted price.

To avoid the error "Warning: A non-numeric value encountered", you will use the following:

```<code>add_filter( 'woocommerce_get_price_html', 'related_product_price_discount', 100, 2 );
function related_product_price_discount( $price_html, $product ) {
    global $woocommerce_loop;

    // make sure this is a related product on product page
    if( is_product() && $woocommerce_loop['name'] == 'related' ){
        $price_html = wc_price( wc_get_price_to_display( $product ) * 0.9 );
    }
    // return related product displayed discounted formatted price
    return $price_html;
}
</code>```

Code goes in functions.php file of your active child theme (active theme). Tested and works.

Body:
I am trying to set the price of all related products on the products page to 10% less = 0.9

The goal is to provide a discount of all related products on the product page but when viewed as a product, give the normal price.

Overall, the idea is to provide incentive that generates up-selling of related products.

I am asking for two things here. ONE: change the product price for related products on the product page (10% off) and TWO: carry that discounted price into the cart and checkout when the related discounted product is added to cart from the product page.

I almost got the first part down, but the code I'm trying to get working is giving me an error saying:

Warning: A non-numeric value encountered

My code so far:

add_filter( 'woocommerce_get_price_html', 'related_product_price_discount', 100, 2 );
function related_product_price_discount( $price, $product ) {
    global $woocommerce_loop;

    // make sure this is a related product on product page
    if( is_product() && $woocommerce_loop['name'] == 'related' ){
        $price = $price * 0.9;
    }
    // return related product price with discount
    return apply_filters( 'woocommerce_get_price', $price );
}

Body:
The rule in StackOverFlow is one question at the time, so I will answer only your first question, which is related to your code issue...

Note that the hook woocommerce_get_price_html is related to the displayed formatted price.

To avoid the error "Warning: A non-numeric value encountered", you will use the following:

add_filter( 'woocommerce_get_price_html', 'related_product_price_discount', 100, 2 );
function related_product_price_discount( $price_html, $product ) {
    global $woocommerce_loop;

    // make sure this is a related product on product page
    if( is_product() && $woocommerce_loop['name'] == 'related' ){
        $price_html = wc_price( wc_get_price_to_display( $product ) * 0.9 );
    }
    // return related product displayed discounted formatted price
    return $price_html;
}

Code goes in functions.php file of your active child theme (active theme). Tested and works.


问:
Find the sum of the first n num
I have an array with numbers. Find the sum of the first N elements to the first zero. Task must be completed with
Example: - summarize the first 3 elements, because next is the element with the number 0.</p>

答:
You can not break the iteration of reduce(). You can use a flag variable based on which you can add value to sum.

Try the following way:

let arr = [10, 20, 3, 0, 16, 35, 1];
let flag = true;
let sumNum = arr.reduce((sum, elem) => {
  if (elem == 0) {
    flag = false;
  };
  if(flag) return sum + elem;
  else return sum + 0;
}, 0)
console.log(sumNum)```

Title: Find the sum of the first n num


答:
You could do this as follows:

let arr = [10, 20, 3, 0, 16, 35, 1];

let sum = arr.slice(0, arr.indexOf(0)).reduce((sum, v) => sum + v);

console.log(sum);```

I first extract the numbers in front of the first zero using Array.slice(). Then I use Array.reduce() to compute the sum of these numbers.

Title: Find the sum of the first n num

Body:
I have an array with numbers. Find the sum of the first N elements to the first zero. Task must be completed with
Example: - summarize the first 3 elements, because next is the element with the number 0.

Body:
You could do this as follows:

let arr = [10, 20, 3, 0, 16, 35, 1];

let sum = arr.slice(0, arr.indexOf(0)).reduce((sum, v) => sum + v);

console.log(sum);

I first extract the numbers in front of the first zero using Array.slice(). Then I use Array.reduce() to compute the sum of these numbers.


问:
Recursive map over array using extension method
I have a collection of LayoutElement that I receive from an API.

For simplicity sake, imagine it contains 2 properties -

String or [LayoutElement]

I'd like to iterate over this collection and if the value has children, loop over the children recursively, returning the LayoutElement that contains a String

Essentially I should end up with a [LayoutElement] that contains only the elements that have a String value.

As this will be used in multiple places, I thought I could create an extension on Array where the element is LayoutElement but I am unsure how best to do this in the case of element.children.

import UIKit

struct LayoutElement {
  let children: [LayoutElement]?
  let text: String?
}

let data = [
  LayoutElement(children: nil, text: "First Text Element"),
  LayoutElement(children: [
    LayoutElement(children: nil, text: "Second Text Element"),
    LayoutElement(children: nil, text: "Third Text Element"),
    LayoutElement(children: [
      LayoutElement(children: nil, text: "Fourth Text Element"),
    ], text: nil)
  ], text: nil),
]

extension Array where Element == LayoutElement {
  var asLayout: [LayoutElement] {
    return map { element in
      if let children = element.children {
        // ???
      } else {
        return element
      }
    }
  }
}

let output = data.asLayout

print(output)
```

答:
You couldn't figure how to do it because you chose the wrong higher-order function. You should use flatMap, not map.

map transforms each array element into another element, but flatMap can transform each element into several other elements. You should use flatMap when the resulting array has a different size than the starting array, which is the case here. data has 2 elements, while output should have 4 elements. map can never increase the number of elements.

```<code>  var asLayout: [LayoutElement] {
    return flatMap { element -> [LayoutElement] in
      // for each element, we return the array of elements into which we want to transform it
      if let children = element.children {
        return children.asLayout
      } else {
        return [element] // we don't want to transform it, so we return an array containing only "element"
      }
    }
  }
</code>```

Returning children.asLayout should do the job.

Or in one line:

```<code>var asLayout: [LayoutElement] {
    flatMap { $0.children?.asLayout ?? [$0] }
}
</code>```

Body:
You couldn't figure how to do it because you chose the wrong higher-order function. You should use flatMap, not map.

map transforms each array element into another element, but flatMap can transform each element into several other elements. You should use flatMap when the resulting array has a different size than the starting array, which is the case here. data has 2 elements, while output should have 4 elements. map can never increase the number of elements.

  var asLayout: [LayoutElement] {
    return flatMap { element -> [LayoutElement] in
      // for each element, we return the array of elements into which we want to transform it
      if let children = element.children {
        return children.asLayout
      } else {
        return [element] // we don't want to transform it, so we return an array containing only "element"
      }
    }
  }

Returning children.asLayout should do the job.

Or in one line:

var asLayout: [LayoutElement] {
    flatMap { $0.children?.asLayout ?? [$0] }
}


答:
```<code>const arr = [10, 20, 3, 0, 16, 35, 1];
const zeroIndex = arr.indexOf(0);
const total = arr.slice(0, zeroIndex > 0 ? zeroIndex : arr.length)
   .reduce(sum, n => sum+n, 0);
console.log(total);
</code>```

Title: Find the sum of the first n num


问:
Access parent documents field in Firestore rules
I'm implementing a recipe book in Firestore where every user is able to see all the recipes all users created but only the original author of the recipe is allowed to edit or delete the recipe. Any user is also allowed to create a new recipe.

My problem is that I am unable to setup the permissions a subcollection to "listen" on a field of the subcollections parentdocument.

Each recipe document contains three things. A field called name where the name of the recipe is stored, a field called creatorUID where the request.auth.uid of the creators uid is stored and a subcollection called ingredients containing documents with some random fields.

```<code>service cloud.firestore {
  match /databases/{database}/documents {

    function isSignedIn() {
      return request.auth != null;
    }

    match /ListOfRecipes/{recipe} {
        allow read, create: if isSignedIn();
        allow update, delete: if resource.data.creatorUID == request.auth.uid;

        match /{list=**} {
            allow read: if isSignedIn();
            // Should return true if recipe.creatorUID has same value as request.auth.uid
            allow write: if recipe.creatorUID == request.auth.uid;
        }
    }
  }
}
</code>```

The problem is that with these rules it only works to create the recipe document. The subcollection and it's documents are not created since the db says

FirebaseError: [code=permission-denied]: Missing or insufficient permissions.
  FirebaseError: Missing or insufficient permissions.

The calls is made from Angular client and it's official library.

答:
Building upon Dan's answer, you should be able to reduce the number of reads on your database for update and delete on the subcollection by adding the creatorUID to the subcollection document.

You'll have to restrict create to just the creator and make sure the creatorUID is set. Here's my modification of Dan's rules:

```<code>service cloud.firestore {
  match /databases/{database}/documents {

    function isSignedIn() {
      return request.auth != null;
    }

    match /ListOfRecipes/{recipe} {
        allow read, create: if isSignedIn();
        allow update, delete: if resource.data.creatorUID == request.auth.uid;

        function recipeData() {
            return get(/databases/$(database)/documents/ListOfRecipes/$(recipe)).data
        }

        match /List/{list} {
            allow read: if isSignedIn();
            allow update, delete: if resource.data.creatorUID == request.auth.uid;
            allow create: if recipeData().creatorUID == request.auth.uid
                          && request.resource.data.creatorUID == request.auth.uid;
        }
    }
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm implementing a recipe book in Firestore where every user is able to see all the recipes all users created but only the original author of the recipe is allowed to edit or delete the recipe. Any user is also allowed to create a new recipe.

My problem is that I am unable to setup the permissions a subcollection to "listen" on a field of the subcollections parentdocument.

Each recipe document contains three things. A field called name where the name of the recipe is stored, a field called creatorUID where the request.auth.uid of the creators uid is stored and a subcollection called ingredients containing documents with some random fields.

service cloud.firestore {
  match /databases/{database}/documents {

    function isSignedIn() {
      return request.auth != null;
    }

    match /ListOfRecipes/{recipe} {
        allow read, create: if isSignedIn();
        allow update, delete: if resource.data.creatorUID == request.auth.uid;

        match /{list=**} {
            allow read: if isSignedIn();
            // Should return true if recipe.creatorUID has same value as request.auth.uid
            allow write: if recipe.creatorUID == request.auth.uid;
        }
    }
  }
}

The problem is that with these rules it only works to create the recipe document. The subcollection and it's documents are not created since the db says

FirebaseError: [code=permission-denied]: Missing or insufficient permissions.
  FirebaseError: Missing or insufficient permissions.

The calls is made from Angular client and it's official library.

Body:
Building upon Dan's answer, you should be able to reduce the number of reads on your database for update and delete on the subcollection by adding the creatorUID to the subcollection document.

You'll have to restrict create to just the creator and make sure the creatorUID is set. Here's my modification of Dan's rules:

service cloud.firestore {
  match /databases/{database}/documents {

    function isSignedIn() {
      return request.auth != null;
    }

    match /ListOfRecipes/{recipe} {
        allow read, create: if isSignedIn();
        allow update, delete: if resource.data.creatorUID == request.auth.uid;

        function recipeData() {
            return get(/databases/$(database)/documents/ListOfRecipes/$(recipe)).data
        }

        match /List/{list} {
            allow read: if isSignedIn();
            allow update, delete: if resource.data.creatorUID == request.auth.uid;
            allow create: if recipeData().creatorUID == request.auth.uid
                          && request.resource.data.creatorUID == request.auth.uid;
        }
    }
  }
}


问:
socket.io: Disconnect event - 'transport close', 'client namespace disconnect', 'transport error' and 'forced close'
Using socket.io v1.2.1 (only using the "polling" transport), sometimes my clients experience disconnections.

About 50% of the time I get ping timeout on my disconnect event callback function, which is reasonable.

Other times, I get transport close, client namespace disconnect, transport error and forced close. I did not find any reference to those disconnection reasons in the documentation, and was not able to really understand their meaning from the code.

I want to make sure I handle each disconnection the best way (and maybe prevent them).

Maybe someone can shed a little light about these reasons.

答:
Try this code at server side

```<code>var fs = require('fs');
var pkey = fs.readFileSync('/etc/ssl/private/ssl.key'); //Replace the path of your SSL key
var pcert = fs.readFileSync('/etc/ssl/certs/ssl.crt');//Replace the path of your SSL cert
var options = {
  key: pkey,
  cert: pcert
};

var app = require('https').createServer(options);

var io = require('socket.io')(app, {'pingTimeout': 180000, 'pingInterval': 25000});
</code>```

Here pingInterval is important, Keep it low, I tried various values and found 25 sec is good to keep socket keep pinging before it get timeout.

The main issue is there if within 60 sec there is no ping/pong, then it will disconnect and try to auto reconnect.  Also, I found pingTimeout at server side and timeout and client side not able to help to disconnect the socket in 60 sec. It's happening due to chrome latest version 83.

Body:
Try this code at server side

var fs = require('fs');
var pkey = fs.readFileSync('/etc/ssl/private/ssl.key'); //Replace the path of your SSL key
var pcert = fs.readFileSync('/etc/ssl/certs/ssl.crt');//Replace the path of your SSL cert
var options = {
  key: pkey,
  cert: pcert
};

var app = require('https').createServer(options);

var io = require('socket.io')(app, {'pingTimeout': 180000, 'pingInterval': 25000});

Here pingInterval is important, Keep it low, I tried various values and found 25 sec is good to keep socket keep pinging before it get timeout.

The main issue is there if within 60 sec there is no ping/pong, then it will disconnect and try to auto reconnect.  Also, I found pingTimeout at server side and timeout and client side not able to help to disconnect the socket in 60 sec. It's happening due to chrome latest version 83.


问:
How to Export excel data to MS Access by Querying first the MAx coloumn and adding 1?
Hi Im making a Excel Form in which my Database is an access.

First I Encode data in Excel then Using Command Button to Post these data.

The code within the Command Button.. first get the Max Number from Access and use that Number to Complete the Data in Excel to be exported to Access. The Problem is If I use 2 and above users to simultaneously Post it will consolidate all the data into one with the same Number.
What I want is to lock opening data until posted since i need to get the max number of a column then add 1 first then import a complete set of data including the MAX number as a control number.

I tried using Do While adStateOpen <> 1 and also Do While IsRecordBusy = True then wait  and loop and set the recordset to nothing instead of closing it twice. But it wont work it will consolidate the data with the same control number.

Below is my Code

```<code>Option Explicit

Sub ImportJEData()

Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rst As ADODB.Recordset 'dim the ADO recordset class
Dim dbPath
Dim x As Long, i As Long
Dim nextrow As Long
Dim Var
Dim LockType
Dim SQL
Dim IsRecordBusy

'add error handling
On Error GoTo errHandler:

'Variables for file path and last row of data
dbPath = Sheets("Update Version").Range("b1").Value
Set Var = Sheets("JE FORM").Range("F14")
nextrow = Sheets("LEDGERTEMPFORM").Cells(Rows.Count - 5, 1).End(xlUp).Row

'Initialise the collection class variable
Set cnn = New ADODB.Connection

'Create the ADODB recordset object. for Max Number
Set rst = New ADODB.Recordset 'assign memory to the recordset
LockType = adLockPessimistic

'Do While adStateOpen <> 1
Do While IsRecordBusy = True
Application.Wait (Now + TimeValue("0:00:01") / 1000)
Loop

SQL = "SELECT distinct Max(DVNumber),Max(ChckID) FROM DV "

rst.Open SQL, cnn

Sheets("Max").Range("A2").CopyFromRecordset rst

Set rst = Nothing

Set rst = New ADODB.Recordset 'assign memory to the recordset

rst.Open Source:="DV", ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockPessimistic, _
Options:=adCmdTable

On Error Resume Next

'you now have the recordset object
'add the values to it
For x = 7 To nextrow
rst.AddNew
For i = 1 To 37
rst(Sheets("LEDGERTEMPFORM").Cells(6, i).Value) = Sheets("LEDGERTEMPFORM").Cells(x, i).Value
Next i
rst.Update
Next x

'close the recordset
rst.Close
' Close the connection
cnn.Close
'clear memory
Set rst = Nothing
Set cnn = Nothing

'Update the sheet

Application.ScreenUpdating = True

'Clear the data
On Error GoTo 0
Exit Sub
errHandler:

'clear memory
Set rst = Nothing
Set cnn = Nothing
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Export_Data"

End Sub
</code>```

答:
Im finally done with this code. I just added another Table in access where such table is unique the uses sql to get the max+1 and insert it back and loop it if error occurs because of the duplicate. Heres the code below

```<code>Do
On Error Resume Next 'reset Err.obj.

     'Get the Max ID +1
    Set rst = Nothing
    Set rst = New ADODB.Recordset 'assign memory to the recordset
    SQL = "SELECT Max(ApNumber)+1 FROM PayVoucherID "
    rst.Open SQL, cnn

    'Check if the recordset is empty.
    'Copy Recordset to the Temporary Cell
    Sheets("MAX").Range("A2").CopyFromRecordset rst

    'Insert the Data to Database And Check If no Errors
    Sql2 = "INSERT INTO PayVoucherID(ApNumber)Values('" & Sheets("MAX").Range("A2") & "') "
    cnn.Execute Sql2

Loop Until (Err.Number = 0)
</code>```

Hope this helps for Excel Front users.

Body:
Hi Im making a Excel Form in which my Database is an access.

First I Encode data in Excel then Using Command Button to Post these data.

The code within the Command Button.. first get the Max Number from Access and use that Number to Complete the Data in Excel to be exported to Access. The Problem is If I use 2 and above users to simultaneously Post it will consolidate all the data into one with the same Number.
What I want is to lock opening data until posted since i need to get the max number of a column then add 1 first then import a complete set of data including the MAX number as a control number.

I tried using Do While adStateOpen <> 1 and also Do While IsRecordBusy = True then wait  and loop and set the recordset to nothing instead of closing it twice. But it wont work it will consolidate the data with the same control number.

Below is my Code

Option Explicit

Sub ImportJEData()

Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rst As ADODB.Recordset 'dim the ADO recordset class
Dim dbPath
Dim x As Long, i As Long
Dim nextrow As Long
Dim Var
Dim LockType
Dim SQL
Dim IsRecordBusy

'add error handling
On Error GoTo errHandler:

'Variables for file path and last row of data
dbPath = Sheets("Update Version").Range("b1").Value
Set Var = Sheets("JE FORM").Range("F14")
nextrow = Sheets("LEDGERTEMPFORM").Cells(Rows.Count - 5, 1).End(xlUp).Row

'Initialise the collection class variable
Set cnn = New ADODB.Connection

'Create the ADODB recordset object. for Max Number
Set rst = New ADODB.Recordset 'assign memory to the recordset
LockType = adLockPessimistic

'Do While adStateOpen <> 1
Do While IsRecordBusy = True
Application.Wait (Now + TimeValue("0:00:01") / 1000)
Loop

SQL = "SELECT distinct Max(DVNumber),Max(ChckID) FROM DV "

rst.Open SQL, cnn

Sheets("Max").Range("A2").CopyFromRecordset rst

Set rst = Nothing

Set rst = New ADODB.Recordset 'assign memory to the recordset

rst.Open Source:="DV", ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockPessimistic, _
Options:=adCmdTable

On Error Resume Next

'you now have the recordset object
'add the values to it
For x = 7 To nextrow
rst.AddNew
For i = 1 To 37
rst(Sheets("LEDGERTEMPFORM").Cells(6, i).Value) = Sheets("LEDGERTEMPFORM").Cells(x, i).Value
Next i
rst.Update
Next x

'close the recordset
rst.Close
' Close the connection
cnn.Close
'clear memory
Set rst = Nothing
Set cnn = Nothing

'Update the sheet

Application.ScreenUpdating = True

'Clear the data
On Error GoTo 0
Exit Sub
errHandler:

'clear memory
Set rst = Nothing
Set cnn = Nothing
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Export_Data"

End Sub

Body:
Im finally done with this code. I just added another Table in access where such table is unique the uses sql to get the max+1 and insert it back and loop it if error occurs because of the duplicate. Heres the code below

Do
On Error Resume Next 'reset Err.obj.

     'Get the Max ID +1
    Set rst = Nothing
    Set rst = New ADODB.Recordset 'assign memory to the recordset
    SQL = "SELECT Max(ApNumber)+1 FROM PayVoucherID "
    rst.Open SQL, cnn

    'Check if the recordset is empty.
    'Copy Recordset to the Temporary Cell
    Sheets("MAX").Range("A2").CopyFromRecordset rst

    'Insert the Data to Database And Check If no Errors
    Sql2 = "INSERT INTO PayVoucherID(ApNumber)Values('" & Sheets("MAX").Range("A2") & "') "
    cnn.Execute Sql2

Loop Until (Err.Number = 0)

Hope this helps for Excel Front users.


问:
When to use padding in Conv2d() and when to do ReflectionPad2d() Pytorch
I have two PyTorch models that are equivalent (I think), the only difference between them is the padding:

```<code>import torch
import torch.nn as nn

i = torch.arange(9, dtype=torch.float).reshape(1,1,3,3)
# First model:
model1 = nn.Conv2d(1, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), padding_mode='reflection')
# tensor([[[[-0.6095, -0.0321,  2.2022],
#           [ 0.1018,  1.7650,  5.5392],
#           [ 1.7988,  3.9165,  5.6506]]]], grad_fn=<MkldnnConvolutionBackward>)

# Second model:
model2 = nn.Sequential(nn.ReflectionPad2d((1, 1, 1, 1)),
             nn.Conv2d(1, 1, kernel_size=3))
# tensor([[[[1.4751, 1.5513, 2.6566],
#           [4.0281, 4.1043, 5.2096],
#           [2.6149, 2.6911, 3.7964]]]], grad_fn=<MkldnnConvolutionBackward>)
</code>```

I was wondering why and when you use both approaches, the output of both is different but as I see it they should be the same, because the padding is of type reflection.

Would appreciate some help in understanding it.

EDIT

After what @Ash said, I wanted to check wheter or not the weights had influence so I pinned all of them to the same value and still there is a difference between the 2 methods:

```<code>import torch
import torch.nn as nn

i = torch.arange(9, dtype=torch.float).reshape(1,1,3,3)
# First model:
model1 = nn.Conv2d(1, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), padding_mode='reflection')
model1.weight.data = torch.full(model1.weight.data.shape, 0.4)
print(model1(i))
print(model1.weight)
# tensor([[[[ 3.4411,  6.2411,  5.0412],
#           [ 8.6411, 14.6411, 11.0412],
#           [ 8.2411, 13.4411,  9.8412]]]], grad_fn=<MkldnnConvolutionBackward>)
# Parameter containing:
# tensor([[[[0.4000, 0.4000, 0.4000],
#           [0.4000, 0.4000, 0.4000],
#           [0.4000, 0.4000, 0.4000]]]], requires_grad=True)

# Second model:
model2 = [nn.ReflectionPad2d((1, 1, 1, 1)),
             nn.Conv2d(1, 1, kernel_size=3)]
model2[1].weight.data = torch.full(model2[1].weight.data.shape, 0.4)
model2 = nn.Sequential(*model2)
print(model2(i))
print(model2[1].weight)
# tensor([[[[ 9.8926, 11.0926, 12.2926],
#           [13.4926, 14.6926, 15.8926],
#           [17.0926, 18.2926, 19.4926]]]], grad_fn=<MkldnnConvolutionBackward>)
# Parameter containing:
# tensor([[[[0.4000, 0.4000, 0.4000],
#           [0.4000, 0.4000, 0.4000],
#           [0.4000, 0.4000, 0.4000]]]], requires_grad=True)
</code>```

答:
the output of both is different but as I see it they should be the same

I don't think that the different outputs that you get are only related to how the reflective padding is implemented. In the code snippet that you provide, the values of the weights and biases of the convolutions from model1 and model2 differ, since they are initialized randomly and you don't seem to fix their values in the code.

EDIT:

Following your new edit, it seems that for versions prior to 1.5, looking at  the implementation of the forward pass in <your_torch_install>/nn/modules/conv.pyshows that "reflection" is not supported. It wont complain about arbitrary strings instead of "reflection" either, but will default to zero-padding.

Body:
I have two PyTorch models that are equivalent (I think), the only difference between them is the padding:

import torch
import torch.nn as nn

i = torch.arange(9, dtype=torch.float).reshape(1,1,3,3)
# First model:
model1 = nn.Conv2d(1, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), padding_mode='reflection')
# tensor([[[[-0.6095, -0.0321,  2.2022],
#           [ 0.1018,  1.7650,  5.5392],
#           [ 1.7988,  3.9165,  5.6506]]]], grad_fn=<MkldnnConvolutionBackward>)

# Second model:
model2 = nn.Sequential(nn.ReflectionPad2d((1, 1, 1, 1)),
             nn.Conv2d(1, 1, kernel_size=3))
# tensor([[[[1.4751, 1.5513, 2.6566],
#           [4.0281, 4.1043, 5.2096],
#           [2.6149, 2.6911, 3.7964]]]], grad_fn=<MkldnnConvolutionBackward>)

I was wondering why and when you use both approaches, the output of both is different but as I see it they should be the same, because the padding is of type reflection.

Would appreciate some help in understanding it.

EDIT

After what @Ash said, I wanted to check wheter or not the weights had influence so I pinned all of them to the same value and still there is a difference between the 2 methods:

import torch
import torch.nn as nn

i = torch.arange(9, dtype=torch.float).reshape(1,1,3,3)
# First model:
model1 = nn.Conv2d(1, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), padding_mode='reflection')
model1.weight.data = torch.full(model1.weight.data.shape, 0.4)
print(model1(i))
print(model1.weight)
# tensor([[[[ 3.4411,  6.2411,  5.0412],
#           [ 8.6411, 14.6411, 11.0412],
#           [ 8.2411, 13.4411,  9.8412]]]], grad_fn=<MkldnnConvolutionBackward>)
# Parameter containing:
# tensor([[[[0.4000, 0.4000, 0.4000],
#           [0.4000, 0.4000, 0.4000],
#           [0.4000, 0.4000, 0.4000]]]], requires_grad=True)

# Second model:
model2 = [nn.ReflectionPad2d((1, 1, 1, 1)),
             nn.Conv2d(1, 1, kernel_size=3)]
model2[1].weight.data = torch.full(model2[1].weight.data.shape, 0.4)
model2 = nn.Sequential(*model2)
print(model2(i))
print(model2[1].weight)
# tensor([[[[ 9.8926, 11.0926, 12.2926],
#           [13.4926, 14.6926, 15.8926],
#           [17.0926, 18.2926, 19.4926]]]], grad_fn=<MkldnnConvolutionBackward>)
# Parameter containing:
# tensor([[[[0.4000, 0.4000, 0.4000],
#           [0.4000, 0.4000, 0.4000],
#           [0.4000, 0.4000, 0.4000]]]], requires_grad=True)


问:
Problems with if ....==NULL in C
I have this code, note that it is shortened down. The problem is if the file exists
it still overwrites it. Been 30 years since I did any programming so bear with me. Thanks!</p>

```<code>FILE *openFil(FILE *open, char namn[]);

int main(int argc, const char * argv[])
{
    FILE *openFil(FILE *open, char namn[]);
    FILE *anmal =NULL;

    char filNamn[] = "ANMAL.DAT";
    postTypAnm pAnm;
    anmal = openFil(anmal, filNamn);
}

FILE *openFil(FILE *pointer, char name[])
{
    if ((pointer =fopen(name, "r+b"))== NULL)
        if ((pointer =fopen(name, "w+b"))== NULL)
        {
            /* It Enters here as well, but it should not do that or????? */
            printf("error\n");
            exit(0);
        }
    return pointer;
}
</code>```

答:
Here's a working example.

```<code>#include <errno.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

bool openFile(FILE **ptr,
    const char *fileName);

int main(int argc, const char * argv[]) {
    FILE *anmal = NULL;
    const char *fileName = "ANMAL.DAT";

    if(!openFile(&anmal, fileName)) {
        exit(EXIT_FAILURE);
    }
}

bool openFile(FILE **ptr,
    const char *fileName)
{
    *ptr = fopen(fileName, "w+bx");
    if(!*ptr) {
        perror("Error opening file: ");
        return false;
    }

    return true;
}

</code>```

This is using the x extension in GNU C to test whether the file exists.

As other people have pointed out, there are numerous problems in your original code.

You've redeclared the function prototype for openFil within main.

In openFil there's no point in both accepting the FILE pointer as
a parameter and overwriting it with the return value. Especially if
you're expecting to input a NULL pointer and use the function to
initialise it. Either use a pointer-to-pointer as a parameter so you
can modify the pointer within the function, or ignore it completely
and set its value with the function's return value. Not both.

You're not actually testing for whether the file exists at all. According to the manual pages for fopen (man fopen) neither of the flags you used in opening the file (r+ and w+) care whether the file exists. r+ opens for reading/writing and always positions the stream at the beginning of the file. w+ opens for reading/writing, truncating the file if it exists already. This explains why you didn't get the effect you intended.

Title: Problems with if ....==NULL in C

Body:
I have this code, note that it is shortened down. The problem is if the file exists
it still overwrites it. Been 30 years since I did any programming so bear with me. Thanks!

FILE *openFil(FILE *open, char namn[]);

int main(int argc, const char * argv[])
{
    FILE *openFil(FILE *open, char namn[]);
    FILE *anmal =NULL;

    char filNamn[] = "ANMAL.DAT";
    postTypAnm pAnm;
    anmal = openFil(anmal, filNamn);
}

FILE *openFil(FILE *pointer, char name[])
{
    if ((pointer =fopen(name, "r+b"))== NULL)
        if ((pointer =fopen(name, "w+b"))== NULL)
        {
            /* It Enters here as well, but it should not do that or????? */
            printf("error\n");
            exit(0);
        }
    return pointer;
}

Body:
Here's a working example.

#include <errno.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

bool openFile(FILE **ptr,
    const char *fileName);

int main(int argc, const char * argv[]) {
    FILE *anmal = NULL;
    const char *fileName = "ANMAL.DAT";

    if(!openFile(&anmal, fileName)) {
        exit(EXIT_FAILURE);
    }
}

bool openFile(FILE **ptr,
    const char *fileName)
{
    *ptr = fopen(fileName, "w+bx");
    if(!*ptr) {
        perror("Error opening file: ");
        return false;
    }

    return true;
}

This is using the x extension in GNU C to test whether the file exists.

As other people have pointed out, there are numerous problems in your original code.

You've redeclared the function prototype for openFil within main.

In openFil there's no point in both accepting the FILE pointer as
a parameter and overwriting it with the return value. Especially if
you're expecting to input a NULL pointer and use the function to
initialise it. Either use a pointer-to-pointer as a parameter so you
can modify the pointer within the function, or ignore it completely
and set its value with the function's return value. Not both.

You're not actually testing for whether the file exists at all. According to the manual pages for fopen (man fopen) neither of the flags you used in opening the file (r+ and w+) care whether the file exists. r+ opens for reading/writing and always positions the stream at the beginning of the file. w+ opens for reading/writing, truncating the file if it exists already. This explains why you didn't get the effect you intended.


问:
Hackerearth policeman and theives problem
I am trying to solve the Policeman and Theives problem in Hackeearth website. I am able to reduce the time complexity but three test cases are failing. There seems to be a bug in the solution which causes a small mismatch. I am struggling to find the error for weeks. Below are the problem statement and my code,

Policeman and Thieves Problem statement:

You are given a grid of size  that has the following specifications:

Each cell in the grid contains either a policeman or a thief.

A policeman can only catch a thief if both of them are in the same row.

Each policeman can only catch one thief.

A policeman cannot catch a thief who is more than K units away from the policeman.
Write a program to find the maximum number of thieves that can be caught in the grid.

Input format

First line: T (number of test cases)

For each test case,

First-line contains Two space-separated integers N and K

Next N lines contain N space-separated characters (denoting each cell in the grid)

Output format

For each test case, print the maximum number of thieves that can be caught in the grid.

My code:

```<code>import java.io.*;
import java.util.*;

public class TestClass {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter wr = new PrintWriter(System.out);
        int T = Integer.parseInt(br.readLine().trim());
        for(int t_i=0; t_i<T; t_i++)
        {
            String[] line = br.readLine().split(" ");
            int N = Integer.parseInt(line[0]);
            int K = Integer.parseInt(line[1]);
            char[][] A = new char[N][N];
            for(int i_A=0; i_A<N; i_A++)
            {
                String[] arr_A = br.readLine().split(" ");
                for(int j_A=0; j_A<arr_A.length; j_A++)
                {
                    A[i_A][j_A] = arr_A[j_A].charAt(0);
                }
            }

            int out_ = solution(A, K);
            System.out.println(out_);
            System.out.println("");
        }

        wr.close();
        br.close();
    }
    static int solution(char[][] A, int K){
        int count = 0;
        for(int i=0;i<A.length;i++){
            for(int j=0;j<A[i].length;j++){
                if(A[i][j]=='P'){
                    boolean thiefCaptured = false;
                    int x;
                    if(j-K >0){
                        x = j-K;
                    }else {
                        x = 0;
                    }
                    for(;x<j;x++) {
                        if (A[i][x] == 'T') {
                            A[i][x] = 'X';
                            A[i][j] = 'X';
                            count++;
                            thiefCaptured = true;
                            break;
                        }
                    }
                    int y;
                    if(j+K < A[i].length){
                        y = j+K;
                    }else{
                        y = A[i].length - 1;
                    }
                    for(;(y>j) && (thiefCaptured == false);y--){
                        if(A[i][y]=='T'){
                            A[i][y] = 'X';
                            A[i][j] = 'X';
                            count++;
                            break;
                        }
                    }
                }
            }
        }
        return count;
    }
}
</code>```

My Logic
If an element is considered as the center of our search, then I am first looking for the thieves from the farthest left(by k units) and iterating towards the center. If the thief is not found, then I am looking for the thief from the farthest right(by k units) towards the center.

Failing test case input:

```<code>1
18 2
P P T T T P T P P T T P P P T P P T
P P P P T P P T P P T P P P T P T P
P P P T T T T T P P T P T P T T P T
P P P P P P T P P P T T T P T T T P
P P T P P T P P P T T P P T P P P T
P T P P P P P P P P P P T T P T P P
T P T T T P P P P T P T T T T P T P
T T P T P P P P P P P T T T P T P P
P T T T T P T T P T P P P P T T P T
P T P P T T P P P P P T T P T P P P
P T P T T P T P T P T P P P P P P T
P T P P T P T P T P T P T T T P P P
T T P T P P P P P P T T T P T P T P
P T T P P P P P T P T P T P T P P T
P T P T T P T P T P P P P T P T P P
T P P P T P T P P P P P T T P P P P
P P T P P P P P P P P T T T P P T P
T T T P T P T P T P P T P P T P P P
</code>```

Expected Ouput
113

Actual Output
112

Can you guys help me to figure out where I am going wrong? I am actually trying to figure out the solution for weeks but not able to progress. I know there is a different solution out there for the same question. But the thing is I would like to figure out the issue or the hole in my logic. Please help me out.

Link: Policemen and thieves on hackerearth

答:
I got a solution from GeekForGeeks website, which uses a really simple logic, based on the index of police and thief. I thought to myself, it's that simple!!!?? Well, it's how the world works. Anyways here is the optimum solution for the above problem,

```<code>import java.io.*;
import java.util.*;

public class TestClass {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter wr = new PrintWriter(System.out);
        int T = Integer.parseInt(br.readLine().trim());
        for(int t_i=0; t_i<T; t_i++)
        {
            String[] line = br.readLine().split(" ");
            int N = Integer.parseInt(line[0]);
            int K = Integer.parseInt(line[1]);
            char[][] A = new char[N][N];
            for(int i_A=0; i_A<N; i_A++)
            {
                String[] arr_A = br.readLine().split(" ");
                for(int j_A=0; j_A<arr_A.length; j_A++)
                {
                    A[i_A][j_A] = arr_A[j_A].charAt(0);
                }
            }

            int out_ = solution(A, K);
            System.out.println(out_);
            System.out.println("");
        }

        wr.close();
        br.close();
    }
    static int solution(char[][] arr, int K){
        int count = 0;
        for(int i=0;i<arr.length;i++){
                ArrayList<Integer> thi = new ArrayList<>();
                ArrayList<Integer> pol = new ArrayList<>();
                for (int s = 0; s < arr[i].length; s++) {
                    if (arr[i][s] == 'P')
                        pol.add(s);
                    else if (arr[i][s] == 'T')
                        thi.add(s);
                }
                int l = 0, r = 0;
                while (l < thi.size() && r < pol.size()) {
                    if (Math.abs(thi.get(l) - pol.get(r)) <= K) {
                        count++;
                        l++;
                        r++;
                    }
                    else if (thi.get(l) < pol.get(r))
                        l++;
                    else
                        r++;
                }
        }
        return count;
    }
}
</code>```

Link: Policeman and Thieves Geek for Geeks

Body:
I am trying to solve the Policeman and Theives problem in Hackeearth website. I am able to reduce the time complexity but three test cases are failing. There seems to be a bug in the solution which causes a small mismatch. I am struggling to find the error for weeks. Below are the problem statement and my code,

Policeman and Thieves Problem statement:

You are given a grid of size  that has the following specifications:

Each cell in the grid contains either a policeman or a thief.

A policeman can only catch a thief if both of them are in the same row.

Each policeman can only catch one thief.

A policeman cannot catch a thief who is more than K units away from the policeman.
Write a program to find the maximum number of thieves that can be caught in the grid.

Input format

First line: T (number of test cases)

For each test case,

First-line contains Two space-separated integers N and K

Next N lines contain N space-separated characters (denoting each cell in the grid)

Output format

For each test case, print the maximum number of thieves that can be caught in the grid.

My code:

import java.io.*;
import java.util.*;

public class TestClass {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter wr = new PrintWriter(System.out);
        int T = Integer.parseInt(br.readLine().trim());
        for(int t_i=0; t_i<T; t_i++)
        {
            String[] line = br.readLine().split(" ");
            int N = Integer.parseInt(line[0]);
            int K = Integer.parseInt(line[1]);
            char[][] A = new char[N][N];
            for(int i_A=0; i_A<N; i_A++)
            {
                String[] arr_A = br.readLine().split(" ");
                for(int j_A=0; j_A<arr_A.length; j_A++)
                {
                    A[i_A][j_A] = arr_A[j_A].charAt(0);
                }
            }

            int out_ = solution(A, K);
            System.out.println(out_);
            System.out.println("");
        }

        wr.close();
        br.close();
    }
    static int solution(char[][] A, int K){
        int count = 0;
        for(int i=0;i<A.length;i++){
            for(int j=0;j0){
                        x = j-K;
                    }else {
                        x = 0;
                    }
                    for(;x<j;x++) {
                        if (A[i][x] == 'T') {
                            A[i][x] = 'X';
                            A[i][j] = 'X';
                            count++;
                            thiefCaptured = true;
                            break;
                        }
                    }
                    int y;
                    if(j+K j) && (thiefCaptured == false);y--){
                        if(A[i][y]=='T'){
                            A[i][y] = 'X';
                            A[i][j] = 'X';
                            count++;
                            break;
                        }
                    }
                }
            }
        }
        return count;
    }
}

My Logic
If an element is considered as the center of our search, then I am first looking for the thieves from the farthest left(by k units) and iterating towards the center. If the thief is not found, then I am looking for the thief from the farthest right(by k units) towards the center.

Failing test case input:

1
18 2
P P T T T P T P P T T P P P T P P T
P P P P T P P T P P T P P P T P T P
P P P T T T T T P P T P T P T T P T
P P P P P P T P P P T T T P T T T P
P P T P P T P P P T T P P T P P P T
P T P P P P P P P P P P T T P T P P
T P T T T P P P P T P T T T T P T P
T T P T P P P P P P P T T T P T P P
P T T T T P T T P T P P P P T T P T
P T P P T T P P P P P T T P T P P P
P T P T T P T P T P T P P P P P P T
P T P P T P T P T P T P T T T P P P
T T P T P P P P P P T T T P T P T P
P T T P P P P P T P T P T P T P P T
P T P T T P T P T P P P P T P T P P
T P P P T P T P P P P P T T P P P P
P P T P P P P P P P P T T T P P T P
T T T P T P T P T P P T P P T P P P

Expected Ouput
113

Actual Output
112

Can you guys help me to figure out where I am going wrong? I am actually trying to figure out the solution for weeks but not able to progress. I know there is a different solution out there for the same question. But the thing is I would like to figure out the issue or the hole in my logic. Please help me out.

Link: Policemen and thieves on hackerearth

Body:
I got a solution from GeekForGeeks website, which uses a really simple logic, based on the index of police and thief. I thought to myself, it's that simple!!!?? Well, it's how the world works. Anyways here is the optimum solution for the above problem,

import java.io.*;
import java.util.*;

public class TestClass {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter wr = new PrintWriter(System.out);
        int T = Integer.parseInt(br.readLine().trim());
        for(int t_i=0; t_i<T; t_i++)
        {
            String[] line = br.readLine().split(" ");
            int N = Integer.parseInt(line[0]);
            int K = Integer.parseInt(line[1]);
            char[][] A = new char[N][N];
            for(int i_A=0; i_A<N; i_A++)
            {
                String[] arr_A = br.readLine().split(" ");
                for(int j_A=0; j_A<arr_A.length; j_A++)
                {
                    A[i_A][j_A] = arr_A[j_A].charAt(0);
                }
            }

            int out_ = solution(A, K);
            System.out.println(out_);
            System.out.println("");
        }

        wr.close();
        br.close();
    }
    static int solution(char[][] arr, int K){
        int count = 0;
        for(int i=0;i<arr.length;i++){
                ArrayList<Integer> thi = new ArrayList<>();
                ArrayList<Integer> pol = new ArrayList<>();
                for (int s = 0; s < arr[i].length; s++) {
                    if (arr[i][s] == 'P')
                        pol.add(s);
                    else if (arr[i][s] == 'T')
                        thi.add(s);
                }
                int l = 0, r = 0;
                while (l < thi.size() && r < pol.size()) {
                    if (Math.abs(thi.get(l) - pol.get(r)) <= K) {
                        count++;
                        l++;
                        r++;
                    }
                    else if (thi.get(l) < pol.get(r))
                        l++;
                    else
                        r++;
                }
        }
        return count;
    }
}

Link: Policeman and Thieves Geek for Geeks


问:
flask-socketio on uWSGI
I have this flask-socketio app

```<code>(venv) ubuntu@ip-172-31-18-21:~/code$ more app.py
from flask_socketio import SocketIO, send, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from time import sleep
from threading import Thread, Event

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'

socketio = SocketIO(app, async_mode='gevent')

thread = Thread()
thread_stop_event = Event()

def firstFunction():
    print("*** First function")

def backgroundTask():
    while not thread_stop_event.isSet():
        socketio.emit('bg-socketio', {'data':'background-data'}, namespace='/', broadcast=True)
        socketio.sleep(2)

def startBackgroundTask():
    global thread

    if not thread.is_alive():
        thread = socketio.start_background_task(backgroundTask)

@app.route('/')
def main():
    return render_template('index.html', title='SocketIO')

@socketio.on('connect_event', namespace='/')
def handle_message_client_connected(message):
    print("*** Client connected")
    emit('c-socketio', {'data':' you connected!'}, namespace='/')

if __name__ == '__main__':
    firstFunction()
    startBackgroundTask()
    socketio.run(app, host='0.0.0.0', port=5000)
</code>```

I want firstFunction() and startBackgroundTask() to run whenever the app starts.

What is the best practice for running this on uWSGI?
I've been trying to do this without any success, keep getting errors
https://flask-socketio.readthedocs.io/en/latest/#uwsgi-web-server

Error:
* running gevent loop engine [addr:0x5561d3f745a0] *
DAMN ! worker 1 (pid: 13772) died :( trying respawn ...
worker respawning too fast !!! i have to sleep a bit (2 seconds)...
Respawned uWSGI worker 1 (new pid: 13773)

Also tried this

```<code>uwsgi --socket 0.0.0.0:5000 --protocol=http --enable-threads -w wsgi:app

(venv) ubuntu@ip-172-31-18-21:~/code$ more wsgi.py
from uapp import app

if __name__ == "__main__":
    app.run()
</code>```

with uapp.py changed to

```<code>if __name__ == '__main__':
    firstFunction()
    startBackgroundTask()
    app.run(host='0.0.0.0', port=5000)
</code>```

but this does not run firstFunction() or startBackgroundTask()

I'm pretty much stuck, looking for some suggestions.

答:
The simple answer to your question is to change this:

if __name__ == '__main__':
    firstFunction()
    startBackgroundTask()
    app.run(host='0.0.0.0', port=5000)
```

<p>to this:</p>

<pre class="lang-py prettyprint-override"><code>firstFunction()
startBackgroundTask()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
</code>```

You have a couple other issues that you need to address, though.

The async_mode variable is set to gevent, but you are using uWSGI as a server. Either change it to gevent_uwsgi or remove it, so that it is automatically set at runtime for you.

The command to start a Flask-SocketIO app with uWSGI is shown in the documentation:

```<code>uwsgi --http :5000 --gevent 1000 --http-websockets --master --wsgi-file app.py --callable app
</code>```

You need to also have gevent installed.

Title: flask-socketio on uWSGI

Body:
I have this flask-socketio app

(venv) ubuntu@ip-172-31-18-21:~/code$ more app.py
from flask_socketio import SocketIO, send, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from time import sleep
from threading import Thread, Event

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'

socketio = SocketIO(app, async_mode='gevent')

thread = Thread()
thread_stop_event = Event()

def firstFunction():
    print("*** First function")

def backgroundTask():
    while not thread_stop_event.isSet():
        socketio.emit('bg-socketio', {'data':'background-data'}, namespace='/', broadcast=True)
        socketio.sleep(2)

def startBackgroundTask():
    global thread

    if not thread.is_alive():
        thread = socketio.start_background_task(backgroundTask)

@app.route('/')
def main():
    return render_template('index.html', title='SocketIO')

@socketio.on('connect_event', namespace='/')
def handle_message_client_connected(message):
    print("*** Client connected")
    emit('c-socketio', {'data':' you connected!'}, namespace='/')

if __name__ == '__main__':
    firstFunction()
    startBackgroundTask()
    socketio.run(app, host='0.0.0.0', port=5000)

I want firstFunction() and startBackgroundTask() to run whenever the app starts.

What is the best practice for running this on uWSGI?
I've been trying to do this without any success, keep getting errors
https://flask-socketio.readthedocs.io/en/latest/#uwsgi-web-server

Error:
* running gevent loop engine [addr:0x5561d3f745a0] *
DAMN ! worker 1 (pid: 13772) died :( trying respawn ...
worker respawning too fast !!! i have to sleep a bit (2 seconds)...
Respawned uWSGI worker 1 (new pid: 13773)

Also tried this

uwsgi --socket 0.0.0.0:5000 --protocol=http --enable-threads -w wsgi:app

(venv) ubuntu@ip-172-31-18-21:~/code$ more wsgi.py
from uapp import app

if __name__ == "__main__":
    app.run()

with uapp.py changed to

if __name__ == '__main__':
    firstFunction()
    startBackgroundTask()
    app.run(host='0.0.0.0', port=5000)

but this does not run firstFunction() or startBackgroundTask()

I'm pretty much stuck, looking for some suggestions.

Body:
The simple answer to your question is to change this:

if __name__ == '__main__':
    firstFunction()
    startBackgroundTask()
    app.run(host='0.0.0.0', port=5000)

to this:

firstFunction()
startBackgroundTask()

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

You have a couple other issues that you need to address, though.

The async_mode variable is set to gevent, but you are using uWSGI as a server. Either change it to gevent_uwsgi or remove it, so that it is automatically set at runtime for you.

The command to start a Flask-SocketIO app with uWSGI is shown in the documentation:

uwsgi --http :5000 --gevent 1000 --http-websockets --master --wsgi-file app.py --callable app

You need to also have gevent installed.


问:
Spark SQL - Generate array of arrays from the sql function
I want to create an array of arrays. This is my data table:

```<code>// A case class for our sample table
case class Testing(name: String, age: Int, salary: Int)

// Create an RDD with some data
val x = sc.parallelize(Array(
    Testing(null, 21, 905),
    Testing("Noelia", 26, 1130),
    Testing("Pilar", 52,  1890),
    Testing("Roberto", 31, 1450)
 ))

// Convert RDD to a DataFrame
val df = sqlContext.createDataFrame(x)

// For SQL usage we need to register the table
df.registerTempTable("df")
</code>```

I want to create an array of integer column "age". For that I use "collect_list":

```<code>sqlContext.sql("SELECT collect_list(age) as age from df").show
</code>```

But now I want to generate an array containing multiple arrays as created above:

```<code> sqlContext.sql("SELECT collect_list(collect_list(age), collect_list(salary)) as arrayInt from df").show
</code>```

But this does not work , or use the function org.apache.spark.sql.functions.array. Any ideas?

答:
Let's create the DataFrame the way have created above.

```<code>// A case class for our sample table
import org.apache.spark.sql.functions._

case class Testing(name: String, age: Int, salary: Int)

// Create an RDD with some data
val x = sc.parallelize(Array(
    Testing(null, 21, 905),
    Testing("Noelia", 26, 1130),
    Testing("Pilar", 52,  1890),
    Testing("Roberto", 31, 1450)
 ))

// Convert RDD to a DataFrame
val df = spark.createDataFrame(x)
</code>```

Here we can use array_union function to achieve the desired result. array_unionfunction will return the union of all elements from the input arrays. This function is available since spark 2.4.0

// Scala Ref : https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$

// Pyspark Ref : https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.array_union

```<code>df.select(collect_list("age").as("age"), collect_list("salary").as("salary"))
  .withColumn("new_col", array_union($"age", $"salary")).show(truncate=false)
</code>```

// Output

```<code>+----------------+-----------------------+---------------------------------------+
|age             |salary                 |new_col                                |
+----------------+-----------------------+---------------------------------------+
|[21, 26, 52, 31]|[905, 1130, 1890, 1450]|[21, 26, 52, 31, 905, 1130, 1890, 1450]|
+----------------+-----------------------+---------------------------------------+
</code>```

I hope this helps.

Body:
I want to create an array of arrays. This is my data table:

// A case class for our sample table
case class Testing(name: String, age: Int, salary: Int)

// Create an RDD with some data
val x = sc.parallelize(Array(
    Testing(null, 21, 905),
    Testing("Noelia", 26, 1130),
    Testing("Pilar", 52,  1890),
    Testing("Roberto", 31, 1450)
 ))

// Convert RDD to a DataFrame
val df = sqlContext.createDataFrame(x)

// For SQL usage we need to register the table
df.registerTempTable("df")

I want to create an array of integer column "age". For that I use "collect_list":

sqlContext.sql("SELECT collect_list(age) as age from df").show

But now I want to generate an array containing multiple arrays as created above:

 sqlContext.sql("SELECT collect_list(collect_list(age), collect_list(salary)) as arrayInt from df").show

But this does not work , or use the function org.apache.spark.sql.functions.array. Any ideas?

Body:
Let's create the DataFrame the way have created above.

// A case class for our sample table
import org.apache.spark.sql.functions._

case class Testing(name: String, age: Int, salary: Int)

// Create an RDD with some data
val x = sc.parallelize(Array(
    Testing(null, 21, 905),
    Testing("Noelia", 26, 1130),
    Testing("Pilar", 52,  1890),
    Testing("Roberto", 31, 1450)
 ))

// Convert RDD to a DataFrame
val df = spark.createDataFrame(x)

Here we can use array_union function to achieve the desired result. array_unionfunction will return the union of all elements from the input arrays. This function is available since spark 2.4.0

// Scala Ref : https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.functions$

// Pyspark Ref : https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.functions.array_union

df.select(collect_list("age").as("age"), collect_list("salary").as("salary"))
  .withColumn("new_col", array_union($"age", $"salary")).show(truncate=false)

// Output

+----------------+-----------------------+---------------------------------------+
|age             |salary                 |new_col                                |
+----------------+-----------------------+---------------------------------------+
|[21, 26, 52, 31]|[905, 1130, 1890, 1450]|[21, 26, 52, 31, 905, 1130, 1890, 1450]|
+----------------+-----------------------+---------------------------------------+

I hope this helps.


问:
Azure Functions Proxy 404 on localhost
I have an Azure Function App with a function at the URL http://localhost:7072/api/create-room along with other functions. This particular function is a HTTPTrigger with allowed anonymous access and accepts the GET verb:

[HttpTrigger(AuthorizationLevel.Anonymous, "get")]
```

<p>Along with that, I have a separate function app that hosts only a <code>proxies.json</code> file and serves only as a functions proxy. My proxies function is running on port <code>7071</code> locally.</p>

<p>My proxies file currently looks like this:</p>

```{
    "$schema": "http://json.schemastore.org/proxies",
    "proxies": {
      "chatNegotiate": {
        "matchCondition": {
          "route": "/api/chat/negotiate",
          "methods": [
            "POST"
          ]
        },
        "backendUri": "%chat_api%/api/BeginNegotiate"
      },
      "chatMessages": {
        "matchCondition": {
          "route": "/api/chat/messages",
          "methods": [
            "POST"
          ]
        },
        "backendUri": "%chat_api%/api/PostMessage"
      },
      "createRoom": {
        "matchCondition": {
          "route": "/api/create-room",
          "methods": [
            "GET"
          ]
        },
        "backendUri": "%session_api%/api/CreateRoom"
      }
    }
}
```

<p>When both of these function apps are deployed to Azure, everything works like a dream. I can make requests, they're forwarded on, requests come back. It's all glorious.</p>

<p>However, when I run these functions locally, the request is never forwarded on from the proxy, with the proxy returning a 404. I can hit the function on the other function app running locally on <code>7072</code> directly and all is well there, but not at all when I got via the proxy.</p>

<p>The proxy itself returns:</p>

```[30/05/2020 18:24:30] Host lock lease acquired by instance ID '0000000000000000000000002D5B6BEA'.
[30/05/2020 18:24:34] Executing HTTP request: {
[30/05/2020 18:24:34]   "requestId": "9004b8e2-f208-4a98-8b48-6f85bca41281",
[30/05/2020 18:24:34]   "method": "GET",
[30/05/2020 18:24:34]   "uri": "/api/create-room"
[30/05/2020 18:24:34] }
[30/05/2020 18:24:34] Executed HTTP request: {
[30/05/2020 18:24:34]   "requestId": "9004b8e2-f208-4a98-8b48-6f85bca41281",
[30/05/2020 18:24:34]   "method": "GET",
[30/05/2020 18:24:34]   "uri": "/api/create-room",
[30/05/2020 18:24:34]   "identities": [],
[30/05/2020 18:24:34]   "status": 404,
[30/05/2020 18:24:34]   "duration": 15
[30/05/2020 18:24:34] }
```

From examples I've looked at such as https://chsakell.com/2019/02/03/azure-functions-proxies-in-action/, this should be working fine.

Any suggestions? Thanks in advance for any help you can provide!

答:
I've solved this after all.

proxies.json isn't set to copy to the output directory by default.

You need to ensure that it's set to copy always.

In Visual Studio:

Right click proxies.json > click properties > Set Copy to output directory to Copy Always.

In Visual Studio Code (and other editors):
Open ProjectName.csproj and add an entry to always copy proxies.json to output directory.

```<code><ItemGroup>
  <None Update="proxies.json">
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
  </None>
</ItemGroup>
</code>```

Title: Azure Functions Proxy 404 on localhost

Body:
I have an Azure Function App with a function at the URL http://localhost:7072/api/create-room along with other functions. This particular function is a HTTPTrigger with allowed anonymous access and accepts the GET verb:

[HttpTrigger(AuthorizationLevel.Anonymous, "get")]

Along with that, I have a separate function app that hosts only a proxies.json file and serves only as a functions proxy. My proxies function is running on port 7071 locally.

My proxies file currently looks like this:

{
    "$schema": "http://json.schemastore.org/proxies",
    "proxies": {
      "chatNegotiate": {
        "matchCondition": {
          "route": "/api/chat/negotiate",
          "methods": [
            "POST"
          ]
        },
        "backendUri": "%chat_api%/api/BeginNegotiate"
      },
      "chatMessages": {
        "matchCondition": {
          "route": "/api/chat/messages",
          "methods": [
            "POST"
          ]
        },
        "backendUri": "%chat_api%/api/PostMessage"
      },
      "createRoom": {
        "matchCondition": {
          "route": "/api/create-room",
          "methods": [
            "GET"
          ]
        },
        "backendUri": "%session_api%/api/CreateRoom"
      }
    }
}

When both of these function apps are deployed to Azure, everything works like a dream. I can make requests, they're forwarded on, requests come back. It's all glorious.

However, when I run these functions locally, the request is never forwarded on from the proxy, with the proxy returning a 404. I can hit the function on the other function app running locally on 7072 directly and all is well there, but not at all when I got via the proxy.

The proxy itself returns:

[30/05/2020 18:24:30] Host lock lease acquired by instance ID '0000000000000000000000002D5B6BEA'.
[30/05/2020 18:24:34] Executing HTTP request: {
[30/05/2020 18:24:34]   "requestId": "9004b8e2-f208-4a98-8b48-6f85bca41281",
[30/05/2020 18:24:34]   "method": "GET",
[30/05/2020 18:24:34]   "uri": "/api/create-room"
[30/05/2020 18:24:34] }
[30/05/2020 18:24:34] Executed HTTP request: {
[30/05/2020 18:24:34]   "requestId": "9004b8e2-f208-4a98-8b48-6f85bca41281",
[30/05/2020 18:24:34]   "method": "GET",
[30/05/2020 18:24:34]   "uri": "/api/create-room",
[30/05/2020 18:24:34]   "identities": [],
[30/05/2020 18:24:34]   "status": 404,
[30/05/2020 18:24:34]   "duration": 15
[30/05/2020 18:24:34] }

From examples I've looked at such as https://chsakell.com/2019/02/03/azure-functions-proxies-in-action/, this should be working fine.

Any suggestions? Thanks in advance for any help you can provide!

Body:
I've solved this after all.

proxies.json isn't set to copy to the output directory by default.

You need to ensure that it's set to copy always.

In Visual Studio:

Right click proxies.json > click properties > Set Copy to output directory to Copy Always.

In Visual Studio Code (and other editors):
Open ProjectName.csproj and add an entry to always copy proxies.json to output directory.

<ItemGroup>
  <None Update="proxies.json">
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
  </None>
</ItemGroup>


问:
Spring Webflux Non-Blocking Dependent Resource Calls
I am using Spring Webflux and Spring Data MongoDB Reactive.
In my REST Controller I am trying to get all objects of a kind (e.g. all bikes of a brand) from the database (MongoDB).
My current implementation looks like this:

```<code>@GetMapping("/bybrand/{brandId}")
public Flux<Bike> bikesByBrand(@PathVariable(value = "brandId") String brandId) {
    return bikeRepository.findByBrand( //returns a Flux<Bike>
            brandRepository.findById(brandId) //returns a Mono<Brand>
                    .block() //returns a Brand
    );
}
</code>```

To stay in the reactive pattern I want to avoid the block() call. I tried diverse combinations of map() and doOnSuccess() but didn't find the right way to do what I want to do.
Examples or tutorials I found online did not cover the use case of using dependent calls to the database.
How can I avoid using block() here and what would be the gold standard for accessing the database with a dependent previous call?

Another approach of mine would be the following.

```<code>brandRepository.findById(brandId)
            .doOnSuccess(brand -> bikeRepository.findByBrand(brand));
</code>```

But I can't find a way to finally return the result of the lambda function (the Flux of Bike) in the superior method.

答:
You can use flatMapMany</p>

```<code>return brandRepository.findById(brandId).flatMapMany(bikeRepository::findByBrand)
</code>```

Body:
I am using Spring Webflux and Spring Data MongoDB Reactive.
In my REST Controller I am trying to get all objects of a kind (e.g. all bikes of a brand) from the database (MongoDB).
My current implementation looks like this:

@GetMapping("/bybrand/{brandId}")
public Flux<Bike> bikesByBrand(@PathVariable(value = "brandId") String brandId) {
    return bikeRepository.findByBrand( //returns a Flux<Bike>
            brandRepository.findById(brandId) //returns a Mono<Brand>
                    .block() //returns a Brand
    );
}

To stay in the reactive pattern I want to avoid the block() call. I tried diverse combinations of map() and doOnSuccess() but didn't find the right way to do what I want to do.
Examples or tutorials I found online did not cover the use case of using dependent calls to the database.
How can I avoid using block() here and what would be the gold standard for accessing the database with a dependent previous call?

Another approach of mine would be the following.

brandRepository.findById(brandId)
            .doOnSuccess(brand -> bikeRepository.findByBrand(brand));

But I can't find a way to finally return the result of the lambda function (the Flux of Bike) in the superior method.

Body:
You can use flatMapMany

return brandRepository.findById(brandId).flatMapMany(bikeRepository::findByBrand)


问:
SQL select students logins
I have a table STUDENT_LAST_LOGIN, which contains data about students last logins.

```<code>ID  STUDENT_ID   DATE               TIME
1    A          2020-02-01 12:00    15 MIN
2    B          2020-02-02 12:00    45 MIN
3    C          2020-02-03 12:00    25 MIN
</code>```

In addition there is STUDENT_LOGIN table, which contains data about students all logins.

```<code>ID  STUDENT_ID   DATE               TIME
1    A          2020-02-01 12:00    15 MIN
4    A          2020-01-01 14:00    33 MIN
2    B          2020-02-02 12:00    45 MIN
5    B          2020-01-02 13:30    47 MIN
10   B          2020-01-03 13:30    27 MIN
6    B          2020-01-02 10:00    44 MIN
3    C          2020-02-03 12:00    25 MIN
7    C          2020-01-03 10:00    12 MIN
8    C          2020-01-03 18:00    56 MIN
9    C          2020-01-04 12:00    88 MIN
</code>```

As a result I need to get something like this:

```<code>STUDENT_ID    LAST_LOGIN         LAST_LOGIN_ONE_MONTH_AGO    TIME     TIME_ONE_MONTH_AGO
A            2020-02-01 12:00    2020-01-01 14:00            15 min   33 min
B            2020-02-02 12:00    2020-01-02 13:30            15 min   47 min
C            2020-02-03 12:00    2020-01-03 18:00            25 min   56 min
</code>```

Can you help me write this?

答:
You need to use the windows function as follows:</p>

```<code>SELECT * FROM
(SELECT SLL.STUDENT_ID,
        SLL.DATE LAST_LOGIN,
        SL.DATE LAST_LOGIN_ONE_MONTHE_AGO,
        SLL.TIME,
        SL.TIME TIME_ONE_MONTH_AGO,
        ROW_NUMBER() OVER (PARTITION BY SLL.STUDENT_ID ORDER BY SL.DATE DESC NULLS LAST) AS RN
   FROM STUDENT_LAST_LOGIN SLL LEFT JOIN STUDENT_LOGIN SL
     ON SL.STUDENT_ID = SLL.STUDENT_ID
    AND TRUNC(SL.DATE) = ADD_MONTHS(TRUNC(SLL.DATE),-1)
)
WHERE RN = 1
</code>```

Title: SQL select students logins

Body:
I have a table STUDENT_LAST_LOGIN, which contains data about students last logins.

ID  STUDENT_ID   DATE               TIME
1    A          2020-02-01 12:00    15 MIN
2    B          2020-02-02 12:00    45 MIN
3    C          2020-02-03 12:00    25 MIN

In addition there is STUDENT_LOGIN table, which contains data about students all logins.

ID  STUDENT_ID   DATE               TIME
1    A          2020-02-01 12:00    15 MIN
4    A          2020-01-01 14:00    33 MIN
2    B          2020-02-02 12:00    45 MIN
5    B          2020-01-02 13:30    47 MIN
10   B          2020-01-03 13:30    27 MIN
6    B          2020-01-02 10:00    44 MIN
3    C          2020-02-03 12:00    25 MIN
7    C          2020-01-03 10:00    12 MIN
8    C          2020-01-03 18:00    56 MIN
9    C          2020-01-04 12:00    88 MIN

As a result I need to get something like this:

STUDENT_ID    LAST_LOGIN         LAST_LOGIN_ONE_MONTH_AGO    TIME     TIME_ONE_MONTH_AGO
A            2020-02-01 12:00    2020-01-01 14:00            15 min   33 min
B            2020-02-02 12:00    2020-01-02 13:30            15 min   47 min
C            2020-02-03 12:00    2020-01-03 18:00            25 min   56 min

Can you help me write this?

Body:
You need to use the windows function as follows:

SELECT * FROM
(SELECT SLL.STUDENT_ID,
        SLL.DATE LAST_LOGIN,
        SL.DATE LAST_LOGIN_ONE_MONTHE_AGO,
        SLL.TIME,
        SL.TIME TIME_ONE_MONTH_AGO,
        ROW_NUMBER() OVER (PARTITION BY SLL.STUDENT_ID ORDER BY SL.DATE DESC NULLS LAST) AS RN
   FROM STUDENT_LAST_LOGIN SLL LEFT JOIN STUDENT_LOGIN SL
     ON SL.STUDENT_ID = SLL.STUDENT_ID
    AND TRUNC(SL.DATE) = ADD_MONTHS(TRUNC(SLL.DATE),-1)
)
WHERE RN = 1


问:
TypeError: undefined is not an object (evaluating 'events[genre][0]')
I'm trying to create a custom array but the for loop cannot evaluate events[genre][0].name as events has not been set yet due to the async nature of firebase. Is there any way to only execute the for loop once the data has been set or any workaround for this?</p>

```<code>const Finalized = (props) => {
  const [events, setEvents] = React.useState([]);
  const testEvents = ["arts", "leisure", "sports"];

  React.useEffect(() => {
    firebase
      .database()
      .ref("events")
      .once("value")
      .then((snapshot) => {
        setEvents(snapshot.val());
      });
  });

  let dataJson = {};
  for (i = 0; i < testEvents.length; i++) {
    let genre = testEvents[i];
    dataJson.time = "09:00";
    dataJson.title = "Event" + i;
    dataJson.description = <Text>{events[genre][0].name} </Text>;  //cannot be evaluated as undefined
  }
  console.log(dataJson);
</code>```

答:
You need to wait for events to be fulfilled, you can achieve this that way :

const Finalized = (props) => {
  const [events, setEvents] = React.useState([]);
  const testEvents = ["arts", "leisure", "sports"];

  React.useEffect(() => {
    firebase
      .database()
      .ref("events")
      .once("value")
      .then((snapshot) => {
        setEvents(snapshot.val());
      });

    if (events.length) {
      // use you loop here
    }
  }, events.length);

  ...
}
```

Body:
I'm trying to create a custom array but the for loop cannot evaluate events[genre][0].name as events has not been set yet due to the async nature of firebase. Is there any way to only execute the for loop once the data has been set or any workaround for this?

const Finalized = (props) => {
  const [events, setEvents] = React.useState([]);
  const testEvents = ["arts", "leisure", "sports"];

  React.useEffect(() => {
    firebase
      .database()
      .ref("events")
      .once("value")
      .then((snapshot) => {
        setEvents(snapshot.val());
      });
  });

  let dataJson = {};
  for (i = 0; i < testEvents.length; i++) {
    let genre = testEvents[i];
    dataJson.time = "09:00";
    dataJson.title = "Event" + i;
    dataJson.description = <Text>{events[genre][0].name} </Text>;  //cannot be evaluated as undefined
  }
  console.log(dataJson);


问:
Continue statement in Pl/sql
I am working Oracle 10g. I am running this pl/sql  block

```<code>Declare
cursor Get_Data is select * from employee for update;
data Get_Data%rowtype;

Begin

for data in Get_Data loop
  if(data.salary=5000) then
  continue;
  else
   update employee set salary= salary+3000 where current of Get_Data;
  end if;
end loop;
end;
</code>```

It is giving me this Error  : identifier 'CONTINUE' must be declared

please suggest me how to resolve this problem.

答:
Just a note: CONTINUE is supported only in Oracle 11g.

Refer here:
Oracle® Database PL/SQL Language Reference 11g Release 1 (11.1) > What's New in PL/SQL? > CONTINUE Statement

Title: Continue statement in Pl/sql

Body:
I am working Oracle 10g. I am running this pl/sql  block

Declare
cursor Get_Data is select * from employee for update;
data Get_Data%rowtype;

Begin

for data in Get_Data loop
  if(data.salary=5000) then
  continue;
  else
   update employee set salary= salary+3000 where current of Get_Data;
  end if;
end loop;
end;

It is giving me this Error  : identifier 'CONTINUE' must be declared

please suggest me how to resolve this problem.


答:
You can utilize an external variable stopCounting to flag if the counting should continue or not.

let arr = [10, 20, 3, 0, 16, 35, 1];
let stopCounting = false;

let sumNum = arr.reduce((sum, elem) => {

  if (elem == 0) {
    stopCounting = true;
  }

  return stopCounting ? sum : sum + elem;
}, 0);

console.log(sumNum);```

Title: Find the sum of the first n num

Body:
I have an array with numbers. Find the sum of the first N elements to the first zero. Task must be completed with
Example: - summarize the first 3 elements, because next is the element with the number 0.


问:
how to unit test a function that returns livedata
In my viewModel, I have a function that returns liveData. This function is directly called in the fragment and hence it is observed directly there. I am not able to get how can I test this function since liveData emitted by the function is not getting observed in case of tests and hence it will not return the value.

This is my function, I want to write test for:

```<code>    fun saveRating(rating: Float, eventName: String): LiveData<Response<SaveRatingData?>?> {
        val request = RatingRequest(rating.toDouble(), eventName, false)

        return liveData(viewModelScope.coroutineContext + Dispatchers.IO) {
            emit(repository.saveRatings(request))
        }

    }
</code>```

and this is how I am calling it in a fragment:

```<code>   viewModel.saveRating(rating, npsEventData?.eventName ?: "").observe(this, Observer {
      // on getting data
   })
</code>```

Thanks in advance!

答:
You need to have a testCoroutineDispatcher or testCoroutineScope to be able to set scope of your viewModel to scope of testing.

```<code>class TestCoroutineRule : TestRule {

    private val testCoroutineDispatcher = TestCoroutineDispatcher()

    val testCoroutineScope = TestCoroutineScope(testCoroutineDispatcher)

    override fun apply(base: Statement, description: Description?) = object : Statement() {

        @Throws(Throwable::class)
        override fun evaluate() {

            Dispatchers.setMain(testCoroutineDispatcher)

            base.evaluate()

            Dispatchers.resetMain()
            try {
                testCoroutineScope.cleanupTestCoroutines()
            } catch (exception: Exception) {
                exception.printStackTrace()
            }
        }
    }

    fun runBlockingTest(block: suspend TestCoroutineScope.() -> Unit) =
        testCoroutineScope.runBlockingTest { block() }

}
</code>```

Try-catch block is not mentioned in any official kotlin or Android documents but testing exceptions cause exceptions instead of passing the test as i asked in this here.

And another thing i experienced with testCoroutineDispatcher as dispatcher is not enough for some test to pass, you need to inject coroutineScope instead of dispatcher to viewModel.

For instance

```<code>fun throwExceptionInAScope(coroutineContext: CoroutineContext) {

    viewModelScope.launch(coroutineContext) {

        delay(2000)
        throw RuntimeException("Exception Occurred")
    }
}
</code>```

You have a function like this that throws exception and you pass testCoroutineContext to this test it fails.

```<code>@Test(expected = RuntimeException::class)
fun `Test function that throws exception`() =
    testCoroutineDispatcher.runBlockingTest {

        //  Using testCoroutineDispatcher causes this test to FAIL
        viewModel.throwExceptionInAScope(testCoroutineDispatcher.coroutineContext)

        //  This one passes since we use context of current coroutineScope
        viewModel.throwExceptionInAScope(this.coroutineContext)

    }
</code>```

It passes if you use class MyViewModel(private val coroutineScope: CoroutineScope)

Now, let's get to how to test liveData with asynchronous tasks. I use this class, Google's LiveDataTestUtil class, for synching liveData and

```<code>@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
</code>```

as rule

```<code>fun <T> LiveData<T>.getOrAwaitValue(
    time: Long = 2,
    timeUnit: TimeUnit = TimeUnit.SECONDS,
    afterObserve: () -> Unit = {}
): T {
    var data: T? = null
    val latch = CountDownLatch(1)
    val observer = object : Observer<T> {
        override fun onChanged(o: T?) {
            data = o
            latch.countDown()
            this@getOrAwaitValue.removeObserver(this)
        }
    }
    this.observeForever(observer)

    afterObserve.invoke()

    // Don't wait indefinitely if the LiveData is not set.
    if (!latch.await(time, timeUnit)) {
        this.removeObserver(observer)
        throw TimeoutException("LiveData value was never set.")
    }

    @Suppress("UNCHECKED_CAST")
    return data as T
}

/**
 * Observes a [LiveData] until the `block` is done executing.
 */
fun <T> LiveData<T>.observeForTesting(block: () -> Unit) {
    val observer = Observer<T> { }
    try {
        observeForever(observer)
        block()
    } finally {
        removeObserver(observer)
    }
}
</code>```

Now, you can test it same as you test synchronous code

```<code>@Test
fun `Given repo saves response, it should return the correct one` = testCoroutineScope.runBlockingTest {

        // GIVEN
        val repository = mockk<<Repository>()
        val actual = Response(...)
        coEvery { repository.saveRatings } returns actual

        // WHEN
        val expected = viewModel.saveResponse()

        // THEN
        Truth.assertThat(actual).isEqualTo(expected)

    }
</code>```

I used mockK, which works well with suspending mocking.

Also you don't need to use Dispatchers.IO if you have retrofit or Room function calls, they use their own thread with suspend modifier if you are not doing other task than retrofit or room actions.

Body:
In my viewModel, I have a function that returns liveData. This function is directly called in the fragment and hence it is observed directly there. I am not able to get how can I test this function since liveData emitted by the function is not getting observed in case of tests and hence it will not return the value.

This is my function, I want to write test for:

    fun saveRating(rating: Float, eventName: String): LiveData<Response<SaveRatingData?>?> {
        val request = RatingRequest(rating.toDouble(), eventName, false)

        return liveData(viewModelScope.coroutineContext + Dispatchers.IO) {
            emit(repository.saveRatings(request))
        }

    }

and this is how I am calling it in a fragment:

   viewModel.saveRating(rating, npsEventData?.eventName ?: "").observe(this, Observer {
      // on getting data
   })

Thanks in advance!

Body:
You need to have a testCoroutineDispatcher or testCoroutineScope to be able to set scope of your viewModel to scope of testing.

class TestCoroutineRule : TestRule {

    private val testCoroutineDispatcher = TestCoroutineDispatcher()

    val testCoroutineScope = TestCoroutineScope(testCoroutineDispatcher)

    override fun apply(base: Statement, description: Description?) = object : Statement() {

        @Throws(Throwable::class)
        override fun evaluate() {

            Dispatchers.setMain(testCoroutineDispatcher)

            base.evaluate()

            Dispatchers.resetMain()
            try {
                testCoroutineScope.cleanupTestCoroutines()
            } catch (exception: Exception) {
                exception.printStackTrace()
            }
        }
    }

    fun runBlockingTest(block: suspend TestCoroutineScope.() -> Unit) =
        testCoroutineScope.runBlockingTest { block() }

}

Try-catch block is not mentioned in any official kotlin or Android documents but testing exceptions cause exceptions instead of passing the test as i asked in this here.

And another thing i experienced with testCoroutineDispatcher as dispatcher is not enough for some test to pass, you need to inject coroutineScope instead of dispatcher to viewModel.

For instance

fun throwExceptionInAScope(coroutineContext: CoroutineContext) {

    viewModelScope.launch(coroutineContext) {

        delay(2000)
        throw RuntimeException("Exception Occurred")
    }
}

You have a function like this that throws exception and you pass testCoroutineContext to this test it fails.

@Test(expected = RuntimeException::class)
fun `Test function that throws exception`() =
    testCoroutineDispatcher.runBlockingTest {

        //  Using testCoroutineDispatcher causes this test to FAIL
        viewModel.throwExceptionInAScope(testCoroutineDispatcher.coroutineContext)

        //  This one passes since we use context of current coroutineScope
        viewModel.throwExceptionInAScope(this.coroutineContext)

    }

It passes if you use class MyViewModel(private val coroutineScope: CoroutineScope)

Now, let's get to how to test liveData with asynchronous tasks. I use this class, Google's LiveDataTestUtil class, for synching liveData and

@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()

as rule

fun <T> LiveData<T>.getOrAwaitValue(
    time: Long = 2,
    timeUnit: TimeUnit = TimeUnit.SECONDS,
    afterObserve: () -> Unit = {}
): T {
    var data: T? = null
    val latch = CountDownLatch(1)
    val observer = object : Observer<T> {
        override fun onChanged(o: T?) {
            data = o
            latch.countDown()
            this@getOrAwaitValue.removeObserver(this)
        }
    }
    this.observeForever(observer)

    afterObserve.invoke()

    // Don't wait indefinitely if the LiveData is not set.
    if (!latch.await(time, timeUnit)) {
        this.removeObserver(observer)
        throw TimeoutException("LiveData value was never set.")
    }

    @Suppress("UNCHECKED_CAST")
    return data as T
}

/**
 * Observes a [LiveData] until the `block` is done executing.
 */
fun <T> LiveData<T>.observeForTesting(block: () -> Unit) {
    val observer = Observer<T> { }
    try {
        observeForever(observer)
        block()
    } finally {
        removeObserver(observer)
    }
}

Now, you can test it same as you test synchronous code

@Test
fun `Given repo saves response, it should return the correct one` = testCoroutineScope.runBlockingTest {

        // GIVEN
        val repository = mockk<<Repository>()
        val actual = Response(...)
        coEvery { repository.saveRatings } returns actual

        // WHEN
        val expected = viewModel.saveResponse()

        // THEN
        Truth.assertThat(actual).isEqualTo(expected)

    }

I used mockK, which works well with suspending mocking.

Also you don't need to use Dispatchers.IO if you have retrofit or Room function calls, they use their own thread with suspend modifier if you are not doing other task than retrofit or room actions.


问:
CSS Page-Break Not Working in all Browsers
I'm having trouble getting this working in most browsers, except for IE (it even works correctly in IE6) and Opera.

Firefox separates the divs correctly but only prints the first page.

Chrome and Safari only applies the page break to the last div.

How can I get this working across all browsers correctly?

The HTML:

```<code><div id="leftNav">
  <ul>
    <!--links etc-->
  </ul>
</div>
<div id="mainBody">
 <div id="container">
  <div class="pageBreak">
   <!--content-->
  </div>
  <div class="pageBreak">
   <!--content-->
  </div>
  <div class="pageBreak">
   <!--content-->
  </div>
 </div>
</div>
</code>```

The divs with the IDs #leftNav and #mainBody are are set to float:left, so they display nicely.

I only want to print the .pageBreak classes, hiding the #leftNav and the rest of the #mainBody with CSS.

The CSS:

```<code>@media print
{
 #leftNav
 {
  display:none;
 }
 #mainBody
 {
  border:none;
  margin:none;
  padding:none;
 }
}
</code>```

答: Make sure the parent element has display:block; rather than display: flex;. This helped me fix the issue

Body:
I'm having trouble getting this working in most browsers, except for IE (it even works correctly in IE6) and Opera.

Firefox separates the divs correctly but only prints the first page.

Chrome and Safari only applies the page break to the last div.

How can I get this working across all browsers correctly?

The HTML:

The divs with the IDs #leftNav and #mainBody are are set to float:left, so they display nicely.

I only want to print the .pageBreak classes, hiding the #leftNav and the rest of the #mainBody with CSS.

The CSS:

@media print
{
 #leftNav
 {
  display:none;
 }
 #mainBody
 {
  border:none;
  margin:none;
  padding:none;
 }
}


问:
Java Paths in Windows for Linux environment
I'm developing in Windows and somewhere in the flow I have to access sftp (Linux) server.
I do some logic to prepare filenames I have to copy from the sftp server and I need to generate the full path, therefore I write this line in my code:

```<code>Paths.get(configuration.getSftpServerConfiguration().getRemotePath(), filename).toString();
</code>```

Because I’m running on Windows the paths generated with Windows slash, for example \public\directory\filename.csv

Can I define Paths to work with Linux separator? (I know I can concatenate ‘/’ by myself but looks for me like a bad practice..)

答:
Check this post: Is there a Java utility which will convert a String path to use the correct File separator char?

Basically FilenameUtils.separatorsToSystem(String path), of Apache Commons, will help achieve what you are trying to do.

If you do not want to import the entire dependency this is what the method does:

```<code>String separatorsToSystem(String res) {
    if (res==null) return null;
    if (File.separatorChar=='\\') {
        // From Windows to Linux/Mac
        return res.replace('/', File.separatorChar);
    } else {
        // From Linux/Mac to Windows
        return res.replace('\\', File.separatorChar);
    }
}
</code>```

UPDATE:
As @Slaw said, this solution is still Platform-dependent. You could modify the method to take an extra parameter, and decide if you want the output string in "Unix" or "Windows", something like this:

```<code>String changeFileSeparators(String res, boolean toUnix) {
    if (res==null) return null;
    if (toUnix) {
        // From Windows to Linux/Mac
        return res.replace('\\', '/');
    } else {
        // From Linux/Mac to Windows
        return res.replace('/', '\\');
    }
}
</code>```

Body:
I'm developing in Windows and somewhere in the flow I have to access sftp (Linux) server.
I do some logic to prepare filenames I have to copy from the sftp server and I need to generate the full path, therefore I write this line in my code:

Paths.get(configuration.getSftpServerConfiguration().getRemotePath(), filename).toString();

Because I’m running on Windows the paths generated with Windows slash, for example \public\directory\filename.csv

Can I define Paths to work with Linux separator? (I know I can concatenate ‘/’ by myself but looks for me like a bad practice..)

Body:
Check this post: Is there a Java utility which will convert a String path to use the correct File separator char?

Basically FilenameUtils.separatorsToSystem(String path), of Apache Commons, will help achieve what you are trying to do.

If you do not want to import the entire dependency this is what the method does:

String separatorsToSystem(String res) {
    if (res==null) return null;
    if (File.separatorChar=='\\') {
        // From Windows to Linux/Mac
        return res.replace('/', File.separatorChar);
    } else {
        // From Linux/Mac to Windows
        return res.replace('\\', File.separatorChar);
    }
}

UPDATE:
As @Slaw said, this solution is still Platform-dependent. You could modify the method to take an extra parameter, and decide if you want the output string in "Unix" or "Windows", something like this:

String changeFileSeparators(String res, boolean toUnix) {
    if (res==null) return null;
    if (toUnix) {
        // From Windows to Linux/Mac
        return res.replace('\\', '/');
    } else {
        // From Linux/Mac to Windows
        return res.replace('/', '\\');
    }
}