问:
Why is my Mongodb aggregation pipeline update working in compass, but not working in my node driver

Problem:

I need to only update one document in a nested array of subdocuments. My previous query was updating all matching documents which is no good Example Below. So I decided to use aggregation so that I could add a limit stage so that I could only update one item, but I cannot get the update to happen through node and I am not even getting errors.

Old Query/Update:

This query updates all documents that match the shape of userId: "empty" I need it to only update the first match

           const query = await db.collection('events').updateOne({
                _id: new ObjectId(eventId),
                createdBy: new ObjectId(createdBy),
                "weights.weight": weight
            },
                {
                    $set: {
                        "weights.$.spotsAvailable.$[el2]": {
                            "name": applicantName,
                            "userId": new ObjectId(applicantId)
                        }
                    }
                },
                {
                    arrayFilters: [
                        {
                            "el2.userId": "empty"
                        }
                    ]
                })
```
<p><strong>I have tested the aggregation in the MongoDB compass aggregation builder and it works fine.
But in the actual node code no luck</strong></p>
<hr />
<p>I have tried:</p>
<ol>
<li>Pluging in variables without the <code>new ObjectId</code> syntax</li>
<li>Plugin in variables with the <code>new ObjectId</code> syntax</li>
<li>Using the exact same hardcoded values that I got from copying the aggregation code from compass for the node driver</li>
</ol>
<h2>Example document</h2>
```{
  "_id": {
    "$oid": "6398c34ca67dbe3286452f23"
  },
  "name": "test",
  "createdBy": {
    "$oid": "636c1778f1d09191074f9690"
  },
  "description": "testing",
  "date": {
    "$date": {
      "$numberLong": "1645488000000"
    }
  },
  "location": {
    "type": "Point",
    "coordinates": [
      0,
      0
    ]
  },
  "weights": [
    {
      "spotsAvailable": [
        {
          "name": "empty",
          "userId": "empty"
        },
        {
          "name": "empty",
          "userId": "empty"
        },
        {
          "name": "empty",
          "userId": "empty"
        }
      ],
      "weight": 12
    },
    {
      "spotsAvailable": [
        {
          "name": "empty",
          "userId": "empty"
        },
        {
          "name": "empty",
          "userId": "empty"
        }
      ],
      "weight": 15
    }
  ],
  "eventApplicants": [
    {
      "userId": {
        "$oid": "636c1778f1d09191074f9690"
      },
      "name": "Wayne Wrestler",
      "weight": 15
    }
  ]
}
```
<h2>Code:</h2>
<pre class="lang-js prettyprint-override"><code>const acceptOrRemoveApplicant = async (eventId: ObjectId, createdBy: ObjectId, applicantId: ObjectId, applicantName: string, boolean: boolean, weight: number): Promise<boolean | undefined> => {
    console.log({ eventId, createdBy, applicantId, applicantName, boolean, weight })
    if (boolean == true) {
        try {
            /*
         * Requires the MongoDB Node.js Driver
         * https://mongodb.github.io/node-mongodb-native
         */

            const agg = [
                {
                    '$match': {
                        '_id': new ObjectId('6398c34ca67dbe3286452f23'),
                        'createdBy': new ObjectId('636c1778f1d09191074f9690')
                    }
                }, {
                    '$unwind': {
                        'path': '$weights'
                    }
                }, {
                    '$unwind': {
                        'path': '$weights.spotsAvailable'
                    }
                }, {
                    '$match': {
                        'weights.spotsAvailable.name': 'empty',
                        'weights.weight': 15
                    }
                }, {
                    '$limit': 1
                }, {
                    '$set': {
                        'weights.spotsAvailable.name': 'Wayen',
                        'weights.spotsAvailable.userId': '123456'
                    }
                }
            ]

            const client = await clientPromise;
            const db = client.db();
            const query = db.collection('events').aggregate(agg);

            // const query = await db.collection('events').updateOne({
            //     _id: new ObjectId(eventId),
            //     createdBy: new ObjectId(createdBy),
            //     "weights.weight": weight
            // },
            //     {
            //         $set: {
            //             "weights.$.spotsAvailable.$[el2]": {
            //                 "name": applicantName,
            //                 "userId": new ObjectId(applicantId)
            //             }
            //         }
            //     },
            //     {
            //         arrayFilters: [
            //             {
            //                 "el2.userId": "empty"
            //             }
            //         ]
            //     })

            if (query) {
                console.log("we queried")
                console.log({ query })
                return true
            } else {
                throw new Error("User not added to event")
            }

        } catch (e) {
            console.error(e);
        }
</code>```

Body:
Problem:

I need to only update one document in a nested array of subdocuments. My previous query was updating all matching documents which is no good Example Below. So I decided to use aggregation so that I could add a limit stage so that I could only update one item, but I cannot get the update to happen through node and I am not even getting errors.

Old Query/Update:

This query updates all documents that match the shape of userId: "empty" I need it to only update the first match

           const query = await db.collection('events').updateOne({
                _id: new ObjectId(eventId),
                createdBy: new ObjectId(createdBy),
                "weights.weight": weight
            },
                {
                    $set: {
                        "weights.$.spotsAvailable.$[el2]": {
                            "name": applicantName,
                            "userId": new ObjectId(applicantId)
                        }
                    }
                },
                {
                    arrayFilters: [
                        {
                            "el2.userId": "empty"
                        }
                    ]
                })

I have tested the aggregation in the MongoDB compass aggregation builder and it works fine.
But in the actual node code no luck

I have tried:

Pluging in variables without the new ObjectId syntax

Plugin in variables with the new ObjectId syntax

Using the exact same hardcoded values that I got from copying the aggregation code from compass for the node driver

Example document

{
  "_id": {
    "$oid": "6398c34ca67dbe3286452f23"
  },
  "name": "test",
  "createdBy": {
    "$oid": "636c1778f1d09191074f9690"
  },
  "description": "testing",
  "date": {
    "$date": {
      "$numberLong": "1645488000000"
    }
  },
  "location": {
    "type": "Point",
    "coordinates": [
      0,
      0
    ]
  },
  "weights": [
    {
      "spotsAvailable": [
        {
          "name": "empty",
          "userId": "empty"
        },
        {
          "name": "empty",
          "userId": "empty"
        },
        {
          "name": "empty",
          "userId": "empty"
        }
      ],
      "weight": 12
    },
    {
      "spotsAvailable": [
        {
          "name": "empty",
          "userId": "empty"
        },
        {
          "name": "empty",
          "userId": "empty"
        }
      ],
      "weight": 15
    }
  ],
  "eventApplicants": [
    {
      "userId": {
        "$oid": "636c1778f1d09191074f9690"
      },
      "name": "Wayne Wrestler",
      "weight": 15
    }
  ]
}

Code:

const acceptOrRemoveApplicant = async (eventId: ObjectId, createdBy: ObjectId, applicantId: ObjectId, applicantName: string, boolean: boolean, weight: number): Promise<boolean | undefined> => {
    console.log({ eventId, createdBy, applicantId, applicantName, boolean, weight })
    if (boolean == true) {
        try {
            /*
         * Requires the MongoDB Node.js Driver
         * https://mongodb.github.io/node-mongodb-native
         */

            const agg = [
                {
                    '$match': {
                        '_id': new ObjectId('6398c34ca67dbe3286452f23'),
                        'createdBy': new ObjectId('636c1778f1d09191074f9690')
                    }
                }, {
                    '$unwind': {
                        'path': '$weights'
                    }
                }, {
                    '$unwind': {
                        'path': '$weights.spotsAvailable'
                    }
                }, {
                    '$match': {
                        'weights.spotsAvailable.name': 'empty',
                        'weights.weight': 15
                    }
                }, {
                    '$limit': 1
                }, {
                    '$set': {
                        'weights.spotsAvailable.name': 'Wayen',
                        'weights.spotsAvailable.userId': '123456'
                    }
                }
            ]

            const client = await clientPromise;
            const db = client.db();
            const query = db.collection('events').aggregate(agg);

            // const query = await db.collection('events').updateOne({
            //     _id: new ObjectId(eventId),
            //     createdBy: new ObjectId(createdBy),
            //     "weights.weight": weight
            // },
            //     {
            //         $set: {
            //             "weights.$.spotsAvailable.$[el2]": {
            //                 "name": applicantName,
            //                 "userId": new ObjectId(applicantId)
            //             }
            //         }
            //     },
            //     {
            //         arrayFilters: [
            //             {
            //                 "el2.userId": "empty"
            //             }
            //         ]
            //     })

            if (query) {
                console.log("we queried")
                console.log({ query })
                return true
            } else {
                throw new Error("User not added to event")
            }

        } catch (e) {
            console.error(e);
        }


来源: stackexchange

问:
Oracle Apex Popup LOVs - Additional Outputs
I am using Oracle Apex 22.2 on Centos 7. I have a problem when using the Popup LOVs Additional Outputs. I use it to set the values in an order items Interactive Grid, except for the quantity column, which has to be set manually by the user. If you add a row then come back to edit the quantity, you get the following error message. (Image Below)

"1 error has occurred
Ajax call returned server error ORA-20987: APEX - ERR-1002 Unable to find item ID for item "C19094581743261143" in application "110". - Unexpected error, unable to find item name at application or page level. for ajax_set_session_state."

Even though, I doesn't prevent you from making the edit, but I don't understand why does this error message appear in the first place. What does it mean? And how to fix it? Thank you.

ContentLicense: CC BY-SA 4.0


问:
Python: controlling processes with multiprocessing

Background

I am implementing a program where I am able to start and end another process. I have used the sub-process module to implement (child) processes. I am using the Popen class to start another process.

```<code>from subprocess import Popen, PIPE

class Engine:
   def __init__(self):
    self.processes = list()

   def start_processes(self):
    self.processes.append(Popen(["python","producer.py"], stdout=PIPE, stderr=PIPE))
    self.processes.append(Popen(["python","consumer.py"], stdout=PIPE, stderr=PIPE))

   def end_processes(self):
    for process in self.processes:
        process.kill()

def handle_quit() -> bool:
   u_input = input("Quit?")
   if u_input != "q":
     return False
   else:
     return True

if __name__ == "__main__":
    # Initialise quit flag
    quit_flag = False

    # Create engine
    app_engine = Engine()

    # Start processes
    app_engine.start_processes()

    # Handle input
    while not quit_flag:
        quit_flag = handle_quit()

    # Stop processes
    app_engine.end_processes()

</code>```

Problem

I'd like to be able to control all my sub-process within the engine class. I think this is the right way? Any other ideas?

Body:
Background

I am implementing a program where I am able to start and end another process. I have used the sub-process module to implement (child) processes. I am using the Popen class to start another process.

from subprocess import Popen, PIPE

class Engine:
   def __init__(self):
    self.processes = list()

   def start_processes(self):
    self.processes.append(Popen(["python","producer.py"], stdout=PIPE, stderr=PIPE))
    self.processes.append(Popen(["python","consumer.py"], stdout=PIPE, stderr=PIPE))

   def end_processes(self):
    for process in self.processes:
        process.kill()

def handle_quit() -> bool:
   u_input = input("Quit?")
   if u_input != "q":
     return False
   else:
     return True

if __name__ == "__main__":
    # Initialise quit flag
    quit_flag = False

    # Create engine
    app_engine = Engine()

    # Start processes
    app_engine.start_processes()

    # Handle input
    while not quit_flag:
        quit_flag = handle_quit()

    # Stop processes
    app_engine.end_processes()

Problem

I'd like to be able to control all my sub-process within the engine class. I think this is the right way? Any other ideas?


问:
FCM Admin Sent Notifications don't Open Links When Clicked
I'm trying to get our FCM Message notification on devices to open a URL when clicked on various devices. I've tried click_action and link in the various object configurations supplied with the target the URL string but nothing seems to work. Currently the object is defined as

const fcmMessage = {
    data: {
      time_to_live: (60 * 120).toString(),
      notification: JSON.stringify({
        title: `Title String`,
        body: message_text,
        link: `${process.env.FCM_ACTION_LINK}/user/messages?room_id=${message_room_id}`,
        room_id: message_room_id
      }),
    },
  };
```

I've tried changing where link is placed in the object definition outside of notification and also changing the keyname to click_action but nothing seems to get the URL to open when clicked in the received notification.

Body:
I'm trying to get our FCM Message notification on devices to open a URL when clicked on various devices. I've tried click_action and link in the various object configurations supplied with the target the URL string but nothing seems to work. Currently the object is defined as

const fcmMessage = {
    data: {
      time_to_live: (60 * 120).toString(),
      notification: JSON.stringify({
        title: `Title String`,
        body: message_text,
        link: `${process.env.FCM_ACTION_LINK}/user/messages?room_id=${message_room_id}`,
        room_id: message_room_id
      }),
    },
  };

I've tried changing where link is placed in the object definition outside of notification and also changing the keyname to click_action but nothing seems to get the URL to open when clicked in the received notification.


问:
How can i keep the value after updated page React js
guys!

I am doing a prize draw website. I need to compare timePrize and datePrize to a live date, when both been equals, i want to show the winners name. My problem is: every time i reload the page, the winners name disappear.

Can someone help me?

```<code>import RandomNumber from "components/RandomNumber";
import { useCallback, useEffect, useRef, useState } from "react";
import "./styles.css";

const Datetime = () => {
  const [dateState, setDateState] = useState(new Date());
  const winnerRef = useRef("");

  let timePrize = "18:35:40";
  const datePrize = "13/12/2022";

  useEffect(() => {
    var timer = setInterval(() => setDateState(new Date()), 1000);
    return function cleanup() {
      clearInterval(timer);
    };
  });

  console.log(winnerRef.current)

  const isWinner = useCallback(() => {
    if (
      datePrize === dateState.toLocaleDateString() &&
      timePrize === dateState.toLocaleTimeString()
    ) {
      timePrize = '0'
      winnerRef.current = RandomNumber();
    }
  }, [dateState, timePrize]);

  useEffect(() => isWinner(), [isWinner]);

  const currentDate = dateState.toLocaleDateString("pt-BR", {
    day: "numeric",
    month: "long",
    year: "numeric",
  });

  const currentTime = dateState.toLocaleString("pt-BR", {
    hour: "numeric",
    minute: "numeric",
    second: "numeric",
    hour12: true,
  });

  return (
    <>
      <p className="date-custom">{currentDate}</p>
      <p className="time-custom">{currentTime}</p>

      <div>{winnerRef.current}</div>
    </>
  );
};

export default Datetime;

</code>```

RandomNumber code:

```<code>const RandomNumber = () => {
  var items = [
    1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 19, 20, 21, 24, 26, 27, 28, 29, 30,
    31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 49, 50, 56,
  ];
  let item = items[Math.floor(Math.random() * items.length)];
  console.log(typeof item);

  const numberToName = (item: number) => {
    if (item === 1) {
      return `Philipe Jensen ${item}`;
    } else if (item === 2) {
      return `Jão  ${item}`;
    } else if (item === 3) {
      return `Xepa ${item}`;
    } else if (
      item === 5 ||
      item === 7 ||
      item === 10 ||
      item === 11 ||
      item === 15 ||
      item === 19 ||
      item === 26 ||
      item === 29 ||
      item === 30 ||
      item === 50
    ) {
      return `Leleo ${item}`;
    } else if (item === 8) {
      return `Felipe ${item}`;
    } else if (item === 9 || item === 21) {
      return `Pimpão ${item}`;
    } else if (item === 12) {
      return `Monteiro ${item}`;
    } else if (item === 13) {
      return `May ${item}`;
    } else if (item === 20) {
      return `Bugs ${item}`;
    } else if (item === 24 || item === 56) {
      return `Vev ${item}`;
    } else if (item === 27) {
      return `Tic ${item}`;
    } else if (item === 28) {
      return `Helo Ams ${item}`;
    } else if (
      item === 31 ||
      item === 32 ||
      item === 33 ||
      item === 34 ||
      item === 35 ||
      item === 36 ||
      item === 37 ||
      item === 38 ||
      item === 39 ||
      item === 40 ||
      item === 41 ||
      item === 42 ||
      item === 43 ||
      item === 44 ||
      item === 45 ||
      item === 46
    ) {
      return `Izumi ${item}`;
    } else if (item === 49) {
      return `Geobanna ${item}`;
    }
  };

  return numberToName(item) || '';
};

export default RandomNumber;
</code>```

I want to show the winners name and fixed it, however, when i updated the page, the winners name disappear.

Thanks!

Body:
guys!

I am doing a prize draw website. I need to compare timePrize and datePrize to a live date, when both been equals, i want to show the winners name. My problem is: every time i reload the page, the winners name disappear.

Can someone help me?

import RandomNumber from "components/RandomNumber";
import { useCallback, useEffect, useRef, useState } from "react";
import "./styles.css";

const Datetime = () => {
  const [dateState, setDateState] = useState(new Date());
  const winnerRef = useRef("");

  let timePrize = "18:35:40";
  const datePrize = "13/12/2022";

  useEffect(() => {
    var timer = setInterval(() => setDateState(new Date()), 1000);
    return function cleanup() {
      clearInterval(timer);
    };
  });

  console.log(winnerRef.current)

  const isWinner = useCallback(() => {
    if (
      datePrize === dateState.toLocaleDateString() &&
      timePrize === dateState.toLocaleTimeString()
    ) {
      timePrize = '0'
      winnerRef.current = RandomNumber();
    }
  }, [dateState, timePrize]);

  useEffect(() => isWinner(), [isWinner]);

  const currentDate = dateState.toLocaleDateString("pt-BR", {
    day: "numeric",
    month: "long",
    year: "numeric",
  });

  const currentTime = dateState.toLocaleString("pt-BR", {
    hour: "numeric",
    minute: "numeric",
    second: "numeric",
    hour12: true,
  });

  return (
    <>

{currentDate}

{currentTime}

{winnerRef.current}

    </>
  );
};

export default Datetime;

RandomNumber code:

const RandomNumber = () => {
  var items = [
    1, 2, 3, 5, 7, 8, 9, 10, 11, 12, 13, 14, 19, 20, 21, 24, 26, 27, 28, 29, 30,
    31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 49, 50, 56,
  ];
  let item = items[Math.floor(Math.random() * items.length)];
  console.log(typeof item);

  const numberToName = (item: number) => {
    if (item === 1) {
      return `Philipe Jensen ${item}`;
    } else if (item === 2) {
      return `Jão  ${item}`;
    } else if (item === 3) {
      return `Xepa ${item}`;
    } else if (
      item === 5 ||
      item === 7 ||
      item === 10 ||
      item === 11 ||
      item === 15 ||
      item === 19 ||
      item === 26 ||
      item === 29 ||
      item === 30 ||
      item === 50
    ) {
      return `Leleo ${item}`;
    } else if (item === 8) {
      return `Felipe ${item}`;
    } else if (item === 9 || item === 21) {
      return `Pimpão ${item}`;
    } else if (item === 12) {
      return `Monteiro ${item}`;
    } else if (item === 13) {
      return `May ${item}`;
    } else if (item === 20) {
      return `Bugs ${item}`;
    } else if (item === 24 || item === 56) {
      return `Vev ${item}`;
    } else if (item === 27) {
      return `Tic ${item}`;
    } else if (item === 28) {
      return `Helo Ams ${item}`;
    } else if (
      item === 31 ||
      item === 32 ||
      item === 33 ||
      item === 34 ||
      item === 35 ||
      item === 36 ||
      item === 37 ||
      item === 38 ||
      item === 39 ||
      item === 40 ||
      item === 41 ||
      item === 42 ||
      item === 43 ||
      item === 44 ||
      item === 45 ||
      item === 46
    ) {
      return `Izumi ${item}`;
    } else if (item === 49) {
      return `Geobanna ${item}`;
    }
  };

  return numberToName(item) || '';
};

export default RandomNumber;

I want to show the winners name and fixed it, however, when i updated the page, the winners name disappear.

Thanks!


问:
Match nearest timestamp without set_index
I have 2 dataframes that contain event activities from various applications.

I want to merge them together and match up the events from the 2nd dataframe where the date field is less than(before) the date in the 1st dataframe wherever the user and system are the same.  Also, if there is no event in Data2 or the only events in Data2 occur on or after the dates in Data1, those should just return as null, NaN, or blank.

I've found numerous ways to do this by using set_index and nearest, however if I set the index to the 3 columns in question I get errors since my index would contain duplicate values in the index.  The error about the index needing to be unique makes perfect sense, however now I am wondering how I can do this without relying on indexes.

Sample data:

```<code>data1 = {
'user':["bob", "bob", "bob", "bob", "bob", "bob", "jeb", "sue"],
'system':["A", "A", "A", "A", "B", "B", "A", "B"],
'date':[
    '2022-12-11 10:00:00',
    '2022-12-11 10:00:00',
    '2022-12-11 10:00:01',
    '2022-12-09 10:00:01',
    '2022-12-10 11:00:01',
    '2022-12-15 11:00:01',
    '2022-12-10 10:00:01',
    '2022-12-10 10:00:01'],
'other_data': ["Blah", "Blah","Blah", "Blah", "Blah", "Blah", "Blah", "Blah"]
}

data2 = {
'user':["bob", "bob", "bob", "bob", "bob", "bob", "jeb", "sue", "sue", "ted"],
'system':["A", "A", "A", "B", "B", "B", "B", "B", "B", "A"],
'date':[
    '2022-12-11 11:00:00',
    '2022-12-11 10:00:00',
    '2022-12-11 09:59:00',
    '2022-12-11 11:00:00',
    '2022-12-11 10:00:00',
    '2022-12-11 09:59:00',
    '2022-12-10 08:00:01',
    '2022-12-01 10:00:01',
    '2022-12-13 10:00:01',
    '2022-12-01 10:00:01'],
'other_data': ["Blah", "Blah","Blah", "Blah", "Blah", "Blah", "Blah", "Blah", "Blah", "Blah"]
}

dfData1 = pd.DataFrame(data=data1)
dfData1['date'] = pd.to_datetime(dfData1['date'])
dfData2 = pd.DataFrame(data=data2)
dfData2['date'] = pd.to_datetime(dfData2['date'])
</code>```

Looking to get a dataframe returned similar to this:

user_1
system_1
date_1
other_data_1
user_2
system_2
date_2
other_data_2

bob
A
2022-12-11 10:00:00
Blah
bob A
2022-12-11 09:59:00
Blah

bob
A
2022-12-11 10:00:00
Blah
bob A
2022-12-11 09:59:00
Blah

bob
A
2022-12-11 10:00:01
Blah
bob A
2022-12-11 10:00:00
Blah

bob
A
2022-12-09 10:00:01
Blah
NaN
NaN
NaN
NaN

bob
B
2022-12-10 11:00:01
Blah
NaN
NaN
NaN
NaN

bob
B
2022-12-15 11:00:01
Blah
bob B
2022-12-11 11:00:00
Blah

jeb
A
2022-12-10 10:00:01
Blah
jeb B
2022-12-10 08:00:01
Blah

sue
B
2022-12-10 10:00:01
Blah
sue B
2022-12-01 10:00:01
Blah

How does one merge data like this on multiple columns without setting those columns as the index to avoid the issue of duplicate index values?

Edit:

This gets me closer by adding temp date fields to merge and using pd.merge_asof

```<code>dfData1['mdate'] = dfData1['date']
dfData2['mdate'] = dfData2['date']
dfData1.sort_values(['mdate'], inplace=True)
dfData2.sort_values(['mdate'], inplace=True)

pd.merge_asof(
    dfData1[(dfData1['user']=="bob") & (dfData1['system']=="A")],
    dfData2[(dfData2['user']=="bob") & (dfData2['system']=="A")],
    on="mdate",
    by=["user", "system"],
    suffixes=["_1","_2"]
)
</code>```

This also does a less than or equal to on the compare and there doesn't appear to be a just less than merge option, but I can also just add 1 second to all the all values in  dfData2["mdate"] to compensate for that.

However, the merge only works if I am subsetting to unique user/system rows for the merge_asof.  I could loop through each subset of user/system data in the dataframes and reassemble later, but I'm still wondering if there's a more efficient way to do this?

Body:
I have 2 dataframes that contain event activities from various applications.

I want to merge them together and match up the events from the 2nd dataframe where the date field is less than(before) the date in the 1st dataframe wherever the user and system are the same.  Also, if there is no event in Data2 or the only events in Data2 occur on or after the dates in Data1, those should just return as null, NaN, or blank.

I've found numerous ways to do this by using set_index and nearest, however if I set the index to the 3 columns in question I get errors since my index would contain duplicate values in the index.  The error about the index needing to be unique makes perfect sense, however now I am wondering how I can do this without relying on indexes.

Sample data:

data1 = {
'user':["bob", "bob", "bob", "bob", "bob", "bob", "jeb", "sue"],
'system':["A", "A", "A", "A", "B", "B", "A", "B"],
'date':[
    '2022-12-11 10:00:00',
    '2022-12-11 10:00:00',
    '2022-12-11 10:00:01',
    '2022-12-09 10:00:01',
    '2022-12-10 11:00:01',
    '2022-12-15 11:00:01',
    '2022-12-10 10:00:01',
    '2022-12-10 10:00:01'],
'other_data': ["Blah", "Blah","Blah", "Blah", "Blah", "Blah", "Blah", "Blah"]
}

data2 = {
'user':["bob", "bob", "bob", "bob", "bob", "bob", "jeb", "sue", "sue", "ted"],
'system':["A", "A", "A", "B", "B", "B", "B", "B", "B", "A"],
'date':[
    '2022-12-11 11:00:00',
    '2022-12-11 10:00:00',
    '2022-12-11 09:59:00',
    '2022-12-11 11:00:00',
    '2022-12-11 10:00:00',
    '2022-12-11 09:59:00',
    '2022-12-10 08:00:01',
    '2022-12-01 10:00:01',
    '2022-12-13 10:00:01',
    '2022-12-01 10:00:01'],
'other_data': ["Blah", "Blah","Blah", "Blah", "Blah", "Blah", "Blah", "Blah", "Blah", "Blah"]
}

dfData1 = pd.DataFrame(data=data1)
dfData1['date'] = pd.to_datetime(dfData1['date'])
dfData2 = pd.DataFrame(data=data2)
dfData2['date'] = pd.to_datetime(dfData2['date'])

Looking to get a dataframe returned similar to this:

user_1
system_1
date_1
other_data_1
user_2
system_2
date_2
other_data_2

bob
A
2022-12-11 10:00:00
Blah
bob A
2022-12-11 09:59:00
Blah

bob
A
2022-12-11 10:00:00
Blah
bob A
2022-12-11 09:59:00
Blah

bob
A
2022-12-11 10:00:01
Blah
bob A
2022-12-11 10:00:00
Blah

bob
A
2022-12-09 10:00:01
Blah
NaN
NaN
NaN
NaN

bob
B
2022-12-10 11:00:01
Blah
NaN
NaN
NaN
NaN

bob
B
2022-12-15 11:00:01
Blah
bob B
2022-12-11 11:00:00
Blah

jeb
A
2022-12-10 10:00:01
Blah
jeb B
2022-12-10 08:00:01
Blah

sue
B
2022-12-10 10:00:01
Blah
sue B
2022-12-01 10:00:01
Blah

How does one merge data like this on multiple columns without setting those columns as the index to avoid the issue of duplicate index values?

Edit:

This gets me closer by adding temp date fields to merge and using pd.merge_asof

dfData1['mdate'] = dfData1['date']
dfData2['mdate'] = dfData2['date']
dfData1.sort_values(['mdate'], inplace=True)
dfData2.sort_values(['mdate'], inplace=True)

pd.merge_asof(
    dfData1[(dfData1['user']=="bob") & (dfData1['system']=="A")],
    dfData2[(dfData2['user']=="bob") & (dfData2['system']=="A")],
    on="mdate",
    by=["user", "system"],
    suffixes=["_1","_2"]
)

This also does a less than or equal to on the compare and there doesn't appear to be a just less than merge option, but I can also just add 1 second to all the all values in  dfData2["mdate"] to compensate for that.

However, the merge only works if I am subsetting to unique user/system rows for the merge_asof.  I could loop through each subset of user/system data in the dataframes and reassemble later, but I'm still wondering if there's a more efficient way to do this?


问:
Graph API --> receiving empty array of scheduleItems when call POST /me/calendar/getSchedule
I am calling Graph Api endpoint "/me/calendar/getSchedule" to receive schedule for specific room (I am testing in Graph Explorer). Despite of the fact that I have full list of the events including this this room in given timestamps, I receive in scheduleInformation an empty array of scheduledItems.

For test I did the same, but for the user who scheduled this events and it worked perfectly. What could be the reason?

Body req :

```<code>`{
"schedules": [
        "room@mail.com"
    ],
    "startTime": {
        "dateTime": "2022-12-11T09:00:00",
        "timeZone": "UTC"
    },
    "endTime": {
        "dateTime": "2022-12-13T23:59:00",
        "timeZone": "UTC"
    }
}`
</code>```

Bopdy resp:

```<code>`{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#Collection(microsoft.graph.scheduleInformation)",
    "value": [
        {
            "scheduleId": "room@mail.com",
            "availabilityView": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
            "scheduleItems": []
        }
    ]
}`
</code>```

Event is created in this location , but like there is no relations between what I am creating and the room resources . E.g. thi is an event I have created:

```<code> {
        "@odata.etag": "W/\"1z8A//yOl0a9+ObgH9y4KQAAAfmk/Q==\"",
        "id": "some id",
        "subject": "Let's go for lunch",
        "bodyPreview": "Does mid month work for you?",
        "body": {
            "contentType": "html",
            "content": "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"></head><body>Does mid month work for you?</body></html>"
        },
        "start": {
            "dateTime": "2022-12-13T12:00:00.0000000",
            "timeZone": "UTC"
        },
        "end": {
            "dateTime": "2022-12-14T14:00:00.0000000",
            "timeZone": "UTC"
        },
        "location": {
            "displayName": "room@mail.com",
            "locationType": "default",
            "uniqueId": "room@mail.com",
            "uniqueIdType": "private"
        },
        "attendees": [],
        "organizer": {
            "emailAddress": {
                "name": "admin",
                "address": "admin@mail.com"
            }
        }
    }
</code>```

Body:
I am calling Graph Api endpoint "/me/calendar/getSchedule" to receive schedule for specific room (I am testing in Graph Explorer). Despite of the fact that I have full list of the events including this this room in given timestamps, I receive in scheduleInformation an empty array of scheduledItems.

For test I did the same, but for the user who scheduled this events and it worked perfectly. What could be the reason?

Body req :

`{
"schedules": [
        "room@mail.com"
    ],
    "startTime": {
        "dateTime": "2022-12-11T09:00:00",
        "timeZone": "UTC"
    },
    "endTime": {
        "dateTime": "2022-12-13T23:59:00",
        "timeZone": "UTC"
    }
}`

Bopdy resp:

`{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#Collection(microsoft.graph.scheduleInformation)",
    "value": [
        {
            "scheduleId": "room@mail.com",
            "availabilityView": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
            "scheduleItems": []
        }
    ]
}`

Event is created in this location , but like there is no relations between what I am creating and the room resources . E.g. thi is an event I have created:

 {
        "@odata.etag": "W/\"1z8A//yOl0a9+ObgH9y4KQAAAfmk/Q==\"",
        "id": "some id",
        "subject": "Let's go for lunch",
        "bodyPreview": "Does mid month work for you?",
        "body": {
            "contentType": "html",
            "content": "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">Does mid month work for you?"
        },
        "start": {
            "dateTime": "2022-12-13T12:00:00.0000000",
            "timeZone": "UTC"
        },
        "end": {
            "dateTime": "2022-12-14T14:00:00.0000000",
            "timeZone": "UTC"
        },
        "location": {
            "displayName": "room@mail.com",
            "locationType": "default",
            "uniqueId": "room@mail.com",
            "uniqueIdType": "private"
        },
        "attendees": [],
        "organizer": {
            "emailAddress": {
                "name": "admin",
                "address": "admin@mail.com"
            }
        }
    }


问:
Getting an error converting a React Js application to Liferay
I am trying to create a simple react application from Liferay. Executed the command:

```<code>yo liferay-js
</code>```

And added a new project. I am able to run the basic application with the 'Hello World' text but when I try to import any file, I am getting the error like this:

```<code>'Uncaught SyntaxError: Cannot use import statement outside a module (at....'
</code>```

I also have the 'type': 'module' in my package.json but nothing seems to work. Any help is appreciated.

Body:
I am trying to create a simple react application from Liferay. Executed the command:

yo liferay-js

And added a new project. I am able to run the basic application with the 'Hello World' text but when I try to import any file, I am getting the error like this:

'Uncaught SyntaxError: Cannot use import statement outside a module (at....'

I also have the 'type': 'module' in my package.json but nothing seems to work. Any help is appreciated.


问:
Get Rid of Basic App.config File In .Net 4.8 Application
I have the following basic .Net 4.8 application:

```<code>using System;
using System.Windows;
namespace BlackScreen
{
  public partial class App : Application
  {
    [STAThread]
    public static void Main()
    {
      App app = new App();
      Window window = new Window();
      window.Show();
      app.MainWindow = window;
      app.Run();
    }
  }
}
</code>```

with the following App.config file:

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
  </startup>
</configuration>
</code>```

How would I get rid of this App.config file and set the supportedRuntime value programatically (or via the csproj file) so that the end result is no .config file being required alongside the final exe file?

Body:
I have the following basic .Net 4.8 application:

using System;
using System.Windows;
namespace BlackScreen
{
  public partial class App : Application
  {
    [STAThread]
    public static void Main()
    {
      App app = new App();
      Window window = new Window();
      window.Show();
      app.MainWindow = window;
      app.Run();
    }
  }
}

with the following App.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
  </startup>
</configuration>

How would I get rid of this App.config file and set the supportedRuntime value programatically (or via the csproj file) so that the end result is no .config file being required alongside the final exe file?


问:
Is there a way to disable this pop up?
I didn't use Visual Studio for a while and this started to show up now everytime it want's to autocomplete a line.

I tried looking in the settings but couldn't find a option to disable it. I just don't like it being there. My version of VS is 17.4.1

Title: Is there a way to disable this pop up?


问:
Async IAsyncEnumerable using Newtonsoft in ASP.net
I have a asp.net application that uses

```<code>builder.Services.AddControllers()
    .AddNewtonsoftJson();
</code>```

This causes the return of the controller not to run asynchronous

```<code>        [HttpGet("IAsyncTest")]
        public IAsyncEnumerable<TestDTO> GetTestValue()
        {
            return _getValues();
        }

        private static readonly TestDTO[] _values = new[]
        {
            new TestDTO {IntValue= 1, StringValue = "Value 1"},
            new TestDTO {IntValue= 2, StringValue = "Value 2"},
            new TestDTO {IntValue= 3, StringValue = "Value 3"},
            new TestDTO {IntValue= 4, StringValue = "Value 4"},
            new TestDTO {IntValue= 5, StringValue = "Value 5"},
        };

        private async IAsyncEnumerable<TestDTO> _getValues()
        {
            foreach (var value in _values)
            {
                yield return value;
                await Task.Delay(TimeSpan.FromSeconds(20));
            }
        }
</code>```

Is there a way to use Newtonsoft only in certain controllers not all of them? Or specify which controller uses Text.Json.

Or Is it possible to create a custom formatter that uses that Text.Json for IAsyncEnumerable.

Code example is here: GitHub Link

Thanks for helping

Body:
I have a asp.net application that uses

builder.Services.AddControllers()
    .AddNewtonsoftJson();

This causes the return of the controller not to run asynchronous

        [HttpGet("IAsyncTest")]
        public IAsyncEnumerable<TestDTO> GetTestValue()
        {
            return _getValues();
        }

        private static readonly TestDTO[] _values = new[]
        {
            new TestDTO {IntValue= 1, StringValue = "Value 1"},
            new TestDTO {IntValue= 2, StringValue = "Value 2"},
            new TestDTO {IntValue= 3, StringValue = "Value 3"},
            new TestDTO {IntValue= 4, StringValue = "Value 4"},
            new TestDTO {IntValue= 5, StringValue = "Value 5"},
        };

        private async IAsyncEnumerable<TestDTO> _getValues()
        {
            foreach (var value in _values)
            {
                yield return value;
                await Task.Delay(TimeSpan.FromSeconds(20));
            }
        }

Is there a way to use Newtonsoft only in certain controllers not all of them? Or specify which controller uses Text.Json.

Or Is it possible to create a custom formatter that uses that Text.Json for IAsyncEnumerable.

Code example is here: GitHub Link

Thanks for helping


问:
Setting up hypertables in TimescaleDB with multiple time-series
I am about to integrate TimescaleDB in my django project, but what’s unclear to me is how timescale groups different timestamps together to form a time-series.

Imagine I have multiple Drinks (coca-cola, lime-juice etc, fanta, water…). I can have a million drinks in my database. Each drink can have multiple time-series related to it. A time-series of consumption data over the years, a time-series of customer data over the years etc… Then imagine I also have food data with the same assumptions. I want to save all those data in a hypertable.

I can start by creating a hypertable and inject all consumption data for Coca-Cola in the year 2018. Now i also want to store customer data for Coca-Cola too, but the time-stamps will collide. I will have 2022-12-03 multiple times. Thus timescale must have a best-practice of how to group timestamps together to from a time-series. Otherwise I could only have a single time-series in a hypertable.

I see two solutions:

I can save a foreign key or an object-id with the timestamp. E.g. 2022-01-01 and 5, whereas 5 is the id of coca cola object.

Or I can create a meta-table which stores the meta-information about the timestamp. The meta object holds the information to which object the timestamp belongs to. E.g. in the meta model I can save the id for the coca-cola object and also other meta information (e.g. the amount of sugar during the whole year in the drink). I see the advantage of storing more meta information as important, so I’d prefer this approach.

My question though is: Is that how timescale is supposed to be used? Or is the idea to have one hypertable per drink in this case? That would surprise me because then I’d have millions of hypertables. Or will I lose performance if I design my setup as explained above? Or to put it simple: What is the best practice of grouping timestamps together to a time-series in timescale.

Thanks a bunch for the feedback


问:
How to make KeyboardInterrupt outside of console?
I'm using PyAutoGui for automation of adding data to certain fullscreen app. Problem is, when I try to Alt+Tab back to my IDE it constantly brings app back to front and messes up my code by pasting data there. I need a way to either prevent script from working when I press Alt+Tab or when window comes out of focus. How do I do that?

I tried:
Ctrl-C
Ctrl-Pause

import _thread

def input_thread(a_list):
    raw_input()             # use input() in Python3
    a_list.append(True)

def do_stuff():
    a_list = []
    _thread.start_new_thread(input_thread, (a_list,))
    while not a_list:
        stuff()
```


问:
Is there a way to filter a list, find a specific item and replace it with a list in the same lambda?
I am trying to enhance a lambda expression which is currently filtering out on a specific property of the List of items and then maps over filtered list to return a List. This is the expected return type. I am now trying to find if a specific value exists in the return type (List) and replace it with another list. I have tried using any/contains but I lose access to the original list. Is it even possible to do all this in the same lambda?
This is the current lambda:</p>
```<code>val primaryUsers = usersList
        .filter { it.primaryUserGroups.any { userId -> userIds.contains(userId) } }
        .map { it.username }
</code>```

Body:
I am trying to enhance a lambda expression which is currently filtering out on a specific property of the List of items and then maps over filtered list to return a List. This is the expected return type. I am now trying to find if a specific value exists in the return type (List) and replace it with another list. I have tried using any/contains but I lose access to the original list. Is it even possible to do all this in the same lambda?
This is the current lambda:

val primaryUsers = usersList
        .filter { it.primaryUserGroups.any { userId -> userIds.contains(userId) } }
        .map { it.username }


问:
How would I sort a 2D array of strings to display the top 5 most occurring Names?
My goal with my program is to take a 2D array that is storing names and sort them from the most occurring to least occurring. In this array there are multiple occurrences of the same name.
The desired output should look like this:

```<code>TOP 5 PLAYERS
1. GEORGE - WINS: X
2. HENRY - WINS: X
3. JOHN - WINS: X
4. MARRY - WINS: X
5. JULIA - WINS: X
</code>```

Where X represents the amount of times their name occurs in the 2D array.

Unfortunately due to my professors rules, we aren't allowed to use anything from the <string.h> library. We are only permitted functions from the <stdio.h> library.

Here's what my function looks like at the moment. I'm pulling the names from a file named scores.txt and saving them to the array and displaying them. I just don't have a way to order them.

```<code>void leaderboard(FILE *scores) {

    int totalNames = 4;
    int row;
    char tempName[MAX_USERNAME_CHARS-1];
    char namesArray[500][MAX_USERNAME_CHARS-1];

    scores = fopen("scores.txt","r");

        while (fscanf(scores,"%s",tempName) == 1) {
            int strlength;
            for (strlength = 0; tempName[strlength] != '\0';strlength++);

            for (int i=0; i <= strlength; i++) {
                namesArray[row][i] = tempName[i];
            }
            row++;
        }

    //Insert Sorting Code Here

    printf("\nTOP 5 PLAYERS\n");
    for (int i=0;i<=totalNames;i++) {
        printf("%d. ",i+1);
        for (int j=0;j<=MAX_USERNAME_CHARS-2;j++) {
            printf("%c",namesArray[i][j]);
        }
        printf(" - WINS: X\n");
    }
}
</code>```

This function currently only prints out the first 5 names it grabs from the file.

Body:
My goal with my program is to take a 2D array that is storing names and sort them from the most occurring to least occurring. In this array there are multiple occurrences of the same name.
The desired output should look like this:

TOP 5 PLAYERS
1. GEORGE - WINS: X
2. HENRY - WINS: X
3. JOHN - WINS: X
4. MARRY - WINS: X
5. JULIA - WINS: X

Where X represents the amount of times their name occurs in the 2D array.

Unfortunately due to my professors rules, we aren't allowed to use anything from the <string.h> library. We are only permitted functions from the <stdio.h> library.

Here's what my function looks like at the moment. I'm pulling the names from a file named scores.txt and saving them to the array and displaying them. I just don't have a way to order them.

void leaderboard(FILE *scores) {

    int totalNames = 4;
    int row;
    char tempName[MAX_USERNAME_CHARS-1];
    char namesArray[500][MAX_USERNAME_CHARS-1];

    scores = fopen("scores.txt","r");

        while (fscanf(scores,"%s",tempName) == 1) {
            int strlength;
            for (strlength = 0; tempName[strlength] != '\0';strlength++);

            for (int i=0; i <= strlength; i++) {
                namesArray[row][i] = tempName[i];
            }
            row++;
        }

    //Insert Sorting Code Here

    printf("\nTOP 5 PLAYERS\n");
    for (int i=0;i<=totalNames;i++) {
        printf("%d. ",i+1);
        for (int j=0;j<=MAX_USERNAME_CHARS-2;j++) {
            printf("%c",namesArray[i][j]);
        }
        printf(" - WINS: X\n");
    }
}

This function currently only prints out the first 5 names it grabs from the file.


问:
Is there a way to output something if the user hasn't responded for a certain amount of time?
I'm messing around with Linux Bash Shell Scripting for a class and have this written so far:

```<code>#! /bin/bash
        num=0
        while [ $num -lt 1 ]
        do
                echo "What is your name?"
                read name
                echo "Your name is $name? Respond with Y or N"
                read response
                if [ $response == "Y" ]; then
                        echo "What an interesting name $name"
                        num=1
                        break
                elif [ $response == "N" ]; then
                        echo "Why would you lie $name? Wait that's not even you>
                        continue
                else
                        echo "Why don't you respond $name, or are you lying?"
                        continue
                fi
        done

</code>```

It's a simple program that asks the user for their name. Then they type in their name and it asks the user if that's their name and they respond Yes(Y) or No(N). At this point I want there to be a timer that if the user doesn't respond for 5 seconds then it displays "Why don't you respond $name, or are you lying?". Is there anyway to do this? Thank you and I appreciate your answers :)

I looked up possible solutions and only saw the sleep command come up. I'm not sure how I could implement this as my understanding of the sleep command is that it will stop the program and wait however much time before continuing instead of running alongside my code.

Body:
I'm messing around with Linux Bash Shell Scripting for a class and have this written so far:

#! /bin/bash
        num=0
        while [ $num -lt 1 ]
        do
                echo "What is your name?"
                read name
                echo "Your name is $name? Respond with Y or N"
                read response
                if [ $response == "Y" ]; then
                        echo "What an interesting name $name"
                        num=1
                        break
                elif [ $response == "N" ]; then
                        echo "Why would you lie $name? Wait that's not even you>
                        continue
                else
                        echo "Why don't you respond $name, or are you lying?"
                        continue
                fi
        done

It's a simple program that asks the user for their name. Then they type in their name and it asks the user if that's their name and they respond Yes(Y) or No(N). At this point I want there to be a timer that if the user doesn't respond for 5 seconds then it displays "Why don't you respond $name, or are you lying?". Is there anyway to do this? Thank you and I appreciate your answers :)

I looked up possible solutions and only saw the sleep command come up. I'm not sure how I could implement this as my understanding of the sleep command is that it will stop the program and wait however much time before continuing instead of running alongside my code.


问:
R forestplot package blank lines with section headings
I want to generate a forest plot using the forestplot package in R that looks like the following image

I have several sections I want to join together in a single long plot with a single axis at the bottom, but with the section headings separating each one. I can generate each forestplot independently and put them together, but the elements do not line up.

How do I generate the plot like this?


问:
I get an TS18003 error when compiling my typescript on VS Code. None of the other suggestions work
I try the command on my VS Code terminal: "npm run build"

I get the following error.

error TS18003: No inputs were found in config file 'C:/Users/my_name/pallind2/tsconfig.json'. Specified 'include' paths were '["**/*"]' and 'exclude' paths were '["lib"]'.

This is a learning training exercise to create index.d.ts, index.ts.map, index.js, and index.js.map.

All the suggestions seem to be to add a ts file, but that doesn't work.

I got this before, and I had to recreate the entire thing with a new name.  Didn't work this time.

Again, please don't tell me the "add empty file" solution. It doesn't work.

This is part of a learning exercise.

This is the code in the index.ts file.

```<code>```
export function isPalindrome (str: string){
    return str === str.split('').reverse().join('');
}

```
</code>```

This my package.json file contents.

```<code>    {
      "name": "pallind2",
      "version": "1.0.0",
      "description": "",
      "main": "lib",
      "types": "lib",
      "scripts": {
      "build": "tsc"
    },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "devDependencies": {
      "typescript": "^4.9.4"
  }
}
</code>```

This is the tsconfig.json file.

```<code>{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */
    "rootDir": "src",                                    /* Specify the root folder within your source files. */
    // "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
    // "resolveJsonModule": true,                        /* Enable importing .json files. */
    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

    /* Emit */
    "declaration": true,                                 /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    "declarationMap": true,                              /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    "sourceMap": true,                                   /* Create source map files for emitted JavaScript files. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
    "outDir": "lib",                                     /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

</code>```
```<code></code>```

Body:
I try the command on my VS Code terminal: "npm run build"

I get the following error.

error TS18003: No inputs were found in config file 'C:/Users/my_name/pallind2/tsconfig.json'. Specified 'include' paths were '["**/*"]' and 'exclude' paths were '["lib"]'.

This is a learning training exercise to create index.d.ts, index.ts.map, index.js, and index.js.map.

All the suggestions seem to be to add a ts file, but that doesn't work.

I got this before, and I had to recreate the entire thing with a new name.  Didn't work this time.

Again, please don't tell me the "add empty file" solution. It doesn't work.

This is part of a learning exercise.

This is the code in the index.ts file.

```
export function isPalindrome (str: string){
    return str === str.split('').reverse().join('');
}

```

This my package.json file contents.

    {
      "name": "pallind2",
      "version": "1.0.0",
      "description": "",
      "main": "lib",
      "types": "lib",
      "scripts": {
      "build": "tsc"
    },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "devDependencies": {
      "typescript": "^4.9.4"
  }
}

This is the tsconfig.json file.

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo",              /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects. */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
    // "reactNamespace": "",                             /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */
    // "moduleDetection": "auto",                        /* Control what method is used to detect module-format JS files. */

    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */
    "rootDir": "src",                                    /* Specify the root folder within your source files. */
    // "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like './node_modules/@types'. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "moduleSuffixes": [],                             /* List of file name suffixes to search when resolving a module. */
    // "resolveJsonModule": true,                        /* Enable importing .json files. */
    // "noResolve": true,                                /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */

    /* Emit */
    "declaration": true,                                 /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    "declarationMap": true,                              /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    "sourceMap": true,                                   /* Create source map files for emitted JavaScript files. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
    "outDir": "lib",                                     /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types. */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like '__extends' in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing 'const enum' declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,                         /* When type checking, take into account 'null' and 'undefined'. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true,               /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read. */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Add 'undefined' to a type when accessed using an index. */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type. */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}


问:
Next + strapi dynamic homepage don't show up
I have problem with displaying hompage on my site. When I enter page with slug e.g. /blog everything works fine, but problem occurs when I want to go to homepage, then website displays:

This page isn’t working
localhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
I will be grateful for your help

[[slug]].js
`

```<code>import delve from "dlv";
import ErrorPage from "next/error";
import Layout from "../components/layout";
import BlockManager from "../components/shared/BlockManager";
import { getData, handleRedirection } from "../utils";
import { getLocalizedParams } from "../utils/localize";

const Universals = ({ global, pageData, preview }) => {
  if (pageData === null) {
    return <ErrorPage statusCode={404} />;
  }

  const blocks = delve(pageData, "attributes.blocks");
  return (
    <Layout global={global} pageData={pageData} type="pages" preview={preview}>
      {blocks && <BlockManager blocks={blocks} />}
    </Layout>
  );
};

// This gets called on every request
export async function getServerSideProps(context) {
  const { slug, locale } = getLocalizedParams(context.query);

  try {
    const data = getData(
      slug,
      locale,
      "page",
      "collectionType",
      context.preview
    );
    const res = await fetch(delve(data, "data"));
    const json = await res.json();

    if (!json.data.length) {
      return handleRedirection(context.preview, null);
    }

    return {
      props: { pageData: json.data[0], preview: context.preview || null },
    };
  } catch (error) {
    return {
      props: { pageData: null },
    };
  }
}

export default Universals;
</code>```

`

localize.js

`

```<code>import delve from 'dlv';
import { getStrapiURL } from '.';

export function getLocalizedParams(query) {
  const lang = delve(query, 'lang');
  const slug = delve(query, 'slug');

  return { slug: slug || '', locale: lang || 'en' };
}

export function localizePath(localePage, type) {
  const { locale, slug } = localePage;

  switch (type) {
    case 'restaurant':
      return `/restaurants/${slug}?lang=${locale}`;
    case 'article':
      return `/blog/${slug}?lang=${locale}`;

    default:
      return `/${slug}?lang=${locale}`;
  }
}

function getUrl(type, localization, targetLocale) {
  switch (type) {
    case 'pages':
      return `/pages/${delve(localization, 'id')}`;
    case 'restaurant-page':
      return `/restaurant-page?locale=${targetLocale}`;
    case 'blog-page':
      return `/blog-page?locale=${targetLocale}`;
    case 'article':
      return `/articles/${delve(localization, 'id')}?locale=${targetLocale}`;
    case 'restaurant':
      return `/restaurants/${delve(localization, 'id')}?locale=${targetLocale}`;
    default:
      break;
  }
}

export async function getLocalizedData(targetLocale, pageData, type) {
  const localization = pageData.attributes.localizations.data.find(
    (localization) => localization.attributes.locale === 'fr-FR'
  );
  const url = getUrl(type, localization, targetLocale);
  const res = await fetch(getStrapiURL(url));
  const localePage = await res.json();
  return localePage;
}

export async function listLocalizedPaths(pageData, type) {
  const currentPage = {
    locale: pageData.attributes.locale,
    href: localizePath(pageData.attributes, type),
  };
  const paths = await Promise.all(
    pageData.attributes.localizations.data.map(async (localization) => {
      const url = getUrl(type, localization, localization.attributes.locale);
      const res = await fetch(getStrapiURL(url));
      const localePage = await res.json();
      const page = { ...pageData.attributes, ...localePage.data.attributes };
      return {
        locale: page.locale,
        href: localizePath(page, type),
      };
    })
  );

  const localizedPaths = [currentPage, ...paths];
  return localizedPaths;
}
</code>```

`

Body:
I have problem with displaying hompage on my site. When I enter page with slug e.g. /blog everything works fine, but problem occurs when I want to go to homepage, then website displays:

This page isn’t working
localhost redirected you too many times.
Try clearing your cookies.
ERR_TOO_MANY_REDIRECTS
I will be grateful for your help

[[slug]].js
`

import delve from "dlv";
import ErrorPage from "next/error";
import Layout from "../components/layout";
import BlockManager from "../components/shared/BlockManager";
import { getData, handleRedirection } from "../utils";
import { getLocalizedParams } from "../utils/localize";

const Universals = ({ global, pageData, preview }) => {
  if (pageData === null) {
    return <ErrorPage statusCode={404} />;
  }

  const blocks = delve(pageData, "attributes.blocks");
  return (
    <Layout global={global} pageData={pageData} type="pages" preview={preview}>
      {blocks && <BlockManager blocks={blocks} />}
    </Layout>
  );
};

// This gets called on every request
export async function getServerSideProps(context) {
  const { slug, locale } = getLocalizedParams(context.query);

  try {
    const data = getData(
      slug,
      locale,
      "page",
      "collectionType",
      context.preview
    );
    const res = await fetch(delve(data, "data"));
    const json = await res.json();

    if (!json.data.length) {
      return handleRedirection(context.preview, null);
    }

    return {
      props: { pageData: json.data[0], preview: context.preview || null },
    };
  } catch (error) {
    return {
      props: { pageData: null },
    };
  }
}

export default Universals;

`

localize.js

`

import delve from 'dlv';
import { getStrapiURL } from '.';

export function getLocalizedParams(query) {
  const lang = delve(query, 'lang');
  const slug = delve(query, 'slug');

  return { slug: slug || '', locale: lang || 'en' };
}

export function localizePath(localePage, type) {
  const { locale, slug } = localePage;

  switch (type) {
    case 'restaurant':
      return `/restaurants/${slug}?lang=${locale}`;
    case 'article':
      return `/blog/${slug}?lang=${locale}`;

    default:
      return `/${slug}?lang=${locale}`;
  }
}

function getUrl(type, localization, targetLocale) {
  switch (type) {
    case 'pages':
      return `/pages/${delve(localization, 'id')}`;
    case 'restaurant-page':
      return `/restaurant-page?locale=${targetLocale}`;
    case 'blog-page':
      return `/blog-page?locale=${targetLocale}`;
    case 'article':
      return `/articles/${delve(localization, 'id')}?locale=${targetLocale}`;
    case 'restaurant':
      return `/restaurants/${delve(localization, 'id')}?locale=${targetLocale}`;
    default:
      break;
  }
}

export async function getLocalizedData(targetLocale, pageData, type) {
  const localization = pageData.attributes.localizations.data.find(
    (localization) => localization.attributes.locale === 'fr-FR'
  );
  const url = getUrl(type, localization, targetLocale);
  const res = await fetch(getStrapiURL(url));
  const localePage = await res.json();
  return localePage;
}

export async function listLocalizedPaths(pageData, type) {
  const currentPage = {
    locale: pageData.attributes.locale,
    href: localizePath(pageData.attributes, type),
  };
  const paths = await Promise.all(
    pageData.attributes.localizations.data.map(async (localization) => {
      const url = getUrl(type, localization, localization.attributes.locale);
      const res = await fetch(getStrapiURL(url));
      const localePage = await res.json();
      const page = { ...pageData.attributes, ...localePage.data.attributes };
      return {
        locale: page.locale,
        href: localizePath(page, type),
      };
    })
  );

  const localizedPaths = [currentPage, ...paths];
  return localizedPaths;
}

`


问:
My WIndows name seems to be causing problems in packaging
I am getting this error when I try to pack

pyinstaller: error: argument --add-data: invalid add_data_or_binary value: 'c:\users\James Martin\pycharmprojects\cal\lib\site-packages'

I have tried changing the name in the code to just james because I belive that might be the problem but it did not help. Is my line just incorrect?


问:
Regex works in regexer but returning nothing in php preg_match
Using regexr.com my regex is working but preg_match in php returns null.

Tried many times in several php testers.

Regex is:

```<code>/Donor Comment:\*(.*?)\*/
</code>```

Text is:

```<code>United States* > Donor Comment:*Thx Barbara for your wonderful offerings, and thx to > CVRAN for the essential support you provide to asylum seekers and for > the creative fundraising via an Arts Marathon!*
</code>```

Works in Regexr

PHP is:

```<code>preg_match('/Donor Comment:\*(.*?)\*/', $msg, $donor_comment);
</code>```

Preg_match returns null

Body:
Using regexr.com my regex is working but preg_match in php returns null.

Tried many times in several php testers.

Regex is:

/Donor Comment:\*(.*?)\*/

Text is:

United States* > Donor Comment:*Thx Barbara for your wonderful offerings, and thx to > CVRAN for the essential support you provide to asylum seekers and for > the creative fundraising via an Arts Marathon!*

Works in Regexr

PHP is:

preg_match('/Donor Comment:\*(.*?)\*/', $msg, $donor_comment);

Preg_match returns null


问:
How to use static ip address for Firebase to connect to MongoDB
How to use static ip address for Firebase to connect to MongoDB

Hello,

I'm using a Flutter/Firebase project, and for some reasons I need to also user MongoDB.

I saw that you can only authorize some ip to access your Mongo database, which I guess is a good practice.

The problem is that Firebase has dynamic ip addresses for its servers, and I saw that I was possible to assign a static address thanks to this procedure : https://cloud.google.com/functions/docs/networking/network-settings

I followed the procedure, creating a new VPC network, then a NAT cloud, router etc... to finally obtain a static IP (which is described in https://console.cloud.google.com/networking/addresses/list) used by the router.

I thought I followed every step as asked, but when I add that ip address to MongoDB whitelist, the connection between Firebase Cloud Functions and MongoDB seem to still be blocked.

Anyone already tried that and could help me ?


问:
I have a requirement where i should create 6 input boxes initially, have to use form array in reactive forms in angular,
I have a requirement where i should create 6 input boxes initially, have to use form array in reactive forms in angular, it should have formvalidations with min length of 2 max length of 15 characters can someone help me how to use formarray and solve this!

```<code> form: FormGroup;
  fb: FormBuilder = new FormBuilder();
  sealNumberArray: any[] = ['', '', '', '', '', ''];
  group2SealNoArray: any[] = ['', '', '', '', '', ''];
  group3SealNoArray: any[] = ['', '', ''];
 this.form = this.fb.group({
      sealNos: this.fb.array(this.sealNumberArray, {
        validators: [
          Validators.required,
          Validators.minLength(2),
          Validators.maxLength(15),
        ],
      }),
      group2SealNos: this.fb.array(this.group2SealNoArray, {
        validators: [Validators.minLength(2), Validators.maxLength(15)],
      }),
      group3SealNos: this.fb.array(this.group3SealNoArray, {
        validators: [Validators.minLength(2), Validators.maxLength(15)],
      }),
    });
onDoneBtn() {
    const result = this.form.value;
    this.dialogRef.close(result);
}

<html>
<form [formGroup]="form">
      <div class="row">
        <div
          class="col-md-4"
          *ngFor="let sealno of sealNumberArray; let i = index"
          formArrayName="sealNos"
        >
          <cn-form-input
            label="{{
              'SHARED.ORDER_FORM.LOADED_SHIPMENT.LABELS.SEAL_NUMBER' | translate
            }}"
            formControlName="{{ i }}"
            [maxLen]="15"

          ></cn-form-input>
          <div *ngIf="this.form.controls.sealNos.touched && sealno.length<2">please enter atleast 2 characters</div>

        </div>
        </div>
      <div class="row" *ngIf="counter===1">
        <div
          class="col-md-4"
          *ngFor="let sealNos of group2SealNoArray; let i = index"
          formArrayName="group2SealNos"
        >
          <cn-form-input
            label="{{
              'SHARED.ORDER_FORM.LOADED_SHIPMENT.LABELS.SEAL_NUMBER'
                | translate
            }}"
            formControlName="{{ i }}"
            [maxLen]="15"
          ></cn-form-input>
        </div>
      </div>
      <div class="row" *ngIf="counter===2">
        <div
        class="col-md-4"
        *ngFor="let sealNos of group2SealNoArray; let i = index"
        formArrayName="group2SealNos"
      >
        <cn-form-input
          label="{{
            'SHARED.ORDER_FORM.LOADED_SHIPMENT.LABELS.SEAL_NUMBER'
              | translate
          }}"
          formControlName="{{ i }}"
          [maxLen]="15"
        ></cn-form-input>
      </div>
        <div
          class="col-md-4"
          *ngFor="let sealNos of group3SealNoArray; let i = index"
          formArrayName="group3SealNos"
        >
          <cn-form-input
            label="{{
              'SHARED.ORDER_FORM.LOADED_SHIPMENT.LABELS.SEAL_NUMBER'
                | translate
            }}"
            formControlName="{{ i }}"
            [maxLen]="15"
          ></cn-form-input>
        </div>
      </div>
      <div class="sealno-btn mt-3">
        <cn-button
          text="{{
            'SHARED.ORDER_FORM.LOADED_SHIPMENT.LABELS.ADD_SEAL_NO' | translate
          }}"
          [variant]="btnIcon"
          icon="plus3"
          [disabled]="disabled"
          (click)="addSealNoBtn()"
        ></cn-button>
      </div>
      <div class="button-wrapper">
        <mat-divider class="mb-3"></mat-divider>
      </div>

      <cn-button
        [variant]="btnPrimary"
        text="{{
          'SHARED.ORDER_FORM.LOADED_SHIPMENT.BUTTONS.DONE' | translate
        }}"
        (click)="onDoneBtn()"
      ></cn-button>
      <cn-button
        class="cancel-btn"
        [variant]="btnSecondary"
        text="{{
          'SHARED.ORDER_FORM.LOADED_SHIPMENT.BUTTONS.CANCEL' | translate
        }}"
        mat-dialog-close
      ></cn-button>
    </form>

</code>```

formvalidations is not working with this code

Body:
I have a requirement where i should create 6 input boxes initially, have to use form array in reactive forms in angular, it should have formvalidations with min length of 2 max length of 15 characters can someone help me how to use formarray and solve this!

 form: FormGroup;
  fb: FormBuilder = new FormBuilder();
  sealNumberArray: any[] = ['', '', '', '', '', ''];
  group2SealNoArray: any[] = ['', '', '', '', '', ''];
  group3SealNoArray: any[] = ['', '', ''];
 this.form = this.fb.group({
      sealNos: this.fb.array(this.sealNumberArray, {
        validators: [
          Validators.required,
          Validators.minLength(2),
          Validators.maxLength(15),
        ],
      }),
      group2SealNos: this.fb.array(this.group2SealNoArray, {
        validators: [Validators.minLength(2), Validators.maxLength(15)],
      }),
      group3SealNos: this.fb.array(this.group3SealNoArray, {
        validators: [Validators.minLength(2), Validators.maxLength(15)],
      }),
    });
onDoneBtn() {
    const result = this.form.value;
    this.dialogRef.close(result);
}

<form [formGroup]="form">

          <cn-form-input
            label="{{
              'SHARED.ORDER_FORM.LOADED_SHIPMENT.LABELS.SEAL_NUMBER' | translate
            }}"
            formControlName="{{ i }}"
            [maxLen]="15"

          ></cn-form-input>
          <div *ngIf="this.form.controls.sealNos.touched && sealno.length<2">please enter atleast 2 characters

          <cn-form-input
            label="{{
              'SHARED.ORDER_FORM.LOADED_SHIPMENT.LABELS.SEAL_NUMBER'
                | translate
            }}"
            formControlName="{{ i }}"
            [maxLen]="15"
          ></cn-form-input>

        <cn-form-input
          label="{{
            'SHARED.ORDER_FORM.LOADED_SHIPMENT.LABELS.SEAL_NUMBER'
              | translate
          }}"
          formControlName="{{ i }}"
          [maxLen]="15"
        ></cn-form-input>

          <cn-form-input
            label="{{
              'SHARED.ORDER_FORM.LOADED_SHIPMENT.LABELS.SEAL_NUMBER'
                | translate
            }}"
            formControlName="{{ i }}"
            [maxLen]="15"
          ></cn-form-input>

        <cn-button
          text="{{
            'SHARED.ORDER_FORM.LOADED_SHIPMENT.LABELS.ADD_SEAL_NO' | translate
          }}"
          [variant]="btnIcon"
          icon="plus3"
          [disabled]="disabled"
          (click)="addSealNoBtn()"
        ></cn-button>

        <mat-divider class="mb-3"></mat-divider>

      <cn-button
        [variant]="btnPrimary"
        text="{{
          'SHARED.ORDER_FORM.LOADED_SHIPMENT.BUTTONS.DONE' | translate
        }}"
        (click)="onDoneBtn()"
      ></cn-button>
      <cn-button
        class="cancel-btn"
        [variant]="btnSecondary"
        text="{{
          'SHARED.ORDER_FORM.LOADED_SHIPMENT.BUTTONS.CANCEL' | translate
        }}"
        mat-dialog-close
      ></cn-button>
    </form>

formvalidations is not working with this code


问:
Drag and Drop doesn't work for an even number of elements
I create new elements on button click.

When the number of elements is not even, everything works fine.
But when the number becomes even, drag and drop starts to work strangely

It seems that the outer element blocks access to the inner ones for the dragover.

https://codepen.io/korno_no/pen/poKXdoq

```<code>dragAndDrop(){
        taskBoardList.addEventListener('dragstart', (evt) => {
            evt.target.classList.add('task__selected');
          })
        taskBoardList.addEventListener('dragend', (evt) => {
            evt.target.classList.remove('task__selected');
        });
        taskBoardList.addEventListener('dragover', (evt) => {
            evt.preventDefault();

            const activeElement = taskBoardList.querySelector(`.task__selected`)
            const currentElement = evt.target;
            const isMoveable = activeElement !== currentElement && currentElement.classList.contains(`task`);
            if (!isMoveable) {
                console.log(currentElement)
                return
            }
            const nextElement = (currentElement === activeElement.nextElementSibling) ?
            currentElement.nextElementSibling :
            currentElement;
            taskBoardList.insertBefore(activeElement, nextElement);
        });
    }
</code>```

Body:
I create new elements on button click.

When the number of elements is not even, everything works fine.
But when the number becomes even, drag and drop starts to work strangely

It seems that the outer element blocks access to the inner ones for the dragover.

https://codepen.io/korno_no/pen/poKXdoq

dragAndDrop(){
        taskBoardList.addEventListener('dragstart', (evt) => {
            evt.target.classList.add('task__selected');
          })
        taskBoardList.addEventListener('dragend', (evt) => {
            evt.target.classList.remove('task__selected');
        });
        taskBoardList.addEventListener('dragover', (evt) => {
            evt.preventDefault();

            const activeElement = taskBoardList.querySelector(`.task__selected`)
            const currentElement = evt.target;
            const isMoveable = activeElement !== currentElement && currentElement.classList.contains(`task`);
            if (!isMoveable) {
                console.log(currentElement)
                return
            }
            const nextElement = (currentElement === activeElement.nextElementSibling) ?
            currentElement.nextElementSibling :
            currentElement;
            taskBoardList.insertBefore(activeElement, nextElement);
        });
    }


问:
How to create a common validation utility JAR to be used across Spring Boot APIs?
I am working with multiple REST APIs that share common domain elements from the DB. The validations for these elements are common across these APIs and I feel we are violating the DRY principle by repeating these validations within a single REST API and across all other APIs. I have created custom validations to be re-used within the API that I am currently working. Are there any references that we can move these validations to a common utility JAR so that other APIs can also use them?

Created custom validation annotations with in a single API. Need to move these validations to a common validation utility service.