问:
Replace the text in pdf using python without changing the pdf structure
Each pdf has different encoded formats, Able to replace some pdf's. But some are not. What is the reason behind this? I am stuck at this point

Ex:1

Tm 0 g [(Amount In)1( Words: )] TJ /FAAABC 8 Tf [(Three Lakh)-1( S)1(e)-1(ven Thousand)-1( S)1(e)-1(ven Hund)-1(red Ninety Two Rup)-1(ees And Two Paise Only)] TJ ET Q Q Q q 1 0 0 1 0 442.59799194 cm q 1 g 0.125 0.25 m 560.02502441 0.25 l 560.02502441 8.25 l 0.125 8.25 l h f* Q q 0.125 0.25 m 560.02502441 0.25 l 560.02502441 8.25 l 0.125 8.25 l h W n q 1 0 0 1 0.125 0.25 cm Q Q Q q 1 0 0 1 0 450.84799194 cm q 1 g 0.125 0.25 m 560.02502441 0.25 l 560.02502441 9.75 l 0.125 9.75 l h f* Q q 0.125 0.25 m 560.02502441 0.25 l 560.02502441 9.75 l 0.125 9.75 l h W n q 1 0 0 1 5.625 0.25 cm BT /FAAAAJ 8 Tf 1 0 0 -1 0 6.8499999

Ex:2

' 8 Tf', '(  :Two Thousand Eight Hundred Eighty Three Only)Tj', '1 0 0 1 34.85 237.161 Tm', '/F2',

After running the python script, These are the examples.

Ex:1 - I'm unable to replace the text and

Ex:2 - able to replace the text

Can anyone suggest what is ex:1 format and how to replace that text?

def replace_text(content, replacements = dict()):
    lines = content.splitlines()
    result = ""
    in_text = False

    for line in lines:
        if line == "BT":
            in_text = True

        elif line == "ET":
            in_text = False

        elif in_text:
            cmd = line[-2:]
            if cmd.lower() == 'tj':
                replaced_line = line
                for k, v in replacements.items():
                    replaced_line = replaced_line.replace(k, v)
                result += replaced_line + "\n"
            else:
                result += line + "\n"
            continue

        result += line + "\n"

    return result

def process_data(object, replacements):
    data = object.getData()
    decoded_data = data.decode('utf-8')
    replaced_data = replace_text(decoded_data, replacements)
    encoded_data = replaced_data.encode('utf-8')
    if object.decodedSelf is not None:
        object.decodedSelf.setData(encoded_data)
    else:
        object.setData(encoded_data)

if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("-i", "--input", required=True, help="path to PDF document")  #Canon Rental
    args = vars(ap.parse_args())
    in_file = args\["input"\]
    filename_base = in_file.replace(os.path.splitext(in_file)\[1\], "")
    replacements = {'02-JUN-21': '03 June 2022', '16 November 2022': '03 June 2022'}

    pdf = PdfFileReader(in_file)
    writer = PdfFileWriter()
    for page_number in range(0, pdf.getNumPages()):

        page = pdf.getPage(page_number)
        contents = page.getContents()
        if isinstance(contents, DecodedStreamObject) or isinstance(contents, EncodedStreamObject):
            process_data(contents, replacements)
        elif len(contents) > 0:
            for obj in contents:
                if isinstance(obj, DecodedStreamObject) or isinstance(obj, EncodedStreamObject):
                    streamObj = obj.getObject()
                    process_data(streamObj, replacements)
        page[NameObject("/Contents")] = contents.decodedSelf
        writer.addPage(page)

         with open(filename_base + f"_result_{i}.pdf", 'wb') as out_file:
            writer.write(out_file)

```


来源: stackexchange

问:
Why is datetime-local failing to validate the value in google chrome?
I recently updated chrome browser and all of a sudden the datetime-local input type is failing to validate. I keep receiving the following warning.
Image with the warning
I mention that input properties are set correctly.
image with the input html code

My code for the input:

```<code><input type="datetime-local" class="form-control" name="reg_date" id="reg_date" value="<?= date('Y-m-d\TH:i:s') ?>">
</code>```

I'm using Chrome Version 108.0.5359.99 (Official Build) (64-bit)
Has anybody encountered this issue ?

I tried to check with different dates, works perfect on Firefox, chrome still failing to validate

ContentLicense: CC BY-SA 4.0

Body:
I recently updated chrome browser and all of a sudden the datetime-local input type is failing to validate. I keep receiving the following warning.
Image with the warning
I mention that input properties are set correctly.
image with the input html code

My code for the input:

<input type="datetime-local" class="form-control" name="reg_date" id="reg_date" value="<?= date('Y-m-d\TH:i:s') ?>">

I'm using Chrome Version 108.0.5359.99 (Official Build) (64-bit)
Has anybody encountered this issue ?

I tried to check with different dates, works perfect on Firefox, chrome still failing to validate


问:
React-Native 'syscall' is deprecated: first deprecated in iOS 10.0 - syscall(2) is unsupported
I get the following error after i run my iOS react-native app with xcode.

```<code>'syscall' is deprecated: first deprecated in iOS 10.0 - syscall(2) is unsupported; please switch to a supported interface. For SYS_kdebug_trace use kdebug_signpost().
</code>```

I use iOS 12.0 and react-native 0.68.0
React is 17.0.2

i already tried this solution but with no effect.

https://github.com/google/glog/pull/685

Can someone help me with this problem?

Body:
I get the following error after i run my iOS react-native app with xcode.

'syscall' is deprecated: first deprecated in iOS 10.0 - syscall(2) is unsupported; please switch to a supported interface. For SYS_kdebug_trace use kdebug_signpost().

I use iOS 12.0 and react-native 0.68.0
React is 17.0.2

i already tried this solution but with no effect.

https://github.com/google/glog/pull/685

Can someone help me with this problem?


问:
No captured browser
I have been searching through various responses on this issue and still havent found a resolution. Has anyone been able to fix the karma warning? This is an angular project.</p>
```<code>√ Browser application bundle generation complete.
12 12 2022 02:51:03.216:WARN [karma]: No captured browser, open http://localhost:9876/
12 12 2022 02:51:03.225:INFO [karma-server]: Karma v6.4.1 server started at http://localhost:9876/
12 12 2022 02:51:03.225:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
12 12 2022 02:51:03.229:INFO [launcher]: Starting browser Chrome
12 12 2022 02:51:03.752:INFO [Chrome 108.0.0.0 (Windows 10)]: Connected on socket VbweAHLyodUBm4G5AAAB with id 55148481
Chrome 108.0.0.0 (Windows 10): Executed 17 of 17 SUCCESS (0.123 secs / 0.085 secs)
TOTAL: 17 SUCCESS
</code>```

Title: No captured browser

Body:
I have been searching through various responses on this issue and still havent found a resolution. Has anyone been able to fix the karma warning? This is an angular project.

√ Browser application bundle generation complete.
12 12 2022 02:51:03.216:WARN [karma]: No captured browser, open http://localhost:9876/
12 12 2022 02:51:03.225:INFO [karma-server]: Karma v6.4.1 server started at http://localhost:9876/
12 12 2022 02:51:03.225:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
12 12 2022 02:51:03.229:INFO [launcher]: Starting browser Chrome
12 12 2022 02:51:03.752:INFO [Chrome 108.0.0.0 (Windows 10)]: Connected on socket VbweAHLyodUBm4G5AAAB with id 55148481
Chrome 108.0.0.0 (Windows 10): Executed 17 of 17 SUCCESS (0.123 secs / 0.085 secs)
TOTAL: 17 SUCCESS


问:
Foreach function to extract data from a css file
I am having trouble applying the for each function to extract data into a map from my civ file. it gives me a lot of errors but the most common is that is undefined</p>
```<code>var db = d3.map();
var setDb = function(cancerData) {
  cancerData.forEach(function(d) {
    db.set(
         {"x": 2011, "y": +d.adjusted_rate_2011},
         {"x": 2013, "y": +d.adjusted_rate_2013},
         {"x": 2015, "y": +d.adjusted_rate_2015},
         {"x": 2017, "y": +d.adjusted_rate_2017},
         {"x": 2019, "y": +d.adjusted_rate_2019}
    );
  });
};
setDb(cancerData.features);
console.log(db);
</code>```

Body:
I am having trouble applying the for each function to extract data into a map from my civ file. it gives me a lot of errors but the most common is that is undefined

var db = d3.map();
var setDb = function(cancerData) {
  cancerData.forEach(function(d) {
    db.set(
         {"x": 2011, "y": +d.adjusted_rate_2011},
         {"x": 2013, "y": +d.adjusted_rate_2013},
         {"x": 2015, "y": +d.adjusted_rate_2015},
         {"x": 2017, "y": +d.adjusted_rate_2017},
         {"x": 2019, "y": +d.adjusted_rate_2019}
    );
  });
};
setDb(cancerData.features);
console.log(db);


问:
return ATL Com Interface From COM Method
i returned an ATL COM Interface from another CO Method from C++ to C#,
but I don't know how correctly I should manage the lifetime of the object that I created from c++, should I cache it and release it when the main interface released?</p>


问:
Merging data frame to create a unique dataframe in Python?
I have three Data Frame df1, df2, df3. I wanted to merge these data frames using "EMAIL" as the unique id. I tried to merge using outer join. It does work, but duplication occurs. But i wanted to merge these data frames using EMAIL id, but also pick the values from the other columns if there is anything existing in some fields.

These are my data frames: Initially I am displaying three data frames for the experts understanding.

Input

```<code>for df in (df1, df2, df3):
    print(df.head())
</code>```

output

```<code>  EMAIL      NAME
0  a@a.com    a
2  c@c.com    c

     EMAIL  MOBILE
0  d@d.com      97
1  c@c.com      91

     EMAIL  MOBILE
0  a@a.com     NaN
1  a@a.com    81.0
2  c@c.com    66.0
</code>```

Now, I tried outer join to merge these data frames using EMAIL ID. As the result the output obtained is shown below:

input

```<code>df12=pd.merge(df1, df2, how='outer',  on=["EMAIL"])
df23=pd.merge(df12, df3, how='outer',  on=["EMAIL","MOBILE"])
df23
</code>```

output obtained:

```<code>          EMAIL   NAME  MOBILE_x    MOBILE_y
0        a@a.com   a      NaN         NaN
1        a@a.com   a      NaN         81.0
2        c@c.com   c      91.0        66.0
3        d@d.com  NaN     97.0        NaN
</code>```

But the output I am looking for is shown below:

```<code>        EMAIL   NAME  MOBILE_x  MOBILE_y
0      a@a.com   a      81        NaN
1      c@c.com   c     91.0      66.0
2      d@d.com  NaN    97.0       NaN
</code>```

Basically I wanted to merge all the data frames using email and every data frame structure is different. I wanted to extract fields with unique fields and form a new data frame.

Body:
I have three Data Frame df1, df2, df3. I wanted to merge these data frames using "EMAIL" as the unique id. I tried to merge using outer join. It does work, but duplication occurs. But i wanted to merge these data frames using EMAIL id, but also pick the values from the other columns if there is anything existing in some fields.

These are my data frames: Initially I am displaying three data frames for the experts understanding.

Input

for df in (df1, df2, df3):
    print(df.head())

output

  EMAIL      NAME
0  a@a.com    a
2  c@c.com    c

     EMAIL  MOBILE
0  d@d.com      97
1  c@c.com      91

     EMAIL  MOBILE
0  a@a.com     NaN
1  a@a.com    81.0
2  c@c.com    66.0

Now, I tried outer join to merge these data frames using EMAIL ID. As the result the output obtained is shown below:

input

df12=pd.merge(df1, df2, how='outer',  on=["EMAIL"])
df23=pd.merge(df12, df3, how='outer',  on=["EMAIL","MOBILE"])
df23

output obtained:

          EMAIL   NAME  MOBILE_x    MOBILE_y
0        a@a.com   a      NaN         NaN
1        a@a.com   a      NaN         81.0
2        c@c.com   c      91.0        66.0
3        d@d.com  NaN     97.0        NaN

But the output I am looking for is shown below:

        EMAIL   NAME  MOBILE_x  MOBILE_y
0      a@a.com   a      81        NaN
1      c@c.com   c     91.0      66.0
2      d@d.com  NaN    97.0       NaN

Basically I wanted to merge all the data frames using email and every data frame structure is different. I wanted to extract fields with unique fields and form a new data frame.


问:
NextJS on-demand revalidation takes hours for page content to be updated
I have created a nextJS project with 366 pages where each page is statically generated using getStaticProps. Each page receives new content twice a day and I am using on-demand revalidation to update the cache for each single page. The revalidation api call takes around 5 seconds to run, but on refreshing the actual pages it sometimes takes hours before it is updated. Any thoughts as to why this is happening?

My revalidation code looks like this:

```<code>import type { NextApiHandler } from 'next';
import pages from './pages.json';

const secret = process.env.REVALIDATE_SECRET || '';

const handler: NextApiHandler<Data> = async (req, res) => {
  if (req.method !== 'POST') {
    return res.status(401).json({ message: 'Must be a POST request' });
  }
  if (req.headers.signature !== secret) res.status(401).json({ message: 'Invalid signature' });

  try {
    const revalidateResult = await Promise.allSettled([
      res.revalidate('/'),
      ...pages.map(({ slug }) => res.revalidate(`/${slug}`)),
    ]).then(
      (results) => results.filter(({status}) => status === 'rejected'),
    );
    if (revalidateResult.length === 0) {
      return res.status(200).send({message: 'Successfully revalidated all pages'})
    }
    return res.status(500).send({message: `Error: ${revalidateResult.length} / ${pages.length} pages were rejected upon revalidation`})
  } catch (err) {
    return res.status(500).send({ message: `Error revalidating: ${err}` });
  }
};

export default handler;
</code>```

Pages is a list of objects. The objects contain slug among other things:

```<code>// pages.json
[
  {
    'slug': 'slug1',
    ...
  }, {
    'slug': 'slug2',
    ...
  }
]
</code>```

I expected this to successfully update all 366 pages instantly, but it takes more than an hour before the new content is visible upon refresh. It happens regularly that one or two of the pages fail to revalidate where the api for instance returns: Error: 1 / 366 pages were rejected upon revalidation. Not sure yet why that is happening, but I would expect the remaining 365 pages to be updated immediately anyways.

Body:
I have created a nextJS project with 366 pages where each page is statically generated using getStaticProps. Each page receives new content twice a day and I am using on-demand revalidation to update the cache for each single page. The revalidation api call takes around 5 seconds to run, but on refreshing the actual pages it sometimes takes hours before it is updated. Any thoughts as to why this is happening?

My revalidation code looks like this:

import type { NextApiHandler } from 'next';
import pages from './pages.json';

const secret = process.env.REVALIDATE_SECRET || '';

const handler: NextApiHandler<Data> = async (req, res) => {
  if (req.method !== 'POST') {
    return res.status(401).json({ message: 'Must be a POST request' });
  }
  if (req.headers.signature !== secret) res.status(401).json({ message: 'Invalid signature' });

  try {
    const revalidateResult = await Promise.allSettled([
      res.revalidate('/'),
      ...pages.map(({ slug }) => res.revalidate(`/${slug}`)),
    ]).then(
      (results) => results.filter(({status}) => status === 'rejected'),
    );
    if (revalidateResult.length === 0) {
      return res.status(200).send({message: 'Successfully revalidated all pages'})
    }
    return res.status(500).send({message: `Error: ${revalidateResult.length} / ${pages.length} pages were rejected upon revalidation`})
  } catch (err) {
    return res.status(500).send({ message: `Error revalidating: ${err}` });
  }
};

export default handler;

Pages is a list of objects. The objects contain slug among other things:

// pages.json
[
  {
    'slug': 'slug1',
    ...
  }, {
    'slug': 'slug2',
    ...
  }
]

I expected this to successfully update all 366 pages instantly, but it takes more than an hour before the new content is visible upon refresh. It happens regularly that one or two of the pages fail to revalidate where the api for instance returns: Error: 1 / 366 pages were rejected upon revalidation. Not sure yet why that is happening, but I would expect the remaining 365 pages to be updated immediately anyways.


问:
What is wrong with my CASE expression in this SQL query?
I have the following query ready, but it doesn't work. It fails with the reason ERROR: column "yesterday" does not exist Position: 178.

```<code>SELECT 'EMAIL' AS comm_mode
    ,EXTRACT(epoch FROM (sent_at - inserted_at)) AS duration
    ,CASE
        WHEN (EXTRACT(DAY FROM now()) - EXTRACT(DAY FROM inserted_at))=1 THEN "yesterday"
        WHEN (EXTRACT(MONTH FROM now()) - EXTRACT(MONTH FROM inserted_at))=1 THEN "last_month"
    END AS time_period
FROM communications_email
WHERE status = 'sent'
    AND inserted_at >= (NOW() AT TIME ZONE 'utc' - INTERVAL '45 day')
</code>```

What am I doing wrong?

I tried to set the 2 extractions as separate columns, in which case they work and show the values I'm expecting in each individual column. So for column 1 "x_days_ago" it shows the right value, and col2 "x_weeks_ago" it shows the right value, and so on.

(i.e. nothing else seems to be wrong with the rest of the query, only when I add a CASE statement do I get this error.)

I am hoping to get 1 column with "yesterday", "last_week", and "last_month" as string values in a column time_period (the rest can have the string "irrelevant" if an "ELSE" is required).

Body:
I have the following query ready, but it doesn't work. It fails with the reason ERROR: column "yesterday" does not exist Position: 178.

SELECT 'EMAIL' AS comm_mode
    ,EXTRACT(epoch FROM (sent_at - inserted_at)) AS duration
    ,CASE
        WHEN (EXTRACT(DAY FROM now()) - EXTRACT(DAY FROM inserted_at))=1 THEN "yesterday"
        WHEN (EXTRACT(MONTH FROM now()) - EXTRACT(MONTH FROM inserted_at))=1 THEN "last_month"
    END AS time_period
FROM communications_email
WHERE status = 'sent'
    AND inserted_at >= (NOW() AT TIME ZONE 'utc' - INTERVAL '45 day')

What am I doing wrong?

I tried to set the 2 extractions as separate columns, in which case they work and show the values I'm expecting in each individual column. So for column 1 "x_days_ago" it shows the right value, and col2 "x_weeks_ago" it shows the right value, and so on.

(i.e. nothing else seems to be wrong with the rest of the query, only when I add a CASE statement do I get this error.)

I am hoping to get 1 column with "yesterday", "last_week", and "last_month" as string values in a column time_period (the rest can have the string "irrelevant" if an "ELSE" is required).


问:
MUI dataGrid component - custom icons for sort and filter in mui data grid column headers
As per the default behavior of the mui DataGrid component the column's sort and filter icons are shown when we hover on the column header. whereas I want my own sort and filter icons which should always be visible on the column headers and behavior of the sort and filter should remain same as before.


问:
Glue Crawler not deleting SQS messages
I have configured a Glue crawler on s3 events and has a connection established with the SQS queue. When the crawler runs, it starts consuming from the SQS and I can see the messages in queue decreasing. However, after a point, the messages does not get deleted and the crawler finishes.

Any idea why this is happening?

Edit: The event notifications are configured for a specific folder and for a parquet files alone.

Title: Glue Crawler not deleting SQS messages


问:
Change stream update and array of sub document update
need help on writing some proper aggregation for change stream
I am getting data some thing like

```<code>{
  "_id": {
    "$oid": "6285ee2b91c6e50012a76e0b"
  },
  "status": "new",
  "lastUpdatedData": {
    "timestamp": {
      "$date": {
        "$numberLong": "1670602175000"
      }
    },
    "priority": 0,
    "gps": {
      "longitude": 0,
      "latitude": 0,
      "altitude": 0,
      "angle": 0,
      "satellites": 0,
      "speed": 0
    },
    "event_id": 0,
    "properties_count": 8,
    "ioElements": [
      {
        "id": 239,
        "label": "Ignition",
        "value": 0,
        "valueHuman": "Ignition Off",
        "valueDB": 0,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e26"
        }
      },
      {
        "id": 240,
        "label": "Movement",
        "value": 0,
        "valueHuman": "Movement Off",
        "valueDB": 0,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e27"
        }
      },
      {
        "id": 200,
        "label": "Sleep Mode",
        "value": 2,
        "valueHuman": "Deep Sleep",
        "valueDB": 2,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e28"
        }
      },
      {
        "id": 67,
        "label": "Battery Voltage",
        "value": 3791,
        "valueHuman": "3.791 V",
        "valueDB": 3.791,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e2b"
        }
      },
      {
        "id": 68,
        "label": "Battery Current",
        "value": 0,
        "valueHuman": "0 A",
        "valueDB": 0,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e2c"
        }
      }
    ]
  },
  "category": "companyCar"
}
</code>```

My first question is regarding updating the ‘ioElements’ array and I want to update

```<code>{
        "id": 239,
        "label": "Ignition",
        "value": 0,
        "valueHuman": "Ignition Off",
        "valueDB": 0,
      }
</code>```

to

```<code>{
        "id": 239,
        "label": "Ignition",
        "value": 1,
        "valueHuman": "Ignition On",
        "valueDB": 1,
      }
</code>```

I want to perform a kind of upsert on ioElements array i.e update the existing fields with new fields if any new object is present inside ioElements I receive I need to push to ioElements array how to achieve this in an effective way. My current implementation

```<code>ioElements.forEach(async (singleIoEle) => {
          const ioElementExist = await Vehicle.findOne({
            _id: mongoose.Types.ObjectId(vehicleId),
            "lastUpdatedData.ioElements.id": singleIoEle.id,
          });
          if (ioElementExist) {
            await Vehicle.updateMany(
              {
                _id: mongoose.Types.ObjectId(vehicleId),
                "lastUpdatedData.ioElements.id": singleIoEle.id,
              },
              {
                $set: {
                  "lastUpdatedData.ioElements.$": {
                    ...singleIoEle,
                  },
                },
              }
            );
          } else {
            await Vehicle.findByIdAndUpdate(
              mongoose.Types.ObjectId(vehicleId),
              {
                $addToSet: { "lastUpdatedData.ioElements": { ...singleIoEle } },
              }
            );
          }
        }),
</code>```

Can the above code be improved and perform update in effective way?

We also have a change stream opened to show updates on latest values on frontend my change stream aggregation pipeline

```<code>const ids = Array.of(ObjectId(...vehicleIds));
    const pipeline = [
      {
        $match: {
          operationType: 'update',
          'documentKey._id': { $in: ids }
        },
      },
    ];
</code>```

Now issue is this pipeline is triggered on each of ioElement is updated which is creating load on servers. I want to get update only once when my updating code has finished(get update not everytime a single ioElement is update rather get update only one after all the single ioElements are written)

Body:
need help on writing some proper aggregation for change stream
I am getting data some thing like

{
  "_id": {
    "$oid": "6285ee2b91c6e50012a76e0b"
  },
  "status": "new",
  "lastUpdatedData": {
    "timestamp": {
      "$date": {
        "$numberLong": "1670602175000"
      }
    },
    "priority": 0,
    "gps": {
      "longitude": 0,
      "latitude": 0,
      "altitude": 0,
      "angle": 0,
      "satellites": 0,
      "speed": 0
    },
    "event_id": 0,
    "properties_count": 8,
    "ioElements": [
      {
        "id": 239,
        "label": "Ignition",
        "value": 0,
        "valueHuman": "Ignition Off",
        "valueDB": 0,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e26"
        }
      },
      {
        "id": 240,
        "label": "Movement",
        "value": 0,
        "valueHuman": "Movement Off",
        "valueDB": 0,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e27"
        }
      },
      {
        "id": 200,
        "label": "Sleep Mode",
        "value": 2,
        "valueHuman": "Deep Sleep",
        "valueDB": 2,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e28"
        }
      },
      {
        "id": 67,
        "label": "Battery Voltage",
        "value": 3791,
        "valueHuman": "3.791 V",
        "valueDB": 3.791,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e2b"
        }
      },
      {
        "id": 68,
        "label": "Battery Current",
        "value": 0,
        "valueHuman": "0 A",
        "valueDB": 0,
        "_id": {
          "$oid": "63935e17ac1fa5b006927e2c"
        }
      }
    ]
  },
  "category": "companyCar"
}

My first question is regarding updating the ‘ioElements’ array and I want to update

{
        "id": 239,
        "label": "Ignition",
        "value": 0,
        "valueHuman": "Ignition Off",
        "valueDB": 0,
      }

to

{
        "id": 239,
        "label": "Ignition",
        "value": 1,
        "valueHuman": "Ignition On",
        "valueDB": 1,
      }

I want to perform a kind of upsert on ioElements array i.e update the existing fields with new fields if any new object is present inside ioElements I receive I need to push to ioElements array how to achieve this in an effective way. My current implementation

ioElements.forEach(async (singleIoEle) => {
          const ioElementExist = await Vehicle.findOne({
            _id: mongoose.Types.ObjectId(vehicleId),
            "lastUpdatedData.ioElements.id": singleIoEle.id,
          });
          if (ioElementExist) {
            await Vehicle.updateMany(
              {
                _id: mongoose.Types.ObjectId(vehicleId),
                "lastUpdatedData.ioElements.id": singleIoEle.id,
              },
              {
                $set: {
                  "lastUpdatedData.ioElements.$": {
                    ...singleIoEle,
                  },
                },
              }
            );
          } else {
            await Vehicle.findByIdAndUpdate(
              mongoose.Types.ObjectId(vehicleId),
              {
                $addToSet: { "lastUpdatedData.ioElements": { ...singleIoEle } },
              }
            );
          }
        }),

Can the above code be improved and perform update in effective way?

We also have a change stream opened to show updates on latest values on frontend my change stream aggregation pipeline

const ids = Array.of(ObjectId(...vehicleIds));
    const pipeline = [
      {
        $match: {
          operationType: 'update',
          'documentKey._id': { $in: ids }
        },
      },
    ];

Now issue is this pipeline is triggered on each of ioElement is updated which is creating load on servers. I want to get update only once when my updating code has finished(get update not everytime a single ioElement is update rather get update only one after all the single ioElements are written)


问:
How tp import data from csv, dependent on the "path" i'm going
I have a GUI, which should import data from differnt csv-files.
The design looks like this:

Start -> choose the visit-date of the patient (either pre-/ intra/- or postoperative). Now the data from the csv file, corresponding to the visit is importete. this works fine.

As for example:

```<code>class PreoperativeDialog(QDialog):
    """Dialog to introduce all important information of preoperative data ('indication check')"""

    def __init__(self, parent=None):
        """Initializer."""
        super().__init__(parent)

        self.date = 'preoperative'  # defines the date at which data are taken from/saved at
        subj_details = General.read_current_subj()
        General.synchronize_data_with_general(self.date, subj_details.id[0],
                                              messagebox=False)
.
.
.

</code>```

def updatetext(self):
"""adds information extracted from database already provided"""

```<code>df_subj = Content.extract_saved_data(self.date)

self.lineEditFirstDiagnosed.setText(str(df_subj["First_Diagnosed_preop"][0])) \
    if str(df_subj["First_Diagnosed_preop"][0]) != 'nan' else self.lineEditFirstDiagnosed.setText('')
</code>```
```<code>

</code>```

Now I can go a path to open a new window "medication". Medications are different columns in the pre/- intra/- and postoperative csv files. So dependent from where im "coming", the data should be imported from there. For example:

Preoperative -> Medication: data should be imported from preoperative
Postoperative -> Medication: data should be imported from postoperative

So my question is, how i could specify this.

```<code>class MedicationDialog(QDialog):
    """Dialog to introduce the medication at a specific date. All unrelated """

    def __init__(self, visit="unknown", parent=None):
        super().__init__(parent)
</code>```

So here "visit" should be something that is variable, dependent on the path I went. If i just type "preoperative" here, the medication is always imported from that csv.

Unfortunately I'm quite new to coding and i didn't find any way how to do this.

I hope it is kind of understandable what I mean and someone can help me.

Thank you!

Body:
I have a GUI, which should import data from differnt csv-files.
The design looks like this:

Start -> choose the visit-date of the patient (either pre-/ intra/- or postoperative). Now the data from the csv file, corresponding to the visit is importete. this works fine.

As for example:

class PreoperativeDialog(QDialog):
    """Dialog to introduce all important information of preoperative data ('indication check')"""

    def __init__(self, parent=None):
        """Initializer."""
        super().__init__(parent)

        self.date = 'preoperative'  # defines the date at which data are taken from/saved at
        subj_details = General.read_current_subj()
        General.synchronize_data_with_general(self.date, subj_details.id[0],
                                              messagebox=False)
.
.
.

def updatetext(self):
"""adds information extracted from database already provided"""

df_subj = Content.extract_saved_data(self.date)

self.lineEditFirstDiagnosed.setText(str(df_subj["First_Diagnosed_preop"][0])) \
    if str(df_subj["First_Diagnosed_preop"][0]) != 'nan' else self.lineEditFirstDiagnosed.setText('')

Now I can go a path to open a new window "medication". Medications are different columns in the pre/- intra/- and postoperative csv files. So dependent from where im "coming", the data should be imported from there. For example:

Preoperative -> Medication: data should be imported from preoperative
Postoperative -> Medication: data should be imported from postoperative

So my question is, how i could specify this.

class MedicationDialog(QDialog):
    """Dialog to introduce the medication at a specific date. All unrelated """

    def __init__(self, visit="unknown", parent=None):
        super().__init__(parent)

So here "visit" should be something that is variable, dependent on the path I went. If i just type "preoperative" here, the medication is always imported from that csv.

Unfortunately I'm quite new to coding and i didn't find any way how to do this.

I hope it is kind of understandable what I mean and someone can help me.

Thank you!


问:
java.lang.IllegalArgumentException: No view found for id 0x93c3(unknown) for fragment {4660a7b} - (react-native - android)
building native views in android side so can use it in react-native, problem is that in the first render i can create many instance i want, but when navigating to a new screen and using the same component to create the same native view i get this error:

```<code>  java.lang.IllegalArgumentException: No view found for id 0x93c3 (unknown) for fragment MyFragment{4660a7b} (1fddb7f4-9894-4da7-a39c-ae82aadfd9aa id=0x93c3 tag=37827)
</code>```

im following the same example as the docs: https://reactnative.dev/docs/native-components-android#integration-with-an-android-fragment-example just changing its value for mine, but still getting the error.

in android side i have this:

```<code>//class where i create my fragment

public class MyViewManager extends ViewGroupManager<FrameLayout> {

    public static final String REACT_CLASS = "MyViewManager";
    public final int COMMAND_CREATE = 1;
    private int propWidth;
    private int propHeight;
    private int old_value = 0;
    protected String zone_id;
    private String publisher_id;
    FragmentManager fragmet;
    private ReactApplicationContext reactContext;

    public MyViewManager(ReactApplicationContext reactContext) {
        this.reactContext = reactContext;
    }

    @Override
    public String getName() {
        return REACT_CLASS;
    }

    /**
     * Return a FrameLayout which will later hold the Fragment
     */
    @Override
    public FrameLayout createViewInstance(ThemedReactContext reactContext) {
        return new FrameLayout(reactContext);
    }

    /**
     * Map the "create" command to an integer
     */
    @Nullable
    @Override
    public Map<String, Integer> getCommandsMap() {
        return MapBuilder.of("create", COMMAND_CREATE);
    }

    /**
     * Handle "create" command (called from JS) and call createFragment method
     */
    @Override
    public void receiveCommand(
            @NonNull FrameLayout root,
            String commandId,
            @Nullable ReadableArray args
    ) {
        super.receiveCommand(root, commandId, args);
        int reactNativeViewId = args.getInt(0);
        int commandIdInt = Integer.parseInt(commandId);
        this.old_value = reactNativeViewId;

        switch (commandIdInt) {
            case COMMAND_CREATE:
                Log.e("MediumRectangle", "EJECUTAMOS AQUQUIQ" + Integer.toString(reactNativeViewId));
                createFragment(root, reactNativeViewId);
                break;
            default: {}
        }
    }

    @ReactPropGroup(names = {"width", "height", "backgroundColor"}, customType = "Style")
    public void setStyle(FrameLayout view, int index, Integer value) {
        if (index == 0) {
            propWidth = value;
        }

        if (index == 1) {
            propHeight = value;
        }
    }

    @ReactProp(name = "zone_id")
    public void setAdType(FrameLayout view, String zone_id) {
        this.zone_id = zone_id;
    }

    @ReactProp(name = "publisher_id")
    public void setPublisherId(FrameLayout view, String publisher_id) {
        this.publisher_id = publisher_id;
    }

    /**
     * Replace your React Native view with a custom fragment
     */
    public void createFragment(FrameLayout root, int reactNativeViewId) {

        Log.e("MediumRectangle", "CRAETETETT FRAGMEENTNETETTE fragment" + Integer.toString(reactNativeViewId));

        ViewGroup parentView = (ViewGroup) root.findViewById(reactNativeViewId);
        setupLayout(parentView);

        final MyFragment myFragment = new MyFragment(reactNativeViewId, this.reactContext, this.zone_id, publisher_id);
        FragmentActivity activity = (FragmentActivity) reactContext.getCurrentActivity();
        activity.getSupportFragmentManager()
            .beginTransaction()
            .replace(reactNativeViewId, myFragment, String.valueOf(reactNativeViewId))
            .commit();

        FragmentManager fragmentManager = activity.getSupportFragmentManager();
        MyFragment fragment = (MyFragment) fragmentManager.findFragmentById(reactNativeViewId);
        if (fragment ==  null) {
            Log.e("MediumRectangle", "existetet viwewe");
        }else {
            Log.e("MediumRectangle", "no existete view");
        }
    }

    public void setupLayout(View view) {
        Choreographer.getInstance().postFrameCallback(new Choreographer.FrameCallback() {
            @Override
            public void doFrame(long frameTimeNanos) {
                manuallyLayoutChildren(view);
                view.getViewTreeObserver().dispatchOnGlobalLayout();
                Choreographer.getInstance().postFrameCallback(this);
            }
        });
    }

    /**
     * Layout all children properly
     */
    public void manuallyLayoutChildren(View view) {
        // propWidth and propHeight coming from react-native props
        int width = propWidth;
        int height = propHeight;

        view.measure(
                View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));

        view.layout(0, 0, width, height);
    }
}

</code>```
```<code>// class of my fragment

public class MyFragment extends Fragment {

    CustomView customView;

    int viewID;
    ReactApplicationContext reactContext;
    String zone_id;
    String publisher_id;

    protected int getContentViewLayoutId() { return R.layout.activity_display_ad_test; }
    protected int getAdContainerLayoutId() { return R.id.engage_ad; }

    public MyFragment(int reactNativeViewId, ReactApplicationContext reactContext, String zone_id, String publisher_id) {
        this.viewID = reactNativeViewId;
        this.reactContext = reactContext;
        this.zone_id = zone_id;
        this.publisher_id = publisher_id;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        super.onCreateView(inflater, parent, savedInstanceState);
        customView = new CustomView(this.getContext(), this.reactContext, this.publisher_id);
        return customView; // this CustomView could be any view that you want to render
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // do any logic that should happen in an `onCreate` method, e.g:
        //customView.onCreate(savedInstanceState);
    }

    @Override
    public void onPause() {
        super.onPause();
        // do any logic that should happen in an `onPause` method
        // e.g.: customView.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        // do any logic that should happen in an `onResume` method
        // e.g.: customView.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // do any logic that should happen in an `onDestroy` method
        // e.g.: customView.onDestroy();
    }

}
</code>```

and this is the custom view that will appear in the fragment:

```<code>
public class CustomView extends FrameLayout implements AdExecutor.AdLoadCallback, IMAdEngage.AdEventCallback {

    private IMAdSdk sdk_;
    private ReactApplicationContext context;
    private EngageAd banner;
    private ViewGroup container;
    private String zone_id;

    protected int getContentViewLayoutId() { return R.layout.activity_display_ad_test; }
    protected int getAdContainerLayoutId() { return R.id.engage_ad; }

    public CustomView(@NonNull Context context, ReactApplicationContext reactContext, String publisher_id) {

        super(context);

        // set padding and background color
        this.setPadding(16,16,16,16);
        this.setBackgroundColor(Color.parseColor("#5FD3F3"));

        // add default text view
        TextView text = new TextView(context);
        text.setText("Welcome to Android Fragments with React Native.");
        this.addView(text);

     }
}
</code>```

in javascript side i just do:

```<code>import React, { useEffect, useState, useRef } from "react";
import { requireNativeComponent, PixelRatio, UIManager, findNodeHandle, Dimensions, View } from 'react-native';

const MyViewManager = requireNativeComponent('MyViewManager');

const Innity = () => {

  const AD_HEIGHT = PixelRatio.getPixelSizeForLayoutSize(250);
  const AD_WIDTH = PixelRatio.getPixelSizeForLayoutSize(Dimensions.get("window").width);

  const ref = useRef(null);
  const id_ref = useRef(null);
  const [id, setID] = useState(null);

  useEffect(() => {
    create();
  }, []);

  const create = () => {
    const viewId = findNodeHandle(ref.current);
      UIManager.dispatchViewManagerCommand(
        viewId,
        // we are calling the 'create' command
        UIManager.MyViewManager.Commands.create.toString(),
        [viewId],
      );
    }
  }

  return (
    <View
      style = {{
        height: 250,
        backgroundColor: "transparent"
      }}
    >
      <MyViewManager
        style={{
            height: AD_HEIGHT,
            width: AD_WIDTH
        }}
        zone_id = {"medium_rectangle"}
        publisher_id = {"5613"}
        ref={ref}
      >
      </MyViewManager>
    </View>
  );
}

export default Innity;
</code>```

in works in the first render, but like i said when navigation to a new screen and trying to create new instance the error comes out, it has something to do with fragment in android but im newbiew with android studio so dont what to do, searched and tried everything

Body:
building native views in android side so can use it in react-native, problem is that in the first render i can create many instance i want, but when navigating to a new screen and using the same component to create the same native view i get this error:

  java.lang.IllegalArgumentException: No view found for id 0x93c3 (unknown) for fragment MyFragment{4660a7b} (1fddb7f4-9894-4da7-a39c-ae82aadfd9aa id=0x93c3 tag=37827)

im following the same example as the docs: https://reactnative.dev/docs/native-components-android#integration-with-an-android-fragment-example just changing its value for mine, but still getting the error.

in android side i have this:

//class where i create my fragment

public class MyViewManager extends ViewGroupManager<FrameLayout> {

    public static final String REACT_CLASS = "MyViewManager";
    public final int COMMAND_CREATE = 1;
    private int propWidth;
    private int propHeight;
    private int old_value = 0;
    protected String zone_id;
    private String publisher_id;
    FragmentManager fragmet;
    private ReactApplicationContext reactContext;

    public MyViewManager(ReactApplicationContext reactContext) {
        this.reactContext = reactContext;
    }

    @Override
    public String getName() {
        return REACT_CLASS;
    }

    /**
     * Return a FrameLayout which will later hold the Fragment
     */
    @Override
    public FrameLayout createViewInstance(ThemedReactContext reactContext) {
        return new FrameLayout(reactContext);
    }

    /**
     * Map the "create" command to an integer
     */
    @Nullable
    @Override
    public Map<String, Integer> getCommandsMap() {
        return MapBuilder.of("create", COMMAND_CREATE);
    }

    /**
     * Handle "create" command (called from JS) and call createFragment method
     */
    @Override
    public void receiveCommand(
            @NonNull FrameLayout root,
            String commandId,
            @Nullable ReadableArray args
    ) {
        super.receiveCommand(root, commandId, args);
        int reactNativeViewId = args.getInt(0);
        int commandIdInt = Integer.parseInt(commandId);
        this.old_value = reactNativeViewId;

        switch (commandIdInt) {
            case COMMAND_CREATE:
                Log.e("MediumRectangle", "EJECUTAMOS AQUQUIQ" + Integer.toString(reactNativeViewId));
                createFragment(root, reactNativeViewId);
                break;
            default: {}
        }
    }

    @ReactPropGroup(names = {"width", "height", "backgroundColor"}, customType = "Style")
    public void setStyle(FrameLayout view, int index, Integer value) {
        if (index == 0) {
            propWidth = value;
        }

        if (index == 1) {
            propHeight = value;
        }
    }

    @ReactProp(name = "zone_id")
    public void setAdType(FrameLayout view, String zone_id) {
        this.zone_id = zone_id;
    }

    @ReactProp(name = "publisher_id")
    public void setPublisherId(FrameLayout view, String publisher_id) {
        this.publisher_id = publisher_id;
    }

    /**
     * Replace your React Native view with a custom fragment
     */
    public void createFragment(FrameLayout root, int reactNativeViewId) {

        Log.e("MediumRectangle", "CRAETETETT FRAGMEENTNETETTE fragment" + Integer.toString(reactNativeViewId));

        ViewGroup parentView = (ViewGroup) root.findViewById(reactNativeViewId);
        setupLayout(parentView);

        final MyFragment myFragment = new MyFragment(reactNativeViewId, this.reactContext, this.zone_id, publisher_id);
        FragmentActivity activity = (FragmentActivity) reactContext.getCurrentActivity();
        activity.getSupportFragmentManager()
            .beginTransaction()
            .replace(reactNativeViewId, myFragment, String.valueOf(reactNativeViewId))
            .commit();

        FragmentManager fragmentManager = activity.getSupportFragmentManager();
        MyFragment fragment = (MyFragment) fragmentManager.findFragmentById(reactNativeViewId);
        if (fragment ==  null) {
            Log.e("MediumRectangle", "existetet viwewe");
        }else {
            Log.e("MediumRectangle", "no existete view");
        }
    }

    public void setupLayout(View view) {
        Choreographer.getInstance().postFrameCallback(new Choreographer.FrameCallback() {
            @Override
            public void doFrame(long frameTimeNanos) {
                manuallyLayoutChildren(view);
                view.getViewTreeObserver().dispatchOnGlobalLayout();
                Choreographer.getInstance().postFrameCallback(this);
            }
        });
    }

    /**
     * Layout all children properly
     */
    public void manuallyLayoutChildren(View view) {
        // propWidth and propHeight coming from react-native props
        int width = propWidth;
        int height = propHeight;

        view.measure(
                View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY));

        view.layout(0, 0, width, height);
    }
}

// class of my fragment

public class MyFragment extends Fragment {

    CustomView customView;

    int viewID;
    ReactApplicationContext reactContext;
    String zone_id;
    String publisher_id;

    protected int getContentViewLayoutId() { return R.layout.activity_display_ad_test; }
    protected int getAdContainerLayoutId() { return R.id.engage_ad; }

    public MyFragment(int reactNativeViewId, ReactApplicationContext reactContext, String zone_id, String publisher_id) {
        this.viewID = reactNativeViewId;
        this.reactContext = reactContext;
        this.zone_id = zone_id;
        this.publisher_id = publisher_id;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        super.onCreateView(inflater, parent, savedInstanceState);
        customView = new CustomView(this.getContext(), this.reactContext, this.publisher_id);
        return customView; // this CustomView could be any view that you want to render
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // do any logic that should happen in an `onCreate` method, e.g:
        //customView.onCreate(savedInstanceState);
    }

    @Override
    public void onPause() {
        super.onPause();
        // do any logic that should happen in an `onPause` method
        // e.g.: customView.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        // do any logic that should happen in an `onResume` method
        // e.g.: customView.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // do any logic that should happen in an `onDestroy` method
        // e.g.: customView.onDestroy();
    }

}

and this is the custom view that will appear in the fragment:

public class CustomView extends FrameLayout implements AdExecutor.AdLoadCallback, IMAdEngage.AdEventCallback {

    private IMAdSdk sdk_;
    private ReactApplicationContext context;
    private EngageAd banner;
    private ViewGroup container;
    private String zone_id;

    protected int getContentViewLayoutId() { return R.layout.activity_display_ad_test; }
    protected int getAdContainerLayoutId() { return R.id.engage_ad; }

    public CustomView(@NonNull Context context, ReactApplicationContext reactContext, String publisher_id) {

        super(context);

        // set padding and background color
        this.setPadding(16,16,16,16);
        this.setBackgroundColor(Color.parseColor("#5FD3F3"));

        // add default text view
        TextView text = new TextView(context);
        text.setText("Welcome to Android Fragments with React Native.");
        this.addView(text);

     }
}

in javascript side i just do:

import React, { useEffect, useState, useRef } from "react";
import { requireNativeComponent, PixelRatio, UIManager, findNodeHandle, Dimensions, View } from 'react-native';

const MyViewManager = requireNativeComponent('MyViewManager');

const Innity = () => {

  const AD_HEIGHT = PixelRatio.getPixelSizeForLayoutSize(250);
  const AD_WIDTH = PixelRatio.getPixelSizeForLayoutSize(Dimensions.get("window").width);

  const ref = useRef(null);
  const id_ref = useRef(null);
  const [id, setID] = useState(null);

  useEffect(() => {
    create();
  }, []);

  const create = () => {
    const viewId = findNodeHandle(ref.current);
      UIManager.dispatchViewManagerCommand(
        viewId,
        // we are calling the 'create' command
        UIManager.MyViewManager.Commands.create.toString(),
        [viewId],
      );
    }
  }

  return (
    <View
      style = {{
        height: 250,
        backgroundColor: "transparent"
      }}
    >
      <MyViewManager
        style={{
            height: AD_HEIGHT,
            width: AD_WIDTH
        }}
        zone_id = {"medium_rectangle"}
        publisher_id = {"5613"}
        ref={ref}
      >
      </MyViewManager>
    </View>
  );
}

export default Innity;

in works in the first render, but like i said when navigation to a new screen and trying to create new instance the error comes out, it has something to do with fragment in android but im newbiew with android studio so dont what to do, searched and tried everything


问:
After changing the server to Vercel instead of Heroku. It's can't find data and gives me parse error,
This is the error: VM204:1 Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

This is where I'm getting the error:

```<code>const useBooks = () => {
const [books, setBooks] = useState([]);

useEffect(() => {
    fetch('https:xyz.vercel.app/book')
        .then(res => res.json())
        .then(data => setBooks(data))
}, [])
return [books, setBooks];
</code>```

}
export default useBooks;

Backend code:

```<code> //API for getting all data.
    app.get('/book', async (req, res) => {
        const query = {};
        const cursor = bookCollections.find(query);
        const result = await cursor.toArray();
        res.send(result);
    })
</code>```

Response is 404 not found. and it gives HTML instead of json. How can I fix it? This is postman response Screenshort

Body:
This is the error: VM204:1 Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

This is where I'm getting the error:

const useBooks = () => {
const [books, setBooks] = useState([]);

useEffect(() => {
    fetch('https:xyz.vercel.app/book')
        .then(res => res.json())
        .then(data => setBooks(data))
}, [])
return [books, setBooks];

}
export default useBooks;

Backend code:

 //API for getting all data.
    app.get('/book', async (req, res) => {
        const query = {};
        const cursor = bookCollections.find(query);
        const result = await cursor.toArray();
        res.send(result);
    })

Response is 404 not found. and it gives HTML instead of json. How can I fix it? This is postman response Screenshort


问:
Want the website to wait for until Youtube embedded gets fetched
I have a react app where I want to showcase many youtube videos, what I did was to create an array of youtube embed links and map them inside a div. Now the problem is, they load very slowly Is there any way we can load them faster? or can we check something like "areVideosFetched" if it returns true only show otherwise show a lottie(or maybe just show the thumbnail of the video).

This is how i am currently displaying the videos:

```<code><div className={styles.col} id="reel-block">
   <div className={styles.reelsContainer}>
      {youtubeShortsUrlList.map((short, key) => (
        <Reels
          key={i}
          url={list.url}
           isMobileView={false}
        />
   </div>
</div>
</code>```

and this is the reels component:

```<code>const reelRef = useRef();
    useEffect(() => {
        const scroll = document.getElementById("reel-block");
        if (scroll) {
            scroll.addEventListener("scroll", () => {
                reelRef.current.contentWindow.postMessage(
                    '{"event":"command", "func":"stopVideo", "args":""}',
                    "*",
                );
            });
        }
    }, []);
    return (
        <div className={styles.videoReel}>
            <iframe
                ref={reelRef}
                id={props.url}
                loading="lazy"
                className={`${
                    props.isMobileView
                        ? styles.playerMobile
                        : styles.videoPlayer
                }`}
                src={`https://www.youtube.com/embed/${props.url}?autplay=1&loop=1&controls=1&&enablejsapi=1&disablekb=1&&playsinline=1&color=red&showinfo=0&modestbranding=1&rel=0`}
                allow="accelerometer;clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            ></iframe>
        </div>
    );
</code>```

Body:
I have a react app where I want to showcase many youtube videos, what I did was to create an array of youtube embed links and map them inside a div. Now the problem is, they load very slowly Is there any way we can load them faster? or can we check something like "areVideosFetched" if it returns true only show otherwise show a lottie(or maybe just show the thumbnail of the video).

This is how i am currently displaying the videos:

      {youtubeShortsUrlList.map((short, key) => (
        <Reels
          key={i}
          url={list.url}
           isMobileView={false}
        />

and this is the reels component:

const reelRef = useRef();
    useEffect(() => {
        const scroll = document.getElementById("reel-block");
        if (scroll) {
            scroll.addEventListener("scroll", () => {
                reelRef.current.contentWindow.postMessage(
                    '{"event":"command", "func":"stopVideo", "args":""}',
                    "*",
                );
            });
        }
    }, []);
    return (

            <iframe
                ref={reelRef}
                id={props.url}
                loading="lazy"
                className={`${
                    props.isMobileView
                        ? styles.playerMobile
                        : styles.videoPlayer
                }`}
                src={`https://www.youtube.com/embed/${props.url}?autplay=1&loop=1&controls=1&&enablejsapi=1&disablekb=1&&playsinline=1&color=red&showinfo=0&modestbranding=1&rel=0`}
                allow="accelerometer;clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            >

    );


问:
Map ElasticSearch JSON keys to Array
We imported datas from mongodb, and we want to use those datas to create a dashboard. datas are like:

```<code>permissions:{
  "stock":"write",
  "product":"write",
  "bill":"read",
}
</code>```

How can I get the write permission list: ["stock","product"]

in elastic search:

filed:

```<code>permissions.stock: write
permissions.product: write
permissions.bill: write
</code>```

Title: Map ElasticSearch JSON keys to Array

Body:
We imported datas from mongodb, and we want to use those datas to create a dashboard. datas are like:

permissions:{
  "stock":"write",
  "product":"write",
  "bill":"read",
}

How can I get the write permission list: ["stock","product"]

in elastic search:

filed:

permissions.stock: write
permissions.product: write
permissions.bill: write


问:
I am trying to run wmic command for running commands from one computer to another
I am trying to run following command,
wmic /node:amarpc /user:admin /password:myadmin process call create 'cmd.exe /c "tnsping compote"'

But I faced problem of
Access denied

I tried many ways to resolve but can't get solution


问:
deleting and restoring node_modules in ~/.config/yarn/global directory
I am using a mac, where I have installed a number of global tools with yarn (e.g. yarn global add <tool>. I am running into an obscure bug with one of them and I have a hunch that it is something to do with the node_modules directory located at ~/.config/yarn/global directory. For testing purposes I want to try and delete the node_modules directory under global, and then try restoring it (in a normal node project using yarn I would run yarn and yarn build after deleting the node_modules directory but here yarn build don't work as there is no package.json). Does anyone know how I can properly restore the node_modules located at ~/.config/yarn/global directory after deleting it?


问:
How to detect face from rendered video with Arcore AugmentedFace?(android)
I'm android developer.

According to this guide, https://developers.google.com/ar/develop/java/augmented-faces/developer-guide

```<code>// Set a camera configuration that usese the front-facing camera.
val filter = CameraConfigFilter(session).setFacingDirection(CameraConfig.FacingDirection.FRONT)
val cameraConfig = session.getSupportedCameraConfigs(filter)[0]
session.cameraConfig = cameraConfig
</code>```

Using OpenGL and the Arcore SDK, I was able to render and draw some objects on the face vertices where Front-facing Camera Input comes in.

Now I want to render the video and draw some objects on the face (if any) in the video frame.

I expected that rendering the video and putting the textureId of rendered-video in the arcore session would work, but it didn't...

==current situation

I got rendered video on GLSurfaceView, and arcore is still drawing objects on front-facing camera input.

This guide only explains how to set front-facing camera...
I wonder if there is any way to detect face using arcore on a video or image.
Thanks for reading.

Body:
I'm android developer.

According to this guide, https://developers.google.com/ar/develop/java/augmented-faces/developer-guide

// Set a camera configuration that usese the front-facing camera.
val filter = CameraConfigFilter(session).setFacingDirection(CameraConfig.FacingDirection.FRONT)
val cameraConfig = session.getSupportedCameraConfigs(filter)[0]
session.cameraConfig = cameraConfig

Using OpenGL and the Arcore SDK, I was able to render and draw some objects on the face vertices where Front-facing Camera Input comes in.

Now I want to render the video and draw some objects on the face (if any) in the video frame.

I expected that rendering the video and putting the textureId of rendered-video in the arcore session would work, but it didn't...

==current situation

I got rendered video on GLSurfaceView, and arcore is still drawing objects on front-facing camera input.

This guide only explains how to set front-facing camera...
I wonder if there is any way to detect face using arcore on a video or image.
Thanks for reading.


问:
how to pass boolean as props
I'm trying to implement skeleton on my components, I'm using boolean to set if the components are loaded completely or not

Post.jsx (I guess here where the skeleton should show)

```<code>import Skeleton, { SkeletonTheme } from 'react-loading-skeleton'
import 'react-loading-skeleton/dist/skeleton.css'
import styled from 'styled-components'

export default function Post({ post, isPostsLoading }) {
  moment.locale('ar');
  const daysAgo = moment(post.createdAt);

  const rowSkeletons = 6
  const GalleryStyles = styled.div`
    .gallery__grid {
        display: grid;
        gap: 2rem;
        grid-auto-flow: dense;
        grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr));
        justify-content: center;
    }
    .gallery__title {
        font-size: 2rem;
        padding: 1rem;
        text-align: center;
    }`
  if (isPostsLoading) {
    let rows = []
    for (let index = 0; index < rowSkeletons; index++) {
        rows.push(
            <section>
                <article className='item'>
                    <div className='item-img'>
                        <Skeleton width={140} height={140} />
                    </div>
                    <h3 className='item-title'><Skeleton count={4} /></h3>
                    <div className='item-info'>
                        <Skeleton width={160} height={20} />
                        <Skeleton width={30} height={20} />
                        <Skeleton width={22} height={22} circle={true} />
                    </div>
                    <Skeleton height={48} count={2} className='skeleton' />
                </article>
            </section>
        )
    }
    return (
        <SkeletonTheme color='#F5F5F5' highlightColor='#ffffff'>
            <GalleryStyles className='gallery__grid'>
                <h2 className='gallery__title'><Skeleton /></h2>
                <div className='gallery__grid'>
                    {rows}
                </div>
            </GalleryStyles>
        </SkeletonTheme>
    )
}
  return (
    <div className="post">
        <div>
        {post.photo && (
        <Link to={`/post/${post._id}`} className="link">
        <img
        className="postImg"
        src={post.photo}
        alt=""
        />
        </Link>
        )}
        </div>
      <div className="postInfo">
        <Link to={`/post/${post._id}`}
            className="link">
            <span className="postTitle">
              {post.title}
            </span>
        </Link>
        <div>
            <p dir="auto" className="postDesc">
              {post.content}
            </p>
        </div>
            <span className="postDate">
              {daysAgo.fromNow()}
            </span>
        </div>
      </div>
    </div>
  );
}
</code>```

I want each div shows a skeleton till i'ts fully loaded.

Posts.jsx (Here where an array of posts are showing)

```<code>import SearchIcon from '@mui/icons-material/Search';
import CircularProgress from '@mui/material/CircularProgress';

export default function Posts({ posts = [], isPostsLoading}) {
    const [filteredResults, setFilteredResults] = useState([]);
    const [searchInput, setSearchInput] = useState('');
    const [isLoading, setIsLoading] = useState(false);
// HERE isLoading is for search loading
    const filter = (e) => {
      const keyword = e.target.value;
        if (keyword !== '') {
            const filteredData = posts.filter((post) => {
                return Object.values(post)
                .join('')
                .toLowerCase()
                .includes(searchInput.toLowerCase())
            })
            setFilteredResults(filteredData)
        } else {
          setFilteredResults(posts)
        }
        setSearchInput(keyword);
    }
  return (
    <div className="posts">
      <div className="postsContainer">
      <div className="postsSearchContainer">
            <div className="postsSearch">
                  <div class="postsSearchIconContainer">
                      <SearchIcon class="w-5 h-5" />
                  </div>
                    <input type="text"
                    className="postsSearchInput"
                    placeholder=“search”
                    name="postsSearchText"
                    id="postsSearchText"
                    onChange={filter}
                    />
              </div>
              {/* ENDS OF POSTSSEARCHCONTAINER */}
      </div>
      {/* ENDS OF POSTSSEARCH */}
    <div className="postsBoxContainer">
      <div className="postsBox">
      {isLoading ? (
          <Box sx={{ display: 'flex' }}>
            <CircularProgress />
          </Box>
      ) : (
        filteredResults.length > 0 ? (
          filteredResults.map((filteredPosts) => (
            <Post post={filteredPosts} />
          ))
          ) : (posts.map((post) => (
            <Post isPostsLoading={isPostsLoading} post={post} />
          )) )
        )
        }
      </div>
      </div>
      {/* ENDS OF POSTSBOX */}
      </div>
      {/* ENDS OF POSTCONTAINER */}
    </div>
    //ENDS OF POSTS

  );
};
</code>```

AllPosts.jsx (Here Where I'm using the api to fetch all the posts and using the boolean to know if it's loaded or not)

```<code>export default function AllPosts() {
  const [posts, setPosts] = useState([]);
  const { search } = useLocation();
  const [isPostsLoading, setIsPostsLoading] = useState(true);

  useEffect(() => {
    const fetchPosts = async () => {
      const res = await axios.get("/posts" + search);
      setPosts(res.data);
      setIsPostsLoading(false);
    };
    fetchPosts();
  }, [search]);

  return (
    <>
      <div className="posts">
        {/* <Header /> */}
        <div className="header">
        <div className="headerTitle">
            <span className="headerTitleLg">المقالات</span>
        </div>
        </div>
        <div className="postsContent">
        <Posts posts={posts} />
        </div>
      </div>
    </>
  );
}
</code>```

The question is how to pass booleans as props to the other components

Title: how to pass boolean as props

Body:
I'm trying to implement skeleton on my components, I'm using boolean to set if the components are loaded completely or not

Post.jsx (I guess here where the skeleton should show)

import Skeleton, { SkeletonTheme } from 'react-loading-skeleton'
import 'react-loading-skeleton/dist/skeleton.css'
import styled from 'styled-components'

export default function Post({ post, isPostsLoading }) {
  moment.locale('ar');
  const daysAgo = moment(post.createdAt);

  const rowSkeletons = 6
  const GalleryStyles = styled.div`
    .gallery__grid {
        display: grid;
        gap: 2rem;
        grid-auto-flow: dense;
        grid-template-columns: repeat(auto-fit, minmax(min(100%, 260px), 1fr));
        justify-content: center;
    }
    .gallery__title {
        font-size: 2rem;
        padding: 1rem;
        text-align: center;
    }`
  if (isPostsLoading) {
    let rows = []
    for (let index = 0; index < rowSkeletons; index++) {
        rows.push(

                        <Skeleton width={140} height={140} />

<Skeleton count={4} />

                        <Skeleton width={160} height={20} />
                        <Skeleton width={30} height={20} />
                        <Skeleton width={22} height={22} circle={true} />

                    <Skeleton height={48} count={2} className='skeleton' />

        )
    }
    return (
        <SkeletonTheme color='#F5F5F5' highlightColor='#ffffff'>
            <GalleryStyles className='gallery__grid'>

<Skeleton />

                    {rows}

            </GalleryStyles>
        </SkeletonTheme>
    )
}
  return (

        {post.photo && (
        <Link to={`/post/${post._id}`} className="link">

        </Link>
        )}

        <Link to={`/post/${post._id}`}
            className="link">

              {post.title}

        </Link>

              {post.content}

              {daysAgo.fromNow()}

  );
}

I want each div shows a skeleton till i'ts fully loaded.

Posts.jsx (Here where an array of posts are showing)

import SearchIcon from '@mui/icons-material/Search';
import CircularProgress from '@mui/material/CircularProgress';

export default function Posts({ posts = [], isPostsLoading}) {
    const [filteredResults, setFilteredResults] = useState([]);
    const [searchInput, setSearchInput] = useState('');
    const [isLoading, setIsLoading] = useState(false);
// HERE isLoading is for search loading
    const filter = (e) => {
      const keyword = e.target.value;
        if (keyword !== '') {
            const filteredData = posts.filter((post) => {
                return Object.values(post)
                .join('')
                .toLowerCase()
                .includes(searchInput.toLowerCase())
            })
            setFilteredResults(filteredData)
        } else {
          setFilteredResults(posts)
        }
        setSearchInput(keyword);
    }
  return (

                      <SearchIcon class="w-5 h-5" />

                    <input type="text"
                    className="postsSearchInput"
                    placeholder=“search”
                    name="postsSearchText"
                    id="postsSearchText"
                    onChange={filter}
                    />

              {/* ENDS OF POSTSSEARCHCONTAINER */}

      {/* ENDS OF POSTSSEARCH */}

      {isLoading ? (
          <Box sx={{ display: 'flex' }}>
            <CircularProgress />
          </Box>
      ) : (
        filteredResults.length > 0 ? (
          filteredResults.map((filteredPosts) => (
            <Post post={filteredPosts} />
          ))
          ) : (posts.map((post) => (
            <Post isPostsLoading={isPostsLoading} post={post} />
          )) )
        )
        }

      {/* ENDS OF POSTSBOX */}

      {/* ENDS OF POSTCONTAINER */}

    //ENDS OF POSTS

  );
};

AllPosts.jsx (Here Where I'm using the api to fetch all the posts and using the boolean to know if it's loaded or not)

export default function AllPosts() {
  const [posts, setPosts] = useState([]);
  const { search } = useLocation();
  const [isPostsLoading, setIsPostsLoading] = useState(true);

  useEffect(() => {
    const fetchPosts = async () => {
      const res = await axios.get("/posts" + search);
      setPosts(res.data);
      setIsPostsLoading(false);
    };
    fetchPosts();
  }, [search]);

  return (
    <>

        {/*  */}

            المقالات

        <Posts posts={posts} />

    </>
  );
}

The question is how to pass booleans as props to the other components


问:
Remove Last few charcters from a vriable in info.plist of xcode
I am using flutter to develop an ios and android app. and I use "$(FLUTTER_BUILD_NAME)$(FLUTTER_BUILD_NUMBER)"; to set the version name of the app.
As I use fastlane to automate the build version updates and want the version to show the build number.

Flutter requires  version number to be of this format version: 3.2.0+6007 I have to use here the x.y.z+buildnumber. I want my app to have x.y.buildnumber as its version.

In android gradle I have achieved this as follows. I remove the last charcter of the version name and append version code

```<code>def flutterVersionCode = localProperties.getProperty('flutter.versionCode')

def flutterVersionName = localProperties.getProperty('flutter.versionName')
flutterVersionName=flutterVersionName.substring(0, flutterVersionName.length() - 1)+flutterVersionCode
</code>```

In iOS I want to acheive the same. Currently I cab do it as this "$(FLUTTER_BUILD_NAME)$(FLUTTER_BUILD_NUMBER)"; which will make it x.y.z.buildnumber. How can i remove one last char from the $(FLUTTER_BUILD_NAME) in info.plist

Body:
I am using flutter to develop an ios and android app. and I use "$(FLUTTER_BUILD_NAME)$(FLUTTER_BUILD_NUMBER)"; to set the version name of the app.
As I use fastlane to automate the build version updates and want the version to show the build number.

Flutter requires  version number to be of this format version: 3.2.0+6007 I have to use here the x.y.z+buildnumber. I want my app to have x.y.buildnumber as its version.

In android gradle I have achieved this as follows. I remove the last charcter of the version name and append version code

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')

def flutterVersionName = localProperties.getProperty('flutter.versionName')
flutterVersionName=flutterVersionName.substring(0, flutterVersionName.length() - 1)+flutterVersionCode

In iOS I want to acheive the same. Currently I cab do it as this "$(FLUTTER_BUILD_NAME)$(FLUTTER_BUILD_NUMBER)"; which will make it x.y.z.buildnumber. How can i remove one last char from the $(FLUTTER_BUILD_NAME) in info.plist


问:
WP CRON job not firing callback function, but function is working when called from elsewhere

The problem

I'm making a plugin. I have a function which goal is to loop throught every post of a given post_type, and store a given metafield value in a different table, along with the ID of the post and the date of the day. To give you some context, it's to keep tracks of products prices.
The function works perfectly when called "manually" with the admin_menu hook, I got my table populated with all the data.
Now I want this function to run once every day so I set up a CRON JOB with wp_schedule_events. WP controls shows the schedule CRON JOB, but the callback function is never executed, and there's no errors, no log whatsoever :/

The Code

The way I scheduled the CRON JOB

```<code>function schedule_price_curve_update( $args ) {
    if ( ! wp_next_scheduled( 'update_product_price_curve') ) {
        $time=time();
        $time=$time+60;
        wp_schedule_event($time, 'daily', 'update_product_price_curve', $args );
    }
}
</code>```

My callback function to insert data to the dedicated table, and the hook for the CRON Job.

```<code>function bulk_update_product_price_curve( $setup_table_name) {
    $args = array(
        'post_type' => 'bons-plans',
        'posts_per_page' => -1,
        'post_status' => 'publish',
    );
    $posts_array = get_posts( $args );

    global $wpdb;
    $table_name = $wpdb->prefix . $setup_table_name;
    $date = date('Y/d/m');

    foreach( $posts_array as $post_array ){
        $price = get_post_meta( $post_array->ID, 'prix-promo', true);
        $wpdb->insert($table_name, array('product_id' => $post_array->ID, 'date' => $date, 'product_price' => $price));;
    }

}

add_action( 'update_product_price_curve', 'bulk_update_product_price_curve' );
</code>```

The $table_name will be setup by user in the admin setting page of the plugin. As of now I set the $arg of the schedule_price_curve_update( $args ) manually. No probleme on this part. Again, WP Control assure me the job is scheduled with the right arguments.

If anyone have any idea of why my callback function is not firing ? That's kind of frustrating as there's no error or nothing to give me any hint on why this isn't working... So there's also that : how can I debug this ?

Body:
The problem

I'm making a plugin. I have a function which goal is to loop throught every post of a given post_type, and store a given metafield value in a different table, along with the ID of the post and the date of the day. To give you some context, it's to keep tracks of products prices.
The function works perfectly when called "manually" with the admin_menu hook, I got my table populated with all the data.
Now I want this function to run once every day so I set up a CRON JOB with wp_schedule_events. WP controls shows the schedule CRON JOB, but the callback function is never executed, and there's no errors, no log whatsoever :/

The Code

The way I scheduled the CRON JOB

function schedule_price_curve_update( $args ) {
    if ( ! wp_next_scheduled( 'update_product_price_curve') ) {
        $time=time();
        $time=$time+60;
        wp_schedule_event($time, 'daily', 'update_product_price_curve', $args );
    }
}

My callback function to insert data to the dedicated table, and the hook for the CRON Job.

function bulk_update_product_price_curve( $setup_table_name) {
    $args = array(
        'post_type' => 'bons-plans',
        'posts_per_page' => -1,
        'post_status' => 'publish',
    );
    $posts_array = get_posts( $args );

    global $wpdb;
    $table_name = $wpdb->prefix . $setup_table_name;
    $date = date('Y/d/m');

    foreach( $posts_array as $post_array ){
        $price = get_post_meta( $post_array->ID, 'prix-promo', true);
        $wpdb->insert($table_name, array('product_id' => $post_array->ID, 'date' => $date, 'product_price' => $price));;
    }

}

add_action( 'update_product_price_curve', 'bulk_update_product_price_curve' );

The $table_name will be setup by user in the admin setting page of the plugin. As of now I set the $arg of the schedule_price_curve_update( $args ) manually. No probleme on this part. Again, WP Control assure me the job is scheduled with the right arguments.

If anyone have any idea of why my callback function is not firing ? That's kind of frustrating as there's no error or nothing to give me any hint on why this isn't working... So there's also that : how can I debug this ?


问:
Trying to install Android SDK 31 and NDK 25 for Delphi 10.4 - what to provide in Delphi SDK manager wizards?
I have Delphi 10.4 with default Android SDK 25 installation (located C:\Users\Public\Documents\Embarcadero\Studio\21.0\CatalogRepository\AndroidSDK-2525-21.0.38860.1461) and Andoird NDK 21 installation (located C:\Users\Public\Documents\Embarcadero\Studio\21.0\CatalogRepository\AndroidNDK-21-21.0.38860.1461\android-ndk-r21). One should take into account, that SDK and NDK locations are Delphi version specific and there is no indication that they are placed inside some special SDK or NDK roots.

As of 2022.12 Google Play requires all new Android apps to have Android SDK 31 targeting and that means that I should install Android SDK 31/NDK 25 on my computer and do integration inside Delphi 10.4 IDE.

I had to do manual SDK install. I have choosen D:\PlatformSDKs\android-sdk-windows as my sdk_root. I downloaded cmdline-tools from https://developer.android.com/studio "Command line tools only", unzipped and ran the installation command:

```<code>D:\cmdline-tools\bin>sdkmanager --sdk_root="D:\PlatformSDKs\android-sdk-windows"  "build-tools;33.0.1" "extras;google;usb_driver" "platforms;android-31" "tools"
</code>```

It completed successfully. I went to https://github.com/android/ndk/wiki and downloaded android-ndk-r25b-windows.zip and unzipped as directory D:\PlatformSDKs\android-ndk-r25b.

After this I tried to integrate my SDK 31/NDK 25 as new target platform inside Delphi 10.4. IDE - there is wizard with multiple steps/forms for it.

But 2 forms from this wizard required me to provide specific directories/exe files from my new installations but I could not find anything resembling such artifcats inside my new installations.

There are those 2 forms:

The first problematic form required me to point to arm-linux-androideabi-ld.exe and arm-linux.androideabi-strip.exe locations but I could not find such artifacts, I just provided what I could find in my NDK installation. The following picutres show the empty paths and what I have put into them to enable furhter steps.

While I could fool the first problematic form in the wizard, the second problematic form appeared unsolvable:

It requred me to provide NDK API lcoation (e.g. NDK_BASE_PATH/platforms/android-23), but I had no platforms directory inside my D:\PlatformSDKs\android-ndk-r25b. I have no idea, why there is no such directory and how to get platforms directory with some platfrom (I guess 31 in my case)?

So - I had to abandond the SDK 31/NDK 25 integration inside my Delphi 10.4 for this time. But I am no seekd advice to to complete the integration? What other tools I have to install to fill the missing entries in Delphi 10.4 integration wizard?

Has anyone managed to install SDK 31/NDK 25 with Delphi 10.4 and what did you do?

Of course, I am aware of https://delphiworlds.com/2020/09/manual-android-sdk-ndk-install-delphi/ and http://delphi.org/2019/06/manually-installing-android-sdk-ndk-and-java-for-firemonkey-development/ but they are not mentioning that Delphi wizrd requires me to fill some entries for which there are no counterparts in SDK/NDK installation.

Maybe there are breaking changes that prohibits use of Anroid 31 from Delphi 10.4? Or maybe I can avoid using wizard for the registration and I can do the registration by manually editing Delpi keys in the Windows Registry. I guess - all the information about registered target platforms is saved inside Windows Registry?

Additional info (progress report): I followed the advice of Dalija Prasnikar and I have registered SDK 31 with the existing NDK 21. And now I am getting error message (essential content):

```<code>The command "D:\PlatformSDKs\android-sdk-windows\build-tools\33.0.1\dx.bat" --dex exited with code 9009
</code>```

Indeed, there is no dx.bat in 33 build tools and this has been observed in Exited with code 9009 when building for Android already. Of course, the suggested change of d8.bat to dx.bat failed as mentioned there too.

That is one issue with SDK 31 / build tools 33. Another issue is the set of libraries, that appears in the command line options:

```<code>PATH... & "D:\PlatformSDKs\android-sdk-windows\build-tools\33.0.1\dx.bat" --dex --output="...\classes.dex" "c:\program files (x86)\embarcadero\studio\21.0\lib\android\Release\android-support-v4.dex.jar" "c:\program files (x86)\embarcadero\studio\21.0\lib\android\Release\cloud-messaging.dex.jar" "c:\program files (x86)\embarcadero\studio\21.0\lib\android\Release\fmx.dex.jar" "c:\program files (x86)\embarcadero\studio\21.0\lib\android\Release\google-play-billing.dex.jar" "c:\program files (x86)\embarcadero\studio\21.0\lib\android\Release\google-play-licensing.dex.jar" " exited with code 9009.
</code>```

So, the automatically constructed command line takes some jars from "c:\program files (x86)\embarcadero\studio\21.0\lib\android\Release" and I am not sure whether they are or can be compatible with build tools 33.0 and SDK 31. They may be compatible, but I am not sure.

The references SO question stated, that command lines tools 30 could work, but I am not sure whether this is true for Delphi 10.4/Android 31 combination. I am considering a futher experiment.

Body:
I have Delphi 10.4 with default Android SDK 25 installation (located C:\Users\Public\Documents\Embarcadero\Studio\21.0\CatalogRepository\AndroidSDK-2525-21.0.38860.1461) and Andoird NDK 21 installation (located C:\Users\Public\Documents\Embarcadero\Studio\21.0\CatalogRepository\AndroidNDK-21-21.0.38860.1461\android-ndk-r21). One should take into account, that SDK and NDK locations are Delphi version specific and there is no indication that they are placed inside some special SDK or NDK roots.

As of 2022.12 Google Play requires all new Android apps to have Android SDK 31 targeting and that means that I should install Android SDK 31/NDK 25 on my computer and do integration inside Delphi 10.4 IDE.

I had to do manual SDK install. I have choosen D:\PlatformSDKs\android-sdk-windows as my sdk_root. I downloaded cmdline-tools from https://developer.android.com/studio "Command line tools only", unzipped and ran the installation command:

D:\cmdline-tools\bin>sdkmanager --sdk_root="D:\PlatformSDKs\android-sdk-windows"  "build-tools;33.0.1" "extras;google;usb_driver" "platforms;android-31" "tools"

It completed successfully. I went to https://github.com/android/ndk/wiki and downloaded android-ndk-r25b-windows.zip and unzipped as directory D:\PlatformSDKs\android-ndk-r25b.

After this I tried to integrate my SDK 31/NDK 25 as new target platform inside Delphi 10.4. IDE - there is wizard with multiple steps/forms for it.

But 2 forms from this wizard required me to provide specific directories/exe files from my new installations but I could not find anything resembling such artifcats inside my new installations.

There are those 2 forms:

The first problematic form required me to point to arm-linux-androideabi-ld.exe and arm-linux.androideabi-strip.exe locations but I could not find such artifacts, I just provided what I could find in my NDK installation. The following picutres show the empty paths and what I have put into them to enable furhter steps.

While I could fool the first problematic form in the wizard, the second problematic form appeared unsolvable:

It requred me to provide NDK API lcoation (e.g. NDK_BASE_PATH/platforms/android-23), but I had no platforms directory inside my D:\PlatformSDKs\android-ndk-r25b. I have no idea, why there is no such directory and how to get platforms directory with some platfrom (I guess 31 in my case)?

So - I had to abandond the SDK 31/NDK 25 integration inside my Delphi 10.4 for this time. But I am no seekd advice to to complete the integration? What other tools I have to install to fill the missing entries in Delphi 10.4 integration wizard?

Has anyone managed to install SDK 31/NDK 25 with Delphi 10.4 and what did you do?

Of course, I am aware of https://delphiworlds.com/2020/09/manual-android-sdk-ndk-install-delphi/ and http://delphi.org/2019/06/manually-installing-android-sdk-ndk-and-java-for-firemonkey-development/ but they are not mentioning that Delphi wizrd requires me to fill some entries for which there are no counterparts in SDK/NDK installation.

Maybe there are breaking changes that prohibits use of Anroid 31 from Delphi 10.4? Or maybe I can avoid using wizard for the registration and I can do the registration by manually editing Delpi keys in the Windows Registry. I guess - all the information about registered target platforms is saved inside Windows Registry?

Additional info (progress report): I followed the advice of Dalija Prasnikar and I have registered SDK 31 with the existing NDK 21. And now I am getting error message (essential content):

The command "D:\PlatformSDKs\android-sdk-windows\build-tools\33.0.1\dx.bat" --dex exited with code 9009

Indeed, there is no dx.bat in 33 build tools and this has been observed in Exited with code 9009 when building for Android already. Of course, the suggested change of d8.bat to dx.bat failed as mentioned there too.

That is one issue with SDK 31 / build tools 33. Another issue is the set of libraries, that appears in the command line options:

PATH... & "D:\PlatformSDKs\android-sdk-windows\build-tools\33.0.1\dx.bat" --dex --output="...\classes.dex" "c:\program files (x86)\embarcadero\studio\21.0\lib\android\Release\android-support-v4.dex.jar" "c:\program files (x86)\embarcadero\studio\21.0\lib\android\Release\cloud-messaging.dex.jar" "c:\program files (x86)\embarcadero\studio\21.0\lib\android\Release\fmx.dex.jar" "c:\program files (x86)\embarcadero\studio\21.0\lib\android\Release\google-play-billing.dex.jar" "c:\program files (x86)\embarcadero\studio\21.0\lib\android\Release\google-play-licensing.dex.jar" " exited with code 9009.

So, the automatically constructed command line takes some jars from "c:\program files (x86)\embarcadero\studio\21.0\lib\android\Release" and I am not sure whether they are or can be compatible with build tools 33.0 and SDK 31. They may be compatible, but I am not sure.

The references SO question stated, that command lines tools 30 could work, but I am not sure whether this is true for Delphi 10.4/Android 31 combination. I am considering a futher experiment.


问:
Set initial value for EditorController.basic() in flutter
I am using Quill fork in my flutter app for adding and formatting text. I've successfully added EditorController text in database and when I want to edit this text then it stores the initial added value again in database but not the updated one. Is there any way to set the database value as initial value for EditorController.basic and then update the value and style based on user input?

(widget.isUpdate)
  ? _editorController = widget.description
  : _editorController = EditorController.basic();
```

widget.isUpdate is used for getting the value whether to add or update value.

Body:
I am using Quill fork in my flutter app for adding and formatting text. I've successfully added EditorController text in database and when I want to edit this text then it stores the initial added value again in database but not the updated one. Is there any way to set the database value as initial value for EditorController.basic and then update the value and style based on user input?

(widget.isUpdate)
  ? _editorController = widget.description
  : _editorController = EditorController.basic();

widget.isUpdate is used for getting the value whether to add or update value.


问:
React context provider component's children not re-render?
When I try to modularize react context in my app for more re-useable,
I find that the rendering behavior is different, which confuses me.

So my question is: Why case1 won't print "inner2", but case2 will?

Below it's my code:

codesandbox-demo

I thought the situation should be the same for both, but not.

[UPDATE] Tue Dec 13 2022 12:10:56 GMT+0800

Sorry, my description is not precise enough. What I mean is printing inner2 in the console


问:
Found input variables with inconsistent numbers of samples
I'm using the naive bayes algorithm for my machine learning model and after splitting the data to train and test I added a row to the test data so I can test if it gives the right result or not and when I call the predict function everything works fine but when I call the accuracy score function an error appears Saing:  Found input variables with inconsistent numbers of samples: [41, 42]

```<code>x_train,x_test,y_train,y_test = train_test_split(x,y,test_size = 0.3, random_state = 0)
data = ['test1','test2','test3','test4','test5','test6','test7']
x_test = x_test.append(pd.DataFrame([data],index=[len(x_test)+1],columns=x_test.columns))

x_train = encoder.fit_transform(x_train)
x_test = encoder.transform(x_test)
cols =  x_train.columns
scaler = RobustScaler()
x_train = scaler.fit_transform(x_train)
x_test = scaler.fit_transform(x_test)
x_train = pd.DataFrame(x_train,columns=[cols])
x_test = pd.DataFrame(x_test,columns=[cols])

gnb = GaussianNB()
gnb.fit(x_train,y_train)
y_pred = gnb.predict(x_test)
print("Model Accuracy score:{0:0.4f}".format(accuracy_score(y_test,y_pred)))
</code>```

after the last code line, the error message appears.

Body:
I'm using the naive bayes algorithm for my machine learning model and after splitting the data to train and test I added a row to the test data so I can test if it gives the right result or not and when I call the predict function everything works fine but when I call the accuracy score function an error appears Saing:  Found input variables with inconsistent numbers of samples: [41, 42]

x_train,x_test,y_train,y_test = train_test_split(x,y,test_size = 0.3, random_state = 0)
data = ['test1','test2','test3','test4','test5','test6','test7']
x_test = x_test.append(pd.DataFrame([data],index=[len(x_test)+1],columns=x_test.columns))

x_train = encoder.fit_transform(x_train)
x_test = encoder.transform(x_test)
cols =  x_train.columns
scaler = RobustScaler()
x_train = scaler.fit_transform(x_train)
x_test = scaler.fit_transform(x_test)
x_train = pd.DataFrame(x_train,columns=[cols])
x_test = pd.DataFrame(x_test,columns=[cols])

gnb = GaussianNB()
gnb.fit(x_train,y_train)
y_pred = gnb.predict(x_test)
print("Model Accuracy score:{0:0.4f}".format(accuracy_score(y_test,y_pred)))

after the last code line, the error message appears.


问:
Github Pages deploy fails to load local @font-face
I have a small Next.js app that uses a local @font-face. Everything works fine in the dev environment.

The font .woff file is stored in /public/webfonts. The @font-face import is in the globals.css file:

@font-face {
  font-family: 'My Font';
  src: local('My Font'), local('My-Font'),
    url('../public/webfonts/My-Font.woff')
      format('woff');
  font-weight: normal;
  font-style: normal;
}
```

I've deployed my app using the GitHub actions next.js workflow. The CSS and images are loaded fine but the font is not.

If I try to load the font with a path starting with '/' it throws a 404 error since the base URL is my-user.github.io and not my-user.github.io/my-repo.

If I try to load the font with a relative path it throws a CORS error.

I've searched online and found various answers recommending basically opposite solutions, but nothing works for me.

Anyone with any up-to-date info on how to tweak this issue?

Body:
I have a small Next.js app that uses a local @font-face. Everything works fine in the dev environment.

The font .woff file is stored in /public/webfonts. The @font-face import is in the globals.css file:

@font-face {
  font-family: 'My Font';
  src: local('My Font'), local('My-Font'),
    url('../public/webfonts/My-Font.woff')
      format('woff');
  font-weight: normal;
  font-style: normal;
}

I've deployed my app using the GitHub actions next.js workflow. The CSS and images are loaded fine but the font is not.

If I try to load the font with a path starting with '/' it throws a 404 error since the base URL is my-user.github.io and not my-user.github.io/my-repo.

If I try to load the font with a relative path it throws a CORS error.

I've searched online and found various answers recommending basically opposite solutions, but nothing works for me.

Anyone with any up-to-date info on how to tweak this issue?


问:
Build Docker Image with ansible requires Buildkit, but fails despite enabling buildkit in daemon and/or adding environment variable in ansible
I try to build a collabora Docker Image with ansible. Here is the code:

    - name: Build collabora Docker image
      docker_image:
        source: build
        name: '{{ collabora_docker.image_name }}'
        tag: '{{ collabora_docker.version }}'
        build:
          path: '/tmp/collabora.git/docker/from-packages'
          nocache: yes
          dockerfile: Ubuntu
          args:
            type: cool
            secret_key: '{{ collabora_docker.key }}'
      environment:
        DOCKER_BUILDKIT: 1

```
<p>It fails with the following error msg:</p>
<pre class="lang-none prettyprint-override"><code>Error building repositoryxy/collabora - code: None, message: the --mount option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled
</code>```

As you can see with the code above I already try to pass the environment variable via ansible but to no avail. See also Use BuildKit for docker build within Ansible

I have also tried add the global setting to the docker daemon as described in https://docs.docker.com/build/buildkit/

Since I have BuildKit globally enabled in docker daemon.json, I can now manually build the image on the host with the same ansible user in question without setting the environment variable. Following command builds the docker image in question:
docker build --no-cache --secret id=secret_key,src=secret_key --build-arg type=cool -t repositoryxy/collabora:22.05.8-4 -f Ubuntu .

But when executed within the ansible playbook I'm still getting the above mention error message regarding buildkit not enabled.

Body:
I try to build a collabora Docker Image with ansible. Here is the code:

    - name: Build collabora Docker image
      docker_image:
        source: build
        name: '{{ collabora_docker.image_name }}'
        tag: '{{ collabora_docker.version }}'
        build:
          path: '/tmp/collabora.git/docker/from-packages'
          nocache: yes
          dockerfile: Ubuntu
          args:
            type: cool
            secret_key: '{{ collabora_docker.key }}'
      environment:
        DOCKER_BUILDKIT: 1

It fails with the following error msg:

Error building repositoryxy/collabora - code: None, message: the --mount option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled

As you can see with the code above I already try to pass the environment variable via ansible but to no avail. See also Use BuildKit for docker build within Ansible

I have also tried add the global setting to the docker daemon as described in https://docs.docker.com/build/buildkit/

Since I have BuildKit globally enabled in docker daemon.json, I can now manually build the image on the host with the same ansible user in question without setting the environment variable. Following command builds the docker image in question:
docker build --no-cache --secret id=secret_key,src=secret_key --build-arg type=cool -t repositoryxy/collabora:22.05.8-4 -f Ubuntu .

But when executed within the ansible playbook I'm still getting the above mention error message regarding buildkit not enabled.