问:
ICAL .NET Remove or Delete Event
I am using https://github.com/rianjs/ical.net with .Net 6 API. I am able to create an event like below.

```<code>            var calendar = new Calendar();
            calendar.AddTimeZone(new VTimeZone("America/Chicago"));
            var icalEvent = new CalendarEvent
            {
                Summary = "David's vacation days",
                Description = "Description for event",
                Start = new CalDateTime(2022, 12, 12, 15, 0, 0),
                End = new CalDateTime(2022, 12, 12, 16, 0, 0)
            };
            calendar.Events.Add(icalEvent);

            var iCalSerializer = new CalendarSerializer();
            result = iCalSerializer.SerializeToString(calendar);
</code>```

This creates a .ics file, opening which creates an event in the calendar.

BEGIN:VCALENDAR PRODID:-//github.com/rianjs/ical.net//NONSGML ical.net 4.0//EN VERSION:2.0 BEGIN:VTIMEZONE TZID:America/Chicago X-LIC-LOCATION:America/Chicago END:VTIMEZONE BEGIN:VEVENT DESCRIPTION:Description for event DTEND:20221212T160000 DTSTAMP:20221213T184639Z DTSTART:20221212T150000 SEQUENCE:0 SUMMARY:David's vacation days UID:4aca19e6-a7a8-426c-a488-c2abf789c395 END:VEVENT END:VCALENDAR

I see that if I edit the file and add METHOD:CANCEL, SEQUENCE:1, it opens in outlook with 'Remove from calendar'.

Now, how to do this remove event programmatically? I am hoping iCAL has something instead of me serializing the event to string and add the method etc. to that string manually.

Title: ICAL .NET Remove or Delete Event

Body:
I am using https://github.com/rianjs/ical.net with .Net 6 API. I am able to create an event like below.

            var calendar = new Calendar();
            calendar.AddTimeZone(new VTimeZone("America/Chicago"));
            var icalEvent = new CalendarEvent
            {
                Summary = "David's vacation days",
                Description = "Description for event",
                Start = new CalDateTime(2022, 12, 12, 15, 0, 0),
                End = new CalDateTime(2022, 12, 12, 16, 0, 0)
            };
            calendar.Events.Add(icalEvent);

            var iCalSerializer = new CalendarSerializer();
            result = iCalSerializer.SerializeToString(calendar);

This creates a .ics file, opening which creates an event in the calendar.

BEGIN:VCALENDAR PRODID:-//github.com/rianjs/ical.net//NONSGML ical.net 4.0//EN VERSION:2.0 BEGIN:VTIMEZONE TZID:America/Chicago X-LIC-LOCATION:America/Chicago END:VTIMEZONE BEGIN:VEVENT DESCRIPTION:Description for event DTEND:20221212T160000 DTSTAMP:20221213T184639Z DTSTART:20221212T150000 SEQUENCE:0 SUMMARY:David's vacation days UID:4aca19e6-a7a8-426c-a488-c2abf789c395 END:VEVENT END:VCALENDAR

I see that if I edit the file and add METHOD:CANCEL, SEQUENCE:1, it opens in outlook with 'Remove from calendar'.

Now, how to do this remove event programmatically? I am hoping iCAL has something instead of me serializing the event to string and add the method etc. to that string manually.


来源: stackexchange

问:
import csv into mongodb using mongoimport to insert unique data with out update
I am importing csv data into mongoDb using mongoimport command.

mongoimport -h="127.0.0.1" --port=27017 --db=myapp -c=test--type=csv --mode=upsert --upsertFields=name,place  --file=test.csv --columnsHaveTypes --fields="name.string(),place.string(),designation.string()"

Problem:

I have already have the below data into mongoDB

Name
Place
Designation

ABC
XYZ
Engg

And in the csv file, I have below data

```<code>name,place,designation
ABC,XYZ,
</code>```

when I use the mongoimport command with --mode=upsert , the designation column in the DB is replaced by null.

But I want to either skip this record while importing or not update(or keep) the existing designation column.

Can anyone provide the pointers on this ?

Thanks in Advance!

ContentLicense: CC BY-SA 4.0

Body:
I am importing csv data into mongoDb using mongoimport command.

mongoimport -h="127.0.0.1" --port=27017 --db=myapp -c=test--type=csv --mode=upsert --upsertFields=name,place  --file=test.csv --columnsHaveTypes --fields="name.string(),place.string(),designation.string()"

Problem:

I have already have the below data into mongoDB

Name
Place
Designation

ABC
XYZ
Engg

And in the csv file, I have below data

name,place,designation
ABC,XYZ,

when I use the mongoimport command with --mode=upsert , the designation column in the DB is replaced by null.

But I want to either skip this record while importing or not update(or keep) the existing designation column.

Can anyone provide the pointers on this ?

Thanks in Advance!


问:
c++ exception: override what function does not return anything
In the following programm std::cout << ex.what() << std::endl; does not print anything.
What's the problem with this code?

```<code>#include <iostream>
#include <stdexcept>
#include <string>
#include <sstream>
#include <cstring>

class Interval_OutOfRange : public std::out_of_range {
public:
    std::stringstream ss;
    Interval_OutOfRange(int min, int max, int value)
        : std::out_of_range{"interval value out of range"}
    {
        ss << value << " is not inside intervall [" << min << ", " << max << "]";
    }

    char const * what() const noexcept override {
        return ss.str().c_str();
    }
};

template<int Min, int Max>
class Interval {
public:
    Interval(int value) : value_{value} {
        throw Interval_OutOfRange{Min, Max, value};
    }
    auto get() const { return value_; }
    auto set(int value) { value_ = value; }
private:
    int value_;
};

int main() {
    try {
        Interval<7, 17> obj(19);
    }
    catch (Interval_OutOfRange& ex) {
        std::cout << ex.what() << std::endl;
    }
}
</code>```

Body:
In the following programm std::cout << ex.what() << std::endl; does not print anything.
What's the problem with this code?

#include <iostream>
#include <stdexcept>
#include <string>
#include <sstream>
#include <cstring>

class Interval_OutOfRange : public std::out_of_range {
public:
    std::stringstream ss;
    Interval_OutOfRange(int min, int max, int value)
        : std::out_of_range{"interval value out of range"}
    {
        ss << value << " is not inside intervall [" << min << ", " << max << "]";
    }

    char const * what() const noexcept override {
        return ss.str().c_str();
    }
};

template<int Min, int Max>
class Interval {
public:
    Interval(int value) : value_{value} {
        throw Interval_OutOfRange{Min, Max, value};
    }
    auto get() const { return value_; }
    auto set(int value) { value_ = value; }
private:
    int value_;
};

int main() {
    try {
        Interval<7, 17> obj(19);
    }
    catch (Interval_OutOfRange& ex) {
        std::cout << ex.what() << std::endl;
    }
}


问:
How to store a checkbox value as array in mongoDB with mongoose
I would like to store checkbox a value as array in mongoDB, using mongoose schema.
I can get the values in array if I check more than 2 boxes. But as string when I check only one.

The following is for the checkbox in form in ejs file

```<code><div class="mb-3">
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" id="Culture" value="Culture" name="place[categories]">
      <label class="form-check-label" for="Culture">Culture</label>
   </div>
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" id="Sport" value="Sport"  name="place[categories]">
      <label class="form-check-label" for="Sport">Sport</label>
   </div>
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" id="Nature" value="Nature"  name="place[categories]">
      <label class="form-check-label" for="Nature">Nature</label>
   </div>
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" id="Education" value="Education"  name="place[categories]">
      <label class="form-check-label" for="Education">Education</label>
   </div>
</div>
</code>```

This is mongoose Schema

```<code>const mongoose = require("mongoose");

const placeSchema = new mongoose.Schema({
    title: String,
    categories: [String],
    location: String,
    description: String
})

</code>```

This is backend with express, for your info.

```<code>app.get("/places/new", (req, res) => {
    res.render("places/new.ejs");
});

app.post("/places", async(req, res) => {
    const place = new Place(req.body.place);
    await place.save();
    res.redirect("/places");
});

</code>```

Thank you for reading and I hope I could find solution.

I tried to change the schema design as following, but doesn't go well.

```<code>const categorySchema = new mongoose.Schema({ name: String });

const placeSchema = new mongoose.Schema({
    title: String,
    categories: [categorySchema],
    location: String,
    description: String,
    image: String,
})
</code>```

Body:
I would like to store checkbox a value as array in mongoDB, using mongoose schema.
I can get the values in array if I check more than 2 boxes. But as string when I check only one.

The following is for the checkbox in form in ejs file

      <input class="form-check-input" type="checkbox" id="Culture" value="Culture" name="place[categories]">
      Culture

      <input class="form-check-input" type="checkbox" id="Sport" value="Sport"  name="place[categories]">
      Sport

      <input class="form-check-input" type="checkbox" id="Nature" value="Nature"  name="place[categories]">
      Nature

      <input class="form-check-input" type="checkbox" id="Education" value="Education"  name="place[categories]">
      Education

This is mongoose Schema

const mongoose = require("mongoose");

const placeSchema = new mongoose.Schema({
    title: String,
    categories: [String],
    location: String,
    description: String
})

This is backend with express, for your info.

app.get("/places/new", (req, res) => {
    res.render("places/new.ejs");
});

app.post("/places", async(req, res) => {
    const place = new Place(req.body.place);
    await place.save();
    res.redirect("/places");
});

Thank you for reading and I hope I could find solution.

I tried to change the schema design as following, but doesn't go well.

const categorySchema = new mongoose.Schema({ name: String });

const placeSchema = new mongoose.Schema({
    title: String,
    categories: [categorySchema],
    location: String,
    description: String,
    image: String,
})


问:
Running batch predictions in parallel in Google Vertex AI
Is there a way to run batch predictions in parallel in Vertex AI? In Azure ML studio, we can use ParallelRunStep for the same. The use case is that I have a lot of image files that needs to be classified based on a model in production. I would like to batch, lets say 100 images in parallel to get the predictions for all the images

Thanks


问:
Getting Chart not defined error while trying to create a pie-chart
I got the code below online to create a pie-chart in my react app, but I am getting Chart is not defined error

This is the link to the demo, I got the code from - Doughnut Chart

This is my code below
....................................................................................................................................................................................................

```<code>import React, { PureComponent } from "react";
import { Doughnut } from "react-chartjs-2";
import "chartjs-plugin-doughnut-innertext";

Chart.pluginService.register({
  beforeDraw: function (chart) {
    var width = chart.chart.width,
      height = chart.chart.height,
      ctx = chart.chart.ctx;
    ctx.restore();
    var fontSize = (height / 160).toFixed(2);
    ctx.font = fontSize + "em sans-serif";
    ctx.textBaseline = "top";
    var text = "2.44%",
      textX = Math.round((width - ctx.measureText(text).width) / 2),
      textY = height / 2.2;
    ctx.fillText(text, textX, textY);
    ctx.save();
  }
});
const data = {
  labels: ["Deposits", "Fee"],
  datasets: [
    {
      label: "My First dataset",
      fill: false,
      lineTension: 0.0,
      // backgroundColor: "rgba(75,192,192,0.4)",
      backgroundColor: ["#56d7a3", "#fe8a5d"],
      hoverBackgroundColor: ["#red", "#fe8a5d"],
      data: [100 - 50, 50]
    }
  ]
};

export default class DoughnutDemo extends PureComponent {
  state = {
    legend: []
  };

  componentDidMount() {
    const component = this.doughnut;
    this.setState({ legend: component.chartInstance.legend.legendItems });
  }

  render() {
    const { legend } = this.state;
    return (
      <div>
        <h2>Doughnut Chart with custom legend example</h2>
        <Doughnut
          ref={(ref) => (this.doughnut = ref)}
          data={data}
          options={{
            legend: {
              display: false
            },
            elements: {
              arc: {
                borderWidth: 0
              }
            },
            cutoutPercentage: 75,
            centerText: {
              // color of the text
              color: "#fe8a5d",
              // text to be display in the doughnut chart center
              value: 340,
              //manually adjust the font size on top of the default font size
              fontSizeAdjust: 0.2 // 20% larger of the default size
            }
          }}
        />
      </div>
    );
  }
}
</code>```

Body:
I got the code below online to create a pie-chart in my react app, but I am getting Chart is not defined error

This is the link to the demo, I got the code from - Doughnut Chart

This is my code below
....................................................................................................................................................................................................

import React, { PureComponent } from "react";
import { Doughnut } from "react-chartjs-2";
import "chartjs-plugin-doughnut-innertext";

Chart.pluginService.register({
  beforeDraw: function (chart) {
    var width = chart.chart.width,
      height = chart.chart.height,
      ctx = chart.chart.ctx;
    ctx.restore();
    var fontSize = (height / 160).toFixed(2);
    ctx.font = fontSize + "em sans-serif";
    ctx.textBaseline = "top";
    var text = "2.44%",
      textX = Math.round((width - ctx.measureText(text).width) / 2),
      textY = height / 2.2;
    ctx.fillText(text, textX, textY);
    ctx.save();
  }
});
const data = {
  labels: ["Deposits", "Fee"],
  datasets: [
    {
      label: "My First dataset",
      fill: false,
      lineTension: 0.0,
      // backgroundColor: "rgba(75,192,192,0.4)",
      backgroundColor: ["#56d7a3", "#fe8a5d"],
      hoverBackgroundColor: ["#red", "#fe8a5d"],
      data: [100 - 50, 50]
    }
  ]
};

export default class DoughnutDemo extends PureComponent {
  state = {
    legend: []
  };

  componentDidMount() {
    const component = this.doughnut;
    this.setState({ legend: component.chartInstance.legend.legendItems });
  }

  render() {
    const { legend } = this.state;
    return (

Doughnut Chart with custom legend example

        <Doughnut
          ref={(ref) => (this.doughnut = ref)}
          data={data}
          options={{
            legend: {
              display: false
            },
            elements: {
              arc: {
                borderWidth: 0
              }
            },
            cutoutPercentage: 75,
            centerText: {
              // color of the text
              color: "#fe8a5d",
              // text to be display in the doughnut chart center
              value: 340,
              //manually adjust the font size on top of the default font size
              fontSizeAdjust: 0.2 // 20% larger of the default size
            }
          }}
        />

    );
  }
}


问:
Rails 7 create pdf temp file and send it in POST
In my Rails 7 API only app I'm creating a PDF file with gem Prawn. After creation I want to save that file into Tempfile and then send it to the external service via POST call. To attach file into POST call I've to use Faraday::UploadIO. Unfortunately I'm unable to create Tempfile and pass it into Net::HTTP client.

Here is what I have:

lib/file_io.rb

```<code># require 'file_io' and use FileIO to simplify persistence of IO stream as file
class FileIO < StringIO
  attr_reader :original_filename

  def initialize(stream, filename)
    super(stream)
    @original_filename = filename
  end
end
</code>```

services/mandate/uploader.rb

```<code># class which generates PDF and send it to the API

require 'file_io'
require 'net/http'

module Mandate
  class Uploader
    def send_pdf_file(file_io)
      uri = URI('test_path')
      req = Net::HTTP::Post.new(uri)
      req['apiToken'] = Rails.application.credentials.api_token
      req['Content-Type'] = 'multipart/form-data'
      file = Tempfile.new('mandate.pdf')
      file.write(file_io.read)
      file.close
      req.set_form([['file', Faraday::UploadIO.new(file.path, 'application/pdf')]], 'multipart/form-data')
      res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
        http.request(req)
    end

    def generate_pdf(params)
      FileIO.new(PDFDocument::Generator.new(params).render, 'document.pdf')
    end
  end
end
</code>```

This code produces me an error:

lib/ruby/3.1.0/delegate.rb:349:in `write': "\xFF" from ASCII-8BIT to UTF-8 (Encoding::UndefinedConversionError)

I've tried to force encode the file by:

```<code>  file.write(file_io.read.force_encoding('ASCII-8BIT'))
</code>```

But error message is the same.

Body:
In my Rails 7 API only app I'm creating a PDF file with gem Prawn. After creation I want to save that file into Tempfile and then send it to the external service via POST call. To attach file into POST call I've to use Faraday::UploadIO. Unfortunately I'm unable to create Tempfile and pass it into Net::HTTP client.

Here is what I have:

lib/file_io.rb

# require 'file_io' and use FileIO to simplify persistence of IO stream as file
class FileIO < StringIO
  attr_reader :original_filename

  def initialize(stream, filename)
    super(stream)
    @original_filename = filename
  end
end

services/mandate/uploader.rb

# class which generates PDF and send it to the API

require 'file_io'
require 'net/http'

module Mandate
  class Uploader
    def send_pdf_file(file_io)
      uri = URI('test_path')
      req = Net::HTTP::Post.new(uri)
      req['apiToken'] = Rails.application.credentials.api_token
      req['Content-Type'] = 'multipart/form-data'
      file = Tempfile.new('mandate.pdf')
      file.write(file_io.read)
      file.close
      req.set_form([['file', Faraday::UploadIO.new(file.path, 'application/pdf')]], 'multipart/form-data')
      res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
        http.request(req)
    end

    def generate_pdf(params)
      FileIO.new(PDFDocument::Generator.new(params).render, 'document.pdf')
    end
  end
end

This code produces me an error:

lib/ruby/3.1.0/delegate.rb:349:in `write': "\xFF" from ASCII-8BIT to UTF-8 (Encoding::UndefinedConversionError)

I've tried to force encode the file by:

  file.write(file_io.read.force_encoding('ASCII-8BIT'))

But error message is the same.


问:
In Einsteinpy, how does one plot the output of a single element of a tensor with respect to multiple variables?
I would like to plot a component of the Einstein tensor from a metric in Einsteinpy. In order to get this metric, I used einst=EinsteinTensor.from_metric() and then einst.tensor()[i][j], where i and j are the indices of the component I want to plot. When I print the value of this object, I get an equation, but I can't seem to plot it. Is there any way to plot this object with respect to a set of coordinates (i.e. a 3d surface plot with respect to x and t)?

I figured that because Einsteinpy makes use of scipy, I could simply use the scipy plot3d feature with respect to some coordinates. However, running the code prints the error

TypeError: unhashable type: 'numpy.ndarray'
During handling of the above exception, another exception occurred:
AttributeError: 'ImmutableDenseNDimArray' object has no attribute 'extract_multiplicatively'

(I cut down the error message to hide my file directory and remove some of the line numbers and such)

If it helps, printing the type of the object einst.tensor()[i][j] gives class 'sympy.core.add.Add'.


问:
Can't connect firebase functions with google cloud sql
I'm hosting a sql instance on google cloud sql. Firebase functions worked with this instance flawlessly.
Now it stopped working out of nowhere and I can't seem to get any error.

Code:

```<code> const mssql = require('mssql');
 const settings = require('../settings.js');
    const pool = await mssql.connect(settings.sqlConfig);
    const query = `EXEC spUserDelete @userAuthUid='${userAuthUid}', @value=${value}`
    const queryRes = await pool.request().query(query)
</code>```

It never returns queryRes and instead I always get Timeout error.

Body:
I'm hosting a sql instance on google cloud sql. Firebase functions worked with this instance flawlessly.
Now it stopped working out of nowhere and I can't seem to get any error.

Code:

 const mssql = require('mssql');
 const settings = require('../settings.js');
    const pool = await mssql.connect(settings.sqlConfig);
    const query = `EXEC spUserDelete @userAuthUid='${userAuthUid}', @value=${value}`
    const queryRes = await pool.request().query(query)

It never returns queryRes and instead I always get Timeout error.


问:
Tensorflow Deprecated Layers
I'm trying to use

```<code>tf.contrib.layers.real_valued_column
</code>```

and

```<code>tf.contrib.layers.sparse_column_with_hash_bucket,
</code>```

but they seem to be somewhere else in TF2.0. Can anyone tell me where i can find them?

I just want to know where I could find them today, or what I could use. I am preprocessing my data (multiple numeric and categorical columns) and can't get my NN to work properly

Title: Tensorflow Deprecated Layers

Body:
I'm trying to use

tf.contrib.layers.real_valued_column

and

tf.contrib.layers.sparse_column_with_hash_bucket,

but they seem to be somewhere else in TF2.0. Can anyone tell me where i can find them?

I just want to know where I could find them today, or what I could use. I am preprocessing my data (multiple numeric and categorical columns) and can't get my NN to work properly


问:
Best way to install Facebook Meta Pixel and Conversions Api, and create a Facebook catalogue feed in Python Django?
i have created a simple e-commerce website using Python with Django, and some vanilla JS and Jquery.

However now i need to install an existing Facebook Pixel with events and setup the Conversion API(server-side) events.
Also I need to auto sync the products on save with an already created Facebook Catalogue.

I have read the documentation facebook provides but I can not really comprehend it.
Seeing as it is an e-commerce website, that would imply that orders and carts would have multiple products in them and i would like to handle those events in my backend but I do not know how to proceed.

Are there any tools/python packages that would help me with my goal and which ones should i use?


问:
Show data in Excel by columns when selecting a checkbox
I am new to programming and I am creating a website where the user chooses through a checkbox the data he wants to see and that is stored in my database. Example, if the client only wants to see the Car and price data, he selects them and when he presses a button, the data he requested is downloaded in an Excel file.

The problem is that it doesn't show by columns but it puts all the data in the same column and I can't put everything in the same array because each checkbox has to be independent.

The data looks like this

```<code>Car
Ford
Chevrolete
Tesla

Price
2000
3000
4000

And i want each one to be in a different column
</code>```

This is my code

```<code>if(isset($_POST['respuesta'])){
        if(isset ($_POST['checkbox'])){
            foreach($_POST ['checkbox'] as $checkbox);

        $Auto = $_POST['checkbox'];
         $Color= $_POST['checkbox'];
         $Precio = $_POST['checkbox'];
         $Año = $_POST['checkbox'];

         header('Content-Type:text/csv; charset-latin1');
         header('Content-Disposition: attachment; filename="Reporte.csv"');

         $salida=fopen('php://output', 'W');

         if (in_array('Auto',$_POST['checkbox'])){
            fputcsv($salida, array ('Auto'));

            $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
            $resultados=mysqli_query($enlace, $query);
            while($filaR= $resultados->fetch_assoc())
          fputcsv($salida, array($filaR['Auto']));

    }
        ?>

        <?PHP
         if (in_array('Color',$_POST['checkbox'])){
            fputcsv($salida, array ('Color'));

           $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
           $resultados=mysqli_query($enlace, $query);
           while($filaR= $resultados->fetch_assoc())
          fputcsv($salida, array($filaR['Color']));

    }

        ?>

         <?PHP
          if (in_array('Precio',$_POST['checkbox'])){
         fputcsv($salida, array ('Precio'));

        $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
        $resultados=mysqli_query($enlace, $query);
        while($filaR= $resultados->fetch_assoc())
        fputcsv($salida, array($filaR['Precio']));
         }

         ?>

        <?PHP
        if (in_array('Año', $_POST['checkbox'])){
        fputcsv($salida, array ('Año'));

        $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
        $resultados=mysqli_query($enlace, $query);
        while($filaR= $resultados->fetch_assoc())
        fputcsv($salida, array ($filaR['Año']));
        }

        ?>

</code>```

Body:
I am new to programming and I am creating a website where the user chooses through a checkbox the data he wants to see and that is stored in my database. Example, if the client only wants to see the Car and price data, he selects them and when he presses a button, the data he requested is downloaded in an Excel file.

The problem is that it doesn't show by columns but it puts all the data in the same column and I can't put everything in the same array because each checkbox has to be independent.

The data looks like this

Car
Ford
Chevrolete
Tesla

Price
2000
3000
4000

And i want each one to be in a different column

This is my code

if(isset($_POST['respuesta'])){
        if(isset ($_POST['checkbox'])){
            foreach($_POST ['checkbox'] as $checkbox);

        $Auto = $_POST['checkbox'];
         $Color= $_POST['checkbox'];
         $Precio = $_POST['checkbox'];
         $Año = $_POST['checkbox'];

         header('Content-Type:text/csv; charset-latin1');
         header('Content-Disposition: attachment; filename="Reporte.csv"');

         $salida=fopen('php://output', 'W');

         if (in_array('Auto',$_POST['checkbox'])){
            fputcsv($salida, array ('Auto'));

            $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
            $resultados=mysqli_query($enlace, $query);
            while($filaR= $resultados->fetch_assoc())
          fputcsv($salida, array($filaR['Auto']));

    }
        ?>

        <?PHP
         if (in_array('Color',$_POST['checkbox'])){
            fputcsv($salida, array ('Color'));

           $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
           $resultados=mysqli_query($enlace, $query);
           while($filaR= $resultados->fetch_assoc())
          fputcsv($salida, array($filaR['Color']));

    }

        ?>

         <?PHP
          if (in_array('Precio',$_POST['checkbox'])){
         fputcsv($salida, array ('Precio'));

        $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
        $resultados=mysqli_query($enlace, $query);
        while($filaR= $resultados->fetch_assoc())
        fputcsv($salida, array($filaR['Precio']));
         }

         ?>

        <?PHP
        if (in_array('Año', $_POST['checkbox'])){
        fputcsv($salida, array ('Año'));

        $query = "SELECT * FROM salida WHERE Fecha BETWEEN '$Fecha1' AND '$Fecha2'";
        $resultados=mysqli_query($enlace, $query);
        while($filaR= $resultados->fetch_assoc())
        fputcsv($salida, array ($filaR['Año']));
        }

        ?>


问:
How do i generate a QR code after window.print() is opened?
I'm currently using Angular/Typescript as my codebase. I need to create a QR code (that points back to current URL) that only generates after user chooses to print the screen.

I tried using something like this but I could not get it to only generate after the print dialogue opens up
`

```<code>/ qr-code.component.ts

import { Component, OnInit } from '@angular/core';
import QRCode from 'qrcode';

@Component({
  selector: 'app-qr-code',
  templateUrl: './qr-code.component.html',
  styleUrls: ['./qr-code.component.css']
})
export class QrCodeComponent implements OnInit {
  constructor() {}

  ngOnInit(): void {
    // Generate a QR code with the current URL
    QRCode.toCanvas(window.location.href, (error, canvas) => {
      if (error) {
        console.error(error);
      } else {
        // If the QR code was generated successfully, append it to the component's element
        this.elementRef.nativeElement.appendChild(canvas);
      }
    });
  }
}
</code>```

`

Body:
I'm currently using Angular/Typescript as my codebase. I need to create a QR code (that points back to current URL) that only generates after user chooses to print the screen.

I tried using something like this but I could not get it to only generate after the print dialogue opens up
`

/ qr-code.component.ts

import { Component, OnInit } from '@angular/core';
import QRCode from 'qrcode';

@Component({
  selector: 'app-qr-code',
  templateUrl: './qr-code.component.html',
  styleUrls: ['./qr-code.component.css']
})
export class QrCodeComponent implements OnInit {
  constructor() {}

  ngOnInit(): void {
    // Generate a QR code with the current URL
    QRCode.toCanvas(window.location.href, (error, canvas) => {
      if (error) {
        console.error(error);
      } else {
        // If the QR code was generated successfully, append it to the component's element
        this.elementRef.nativeElement.appendChild(canvas);
      }
    });
  }
}

`


问:
Showing the error popup in VSCode from regular Typescript
I auto generate a bunch of files by running Typescript code in VSCode with the plugin "Run on save".

Whenever the generator runs into an error, I would like an error popup in VSCode:

I tried this approach in my Typescript file, but concluded from Googling that it's only possible to run in an VSCode extension context:

```<code>import vscode from "vscode";

vscode.window.showErrorMessage("Show error");
</code>```

Is there any way to achieve what I want? It doesn't have to be exactly that type of popup, any error popup will do.

Body:
I auto generate a bunch of files by running Typescript code in VSCode with the plugin "Run on save".

Whenever the generator runs into an error, I would like an error popup in VSCode:

I tried this approach in my Typescript file, but concluded from Googling that it's only possible to run in an VSCode extension context:

import vscode from "vscode";

vscode.window.showErrorMessage("Show error");

Is there any way to achieve what I want? It doesn't have to be exactly that type of popup, any error popup will do.


问:
Why does my animation not begin at the time I set it as every single time I refresh or through Live Server?
The issue is I have an animation playing and set an audio clip to sync up to play after 8400 milliseconds and it appeared to match the audio clip.

At one point I changed it to 8600 milliseconds because it appears the audio played too early when opened on Live Server. Now it appears to be back at 8400 milliseconds for the audio to sync properly. I did not touch the CSS animation at all. I am curious as to why this is the case and if this could be a result of opening it via Live Server on VS Code and double-clicking and opening the index.html file on the browser. I don't want to ensure someone's experience when on the web page to be for the audio and animation to be synched up, of course.

I am currently using setTimeout function at 8400 milliseconds to play the audio to sync up with when this specific animation is begins. It functions the way I want right now but I don't want to have to keep editing this (for whatever reason).


问:
Netsuite report shows wrong quantity of good purchased in a pending bills report
it seems to add 2 to the number of goods purchased, when I look into the bill in question the quantity is correct. It happens to every bill for unexplained reasons. Just in case it's relevant, these are all dropshipping items. My bandaid solution was to add a field to the purchase order that has value 2 and subtract it from the quantity. However, I'd be interested to know if there is a more elegant solution and why it's happening</p>


问:
How to add file creation date, user, file name, and file path to header template when creating a new file in VIM / GVIM (v7.4)?
I have a default header file that is loaded by the following command in my ~/.vimrc :

autocmd bufnewfile * so /home/username/.vim/header.txt

It looks like this:

```<code>######################################################
# File name:
# File path:
# Purpose:
# Creation date:
# Last modified:
# Created by:
######################################################
</code>```

I want to update Last modified: with the date/time when saving (using autocmd BufWritePre).  This is working as expected.

I also want to populate File name:, File Path:, Creation date:, and Created by: when a new file is created (using autocmd BufNewFile).  This is not working.  Nothing is added to the header when a new file is created.

This is my code for updating Last modified: when saving a file.  I also added in updating Created by: just to test my pattern match, and this code updates both fields upon file save as expected:

```<code>autocmd! BufWritePre * :call s:timestamp()
" to update timestamp when saving if it's in the first 20 lines of a file
function! s:timestamp()
    let pat = '\(\(Last\)\?\s*\([Cc]hanged\?\|[Mm]odified\|[Uu]pdated\?\)\s*:\s*\).*'
    let rep = '\1' . strftime("%a %d %b %Y %I:%M:%S %p %Z")
    call s:subst(1, 20, pat, rep)

    let pat = '\(Created by\?\s*:\s*\).*'
    let rep =  '\1' . $USER
    call s:subst(1, 20, pat, rep)
endfunction
</code>```

This is my code for updating the File name:, File Path:, Creation date:, and Created by: fields when a new file is created.  It does not work; the fields do not get updated and there is no error message.

```<code>autocmd! BufNewFile * :call s:creationdata()
function! s:creationdata()
  let pat = '\(\(Creation\)\s*\([Dd]ate\)\s*:\s*\).*'
  let rep =  '\1' . strftime("%a %d %b %Y %I:%M:%S %p %Z")
  call s:subst(1, 20, pat, rep)

  let pat = '\(\(File\)\?\s*\([Pp]ath\)\?\s*:\s*\).*'
  let rep =  '\1' .escape(expand("%:p:h"), '/\'. (&magic ? '&~' : ''))
  call s:subst(1, 20, pat, rep)

  let pat = '\(\(File\)\?\s*\([Nn]ame\)\?\s*:\s*\).*'
  let rep =  '\1' . expand("%")
  call s:subst(1, 20, pat, rep)

  let pat = '\(Created by\?\s*:\s*\).*'
  let rep =  '\1' . $USER
  call s:subst(1, 20, pat, rep)
endfunction
</code>```

The subst function called by the functions above is defined as:

```<code>function! s:subst(start, end, pat, rep)
    let lineno = a:start
    while lineno <= a:end
    let curline = getline(lineno)
    if match(curline, a:pat) != -1
        let newline = substitute( curline, a:pat, a:rep, '' )
        if( newline != curline )
        " Only substitute if we made a change
        "silent! undojoin
        keepjumps call setline(lineno, newline)
        endif
    endif
    let lineno = lineno + 1
    endwhile
endfunction
</code>```

I can't figure out why the BufNewFile autocmd doesn't work.  I've tried several other methods that I found via googling, including:

```<code>"  Method 1:  doesn't work; not compatible with vim 7.4?  Gives Error:
"  E16: Invalid rangeError detected while processing BufNewFile Auto commands for "*":
"  E16: Invalid range: 1,10g/File name:.*/s//File name: foo
"  E16: Invalid range: 1,10g/Creation date:.*/s//Creation date: 13-12-2022
autocmd bufnewfile * exe "1," . 10 . "g/File name:.*/s//File name: " .expand("%")
autocmd bufnewfile * exe "1," . 10 . "g/Creation date:.*/s//Creation date: " .strftime("%d-%m-%Y")
</code>```

... and:

```<code>" Method 2:  only works on saving file, not on creating a new file.  No error message.
autocmd BufNewFile,BufWritePre,FileWritePre * ks|call LastMod()|'s
  fun LastMod()
    if line("$") > 20
      let l = 20
    else
      let l = line("$")
    endif
    exe "1," . l . "g/Last modified:/s/Last modified: .*/Last modified: " .
    \ strftime("%Y %b %d")
    exe "1," . l . "g/Creation date:/s/Creation date: .*/Creation date: " .
    \ strftime("%Y %b %d")
  endfun
</code>```

It's as if BufNewFile is the wrong autocmd pattern or something.  But I've checked the docs and online and I think it's correct.

Body:
I have a default header file that is loaded by the following command in my ~/.vimrc :

autocmd bufnewfile * so /home/username/.vim/header.txt

It looks like this:

######################################################
# File name:
# File path:
# Purpose:
# Creation date:
# Last modified:
# Created by:
######################################################

I want to update Last modified: with the date/time when saving (using autocmd BufWritePre).  This is working as expected.

I also want to populate File name:, File Path:, Creation date:, and Created by: when a new file is created (using autocmd BufNewFile).  This is not working.  Nothing is added to the header when a new file is created.

This is my code for updating Last modified: when saving a file.  I also added in updating Created by: just to test my pattern match, and this code updates both fields upon file save as expected:

autocmd! BufWritePre * :call s:timestamp()
" to update timestamp when saving if it's in the first 20 lines of a file
function! s:timestamp()
    let pat = '\(\(Last\)\?\s*\([Cc]hanged\?\|[Mm]odified\|[Uu]pdated\?\)\s*:\s*\).*'
    let rep = '\1' . strftime("%a %d %b %Y %I:%M:%S %p %Z")
    call s:subst(1, 20, pat, rep)

    let pat = '\(Created by\?\s*:\s*\).*'
    let rep =  '\1' . $USER
    call s:subst(1, 20, pat, rep)
endfunction

This is my code for updating the File name:, File Path:, Creation date:, and Created by: fields when a new file is created.  It does not work; the fields do not get updated and there is no error message.

autocmd! BufNewFile * :call s:creationdata()
function! s:creationdata()
  let pat = '\(\(Creation\)\s*\([Dd]ate\)\s*:\s*\).*'
  let rep =  '\1' . strftime("%a %d %b %Y %I:%M:%S %p %Z")
  call s:subst(1, 20, pat, rep)

  let pat = '\(\(File\)\?\s*\([Pp]ath\)\?\s*:\s*\).*'
  let rep =  '\1' .escape(expand("%:p:h"), '/\'. (&magic ? '&~' : ''))
  call s:subst(1, 20, pat, rep)

  let pat = '\(\(File\)\?\s*\([Nn]ame\)\?\s*:\s*\).*'
  let rep =  '\1' . expand("%")
  call s:subst(1, 20, pat, rep)

  let pat = '\(Created by\?\s*:\s*\).*'
  let rep =  '\1' . $USER
  call s:subst(1, 20, pat, rep)
endfunction

The subst function called by the functions above is defined as:

function! s:subst(start, end, pat, rep)
    let lineno = a:start
    while lineno <= a:end
    let curline = getline(lineno)
    if match(curline, a:pat) != -1
        let newline = substitute( curline, a:pat, a:rep, '' )
        if( newline != curline )
        " Only substitute if we made a change
        "silent! undojoin
        keepjumps call setline(lineno, newline)
        endif
    endif
    let lineno = lineno + 1
    endwhile
endfunction

I can't figure out why the BufNewFile autocmd doesn't work.  I've tried several other methods that I found via googling, including:

"  Method 1:  doesn't work; not compatible with vim 7.4?  Gives Error:
"  E16: Invalid rangeError detected while processing BufNewFile Auto commands for "*":
"  E16: Invalid range: 1,10g/File name:.*/s//File name: foo
"  E16: Invalid range: 1,10g/Creation date:.*/s//Creation date: 13-12-2022
autocmd bufnewfile * exe "1," . 10 . "g/File name:.*/s//File name: " .expand("%")
autocmd bufnewfile * exe "1," . 10 . "g/Creation date:.*/s//Creation date: " .strftime("%d-%m-%Y")

... and:

" Method 2:  only works on saving file, not on creating a new file.  No error message.
autocmd BufNewFile,BufWritePre,FileWritePre * ks|call LastMod()|'s
  fun LastMod()
    if line("$") > 20
      let l = 20
    else
      let l = line("$")
    endif
    exe "1," . l . "g/Last modified:/s/Last modified: .*/Last modified: " .
    \ strftime("%Y %b %d")
    exe "1," . l . "g/Creation date:/s/Creation date: .*/Creation date: " .
    \ strftime("%Y %b %d")
  endfun

It's as if BufNewFile is the wrong autocmd pattern or something.  But I've checked the docs and online and I think it's correct.


问:
Python Multiprocessing utilizing another executable program
I am trying to run an executable in a parallel manner. For that I am trying to use multiprocessing library. However, my code is supposed to run another executable file which needs an input file which is created by my code and outputs a results file which I need.

The computation inputs are gathered in an numpy array row wise, I would like to make asynchronous parallel run which will take different rows as inputs, feeds it to the executable program and reads the output file as results and gather them.

Doing the process, I noticed that one core is overwriting the other cores processes in the input file and I want to know if anything can be done to prevent that.

Thanks in advance.


问:
Efficient Data Analysis and Visualization Techniques using PySpark and MongoDB
So I have ingested data to mongodb and I was able to view it using spark
I was able to  to read the data and confirm its there in mongo db

```<code>
`%python
findspark.init()
import pyspark
import pandas as pd
from pyspark import SparkContext
from pyspark.sql import SparkSession
from pyspark.sql import SQLContext
spark = SparkSession.builder.appName('Hai Data Analysis').getOrCreate()
pydf_haidata =spark.read.format("mongo").option("uri","mongodb://127.0.0.1:27017/dbv.ic1").load()
pydf_haidata.printSchema()`
</code>```

Now I'm trying to visualize it using histogram loops etc on the data with pyspark and python codes as follows how do I do that and I m getting errors any suggestions

```<code>fig, axes = plt.subplots(nrows=4, ncols=2, dpi=80, figsize=(11,8))
for i, ax in enumerate(axes.flatten()):
   data = pydf_haidata[pydf_haidata.columns[i]]
   ax.plot(data, color='red', linewidth=1)
   ax.set_title(pydf_haidata.columns[i])
   ax.xaxis.set_ticks_position('none')
   ax.yaxis.set_ticks_position('none')
   ax.spines["top"].set_alpha(0)
   ax.tick_params(labelsize=7)
plt.tight_layout();
fig, axes = plt.subplots(nrows=4, ncols=2, dpi=80, figsize=(11,8))
for i, ax in enumerate(axes.flatten()):
   data = pydf_haidata[pydf_haidata.columns[i+8]]
   ax.plot(data, color='red', linewidth=1)
   ax.set_title(pydf_haidata.columns[i+8])
   ax.xaxis.set_ticks_position('none')
   ax.yaxis.set_ticks_position('none')
   ax.spines["top"].set_alpha(0)
   ax.tick_params(labelsize=7)
plt.tight_layout();

</code>```

I have tried to use pandas to read the data from  pydf_haidata

Body:
So I have ingested data to mongodb and I was able to view it using spark
I was able to  to read the data and confirm its there in mongo db

`%python
findspark.init()
import pyspark
import pandas as pd
from pyspark import SparkContext
from pyspark.sql import SparkSession
from pyspark.sql import SQLContext
spark = SparkSession.builder.appName('Hai Data Analysis').getOrCreate()
pydf_haidata =spark.read.format("mongo").option("uri","mongodb://127.0.0.1:27017/dbv.ic1").load()
pydf_haidata.printSchema()`

Now I'm trying to visualize it using histogram loops etc on the data with pyspark and python codes as follows how do I do that and I m getting errors any suggestions

fig, axes = plt.subplots(nrows=4, ncols=2, dpi=80, figsize=(11,8))
for i, ax in enumerate(axes.flatten()):
   data = pydf_haidata[pydf_haidata.columns[i]]
   ax.plot(data, color='red', linewidth=1)
   ax.set_title(pydf_haidata.columns[i])
   ax.xaxis.set_ticks_position('none')
   ax.yaxis.set_ticks_position('none')
   ax.spines["top"].set_alpha(0)
   ax.tick_params(labelsize=7)
plt.tight_layout();
fig, axes = plt.subplots(nrows=4, ncols=2, dpi=80, figsize=(11,8))
for i, ax in enumerate(axes.flatten()):
   data = pydf_haidata[pydf_haidata.columns[i+8]]
   ax.plot(data, color='red', linewidth=1)
   ax.set_title(pydf_haidata.columns[i+8])
   ax.xaxis.set_ticks_position('none')
   ax.yaxis.set_ticks_position('none')
   ax.spines["top"].set_alpha(0)
   ax.tick_params(labelsize=7)
plt.tight_layout();

I have tried to use pandas to read the data from  pydf_haidata


问:
Force react-native-pager-view to rerender
I'm looking for a way to force the pager view to re-render, i'm trying to dynamically change the content of the pagerview component when the state changes, i'm logging the states and i can see that the contents of the state are actually changing but i'm not seeing any changes happen on the app itself..i think i need to force the pager to re-render so that it shows the newly created components..i'm looking for something similar to flatlist's "extraData" prop.

my code and original question can be found here


问:
Symfony 6.1.4 set environment in code of Command
I have a symfony command ./bin/console <command-name> which starting in my post-install hook

```<code>- name: some-command
  image: my-image
  command: ["./bin/console", "<command-name>"]
  ...
</code>```

I need to always run this command in the custom environment

How I can change environment for this command, for example set --env=test in code of class MyCommand ?

I tried to use

```<code>$this->addOption('env', null, InputOption::VALUE_OPTIONAL, 'environment', 'test');
</code>```

in __construct of command

also

```<code>$input->setOption('env', 'test');
</code>```

but did not get a positive result

Any idea?

P.S.
version:

```<code>"symfony/console": "^5.4"
</code>```

Body:
I have a symfony command ./bin/console <command-name> which starting in my post-install hook

- name: some-command
  image: my-image
  command: ["./bin/console", "<command-name>"]
  ...

I need to always run this command in the custom environment

How I can change environment for this command, for example set --env=test in code of class MyCommand ?

I tried to use

$this->addOption('env', null, InputOption::VALUE_OPTIONAL, 'environment', 'test');

in __construct of command

also

$input->setOption('env', 'test');

but did not get a positive result

Any idea?

P.S.
version:

"symfony/console": "^5.4"


问:
Converting latitude/longitude to decimal degrees for entire data frame
I'm trying to convert columns of latitude and longitude and create a new column for decimal degrees.

Both code examples work great for a single coordinate (also from Stack Overflow), but I need to iterate over multiple columns.

```<code>latitude = "20-18-6.65N"
N = 'N' in latitude
d, m, s = map(float, latitude[:-1].split('-'))
latitude = (d + m / 60. + s / 3600.) * (1 if N else -1)
longitude = "40-17-12.13W"
W = 'W' in longitude
d, m, s = map(float, longitude[:-1].split('-'))
longitude = (d + m / 60. + s / 3600.) * (-1 if W else 1)

print(latitude)
print(longitude)

latitude = ("20-18-6.65N")
longitude = ("40-17-12.13W")

latitude = sum(float(x) / 60 ** n for n, x in enumerate(latitude[:-1].split('-')))  * (1 if 'N' in     latitude[-1] else -1)
longitude = sum(float(x) / 60 ** n for n, x in enumerate(longitude[:-1].split('-'))) * (1 if 'E' in longitude[-1] else -1)

print(latitude, longitude)

latlong = df.iloc[:, 0:3] # Subset for columns needed.
latlong_df = pd.DataFrame(data = latlong) # transform into pandas df.
lats_df = latlong_df.iloc[:, 1] # subset for latitude column.
longs_df = latlong_df.iloc[:, 2] # subset for longitude column.
for i in latlong_df:
    lats_df = sum(float(x) / 60 ** n for n, x in enumerate(lats_df[:-1].split('-')))  * (1 if 'N' in lats_df[-1] else -1)
    longs_df = sum(float(x) / 60 ** n for n, x in enumerate(longs_df[:-1].split('-'))) * (1 if 'E' in longs_df[-1] else -1)
    print(lats_df, longs_df)
</code>```

The last code block results in this error message: AttributeError: 'Series' object has no attribute 'split'

I've tried using a for loop, but I get this error message: 'DataFrame' object has no attribute 'split'. I've also tried using other data types other than a data frame and get the same error message. Any feedback is greatly appreciated!

Body:
I'm trying to convert columns of latitude and longitude and create a new column for decimal degrees.

Both code examples work great for a single coordinate (also from Stack Overflow), but I need to iterate over multiple columns.

latitude = "20-18-6.65N"
N = 'N' in latitude
d, m, s = map(float, latitude[:-1].split('-'))
latitude = (d + m / 60. + s / 3600.) * (1 if N else -1)
longitude = "40-17-12.13W"
W = 'W' in longitude
d, m, s = map(float, longitude[:-1].split('-'))
longitude = (d + m / 60. + s / 3600.) * (-1 if W else 1)

print(latitude)
print(longitude)

latitude = ("20-18-6.65N")
longitude = ("40-17-12.13W")

latitude = sum(float(x) / 60 ** n for n, x in enumerate(latitude[:-1].split('-')))  * (1 if 'N' in     latitude[-1] else -1)
longitude = sum(float(x) / 60 ** n for n, x in enumerate(longitude[:-1].split('-'))) * (1 if 'E' in longitude[-1] else -1)

print(latitude, longitude)

latlong = df.iloc[:, 0:3] # Subset for columns needed.
latlong_df = pd.DataFrame(data = latlong) # transform into pandas df.
lats_df = latlong_df.iloc[:, 1] # subset for latitude column.
longs_df = latlong_df.iloc[:, 2] # subset for longitude column.
for i in latlong_df:
    lats_df = sum(float(x) / 60 ** n for n, x in enumerate(lats_df[:-1].split('-')))  * (1 if 'N' in lats_df[-1] else -1)
    longs_df = sum(float(x) / 60 ** n for n, x in enumerate(longs_df[:-1].split('-'))) * (1 if 'E' in longs_df[-1] else -1)
    print(lats_df, longs_df)

The last code block results in this error message: AttributeError: 'Series' object has no attribute 'split'

I've tried using a for loop, but I get this error message: 'DataFrame' object has no attribute 'split'. I've also tried using other data types other than a data frame and get the same error message. Any feedback is greatly appreciated!


问:
Discord bot returns error when using slash commands with Lambda and API Gateway
I'm building a Discord bot using Lambda and API Gateway, and I'm trying to integrate it with Discord using the INTERACTIONS ENDPOINT URL. I've set up the slash commands using the following script:

```<code>import json
import requests

APPLICATION_ID = "x"
BOT_TOKEN = "x"
GUILD_ID = "x"

HEADERS = {"Authorization": f"Bot {BOT_TOKEN}"}

URL = f"https://discord.com/api/v10/applications/{APPLICATION_ID}/guilds/{GUILD_ID}/commands"

json_file = {
        "name": "hello",
        "type": 1,
        "description": "replies with bar;/"
}

r = requests.post(URL, headers=HEADERS, json=data)
</code>```

The bot is deployed and seems to be working fine, as it's syncing correctly with Discord and appears connected on my server. However, when I try to execute a /hello, I get the following error:

```<code>Cosmic Cat:
This interaction failed
</code>```

I have checked the logs from my Lambda function and there are no errors or exceptions being thrown, even though the logs show that the correct commands should be executed. Here is some of those logs:

```<code>2022-12-13T14:59:34.807-03:00   START RequestId: 58f5bfc7-a85a-494c-a92b-9f746d401ce9 Version: $LATEST
2022-12-13T14:59:34.808-03:00   event: {'rawBody': '{"app_permissions":"...'resource-path': '/discord'}}
2022-12-13T14:59:34.808-03:00   [*] running command...
2022-12-13T14:59:34.808-03:00   command hello
2022-12-13T14:59:34.808-03:00   [*] detected hello. Executing...
2022-12-13T14:59:34.809-03:00   END RequestId: 58f5bfc7-a85a-494c-a92b-9f746d401ce9
</code>```

I have tried troubleshooting the issue by rejoining the bot on the server, adding more logs on Lambda execution, removing and adding API Gateway on INTERACTIONS ENDPOINT URL, but have not been able to resolve the problem. Any suggestions on how to fix this issue would be greatly appreciated.

My repository can be found here: https://github.com/crisdevnull1/cosmic-cat-bot
And the link of the tutorial that I followed: https://oozio.medium.com/serverless-discord-bot-55f95f26f743

Body:
I'm building a Discord bot using Lambda and API Gateway, and I'm trying to integrate it with Discord using the INTERACTIONS ENDPOINT URL. I've set up the slash commands using the following script:

import json
import requests

APPLICATION_ID = "x"
BOT_TOKEN = "x"
GUILD_ID = "x"

HEADERS = {"Authorization": f"Bot {BOT_TOKEN}"}

URL = f"https://discord.com/api/v10/applications/{APPLICATION_ID}/guilds/{GUILD_ID}/commands"

json_file = {
        "name": "hello",
        "type": 1,
        "description": "replies with bar;/"
}

r = requests.post(URL, headers=HEADERS, json=data)

The bot is deployed and seems to be working fine, as it's syncing correctly with Discord and appears connected on my server. However, when I try to execute a /hello, I get the following error:

Cosmic Cat:
This interaction failed

I have checked the logs from my Lambda function and there are no errors or exceptions being thrown, even though the logs show that the correct commands should be executed. Here is some of those logs:

2022-12-13T14:59:34.807-03:00   START RequestId: 58f5bfc7-a85a-494c-a92b-9f746d401ce9 Version: $LATEST
2022-12-13T14:59:34.808-03:00   event: {'rawBody': '{"app_permissions":"...'resource-path': '/discord'}}
2022-12-13T14:59:34.808-03:00   [*] running command...
2022-12-13T14:59:34.808-03:00   command hello
2022-12-13T14:59:34.808-03:00   [*] detected hello. Executing...
2022-12-13T14:59:34.809-03:00   END RequestId: 58f5bfc7-a85a-494c-a92b-9f746d401ce9

I have tried troubleshooting the issue by rejoining the bot on the server, adding more logs on Lambda execution, removing and adding API Gateway on INTERACTIONS ENDPOINT URL, but have not been able to resolve the problem. Any suggestions on how to fix this issue would be greatly appreciated.

My repository can be found here: https://github.com/crisdevnull1/cosmic-cat-bot
And the link of the tutorial that I followed: https://oozio.medium.com/serverless-discord-bot-55f95f26f743


问:
Error that runs mistakenly the previous codes when Actually want to run the current code in NetBeans
I've got problem with my NetBeans app, once I click on the run button, it runs the previous program
I coded. Like in the image, I ran the program (Which is  PasswordGUI) and it indescribably ran the previous code (Which was Ourproject)

.. So, I'm stuck in here and need help

best wishes

I tried to search if my project in the app have kind of untidy which may this problem the untidiness
of my projects..


Title: How to write arrays to .bson file using bson package from pymongo

Body:
I have a dictionary my_dict of the following form. It has two keys, '0' and '1'. For either of these keys, my_dict['0'] is an np.array with np.shape(my_dict['0']) = (10, 400000).

I am trying to use the bson package from PyMongo to write this dictionary to a .bson file. My code is

import bson

with open('file_name.bson', 'wb') as f:
    f.write(bson.encode(my_dict))

However, I get the following error message:

---------------------------------------------------------------------------
InvalidDocument                           Traceback (most recent call last)
Cell In [58], line 2
      1 with open('file_name.bson', 'wb') as f:
----> 2     f.write(bson.encode(my_dict))

File /opt/anaconda3/envs/env/lib/python3.10/site-packages/bson/__init__.py:1021, in encode(document, check_keys, codec_options)
   1018 if not isinstance(codec_options, CodecOptions):
   1019     raise _CODEC_OPTIONS_TYPE_ERROR
-> 1021 return _dict_to_bson(document, check_keys, codec_options)

InvalidDocument: cannot encode object: array([[-6.23719836e+02, -1.36955615e+03, -2.26481493e+03, ...,
        -2.57530488e+05,  1.41191655e+05,  3.68818106e+05],
       [ 3.51672758e+03,  4.23929871e+03,  4.19956936e+03, ...,
        -1.36596353e+07,  2.86662539e+06,  1.44995899e+07],
       [-6.13804894e+03, -3.91523214e+03, -4.16903017e+03, ...,
        -4.40730152e+08,  9.73392618e+07,  4.49351728e+08],
       ...,
       [-2.28620787e+04,  3.11671441e+04, -5.07810896e+04, ...,
        -1.30874776e+15,  7.45906067e+14,  1.16835974e+15],
       [-1.70260327e+05,  4.86525723e+04, -2.65229256e+05, ...,
        -1.91624806e+16,  1.20260881e+16,  1.67045997e+16],
       [-8.67528180e+05,  5.10548548e+04, -1.18028366e+06, ...,
        -2.62114048e+17,  1.77851766e+17,  2.23740879e+17]]), of type: <class 'numpy.ndarray'>

It seems like .bson is struggling with the array structure? This is very odd because I've definitely imported arrays from .bson files before though.

I've been trying to google to see what is going on with this InvalidDocument error but haven't found anything useful yet.

The closest is this site which says the max BSON doc size is 16 MB, but I really don't think my arrays have this issue / I've definitely imported way larger arrays from .bson before

If anyone can give me a pointer, or even just point me towards a gentle page describing how to write a .bson file (I've realy struggled to find a good reference for easy file I/O with bson), please let me know!


问:
Making a zip code choropleth map using R and plotly
I am trying to create a choropleth map for zip codes in R using plotly and running into a few issues. I find a lot of documentation on making choropleth maps for county level data, but not much on zip codes.

I have a data frame that looks like this (not the complete df, there are 60 zip codes in total).

```<code>Zip_list Fail    Pass    Pass/w Conditions
60625   0.278   0.482   0.240
60640   0.288   0.492   0.220
60618   0.247   0.501   0.251
60657   0.281   0.503   0.216
60639   0.283   0.449   0.268
60609   0.321   0.481   0.198
60647   0.229   0.563   0.209
60620   0.350   0.415   0.235
60614   0.215   0.500   0.285
60616   0.261   0.515   0.224
</code>```

I have a geojson file that I downloaded from the Chicago data portal which has the zip code boundaries.
https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-ZIP-Codes/gdcf-axmw

I have been trying to follow along with the examples on their documentation pages.

https://plotly.com/r/mapbox-county-choropleth/

Here is what I have tried:

chi_zips is the geojson file

abcd is my data frame

fig <- plot_ly()
fig <- fig %>% add_trace(
    type="choroplethmapbox",
    geojson=chi_zips,
    locations=as.character(abcd$zip_list),
    z=abcd$Fail,
    colorscale="Viridis",
    featureidkey="objectid",
    zmin=0,
    zmax=1,
    marker=list(line=list(
      width=0),
      opacity=0.5
    )
  )
fig <- fig %>% layout(
    mapbox=list(
      style="carto-positron",
      zoom =2,
      center=list(lon= -95.71, lat=37.09))
  )
fig

```

The map renders but it is blank. Not sure where to go from here. From what I understand I have to match the zip codes my data frame to the locations on the geojson file which is what I thought locations=as.character(abcd$zip_list) was doing.

Body:
I am trying to create a choropleth map for zip codes in R using plotly and running into a few issues. I find a lot of documentation on making choropleth maps for county level data, but not much on zip codes.

I have a data frame that looks like this (not the complete df, there are 60 zip codes in total).

Zip_list Fail    Pass    Pass/w Conditions
60625   0.278   0.482   0.240
60640   0.288   0.492   0.220
60618   0.247   0.501   0.251
60657   0.281   0.503   0.216
60639   0.283   0.449   0.268
60609   0.321   0.481   0.198
60647   0.229   0.563   0.209
60620   0.350   0.415   0.235
60614   0.215   0.500   0.285
60616   0.261   0.515   0.224

I have a geojson file that I downloaded from the Chicago data portal which has the zip code boundaries.
https://data.cityofchicago.org/Facilities-Geographic-Boundaries/Boundaries-ZIP-Codes/gdcf-axmw

I have been trying to follow along with the examples on their documentation pages.

https://plotly.com/r/mapbox-county-choropleth/

Here is what I have tried:

chi_zips is the geojson file

abcd is my data frame

fig <- plot_ly()
fig <- fig %>% add_trace(
    type="choroplethmapbox",
    geojson=chi_zips,
    locations=as.character(abcd$zip_list),
    z=abcd$Fail,
    colorscale="Viridis",
    featureidkey="objectid",
    zmin=0,
    zmax=1,
    marker=list(line=list(
      width=0),
      opacity=0.5
    )
  )
fig <- fig %>% layout(
    mapbox=list(
      style="carto-positron",
      zoom =2,
      center=list(lon= -95.71, lat=37.09))
  )
fig

The map renders but it is blank. Not sure where to go from here. From what I understand I have to match the zip codes my data frame to the locations on the geojson file which is what I thought locations=as.character(abcd$zip_list) was doing.


问:
Setting html form input to session varible
I can't put my form input values into session varible

I need to store form inputs into a session variable because I  have to use them in some other pages
When I print the sessin value below the code I get empty array

```<code><?php
session_start();
include('config/dbConnect.php');

if(isset($_POST["email"])){
    $email = $_POST["email"];
    $_SESSION["email"] = $email;

}
if(isset($_POST["password"])){
    $password = $_POST["password"];
    $_SESSION["password"] = $password;
}

print_r($_SESSION);

?>

<!DOCKTYPE html>
<html>

    <?php

    include('templates/header.php');
    ?>
     <section class='container grey-text'>
      <h4 class='center'>Please Log In</h4>
        <form class='white' action = "" method="SESSION">
            <label >Email</label>
            <input type="text" name="email" method = "SESSION">
            <label >Password</label>
            <input type="text" name="password" method = "SESSION">
            <div class ="center">
                <input type="submit" name="submit" value="Log In" class="btn z-depth-0">
            </div>
        </form>
     </section>

<body>

</html>
</code>```

Body:
I can't put my form input values into session varible

I need to store form inputs into a session variable because I  have to use them in some other pages
When I print the sessin value below the code I get empty array

<?php
session_start();
include('config/dbConnect.php');

if(isset($_POST["email"])){
    $email = $_POST["email"];
    $_SESSION["email"] = $email;

}
if(isset($_POST["password"])){
    $password = $_POST["password"];
    $_SESSION["password"] = $password;
}

print_r($_SESSION);

?>

<!DOCKTYPE html>

    <?php

    include('templates/header.php');
    ?>

Please Log In

        <form class='white' action = "" method="SESSION">
            Email
            <input type="text" name="email" method = "SESSION">
            Password
            <input type="text" name="password" method = "SESSION">

                <input type="submit" name="submit" value="Log In" class="btn z-depth-0">

        </form>


问:
What is the proper use of localCheckpoint()
I am in need of using localCheckpoint() to resize shuffle partitions, but I am unsure how to use it properly. I searched through Github as well as Stackoverflow and found effectively everyone repeating this block of code (with no further context, situation, reasoning, etc) which is from this databricks presentation: https://www.youtube.com/watch?v=daXEp4HmS-E

```<code>df.localCheckpoint(...).repartition(n).write(...)
</code>```

How do I use this properly? For instance, do I:

```<code>df = df.localCheckpoint()
</code>```

or

```<code>df.localCheckpoint()
</code>```

Under what conditions would I repartition? Is specifying the write necessary?

Let's say I have specified my number of shuffle partitions like so:

```<code>spark.conf.set("spark.sql.shuffle.partitions", 1200);

# bunch of work here

# local checkpoint here
</code>```

But I have more work to do, but at a different shuffle scale, so then can I set my shuffle partitions again, like so?

```<code>spark.conf.set("spark.sql.shuffle.partitions", 400);

# more work here

# local checkpoint again
</code>```

Finally, write to disk:

```<code>df.coalesce(n).write....
</code>```

How should localCheckpoint() be used in work that we have to chain together at different shuffle scales?

Also, how can I use two localCheckpoint() operations? If I run one localCheckpoint() on df but then run another on df2; when I return to yet another localCheckpoint() on df, I get:

Checkpoint block rdd_322_17 not found! Either the executor that originally checkpointed this partition is no longer alive, or the original RDD is unpersisted

Body:
I am in need of using localCheckpoint() to resize shuffle partitions, but I am unsure how to use it properly. I searched through Github as well as Stackoverflow and found effectively everyone repeating this block of code (with no further context, situation, reasoning, etc) which is from this databricks presentation: https://www.youtube.com/watch?v=daXEp4HmS-E

df.localCheckpoint(...).repartition(n).write(...)

How do I use this properly? For instance, do I:

df = df.localCheckpoint()

or

df.localCheckpoint()

Under what conditions would I repartition? Is specifying the write necessary?

Let's say I have specified my number of shuffle partitions like so:

spark.conf.set("spark.sql.shuffle.partitions", 1200);

# bunch of work here

# local checkpoint here

But I have more work to do, but at a different shuffle scale, so then can I set my shuffle partitions again, like so?

spark.conf.set("spark.sql.shuffle.partitions", 400);

# more work here

# local checkpoint again

Finally, write to disk:

df.coalesce(n).write....

How should localCheckpoint() be used in work that we have to chain together at different shuffle scales?

Also, how can I use two localCheckpoint() operations? If I run one localCheckpoint() on df but then run another on df2; when I return to yet another localCheckpoint() on df, I get:

Checkpoint block rdd_322_17 not found! Either the executor that originally checkpointed this partition is no longer alive, or the original RDD is unpersisted


问:
Google Drive API: 404 File not found error [custom company domain]
I've been trying to GET google drive file by file id using a service account in NodeJS, but requests are failed with the following error (meaning the lack of access):

```<code>  code: 404,
  errors: [
    {
      message: 'File not found: XXX.',
      domain: 'global',
      reason: 'notFound',
      location: 'fileId',
      locationType: 'parameter'
    }
  ]

</code>```

Scope

I've tried to play around with the scope by adding extra scopes, but essentially https://www.googleapis.com/auth/drive have been always in place.

```<code>const scopes = [
  'https://www.googleapis.com/auth/drive',
  'https://www.googleapis.com/auth/drive.appdata',
  'https://www.googleapis.com/auth/drive.file',
  'https://www.googleapis.com/auth/drive.metadata',
  'https://www.googleapis.com/auth/drive.metadata.readonly',
  'https://www.googleapis.com/auth/drive.photos.readonly',
  'https://www.googleapis.com/auth/drive.readonly',
];
</code>```

Service account

I've created a service account, following the same conventional flow showed in different resources/docs/tutorials (1, 2, 3, etc)

https://console.cloud.google.com/iam-admin/serviceaccounts?project=XXXX

Enabled Google Drive API

https://console.cloud.google.com/marketplace/product/google/drive.googleapis.com

Enabled Domain-wide Delegation in admin google panel with the exact same scope as listed above (also had tested without additionally enabling this)

https://admin.google.com/ac/owl/domainwidedelegation

Source code

There's a google nodejs quickstart out there for accessing drive api that works the way a user granting permissions through oauth2 modal (example), that's not acceptable in my case, since it must be working using service account (akka demon machine-2-machine) without any real user interaction.

I've tried out many ways:

using google-auth-library package:

const { auth } = require('google-auth-library');

const client = auth.fromJSON({
  type: 'service_account',
  project_id: 'XXX',
  private_key_id: 'XXX',
  private_key: 'XXX',
  client_email: 'X@Y.iam.gserviceaccount.com',
  client_id: 'XXXX',
  auth_uri: 'https://accounts.google.com/o/oauth2/auth',
  token_uri: 'https://oauth2.googleapis.com/token',
  auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs',
  client_x509_cert_url:
    'https://www.googleapis.com/robot/v1/metadata/x509/X%40Y.iam.gserviceaccount.com',
});

// also tested with exact same scopes listed above
const scopes = ['https://www.googleapis.com/auth/drive'];
client.scopes = scopes;
// tested both options for `supportsAllDrives`: true/false

const url = `https://www.googleapis.com/drive/v3/files/XXX?fields=name&supportsAllDrives=true`;
client.request({ url }).then(console.log).catch(console.error);
```
<ul>
<li>using ts-google-drive package:</li>
</ul>
```import { TsGoogleDrive } from 'ts-google-drive';

const tsGoogleDrive = new TsGoogleDrive({
  credentials: {
    client_email: 'X@Y.iam.gserviceaccount.com',
    private_key: '',
  },
});

async function getSingleFile(fileId: string): Promise<void> {
  // returns `undefined`, meaning an error
  const file = await tsGoogleDrive.getFile(fileId);
  console.log('file', file);
  if (file) {
    const isFolder = file.isFolder;
    console.log('isFolder', isFolder);
  }
}

getSingleFile('XXX');
```
<ul>
<li>using googleapis</li>
</ul>
<pre class="lang-js prettyprint-override"><code>const { google } = require('googleapis');

const auth = new google.auth.GoogleAuth({
  keyFile: 'service-account.json', // file properly located
  scopes: ..., // same scope
});

const drive = google.drive({ version: 'v3', auth });

const driveResponse = await drive.files.list({
fields: '*',
});

const file = await drive.files.get({
  fileId: 'XXX',
  fields: 'name',
  supportsAllDrives: true,
});

console.log(file); // error!
</code>```

using googleapis with jwtClient

const google = require('googleapis');
const fs = require('fs');
const key = require('./service-account.json');

const scopes = ... // same

const drive = google.google.drive('v3');

const jwtClient = new google.google.auth.JWT(
  key.client_email,
  null,
  key.private_key,
  scopes,
  null,
);

jwtClient.authorize(async (authErr) => {
  if (authErr) {
    console.log(authErr); // NO error here
    return;
  }

  const drive = google.google.drive({ version: 'v3', auth: jwtClient });

  console.log('jwtClient.getCredentials()', jwtClient.getCredentials());
  console.log('jwtClient.apiKey', jwtClient.apiKey);
  console.log('jwtClient.credentials', jwtClient.credentials);
  console.log('jwtClient.gtoken', jwtClient.gtoken);

// errors occur down below when actually requesting the api
  const file = await drive.files.get({
    fileId: 'XXX',
    fields: 'name',
    supportsAllDrives: true,
  });

  console.log(file);
});
```
<p><code>./service-account</code> file structure:</p>
<pre class="lang-json prettyprint-override"><code>{
  "type": "service_account",
  "project_id": "X",
  "private_key_id": "XXXX",
  "client_email": "X@Y.iam.gserviceaccount.com",
  "client_id": "XXX",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/X%Y.iam.gserviceaccount.com"
}

</code>```

Google Drive resources permissions

Since I'm trying to access my internal company's google drive files, I'm running into issues of giving possibly required file permissions to my service account:

attempt to share a folder/drive with my service account ended up being unsuccessful

It's also important to note that I've failed accessing a file that had been shared with my service account granularly (file was in "Shared with me").

Even though any public file in my company's drive can be accessed for no problem.

ER

To have it being able to access the company drive files using a service account (no real user interaction) - to highliht if it's importatn - those are located in "Shared with me" and in "Shared drives".

Body:
I've been trying to GET google drive file by file id using a service account in NodeJS, but requests are failed with the following error (meaning the lack of access):

  code: 404,
  errors: [
    {
      message: 'File not found: XXX.',
      domain: 'global',
      reason: 'notFound',
      location: 'fileId',
      locationType: 'parameter'
    }
  ]

Scope

I've tried to play around with the scope by adding extra scopes, but essentially https://www.googleapis.com/auth/drive have been always in place.

const scopes = [
  'https://www.googleapis.com/auth/drive',
  'https://www.googleapis.com/auth/drive.appdata',
  'https://www.googleapis.com/auth/drive.file',
  'https://www.googleapis.com/auth/drive.metadata',
  'https://www.googleapis.com/auth/drive.metadata.readonly',
  'https://www.googleapis.com/auth/drive.photos.readonly',
  'https://www.googleapis.com/auth/drive.readonly',
];

Service account

I've created a service account, following the same conventional flow showed in different resources/docs/tutorials (1, 2, 3, etc)

https://console.cloud.google.com/iam-admin/serviceaccounts?project=XXXX

Enabled Google Drive API

https://console.cloud.google.com/marketplace/product/google/drive.googleapis.com

Enabled Domain-wide Delegation in admin google panel with the exact same scope as listed above (also had tested without additionally enabling this)

https://admin.google.com/ac/owl/domainwidedelegation

Source code

There's a google nodejs quickstart out there for accessing drive api that works the way a user granting permissions through oauth2 modal (example), that's not acceptable in my case, since it must be working using service account (akka demon machine-2-machine) without any real user interaction.

I've tried out many ways:

using google-auth-library package:

const { auth } = require('google-auth-library');

const client = auth.fromJSON({
  type: 'service_account',
  project_id: 'XXX',
  private_key_id: 'XXX',
  private_key: 'XXX',
  client_email: 'X@Y.iam.gserviceaccount.com',
  client_id: 'XXXX',
  auth_uri: 'https://accounts.google.com/o/oauth2/auth',
  token_uri: 'https://oauth2.googleapis.com/token',
  auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs',
  client_x509_cert_url:
    'https://www.googleapis.com/robot/v1/metadata/x509/X%40Y.iam.gserviceaccount.com',
});

// also tested with exact same scopes listed above
const scopes = ['https://www.googleapis.com/auth/drive'];
client.scopes = scopes;
// tested both options for `supportsAllDrives`: true/false

const url = `https://www.googleapis.com/drive/v3/files/XXX?fields=name&supportsAllDrives=true`;
client.request({ url }).then(console.log).catch(console.error);

using ts-google-drive package:

import { TsGoogleDrive } from 'ts-google-drive';

const tsGoogleDrive = new TsGoogleDrive({
  credentials: {
    client_email: 'X@Y.iam.gserviceaccount.com',
    private_key: '',
  },
});

async function getSingleFile(fileId: string): Promise<void> {
  // returns `undefined`, meaning an error
  const file = await tsGoogleDrive.getFile(fileId);
  console.log('file', file);
  if (file) {
    const isFolder = file.isFolder;
    console.log('isFolder', isFolder);
  }
}

getSingleFile('XXX');

using googleapis

const { google } = require('googleapis');

const auth = new google.auth.GoogleAuth({
  keyFile: 'service-account.json', // file properly located
  scopes: ..., // same scope
});

const drive = google.drive({ version: 'v3', auth });

const driveResponse = await drive.files.list({
fields: '*',
});

const file = await drive.files.get({
  fileId: 'XXX',
  fields: 'name',
  supportsAllDrives: true,
});

console.log(file); // error!

using googleapis with jwtClient

const google = require('googleapis');
const fs = require('fs');
const key = require('./service-account.json');

const scopes = ... // same

const drive = google.google.drive('v3');

const jwtClient = new google.google.auth.JWT(
  key.client_email,
  null,
  key.private_key,
  scopes,
  null,
);

jwtClient.authorize(async (authErr) => {
  if (authErr) {
    console.log(authErr); // NO error here
    return;
  }

  const drive = google.google.drive({ version: 'v3', auth: jwtClient });

  console.log('jwtClient.getCredentials()', jwtClient.getCredentials());
  console.log('jwtClient.apiKey', jwtClient.apiKey);
  console.log('jwtClient.credentials', jwtClient.credentials);
  console.log('jwtClient.gtoken', jwtClient.gtoken);

// errors occur down below when actually requesting the api
  const file = await drive.files.get({
    fileId: 'XXX',
    fields: 'name',
    supportsAllDrives: true,
  });

  console.log(file);
});

./service-account file structure:

{
  "type": "service_account",
  "project_id": "X",
  "private_key_id": "XXXX",
  "client_email": "X@Y.iam.gserviceaccount.com",
  "client_id": "XXX",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/X%Y.iam.gserviceaccount.com"
}

Google Drive resources permissions

Since I'm trying to access my internal company's google drive files, I'm running into issues of giving possibly required file permissions to my service account:

attempt to share a folder/drive with my service account ended up being unsuccessful

It's also important to note that I've failed accessing a file that had been shared with my service account granularly (file was in "Shared with me").

Even though any public file in my company's drive can be accessed for no problem.

ER

To have it being able to access the company drive files using a service account (no real user interaction) - to highliht if it's importatn - those are located in "Shared with me" and in "Shared drives".


问:
React Hooks: Does defining a hook with a default value trigger a rerender due to it being a new object?
I have a hook useHook and it has an optional options param options: {thing1: string}. In this example, the object is assigned when there is not an options param passed.

My question is, when there is not an options parameter will the options object be effectively memoized during the re-render process? Or, will the hook view it as a new object with exactly the same data?

```<code>export const useHook = ({
    options = { thing1: 'test_name'}
}) => {
    // ... Does some logic
}
</code>```

Finally, is a better pattern to require a options param and have one defined?

```<code>export const DEFAULT_USEHOOK_OPTIONS = { thing1: 'test_name'}
</code>```

Body:
I have a hook useHook and it has an optional options param options: {thing1: string}. In this example, the object is assigned when there is not an options param passed.

My question is, when there is not an options parameter will the options object be effectively memoized during the re-render process? Or, will the hook view it as a new object with exactly the same data?

export const useHook = ({
    options = { thing1: 'test_name'}
}) => {
    // ... Does some logic
}

Finally, is a better pattern to require a options param and have one defined?

export const DEFAULT_USEHOOK_OPTIONS = { thing1: 'test_name'}


问:
How to Copy Link to Files in Shared Google Drive (Batch copy)
We use shared google drives and will often link files to one another. E.g., a pdf saved in drive may be discussed in a spreadsheet/doc with a link to drive included. We usually grab these links in a browser or using the "Copy link to clipboard" option on Google Drive for Mac (right click in Finder).

I'm looking to automate some processes and would like to include the Copy Link step as part of the automation.

Digging through the documentation for the google drive api, I've found some options to update permissions, but can't find anything to just copy an existing share link like we do in our workflows.

https://developers.google.com/drive/api/guides/manage-sharing

Does anyone have suggestions on this? We have automation set up in r and python, so options within that would be preferable.


问:
Render custom radio button group with react-jsonschema-form?
I'm using react-jsonschema-form to render a form.
I can't figure out how to render a group of custom radio button elements. all I get is a single element

this is my schema:

```<code>overwrite: {
      type: "number",
      title: "Overwrite",
      default: 2,
      description: "Using enum",
      oneOf: [
        {
          type: "number",
          title: "One",
          enum: [1],
        },
        {
          type: "number",
          title: "2",
          enum: [2],
        },
        {
          type: "number",
          title: "Num 3",
          enum: [3],
        },
      ],
    }
</code>```

My uiSchema:

```<code>      overwrite: {
        "ui:widget": "radio",
      }
</code>```

A custom radio button:

```<code>    const CustomRadio = (props: WidgetProps) => {
      return (
        <>
          <RadioButton
            id={props.id}
            name={props.id}
            value={props.value}
            onChange={(event) => props.onChange(event.target.value)}
            checked={props.defaultChecked}
            disabled={props.disabled}
          />
        </>
      );
    };
</code>```

And finally, the form:

```<code>        <Form
          FieldTemplate={FormRowTemplate}
          schema={FormSchema}
          uiSchema={uiSchema}
          widgets={widgets}
        >
          <>{/* this is to hide the submit button*/}</>
        </Form>
</code>```

Which results in a single, empty radio button:

Thanks for the help!

Body:
I'm using react-jsonschema-form to render a form.
I can't figure out how to render a group of custom radio button elements. all I get is a single element

this is my schema:

overwrite: {
      type: "number",
      title: "Overwrite",
      default: 2,
      description: "Using enum",
      oneOf: [
        {
          type: "number",
          title: "One",
          enum: [1],
        },
        {
          type: "number",
          title: "2",
          enum: [2],
        },
        {
          type: "number",
          title: "Num 3",
          enum: [3],
        },
      ],
    }

My uiSchema:

      overwrite: {
        "ui:widget": "radio",
      }

A custom radio button:

    const CustomRadio = (props: WidgetProps) => {
      return (
        <>
          <RadioButton
            id={props.id}
            name={props.id}
            value={props.value}
            onChange={(event) => props.onChange(event.target.value)}
            checked={props.defaultChecked}
            disabled={props.disabled}
          />
        </>
      );
    };

And finally, the form:

        <Form
          FieldTemplate={FormRowTemplate}
          schema={FormSchema}
          uiSchema={uiSchema}
          widgets={widgets}
        >
          <>{/* this is to hide the submit button*/}</>
        </Form>

Which results in a single, empty radio button:

Thanks for the help!


问:
Publishing Android App from Visual Studio
I do the following steps:

Click on Build (from VS)

Click on Archive (from the VS Dropdown)
VS Archives the app as an APK (it's one file)

Click on Distribute

The Google Play Option is greyed out so I choose Ad Hoc

Add the Signing Identity

Open the Distribution folder

Run zipalign -p -f -v 4 on the apk specifying the output apk

Zipalign appears successful. So I try to upload to Google Play

9 UH OH:
You uploaded an APK with an invalid signature (learn more about signing). Error from apksigner: ERROR (Jar signer XXX.RSA): JAR signature META-INF/XXX.SF indicates the APK is signed using APK Signature Scheme v2 but no such signature was found. Signature stripped? ERROR (Jar signer XXX.RSA): JAR signature META-INF/XXX.SF indicates the APK is signed using APK Signature Scheme v3 but no such signature was found. Signature stripped?

OY VEY. What now?


问:
using str_sub in a function
I have a dataset where the precision of measurements varied between years, however the precision used in each year was not recorded.  Therefore, I want to infer the precision based on the values of the measurements.  For example, in a given year, if all the measurements end in 0, then I can infer the measurements were to the closest 10.  Similarly, if all the measurements end in 0's or 5's, then I can infer the measurements were to the closest 5.

Below is my example dataset and the function I am using to infer the precision of the values for each site in each year.  The str_sub function is throwing an error, that I don't know how to resolve, and this error persists regardless of whether I include the first line (or which option) to create precisionType.

```<code>library(dplyr)
library(stringr)

# example dataset with 3 years and 2 sites
# - first year measurements were to the closest 10
# - second year measurements were to the closest 5
# - third year measurements were to the closest 1
test <- data.frame(
  year = rep(c(rep(1995, 10), rep(1996, 10), rep(1997, 10)), 2),
  site = c(rep(LETTERS[1], 30), rep(LETTERS[2], 30)),
  mass = rep(c(rep(c(10,20,30,40,50), 2), rep(c(10, 25, 30, 35, 50), 2), rep(c(18, 25, 32, 44, 57), 2)), 2))

# function for inferring precision
fun_precision <- function(df, measurement, unit) {
  # set type of precision (e.g., LENGTH, MASS): 2 options and I have tried both
  precisionType <- paste(quo_name(enquo(measurement)), "PRECISION", sep = "_") # option 1
  # precisionType <- paste(deparse(substitute(measurement)), "PRECISION", sep = "_") # option 2

  # determine precision (i.e., by1, by5 or by10 units)
  precision <- df %>%
    # determine last digit in measurement
    mutate(last = as.numeric(str_sub(measurement, -1, -1))) %>%
    # group by year, river and last digit
    group_by(year, site, last) %>%
    # count number of times the last digit occurs
    summarise(n = n()) %>%
    # arrange dataframe from smallest to largest last digits
    arrange(last) %>%
    # switch from long to wide format
    pivot_wider(id_cols      = c(year, site),
                names_from   = last,
                names_prefix = "n", #appends n before last digit (e.g., n1, n2, etc.)
                values_from  = n) %>%
    # determine precision of measurement
    mutate(
      not0    = sum(c_across(c(n1:n9)), na.rm = TRUE),
      not0or5 = sum(c_across(c(n1:n4, n6:n9)), na.rm = TRUE),
      "{precisionType}" = case_when(nNA > 0 & not0 == 0 ~ NA_character_,
                                    not0 == 0           ~ paste("By10", unit, sep = ""),
                                    not0or5 > 0         ~ paste("By1", unit, sep = ""),
                                    !is.na(n0) & !is.na(n5) ~ paste("By5", unit, sep = ""))) %>%
    select(year, site, precisionType)

  # join to initial dataset
  df <- left_join(df, precision)
}

test <- fun_precision(test, mass, "g")
Error in `mutate()`:
! Problem while computing `last = as.numeric(str_sub(measurement, -1, -1))`.
Caused by error in `stri_sub()`:
! object 'mass' not found
Run `rlang::last_error()` to see where the error occurred.
</code>```

Title: using str_sub in a function

Body:
I have a dataset where the precision of measurements varied between years, however the precision used in each year was not recorded.  Therefore, I want to infer the precision based on the values of the measurements.  For example, in a given year, if all the measurements end in 0, then I can infer the measurements were to the closest 10.  Similarly, if all the measurements end in 0's or 5's, then I can infer the measurements were to the closest 5.

Below is my example dataset and the function I am using to infer the precision of the values for each site in each year.  The str_sub function is throwing an error, that I don't know how to resolve, and this error persists regardless of whether I include the first line (or which option) to create precisionType.

library(dplyr)
library(stringr)

# example dataset with 3 years and 2 sites
# - first year measurements were to the closest 10
# - second year measurements were to the closest 5
# - third year measurements were to the closest 1
test <- data.frame(
  year = rep(c(rep(1995, 10), rep(1996, 10), rep(1997, 10)), 2),
  site = c(rep(LETTERS[1], 30), rep(LETTERS[2], 30)),
  mass = rep(c(rep(c(10,20,30,40,50), 2), rep(c(10, 25, 30, 35, 50), 2), rep(c(18, 25, 32, 44, 57), 2)), 2))

# function for inferring precision
fun_precision <- function(df, measurement, unit) {
  # set type of precision (e.g., LENGTH, MASS): 2 options and I have tried both
  precisionType <- paste(quo_name(enquo(measurement)), "PRECISION", sep = "_") # option 1
  # precisionType <- paste(deparse(substitute(measurement)), "PRECISION", sep = "_") # option 2

  # determine precision (i.e., by1, by5 or by10 units)
  precision <- df %>%
    # determine last digit in measurement
    mutate(last = as.numeric(str_sub(measurement, -1, -1))) %>%
    # group by year, river and last digit
    group_by(year, site, last) %>%
    # count number of times the last digit occurs
    summarise(n = n()) %>%
    # arrange dataframe from smallest to largest last digits
    arrange(last) %>%
    # switch from long to wide format
    pivot_wider(id_cols      = c(year, site),
                names_from   = last,
                names_prefix = "n", #appends n before last digit (e.g., n1, n2, etc.)
                values_from  = n) %>%
    # determine precision of measurement
    mutate(
      not0    = sum(c_across(c(n1:n9)), na.rm = TRUE),
      not0or5 = sum(c_across(c(n1:n4, n6:n9)), na.rm = TRUE),
      "{precisionType}" = case_when(nNA > 0 & not0 == 0 ~ NA_character_,
                                    not0 == 0           ~ paste("By10", unit, sep = ""),
                                    not0or5 > 0         ~ paste("By1", unit, sep = ""),
                                    !is.na(n0) & !is.na(n5) ~ paste("By5", unit, sep = ""))) %>%
    select(year, site, precisionType)

  # join to initial dataset
  df <- left_join(df, precision)
}

test <- fun_precision(test, mass, "g")
Error in `mutate()`:
! Problem while computing `last = as.numeric(str_sub(measurement, -1, -1))`.
Caused by error in `stri_sub()`:
! object 'mass' not found
Run `rlang::last_error()` to see where the error occurred.


问:
How to move image objects one at a time?
The code I pasted below moves seven card images from and to predefined spots on a surface. However, I would like the images to move one at a time--image1 moves to (100, 180) and only then does image2 move to (240, 300), etc. Right now all seven images move at the same time.

I have seen SO posts like this  and this, and looked at the referenced pyGame documentation. The sources tell me I need to "pump" the event que but, to be honest, I don't really understand. I understand the concept of event-based programming and writing event handlers, from languages like Delphi, C#, and even the pyQt GUI framework, but beyond that ... struggling. (When do I pump? Does pumping also update? Do I call update() with pump=True?)

NOTE: To clarify, my question is not about how to move an image between given coordinates. The code below already does that. It's about moving image1 between given coordinates before image2 or any other images move. I want image1 to move, then image2, then image3, etc. I don't want all seven images to move simultaneously.

```<code>import pygame

pygame.init()
window = pygame.display.set_mode((1160, 580))
clock = pygame.time.Clock()
pygame.display.set_caption('Blackjack Card Counting Drill')

pos_start = (580, 100)
pos1 = pos_start
pos_end1 = (100, 180)
pos2 = pos_start
pos_end2 = (240, 300)
pos3 = pos_start
pos_end3 = (400, 360)
pos4 = pos_start
pos_end4 = (580, 390)
pos5 = pos_start
pos_end5 = (760, 360)
pos6 = pos_start
pos_end6 = (930, 300)
pos7 = pos_start
pos_end7 = (1060, 180)

speed = 5

# pos = image position coordinates
def move(pos, pos_end):
    # direction = vector whose coordinates are the image's end point - current position
    direction = pygame.math.Vector2(pos_end) - pos
    # as long as the direction vector is longer than the distance we want the image to move/method execution...
    if direction.length() > speed:
        # scale the direction vector so its length=speed, keeping its direction the same
        # so, the vector's still pointing toward the end coordinates, and it's 5 units long
        direction.scale_to_length(speed)
        # take the image's current position and move it 5 units in the right direction
        new_pos = pygame.math.Vector2(pos) + direction
        # return its new location
        pos = (new_pos.x, new_pos.y)
    return pos

bg = pygame.image.load("blackjack_table.jpg")
deck = pygame.image.load('card_back.png')
# scale image to 0.1 size
deck = pygame.transform.rotozoom(deck, 0, 0.1)
image1 = pygame.image.load('2C.png')
image1 = pygame.transform.rotozoom(image1, 0, 0.1)
image2 = pygame.image.load('2C.png')
image2 = pygame.transform.rotozoom(image2, 0, 0.1)
image3 = pygame.image.load('2C.png')
image3 = pygame.transform.rotozoom(image3, 0, 0.1)
image4 = pygame.image.load('2C.png')
image4 = pygame.transform.rotozoom(image4, 0, 0.1)
image5 = pygame.image.load('2C.png')
image5 = pygame.transform.rotozoom(image5, 0, 0.1)
image6 = pygame.image.load('2C.png')
image6 = pygame.transform.rotozoom(image6, 0, 0.1)
image7 = pygame.image.load('2C.png')
image7 = pygame.transform.rotozoom(image7, 0, 0.1)

run = True
while run:
    clock.tick(200)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(bg, (0, 0))
    deck_rect = deck.get_rect(center=pos_start)
    window.blit(deck, deck_rect)
    pos1 = move(pos1, pos_end1)
    image_rect = image1.get_rect(center=pos1)
    window.blit(image1, image_rect)
    pos2 = move(pos2, pos_end2)
    image_rect2 = image2.get_rect(center=pos2)
    window.blit(image2, image_rect2)
    pos3 = move(pos3, pos_end3)
    image_rect3 = image3.get_rect(center=pos3)
    window.blit(image3, image_rect3)
    pos4 = move(pos4, pos_end4)
    image_rect4 = image4.get_rect(center=pos4)
    window.blit(image4, image_rect4)
    pos5 = move(pos5, pos_end5)
    image_rect5 = image5.get_rect(center=pos5)
    window.blit(image5, image_rect5)
    pos6 = move(pos6, pos_end6)
    image_rect6 = image6.get_rect(center=pos6)
    window.blit(image6, image_rect6)
    pos7 = move(pos7, pos_end7)
    image_rect7 = image7.get_rect(center=pos7)
    window.blit(image7, image_rect7)

    pygame.display.update()

pygame.quit()
exit()
</code>```

p.s. I know the code's inefficiently written. It needs to be refactored into procedures.

Body:
The code I pasted below moves seven card images from and to predefined spots on a surface. However, I would like the images to move one at a time--image1 moves to (100, 180) and only then does image2 move to (240, 300), etc. Right now all seven images move at the same time.

I have seen SO posts like this  and this, and looked at the referenced pyGame documentation. The sources tell me I need to "pump" the event que but, to be honest, I don't really understand. I understand the concept of event-based programming and writing event handlers, from languages like Delphi, C#, and even the pyQt GUI framework, but beyond that ... struggling. (When do I pump? Does pumping also update? Do I call update() with pump=True?)

NOTE: To clarify, my question is not about how to move an image between given coordinates. The code below already does that. It's about moving image1 between given coordinates before image2 or any other images move. I want image1 to move, then image2, then image3, etc. I don't want all seven images to move simultaneously.

import pygame

pygame.init()
window = pygame.display.set_mode((1160, 580))
clock = pygame.time.Clock()
pygame.display.set_caption('Blackjack Card Counting Drill')

pos_start = (580, 100)
pos1 = pos_start
pos_end1 = (100, 180)
pos2 = pos_start
pos_end2 = (240, 300)
pos3 = pos_start
pos_end3 = (400, 360)
pos4 = pos_start
pos_end4 = (580, 390)
pos5 = pos_start
pos_end5 = (760, 360)
pos6 = pos_start
pos_end6 = (930, 300)
pos7 = pos_start
pos_end7 = (1060, 180)

speed = 5

# pos = image position coordinates
def move(pos, pos_end):
    # direction = vector whose coordinates are the image's end point - current position
    direction = pygame.math.Vector2(pos_end) - pos
    # as long as the direction vector is longer than the distance we want the image to move/method execution...
    if direction.length() > speed:
        # scale the direction vector so its length=speed, keeping its direction the same
        # so, the vector's still pointing toward the end coordinates, and it's 5 units long
        direction.scale_to_length(speed)
        # take the image's current position and move it 5 units in the right direction
        new_pos = pygame.math.Vector2(pos) + direction
        # return its new location
        pos = (new_pos.x, new_pos.y)
    return pos

bg = pygame.image.load("blackjack_table.jpg")
deck = pygame.image.load('card_back.png')
# scale image to 0.1 size
deck = pygame.transform.rotozoom(deck, 0, 0.1)
image1 = pygame.image.load('2C.png')
image1 = pygame.transform.rotozoom(image1, 0, 0.1)
image2 = pygame.image.load('2C.png')
image2 = pygame.transform.rotozoom(image2, 0, 0.1)
image3 = pygame.image.load('2C.png')
image3 = pygame.transform.rotozoom(image3, 0, 0.1)
image4 = pygame.image.load('2C.png')
image4 = pygame.transform.rotozoom(image4, 0, 0.1)
image5 = pygame.image.load('2C.png')
image5 = pygame.transform.rotozoom(image5, 0, 0.1)
image6 = pygame.image.load('2C.png')
image6 = pygame.transform.rotozoom(image6, 0, 0.1)
image7 = pygame.image.load('2C.png')
image7 = pygame.transform.rotozoom(image7, 0, 0.1)

run = True
while run:
    clock.tick(200)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.blit(bg, (0, 0))
    deck_rect = deck.get_rect(center=pos_start)
    window.blit(deck, deck_rect)
    pos1 = move(pos1, pos_end1)
    image_rect = image1.get_rect(center=pos1)
    window.blit(image1, image_rect)
    pos2 = move(pos2, pos_end2)
    image_rect2 = image2.get_rect(center=pos2)
    window.blit(image2, image_rect2)
    pos3 = move(pos3, pos_end3)
    image_rect3 = image3.get_rect(center=pos3)
    window.blit(image3, image_rect3)
    pos4 = move(pos4, pos_end4)
    image_rect4 = image4.get_rect(center=pos4)
    window.blit(image4, image_rect4)
    pos5 = move(pos5, pos_end5)
    image_rect5 = image5.get_rect(center=pos5)
    window.blit(image5, image_rect5)
    pos6 = move(pos6, pos_end6)
    image_rect6 = image6.get_rect(center=pos6)
    window.blit(image6, image_rect6)
    pos7 = move(pos7, pos_end7)
    image_rect7 = image7.get_rect(center=pos7)
    window.blit(image7, image_rect7)

    pygame.display.update()

pygame.quit()
exit()

p.s. I know the code's inefficiently written. It needs to be refactored into procedures.