问:
How to get TinyMCE Content in Custom Control WP_CUSTOMIZE and Display it in frontend in Wordpress

I created a "WordPress customizer custom tinymce control" and it appears on the customizer page, but I can't show the content where it's needed on the frontend.
 I tried to use **get_theme_mod()** but to no avail.

how can I do that?
Used Codes Below
Thank You

HTML Code:

```<code><div class="bottom-footer">
  <div class="container">
    <div class="copyright">
      <p>© 2020 <a href="/">CONSULTY</a> - Business & Consulting. All rights reserved.</p>
    </div>
  </div>
</div>
</code>```

Custom TinyMCE Class for Custom Control WP CUSTOMIZER

```<code><?php
/**
* TinyMCE Custom Control
*/
if (class_exists('WP_Customize_Control')) {
    class TinyMCE_Editor_Custom_Control extends WP_Customize_Control
    {
        public $type = 'textarea';
        /**
        ** Render the content on the theme customizer page
        */
        public function render_content() { ?>
<label>
    <span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
    <?php
                $settings = array(
                    'media_buttons' => false,
                    'quicktags' => false
                );
                $this->filter_editor_setting_link();
                wp_editor($this->value(), $this->id, $settings );
            ?>
</label>
<?php
            do_action('admin_footer');
            do_action('admin_print_footer_scripts');
        }

        private function filter_editor_setting_link() {
            add_filter( 'the_editor', function( $output ) { return preg_replace( '/<textarea/', '<textarea ' . $this->get_link(), $output, 1 ); } );
        }
    }

    function editor_customizer_script() {
        wp_enqueue_script( 'wp-editor-customizer', CONSULTY_THEME_DIR_URI . '/inc/customizer/assets/consulty-customize.js', array( 'jquery' ), rand(), true );
    }
    add_action( 'customize_controls_enqueue_scripts', 'editor_customizer_script' );
}
</code>```

Customizer JS Code

```<code>(function ($) {
  //
  wp.customizerCtrlEditor = {
    init: function () {
      $(window).load(function () {
        $("textarea.wp-editor-area").each(function () {
          var tArea = $(this),
            id = tArea.attr("id"),
            editor = tinyMCE.get(id),
            setChange,
            content;

          if (editor) {
            editor.onChange.add(function (ed, e) {
              ed.save();
              content = editor.getContent();
              clearTimeout(setChange);
              setChange = setTimeout(function () {
                tArea.val(content).trigger("change");
              }, 500);
            });
          }

          tArea
            .css({
              visibility: "visible",
            })
            .on("keyup", function () {
              content = tArea.val();
              clearTimeout(setChange);
              setChange = setTimeout(function () {
                content.trigger("change");
              }, 500);
            });
        });
      });
    },
  };

  wp.customizerCtrlEditor.init();
  //
})(jQuery);

</code>```

Customizer Setting & Control

```<code><?php
/**
 * TintMCE Editor
 */

$wp_customize->add_setting( 'theme[editor_content]', array(
    'default'           => '',
    'transport'         => 'postMessage',
    'sanitize_callback' => 'wp_kses_post'
) );

$wp_customize->add_control( new TinyMCE_Editor_Custom_Control(
        $wp_customize, 'editor_content', array(
            'label'     => 'CopyRights Text',
            'section'   => 'footer_options',
            'settings'  => 'theme[editor_content]',
            'type'      => 'textarea',
        )
    )
);
</code>```

Please How I can Show the Content in The Footer?

Body:
I created a "WordPress customizer custom tinymce control" and it appears on the customizer page, but I can't show the content where it's needed on the frontend.
 I tried to use **get_theme_mod()** but to no avail.

how can I do that?
Used Codes Below
Thank You

HTML Code:

© 2020 CONSULTY - Business & Consulting. All rights reserved.

Custom TinyMCE Class for Custom Control WP CUSTOMIZER

<?php
/**
* TinyMCE Custom Control
*/
if (class_exists('WP_Customize_Control')) {
    class TinyMCE_Editor_Custom_Control extends WP_Customize_Control
    {
        public $type = 'textarea';
        /**
        ** Render the content on the theme customizer page
        */
        public function render_content() { ?>

    <?php echo esc_html( $this->label ); ?>
    <?php
                $settings = array(
                    'media_buttons' => false,
                    'quicktags' => false
                );
                $this->filter_editor_setting_link();
                wp_editor($this->value(), $this->id, $settings );
            ?>

<?php
            do_action('admin_footer');
            do_action('admin_print_footer_scripts');
        }

        private function filter_editor_setting_link() {
            add_filter( 'the_editor', function( $output ) { return preg_replace( '/<textarea/', '<textarea ' . $this->get_link(), $output, 1 ); } );
        }
    }

    function editor_customizer_script() {
        wp_enqueue_script( 'wp-editor-customizer', CONSULTY_THEME_DIR_URI . '/inc/customizer/assets/consulty-customize.js', array( 'jquery' ), rand(), true );
    }
    add_action( 'customize_controls_enqueue_scripts', 'editor_customizer_script' );
}

Customizer JS Code

(function ($) {
  //
  wp.customizerCtrlEditor = {
    init: function () {
      $(window).load(function () {
        $("textarea.wp-editor-area").each(function () {
          var tArea = $(this),
            id = tArea.attr("id"),
            editor = tinyMCE.get(id),
            setChange,
            content;

          if (editor) {
            editor.onChange.add(function (ed, e) {
              ed.save();
              content = editor.getContent();
              clearTimeout(setChange);
              setChange = setTimeout(function () {
                tArea.val(content).trigger("change");
              }, 500);
            });
          }

          tArea
            .css({
              visibility: "visible",
            })
            .on("keyup", function () {
              content = tArea.val();
              clearTimeout(setChange);
              setChange = setTimeout(function () {
                content.trigger("change");
              }, 500);
            });
        });
      });
    },
  };

  wp.customizerCtrlEditor.init();
  //
})(jQuery);

Customizer Setting & Control

<?php
/**
 * TintMCE Editor
 */

$wp_customize->add_setting( 'theme[editor_content]', array(
    'default'           => '',
    'transport'         => 'postMessage',
    'sanitize_callback' => 'wp_kses_post'
) );

$wp_customize->add_control( new TinyMCE_Editor_Custom_Control(
        $wp_customize, 'editor_content', array(
            'label'     => 'CopyRights Text',
            'section'   => 'footer_options',
            'settings'  => 'theme[editor_content]',
            'type'      => 'textarea',
        )
    )
);

Please How I can Show the Content in The Footer?


来源: stackexchange

问:
Error: expect(jest.fn()).toHaveBeenCalledTimes(expected)
I have a parent component contact form, using react-hook-form. I want to make a test for this component using react testing library. When i try to submit I have got this error:

Error: expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0Jest

```<code>describe("Form", () => {
  const onSubmit = jest.fn();

  const renderForm = () => {
    const Wrapper = (props: { children: React.ReactNode }) => {
      const formMethods = useForm();
      return <FormProvider {...formMethods}>{props.children}</FormProvider>;
    };
    customRender(
      <Wrapper>
        <ContactForm onSubmit={onSubmit} /> //error is here
      </Wrapper>,
      {
        withRouter: true,
      }
    );
  };

  it("successful submit", () => {
    renderForm();
    const emailInput = screen.getByRole("textbox", { name: /email/i })
    const fNameInput = screen.getByRole("textbox", { name: /fname/i });
    const submitButton = screen.getByRole("button", { name: /submit/i });

    expect(emailInput).toBeInTheDocument();
    expect(fNameInput).toBeInTheDocument();

    fireEvent.input(emailInput, "abc@abc.com");
    fireEvent.input(fNameInput, "Alex");
    fireEvent.click(submitButton);

    expect(onSubmit).toHaveBeenCalledTimes(1); //error is here
  });
});
</code>```

Component

```<code>export function ContactForm({ onSubmit }: ContactFormProps) {

  const methods = useForm<FormSchemaType>({
    resolver: zodResolver(FormSchema),
  });
  const { handleSubmit, reset } = methods;
  const onSubmit: SubmitHandler<FormSchemaType> = data => {
    ...
  };

  return (
    <>
      <FormProvider {...methods}>
          <FormWrapper>
            <form onSubmit={handleSubmit(onSubmit)}>
              ....
            </form>
          </FormWrapper>
      </FormProvider>
    </>
  );
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a parent component contact form, using react-hook-form. I want to make a test for this component using react testing library. When i try to submit I have got this error:

Error: expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0Jest

describe("Form", () => {
  const onSubmit = jest.fn();

  const renderForm = () => {
    const Wrapper = (props: { children: React.ReactNode }) => {
      const formMethods = useForm();
      return <FormProvider {...formMethods}>{props.children}</FormProvider>;
    };
    customRender(
      <Wrapper>
        <ContactForm onSubmit={onSubmit} /> //error is here
      </Wrapper>,
      {
        withRouter: true,
      }
    );
  };

  it("successful submit", () => {
    renderForm();
    const emailInput = screen.getByRole("textbox", { name: /email/i })
    const fNameInput = screen.getByRole("textbox", { name: /fname/i });
    const submitButton = screen.getByRole("button", { name: /submit/i });

    expect(emailInput).toBeInTheDocument();
    expect(fNameInput).toBeInTheDocument();

    fireEvent.input(emailInput, "abc@abc.com");
    fireEvent.input(fNameInput, "Alex");
    fireEvent.click(submitButton);

    expect(onSubmit).toHaveBeenCalledTimes(1); //error is here
  });
});

Component

export function ContactForm({ onSubmit }: ContactFormProps) {

  const methods = useForm<FormSchemaType>({
    resolver: zodResolver(FormSchema),
  });
  const { handleSubmit, reset } = methods;
  const onSubmit: SubmitHandler<FormSchemaType> = data => {
    ...
  };

  return (
    <>
      <FormProvider {...methods}>
          <FormWrapper>
            <form onSubmit={handleSubmit(onSubmit)}>
              ....
            </form>
          </FormWrapper>
      </FormProvider>
    </>
  );
}


问:
setup.py is not installing dependencies
I have few dependencies which I am unable to install with PIP using setuptools. Here given below is the content from my setup.py file, in which I am unable to install cosign inside my package.

Note: There is no way to install cosign with pip

```<code>from setuptools import setup

setup(
    name='samplepackage',
    version='1.0',
    description='A useful module',
    author='XYZ',
    packages=['samplepackage'],  #same as name
    install_requires=['wheel',
                 'vault',
                 'cosign'],
   package_data={'': ['*.yaml', '*.*']}
   )
</code>```

How can I mention dependencies or wrap dependencies using setuptools inside my package which are not installing with PIP ?

Title: setup.py is not installing dependencies

Body:
I have few dependencies which I am unable to install with PIP using setuptools. Here given below is the content from my setup.py file, in which I am unable to install cosign inside my package.

Note: There is no way to install cosign with pip

from setuptools import setup

setup(
    name='samplepackage',
    version='1.0',
    description='A useful module',
    author='XYZ',
    packages=['samplepackage'],  #same as name
    install_requires=['wheel',
                 'vault',
                 'cosign'],
   package_data={'': ['*.yaml', '*.*']}
   )

How can I mention dependencies or wrap dependencies using setuptools inside my package which are not installing with PIP ?


问:
Remote-exec not running on my Terraform code
I have this main.tf below. It creates the VMs fine with all the correct stuff. But for some reason it doesn't run the provisioner file and remote-exec section. I copied the code from here.

I'm trying to setup a VM in Proxmox with 2 disks, and create an LVM. This will eventually be for adding ceph cluster.

```<code>terraform {
  required_providers {
    proxmox = {
      source = "telmate/proxmox"
      version = "2.9.11"
    }
  }
}

provider "proxmox" {
  pm_api_url = "https://xxx:8006/api2/json"
  pm_api_token_id = "terraform_token"
  pm_api_token_secret = "xxx"
  pm_tls_insecure = true
}

resource "proxmox_vm_qemu" "node_server" {
  count = 3
  # just want 1 for now, set to 0 and apply to destroy VM
  name = "node-${count.index + 1}"
  target_node = var.proxmox_host
  clone = var.template_name
  agent = 1
  os_type = "cloud-init"
  cores = 2
  sockets = 1
  cpu = "host"
  memory = 4096
  scsihw = "virtio-scsi-pci"
  bootdisk = "scsi0"
  disk {
    slot = 0
    size = "20G"
    type = "scsi"
    storage = "local-lvm"
    iothread = 1
  }
  disk {
    slot = 1
    size = "250G"
    type = "scsi"
    storage = "local-lvm"
    iothread = 1
  }

  provisioner "file" {
    source      = "/home/xxx/terraform-proxmox/setup-disks.sh"
    destination = "/tmp/setup-disks.sh"
  }
  provisioner "remote-exec" {
    inline = [
      "chmod +x /tmp/setup-disks.sh",
      "sudo /tmp/setup-disk.sh",
    ]
  }

  network {
    model = "virtio"
    bridge = "vmbr0"
  }
  lifecycle {
    ignore_changes = [
      network,
    ]
  }

  ipconfig0 = "ip=xxx.5${count.index + 1}/24,gw=xxx"

  sshkeys = <<EOF
  ${var.ssh_key}
  EOF
}
</code>```

Body:
I have this main.tf below. It creates the VMs fine with all the correct stuff. But for some reason it doesn't run the provisioner file and remote-exec section. I copied the code from here.

I'm trying to setup a VM in Proxmox with 2 disks, and create an LVM. This will eventually be for adding ceph cluster.

terraform {
  required_providers {
    proxmox = {
      source = "telmate/proxmox"
      version = "2.9.11"
    }
  }
}

provider "proxmox" {
  pm_api_url = "https://xxx:8006/api2/json"
  pm_api_token_id = "terraform_token"
  pm_api_token_secret = "xxx"
  pm_tls_insecure = true
}

resource "proxmox_vm_qemu" "node_server" {
  count = 3
  # just want 1 for now, set to 0 and apply to destroy VM
  name = "node-${count.index + 1}"
  target_node = var.proxmox_host
  clone = var.template_name
  agent = 1
  os_type = "cloud-init"
  cores = 2
  sockets = 1
  cpu = "host"
  memory = 4096
  scsihw = "virtio-scsi-pci"
  bootdisk = "scsi0"
  disk {
    slot = 0
    size = "20G"
    type = "scsi"
    storage = "local-lvm"
    iothread = 1
  }
  disk {
    slot = 1
    size = "250G"
    type = "scsi"
    storage = "local-lvm"
    iothread = 1
  }

  provisioner "file" {
    source      = "/home/xxx/terraform-proxmox/setup-disks.sh"
    destination = "/tmp/setup-disks.sh"
  }
  provisioner "remote-exec" {
    inline = [
      "chmod +x /tmp/setup-disks.sh",
      "sudo /tmp/setup-disk.sh",
    ]
  }

  network {
    model = "virtio"
    bridge = "vmbr0"
  }
  lifecycle {
    ignore_changes = [
      network,
    ]
  }

  ipconfig0 = "ip=xxx.5${count.index + 1}/24,gw=xxx"

  sshkeys = <<EOF
  ${var.ssh_key}
  EOF
}


问:
How to include a select2 multiselect box in a OpenStreetMap widget for Django Admin?
I have the following model, which contains a MultiPolygonField:

class MyArea(models.Model):
   polygon = models.MultiPolygonField(
        _("Polygon"),
        null=False,
        blank=False,
    )
```
<p>I have this model registered in Django Admin:</p>
<pre class="lang-py prettyprint-override"><code>@admin.register(MyArea)
class MyAreaAdmin(admin.GISModelAdmin): # --> GISModelAdmin to render an OSM map for `polygon`
    pass
</code>```

Which renders the map, as desired:

But now, I would like to include a select2 multiselect box on top of this map, where the user would be able to search another model in our database that contains polygons for administrative regions.

class Locality(models.Model):
   polygon = models.MultiPolygonField(
        _("Locality Polygon"),
        null=False,
        blank=False,
    )
```

So the user would still be able to draw manual polygons if he wants too. But he could also search and select Locality objects that already contain complex administrative regions (polygons). Once a Locality object is selected the map should be refreshed to include the new region.

How should I go about this? I have tried to create custom templates and custom forms, but did not got anywhere close to the solution

Body:
I have the following model, which contains a MultiPolygonField:

class MyArea(models.Model):
   polygon = models.MultiPolygonField(
        _("Polygon"),
        null=False,
        blank=False,
    )

I have this model registered in Django Admin:

@admin.register(MyArea)
class MyAreaAdmin(admin.GISModelAdmin): # --> GISModelAdmin to render an OSM map for `polygon`
    pass

Which renders the map, as desired:

But now, I would like to include a select2 multiselect box on top of this map, where the user would be able to search another model in our database that contains polygons for administrative regions.

class Locality(models.Model):
   polygon = models.MultiPolygonField(
        _("Locality Polygon"),
        null=False,
        blank=False,
    )

So the user would still be able to draw manual polygons if he wants too. But he could also search and select Locality objects that already contain complex administrative regions (polygons). Once a Locality object is selected the map should be refreshed to include the new region.

How should I go about this? I have tried to create custom templates and custom forms, but did not got anywhere close to the solution


问:
Room DB TypeConverter GSon: Unable to create instance of class
I'm facing this problem:

java.lang.RuntimeException: Unable to create instance of class java.text.NumberFormat. Registering an InstanceCreator or a TypeAdapter for this type, or adding a no-args constructor may fix this problem.

It's referred with a data class of mytable "patient":

```<code>@Entity(tableName = "patient")
@Parcelize
data class Patient(
    @PrimaryKey(autoGenerate = true)
    var dataPatientList: @RawValue List<DataPatient> = listOf()
) : Parcelable, Serializable
</code>```

The DataPatient class:

```<code>data class DataPatient(
    val where: String,
    val photoList: MutableList<DataPatientPhotoTaken> = mutableListOf()
): Serializable {

    data class DataPatientPhotoTaken(
        val dateTime: SimpleDateFormat,
        var hasBeenUploadedRedcap: Boolean = false,
        val focusPoint: String,
        val bitmapNotCompressed: Bitmap,
    ): Serializable
}
</code>```

I've implemented a TypeConverter using Gson to be able to store dataPatientList:

```<code>class Converters {
    @TypeConverter
    fun fromDataPatientList(value: List<DataPatient>): String {
        val gson = Gson()
        val type = object : TypeToken<List<DataPatient>>() {}.type
        return gson.toJson(value, type)
    }

    @TypeConverter
    fun toDataPatientList(value: String): List<DataPatient> {
        val gson = Gson()
        val type = object : TypeToken<List<DataPatient>>() {}.type
        return gson.fromJson(value, type) // <----- HERE THE CRASH LOG
    }
}
</code>```

The crash log does not work with line return gson.fromJson(value, type).

Could anyone tell me why?

Body:
I'm facing this problem:

java.lang.RuntimeException: Unable to create instance of class java.text.NumberFormat. Registering an InstanceCreator or a TypeAdapter for this type, or adding a no-args constructor may fix this problem.

It's referred with a data class of mytable "patient":

@Entity(tableName = "patient")
@Parcelize
data class Patient(
    @PrimaryKey(autoGenerate = true)
    var dataPatientList: @RawValue List<DataPatient> = listOf()
) : Parcelable, Serializable

The DataPatient class:

data class DataPatient(
    val where: String,
    val photoList: MutableList<DataPatientPhotoTaken> = mutableListOf()
): Serializable {

    data class DataPatientPhotoTaken(
        val dateTime: SimpleDateFormat,
        var hasBeenUploadedRedcap: Boolean = false,
        val focusPoint: String,
        val bitmapNotCompressed: Bitmap,
    ): Serializable
}

I've implemented a TypeConverter using Gson to be able to store dataPatientList:

class Converters {
    @TypeConverter
    fun fromDataPatientList(value: List<DataPatient>): String {
        val gson = Gson()
        val type = object : TypeToken<List<DataPatient>>() {}.type
        return gson.toJson(value, type)
    }

    @TypeConverter
    fun toDataPatientList(value: String): List<DataPatient> {
        val gson = Gson()
        val type = object : TypeToken<List<DataPatient>>() {}.type
        return gson.fromJson(value, type) // <----- HERE THE CRASH LOG
    }
}

The crash log does not work with line return gson.fromJson(value, type).

Could anyone tell me why?


问:
How do i store pictures in moodle?
I'm trying to create my own Activity in moodle where students can take pictures of their Drivers License and that pictures get stored in moodle, then later opended and shown to the teacher.

My Problem is to store the picture on the moodle side and not downloading it.(like i'm doing right now)

Hopfully someone can help me figure out a way to use the file_storage given by moodle to safe the pictures.

kind regards
J

This is my code for now (view.php) ... I know its not realy in a moodle way but im trying to get it to work first then then clean up the code

```<code>require_once('../../config.php');
require_once($CFG->dirroot . '/mod/driverslicense/lib.php');
require_once($CFG->dirroot . '/mod/assign/locallib.php');
require_once($CFG->dirroot . '/mod/driverslicense/classes/submit/submit.php');
require_once("$CFG->libdir/formslib.php");

$id = required_param('id', PARAM_INT);

list ($course, $cm) = get_course_and_cm_from_cmid($id, 'driverslicense');

require_login($course, true, $cm);

$context = context_module::instance($cm->id);

require_capability('mod/driverslicense:view', $context);

$driverslicense = new assign($context, $cm, $course);
$urlparams = array('id' => $id,
    'action' => optional_param('action', '', PARAM_ALPHA),
    'rownum' => optional_param('rownum', 0, PARAM_INT),
    'useridlistid' => optional_param('useridlistid', $driverslicense->get_useridlist_key_id(), PARAM_ALPHANUM));

$url = new moodle_url('/mod/driverslicense/view.php', $urlparams);
$PAGE->set_url($url);

// Update module completion status.
$driverslicense->set_module_viewed();

// Apply overrides.
$driverslicense->update_effective_access($USER->id);

// Get the driverslicense class to
// render the page.
//echo $driverslicense->view(optional_param('action', '', PARAM_ALPHA));
$mform = new submit();

echo $OUTPUT->header();

echo '<body>
    <div id="container">
        <video autoplay="true" id="video"></video>
        <button id="btn"> Take Picture </button>
        <canvas id="canvas" class="hidden"></canvas>
        <a id="dl-btn" href="frontpic" download="image.png" class="hidden"></a>
    </div>
</body>';

$fs = get_file_storage();

// Prepare file record object
$fileinfo = array(
    'contextid' => $context->id, // ID of context
    'component' => 'mod_driverslicense',     // usually = table name
    'filearea' => 'driverslicense',     // usually = table name
    'itemid' => 0,               // usually = ID of row in table
    'filepath' => '/',           // any path beginning and ending in /
    'filename' => 'driverslicensefront.png'); // any filename

$fs->create_file_from_url($fileinfo, imgURL );

echo $OUTPUT->footer();
?>

<script type="text/javascript">
    const video = document.querySelector('#video')
    const btn = document.querySelector('#btn')
    const canvas = document.querySelector('#canvas')

    if ('mediaDevices' in navigator && 'getUserMedia' in navigator.mediaDevices) {
        navigator.mediaDevices.getUserMedia({video: true})
        .then(stream => {
            video.srcObject = stream
        })
        .catch(error => {
            console.log('An error occured while accessing webcam.')
        })
    }

    btn.addEventListener('click', () =>{
        const width = video.videoWidth, height = video.videoHeight
        const context = canvas.getContext('2d')

        canvas.width = width
        canvas.height = height

        context.drawImage(video, 0, 0, width, height)
        const imgURL = canvas.toDataURL('image/png')

        document.querySelector('#dl-btn').href = imgURL
        document.querySelector('#dl-btn').click()
    })

</script>
</code>```

Title: How do i store pictures in moodle?

Body:
I'm trying to create my own Activity in moodle where students can take pictures of their Drivers License and that pictures get stored in moodle, then later opended and shown to the teacher.

My Problem is to store the picture on the moodle side and not downloading it.(like i'm doing right now)

Hopfully someone can help me figure out a way to use the file_storage given by moodle to safe the pictures.

kind regards
J

This is my code for now (view.php) ... I know its not realy in a moodle way but im trying to get it to work first then then clean up the code

require_once('../../config.php');
require_once($CFG->dirroot . '/mod/driverslicense/lib.php');
require_once($CFG->dirroot . '/mod/assign/locallib.php');
require_once($CFG->dirroot . '/mod/driverslicense/classes/submit/submit.php');
require_once("$CFG->libdir/formslib.php");

$id = required_param('id', PARAM_INT);

list ($course, $cm) = get_course_and_cm_from_cmid($id, 'driverslicense');

require_login($course, true, $cm);

$context = context_module::instance($cm->id);

require_capability('mod/driverslicense:view', $context);

$driverslicense = new assign($context, $cm, $course);
$urlparams = array('id' => $id,
    'action' => optional_param('action', '', PARAM_ALPHA),
    'rownum' => optional_param('rownum', 0, PARAM_INT),
    'useridlistid' => optional_param('useridlistid', $driverslicense->get_useridlist_key_id(), PARAM_ALPHANUM));

$url = new moodle_url('/mod/driverslicense/view.php', $urlparams);
$PAGE->set_url($url);

// Update module completion status.
$driverslicense->set_module_viewed();

// Apply overrides.
$driverslicense->update_effective_access($USER->id);

// Get the driverslicense class to
// render the page.
//echo $driverslicense->view(optional_param('action', '', PARAM_ALPHA));
$mform = new submit();

echo $OUTPUT->header();

echo '

        <video autoplay="true" id="video"></video>
        <button id="btn"> Take Picture </button>
        <canvas id="canvas" class="hidden"></canvas>

';

$fs = get_file_storage();

// Prepare file record object
$fileinfo = array(
    'contextid' => $context->id, // ID of context
    'component' => 'mod_driverslicense',     // usually = table name
    'filearea' => 'driverslicense',     // usually = table name
    'itemid' => 0,               // usually = ID of row in table
    'filepath' => '/',           // any path beginning and ending in /
    'filename' => 'driverslicensefront.png'); // any filename

$fs->create_file_from_url($fileinfo, imgURL );

echo $OUTPUT->footer();
?>


问:
Interpolating the plot in python
I have used scatter plot to plot a 2d lithology map but since i have very less amount of data th plot is discrete. I have three columns x,y and predicted lithology which has numbers ranging from 1 to 6. So there are six lithologies that i have plotted.
Below is the code that i have used

```<code>plt.figure(figsize=[15,10])

colormap = np.array(['blue','green','pink','brown','yellow','white'])

plt.scatter(df_final['x'], df_final['y'],  c=colormap[y_final-1],marker='8')
</code>```

Here df_final is the data set and y_final contains the list of all the predicted lithologies from 1 to 6.
Here is the result that i got using the above code

But as you can see that the plot is discrete and not a continuous plot. I want to plot the lithology as shown in the below figure
enter image description here

Title: Interpolating the plot in python

Body:
I have used scatter plot to plot a 2d lithology map but since i have very less amount of data th plot is discrete. I have three columns x,y and predicted lithology which has numbers ranging from 1 to 6. So there are six lithologies that i have plotted.
Below is the code that i have used

plt.figure(figsize=[15,10])

colormap = np.array(['blue','green','pink','brown','yellow','white'])

plt.scatter(df_final['x'], df_final['y'],  c=colormap[y_final-1],marker='8')

Here df_final is the data set and y_final contains the list of all the predicted lithologies from 1 to 6.
Here is the result that i got using the above code

But as you can see that the plot is discrete and not a continuous plot. I want to plot the lithology as shown in the below figure
enter image description here


问:
Renaming folders in VSC does not update import paths in multi-project
Given a multi-project workspace in Visual Studio Code:

```<code>root
--apps
----Flutter_app_1
----Flutter_app_2
--packages
----Flutter_package_1
----Flutter_package_2
</code>```

If I try to rename a folder in Flutter_package_1, the corresponding import paths inside each app are not updated. Is there any solution to automatically update them?

Body:
Given a multi-project workspace in Visual Studio Code:

root
--apps
----Flutter_app_1
----Flutter_app_2
--packages
----Flutter_package_1
----Flutter_package_2

If I try to rename a folder in Flutter_package_1, the corresponding import paths inside each app are not updated. Is there any solution to automatically update them?


问:
How to disable the Connect button after the button clicked?
My OutPut is this Here,

I'm using the 'connect' button in MainActivity and 'disconnect' button in MainFragment and create the Function for connect and disconnect in MainViewModel.

Whenever I click the 'connect button', it should moves to fragment using databinding to open the Fragment page.(i.e., MainActivity.kt--->MainViewmodel.kt--->MainFragment.kt).

Note that: If I click 'connect' button  should be is invisible in MainFragment, once return to MainActivity, then it should in visible. Not-need to declare the "android:visibility="@{viewModel.connectButtonVisible ? View.VISIBLE : View.GONE}" " in .xml files because it getting error in dataBindingImplemention. I want this visibility in Koltin files as code

Whenever I click the 'Disconnect button', it should get back to MainActivity using databinding.
(i.e.,MainFragment.kt --->MainViewmodel.kt--->MainActivity.kt)

4.Don't use the navigation_graph.xml because databinding is not sufficient for navigation only viewbinding is ok. But I'm using DataBinding only.

I give my sample code.

MainViewModel.kt

```<code>class MainViewModel : ViewModel() {
    val connectionState = MutableLiveData<Boolean>()

    fun connect(){
         connectionState.value = true
    }

    fun disconnect(){
         connectionState.value = false
    }

}
</code>```

Activity_Main.xml

```<code>
<!-- layout for MainActivity -->
<layout>
    <data>
        <variable
            name="viewModel"
            type="com.example.myapp.MainViewModel" />
    </data>
    <LinearLayout>
        <!-- other layout elements -->
        <Button
            android:id="@+id/connect_button"
            android:onClick="@{() -> viewModel.connectionState}"
            android:text="Connect" />
        <!-- other layout elements -->
    </LinearLayout>
</layout>
</code>```

MainActivity.kt

```<code>class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var viewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        binding.viewModel = viewModel

        viewModel.connectionState.observe(this, Observer { isConnected ->
            if (isConnected) {
                supportFragmentManager.beginTransaction()
                    .replace(R.id.fragment_container, MainFragment())
                    .addToBackStack(null)
                    .commit()
            }
        })
    }
}
</code>```

Fragment_main.xml

```<code><!-- layout for MainFragment -->
<layout>
    <data>
        <variable
            name="viewModel"
            type="com.example.myapp.MainViewModel" />
    </data>
    <LinearLayout>
        <!-- other layout elements -->
        <Button
            android:id="@+id/disconnect_button"
            android:onClick="@{() -> viewModel.connectionState}"
            android:text="Disconnect" />
        <!-- other layout elements -->
    </LinearLayout>
</layout>
</code>```

MainFragment.kt

```<code>class MainFragment : Fragment() {

    private lateinit var binding: FragmentMainBinding
    private lateinit var viewModel: MainViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false)
        viewModel = ViewModelProvider(activity!!).get(MainViewModel::class.java)
        binding.viewModel = viewModel

        viewModel.connectionState.observe(viewLifecycleOwner, Observer { isConnected ->
            if (!isConnected) {
                activity!!.supportFragmentManager.popBackStack()
            }
        })
        return binding.root
    }
}
</code>```

My problem is Once the Click the Connect Button it should be disabled and it show the Fragment_main.xml. Again When I Click the Disconnect Button is return back to Activity_main.xml, in Connect will be visible.
Note that: Without using navagation_graph.xml and android:visibility="@{viewModel.connectButtonVisible ? View.VISIBLE : View.GONE}".

Body:
My OutPut is this Here,

I'm using the 'connect' button in MainActivity and 'disconnect' button in MainFragment and create the Function for connect and disconnect in MainViewModel.

Whenever I click the 'connect button', it should moves to fragment using databinding to open the Fragment page.(i.e., MainActivity.kt--->MainViewmodel.kt--->MainFragment.kt).

Note that: If I click 'connect' button  should be is invisible in MainFragment, once return to MainActivity, then it should in visible. Not-need to declare the "android:visibility="@{viewModel.connectButtonVisible ? View.VISIBLE : View.GONE}" " in .xml files because it getting error in dataBindingImplemention. I want this visibility in Koltin files as code

Whenever I click the 'Disconnect button', it should get back to MainActivity using databinding.
(i.e.,MainFragment.kt --->MainViewmodel.kt--->MainActivity.kt)

4.Don't use the navigation_graph.xml because databinding is not sufficient for navigation only viewbinding is ok. But I'm using DataBinding only.

I give my sample code.

MainViewModel.kt

class MainViewModel : ViewModel() {
    val connectionState = MutableLiveData<Boolean>()

    fun connect(){
         connectionState.value = true
    }

    fun disconnect(){
         connectionState.value = false
    }

}

Activity_Main.xml

<layout>
    <data>
        <variable
            name="viewModel"
            type="com.example.myapp.MainViewModel" />
    </data>
    <LinearLayout>

        <Button
            android:id="@+id/connect_button"
            android:onClick="@{() -> viewModel.connectionState}"
            android:text="Connect" />

    </LinearLayout>
</layout>

MainActivity.kt

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var viewModel: MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
        binding.viewModel = viewModel

        viewModel.connectionState.observe(this, Observer { isConnected ->
            if (isConnected) {
                supportFragmentManager.beginTransaction()
                    .replace(R.id.fragment_container, MainFragment())
                    .addToBackStack(null)
                    .commit()
            }
        })
    }
}

Fragment_main.xml

<layout>
    <data>
        <variable
            name="viewModel"
            type="com.example.myapp.MainViewModel" />
    </data>
    <LinearLayout>

        <Button
            android:id="@+id/disconnect_button"
            android:onClick="@{() -> viewModel.connectionState}"
            android:text="Disconnect" />

    </LinearLayout>
</layout>

MainFragment.kt

class MainFragment : Fragment() {

    private lateinit var binding: FragmentMainBinding
    private lateinit var viewModel: MainViewModel

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false)
        viewModel = ViewModelProvider(activity!!).get(MainViewModel::class.java)
        binding.viewModel = viewModel

        viewModel.connectionState.observe(viewLifecycleOwner, Observer { isConnected ->
            if (!isConnected) {
                activity!!.supportFragmentManager.popBackStack()
            }
        })
        return binding.root
    }
}

My problem is Once the Click the Connect Button it should be disabled and it show the Fragment_main.xml. Again When I Click the Disconnect Button is return back to Activity_main.xml, in Connect will be visible.
Note that: Without using navagation_graph.xml and android:visibility="@{viewModel.connectButtonVisible ? View.VISIBLE : View.GONE}".


问:
Problem archiving project to create XcFramework
** I am running following command to create archive. **

`

```<code>xcodebuild archive \
-scheme ScannerV1 \
-configuration Release \
-destination 'generic/platform=iOS Simulator' \
-archivePath './build/ScannerV1.framework-iphonesimulator.xcarchive' \
        SKIP_INSTALL=NO \
BUILD_LIBRARY_FOR_DISTRIBUTION=YES
</code>```

`

This is my pod file
`

```<code>target 'ScannerV1' do
    # Comment the next line if you don't want to use dynamic frameworks
    use_frameworks!

    # Pods for ScannerV1
    pod 'IQKeyboardManagerSwift'
    pod 'ProgressHUD'
    pod 'GoogleMLKit/FaceDetection'
    pod 'GoogleMLKit/BarcodeScanning'
    pod 'GoogleMLKit/TextRecognition','2.2.0'
    pod 'Alamofire'
  #  pod 'SwiftKeychainWrapper'

  end

  post_install do |pi|
    pi.pods_project.targets.each do |t|
      t.build_configurations.each do |config|
        config.build_settings['ONLY_ACTIVE_ARCH'] = 'NO'
        config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '13.0'
        config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
        config.build_settings['BUILD_LIBRARY_FOR_DISTRIBUTION'] = 'YES'

      end
    end
  end
</code>```

`

**This is the error I am getting . **
SwiftEmitModule normal x86_64 Emitting\ module\ for\ ScannerV1 (in target 'ScannerV1' from project 'ScannerV1') (1 failure)

Also as you can see I have commented SwiftKeychainWrapper pod . This is because I was getting error that SwiftKeychainWrapper is not found / No such module SwiftKeychainWrapper .
Now I got an error and that is : error: no such module 'Alamofire'

I mentioned above what I tried . I am expecting to create archive when creating xcframework

Body:
** I am running following command to create archive. **

`

xcodebuild archive \
-scheme ScannerV1 \
-configuration Release \
-destination 'generic/platform=iOS Simulator' \
-archivePath './build/ScannerV1.framework-iphonesimulator.xcarchive' \
        SKIP_INSTALL=NO \
BUILD_LIBRARY_FOR_DISTRIBUTION=YES

`

This is my pod file
`

target 'ScannerV1' do
    # Comment the next line if you don't want to use dynamic frameworks
    use_frameworks!

    # Pods for ScannerV1
    pod 'IQKeyboardManagerSwift'
    pod 'ProgressHUD'
    pod 'GoogleMLKit/FaceDetection'
    pod 'GoogleMLKit/BarcodeScanning'
    pod 'GoogleMLKit/TextRecognition','2.2.0'
    pod 'Alamofire'
  #  pod 'SwiftKeychainWrapper'

  end

  post_install do |pi|
    pi.pods_project.targets.each do |t|
      t.build_configurations.each do |config|
        config.build_settings['ONLY_ACTIVE_ARCH'] = 'NO'
        config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '13.0'
        config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"] = "arm64"
        config.build_settings['BUILD_LIBRARY_FOR_DISTRIBUTION'] = 'YES'

      end
    end
  end

`

**This is the error I am getting . **
SwiftEmitModule normal x86_64 Emitting\ module\ for\ ScannerV1 (in target 'ScannerV1' from project 'ScannerV1') (1 failure)

Also as you can see I have commented SwiftKeychainWrapper pod . This is because I was getting error that SwiftKeychainWrapper is not found / No such module SwiftKeychainWrapper .
Now I got an error and that is : error: no such module 'Alamofire'

I mentioned above what I tried . I am expecting to create archive when creating xcframework


问:
selected option is not unselected while clicking on the element twice
select2 ajax select elements clicking once and unselect element clicking twice. This is by default .but in my case element is selecting by one click but not unselecting clicking twice. what is the problem here

views.py

```<code>
def search(request):
    query=request.GET.get("q")
    print(query)
    vid=Video.objects.filter(tags__name__icontains=query).order_by("name").distinct()
    print(vid)
    vid_list=\[{'id':k.id,"name":k.name,"tags":','.join(k.tags.names())} for k in vid\]

    print(type(vid_list))
    return JsonResponse(vid_list,safe=False)

</code>```

home.html

```<code><div class="form-group">
  <label>Example of multiple select</label>
  <select class="form-control" multiple placeholder="Choose skills" id="some" required>

  </select>
</div>
</code>```

scripts

```<code><script>
  $("p").click(function(){
    $.ajax({
      url:"{%url 'home' %}",
      success:function(data){
        alert("this is a ajax alert")
      }
    })

  })

  $("#some").select2({
    ajax:{
      url:"{% url 'search'%}",
      data: function(params){
        return{
          "q":params.term
        }
      },
      processResults:function(data){
        console.log(data)
        return{
          results:data.map(function(item){
            return{id:item.id,name:item.name,tags:item.tags}
          })
          }
        },
        delay:250,
      cache:true,
      },

    minimumInputLength:1,
    closeOnSelect: false,
    allowClear:true,
    multiple:true,
    placeholder: "Search Video",
    templateResult:function(repo){
      console.log(repo)
      if (repo.loading) return repo.name;

      if (repo && !repo.selected){
        return`
        <span>
          ${repo.name}(${repo.tags})
        </span>
        `
      }

    },
    templateSelection:function(data){
      return`
      <span >
        ${data.name}
      </span>
      `

    },
    escapeMarkup: function (markup) {
      return markup;
    },
  })

  </script>
</code>```

Now i want to know what is the reason behind this .i mean why option is not unselecting when i click second time on the option

Body:
select2 ajax select elements clicking once and unselect element clicking twice. This is by default .but in my case element is selecting by one click but not unselecting clicking twice. what is the problem here

views.py

def search(request):
    query=request.GET.get("q")
    print(query)
    vid=Video.objects.filter(tags__name__icontains=query).order_by("name").distinct()
    print(vid)
    vid_list=\[{'id':k.id,"name":k.name,"tags":','.join(k.tags.names())} for k in vid\]

    print(type(vid_list))
    return JsonResponse(vid_list,safe=False)

home.html

  Example of multiple select
  <select class="form-control" multiple placeholder="Choose skills" id="some" required>

  </select>

scripts

Now i want to know what is the reason behind this .i mean why option is not unselecting when i click second time on the option


问:
Can I update or change a cuda kernel without stopping the process?
I have a cuda kernel that I would like to udpate (ie., change anything between the checks and surf2Dwrite) without having to stop the process; is there a way to achieve some sort of JIT compilation or a microservice architecture equivalent ? If so, how to achieve this ?

Ideally I would like to edit a text with the equations and have it compiled and uploaded as a new kernel, while not exiting the process.
More explicitly, I would like to update the UpdateSurface pixel update functions on the fly:

```<code>int iDivUp(int a, int b) { return a % b != 0 ? a / b + 1 : a / b; }

__global__ void UpdateSurface(cudaSurfaceObject_t surf, unsigned int width, unsigned int height, float time)
{
    unsigned int x = blockIdx.x * blockDim.x + threadIdx.x;
    unsigned int y = blockIdx.y * blockDim.y + threadIdx.y;
    if (y >= height | x >= width) return;

    auto xVar = (float)x / (float)width;
    auto yVar = (float)y / (float)height;
    auto cost = __cosf(time) * 0.5f + 0.5f;
    auto costx = __cosf(time) * 0.5f + xVar;
    auto costy = __cosf(time) * 0.5f + yVar;
    auto costxx = (__cosf(time) * 0.5f + 0.5f) * width;
    auto costyy = (__cosf(time) * 0.5f + 0.5f) * height;
    auto costxMany = __cosf(y * time) * 0.5f + yVar;
    auto costyMany = __cosf((float)x/100 * time) * 0.5f + xVar;
    auto margin = 1;

    float4 pixel{};
    if (y == 0)
        pixel = make_float4(costyMany * 0.3, costyMany * 1, costyMany * 0.4, 1);
    else if (y == height - 1)
        pixel = make_float4(costyMany * 0.6, costyMany * 0.7, costyMany * 1, 1);
    else if (x % 2 == 0)
    {
        if (x > width / 2)
            pixel = make_float4(0.1, 0.5, costx * 1, 1);
        else
            pixel = make_float4(costx * 1, 0.1, 0.2, 1);
    }
    else if (x > width - margin - 1 | x <= margin)
        pixel = make_float4(costxMany, costxMany * 0.9, costxMany * 0.6, 1);
    else
        pixel = make_float4(costx * 0.3, costx * 0.4, costx * 0.6, 1);
    surf2Dwrite(pixel, surf, x * 16, y);
}

void RunKernel(size_t textureW, size_t textureH, cudaSurfaceObject_t surfaceObject, cudaStream_t streamToRun, float animTime)
{
    auto unit = 10;
    dim3 threads(unit, unit);
    dim3 grid(iDivUp(textureW, unit), iDivUp(textureH, unit));
    UpdateSurface <<<grid, threads, 0, streamToRun >>> (surfaceObject, textureW, textureH, animTime);
    getLastCudaError("UpdateSurface execution failed.\n");
}
</code>```

Body:
I have a cuda kernel that I would like to udpate (ie., change anything between the checks and surf2Dwrite) without having to stop the process; is there a way to achieve some sort of JIT compilation or a microservice architecture equivalent ? If so, how to achieve this ?

Ideally I would like to edit a text with the equations and have it compiled and uploaded as a new kernel, while not exiting the process.
More explicitly, I would like to update the UpdateSurface pixel update functions on the fly:

int iDivUp(int a, int b) { return a % b != 0 ? a / b + 1 : a / b; }

__global__ void UpdateSurface(cudaSurfaceObject_t surf, unsigned int width, unsigned int height, float time)
{
    unsigned int x = blockIdx.x * blockDim.x + threadIdx.x;
    unsigned int y = blockIdx.y * blockDim.y + threadIdx.y;
    if (y >= height | x >= width) return;

    auto xVar = (float)x / (float)width;
    auto yVar = (float)y / (float)height;
    auto cost = __cosf(time) * 0.5f + 0.5f;
    auto costx = __cosf(time) * 0.5f + xVar;
    auto costy = __cosf(time) * 0.5f + yVar;
    auto costxx = (__cosf(time) * 0.5f + 0.5f) * width;
    auto costyy = (__cosf(time) * 0.5f + 0.5f) * height;
    auto costxMany = __cosf(y * time) * 0.5f + yVar;
    auto costyMany = __cosf((float)x/100 * time) * 0.5f + xVar;
    auto margin = 1;

    float4 pixel{};
    if (y == 0)
        pixel = make_float4(costyMany * 0.3, costyMany * 1, costyMany * 0.4, 1);
    else if (y == height - 1)
        pixel = make_float4(costyMany * 0.6, costyMany * 0.7, costyMany * 1, 1);
    else if (x % 2 == 0)
    {
        if (x > width / 2)
            pixel = make_float4(0.1, 0.5, costx * 1, 1);
        else
            pixel = make_float4(costx * 1, 0.1, 0.2, 1);
    }
    else if (x > width - margin - 1 | x <= margin)
        pixel = make_float4(costxMany, costxMany * 0.9, costxMany * 0.6, 1);
    else
        pixel = make_float4(costx * 0.3, costx * 0.4, costx * 0.6, 1);
    surf2Dwrite(pixel, surf, x * 16, y);
}

void RunKernel(size_t textureW, size_t textureH, cudaSurfaceObject_t surfaceObject, cudaStream_t streamToRun, float animTime)
{
    auto unit = 10;
    dim3 threads(unit, unit);
    dim3 grid(iDivUp(textureW, unit), iDivUp(textureH, unit));
    UpdateSurface <<<grid, threads, 0, streamToRun >>> (surfaceObject, textureW, textureH, animTime);
    getLastCudaError("UpdateSurface execution failed.\n");
}


问:
how to work with types of a dependency with two different version
How to work with types of dependency required by two dependency having different version i.e

I ran this command ttsc -p tsconfig.sdk.json which gave following error

```<code>node_modules/react-native-webrtc/node_modules/event-target-shim/index.d.ts:377:34 - error TS1005: ']' expected.
377     [P in string & keyof TEventMap as `on${P}`]: EventTarget.CallbackFunction<TEventTarget, TEventMap[P]> | null;                                       ~~
node_modules/react-native-webrtc/node_modules/event-target-shim/index.d.ts:377:45 - error TS1005: ';' expected.
377     [P in string & keyof TEventMap as `on${P}`]: EventTarget.CallbackFunction<TEventTarget, TEventMap[P]> | null;                                               ~
node_modules/react-native-webrtc/node_modules/event-target-shim/index.d.ts:377:46 - error TS1128: Declaration or statement expected.
377     [P in string & keyof TEventMap as `on${P}`]: EventTarget.CallbackFunction<TEventTarget, TEventMap[P]> | null;
node_modules/react-native-webrtc/node_modules/event-target-shim/index.d.ts:377:105 - error TS1005: '(' expected.
377     [P in string & keyof TEventMap as `on${P}`]: EventTarget.CallbackFunction<TEventTarget, TEventMap[P]> | null;                                                                                ~

node_modules/react-native-webrtc/node_modules/event-target-shim/index.d.ts:377:111 - error TS1005: ')' expected.
</code>```

Shimmer is used as a dependency by the two packages I am using

react-native-webrtc

react-native (react-native uses dependency abort-controller which uses event-target-shim

```<code>        "node_modules/abort-controller": {
            "version": "3.0.0",
            "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
            "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
            "dependencies": {
                "event-target-shim": "^5.0.0"
            },
            "engines": {
                "node": ">=6.5"
            }
        },
           "node_modules/react-native-webrtc": {
            "version": "1.100.1",
            "resolved": "https://registry.npmjs.org/react-native-webrtc/-/react-native-webrtc-1.100.1.tgz",
            "integrity": "sha512-2dF8HrZWdfrbm1NLso424xgNeGFf4WK5Jlqs7ecVDvCMWHTYVHVwyNt52zx1yiOMEqQWk4edOd4xhWJfUiOvMg==",
            "hasInstallScript": true,
            "dependencies": {
                "base64-js": "1.5.1",
                "event-target-shim": "6.0.2",
                "tar": "6.1.11"
            },
            "peerDependencies": {
                "react-native": ">=0.60.0"
            }
        },
        "node_modules/react-native-webrtc/node_modules/event-target-shim": {
            "version": "6.0.2",
            "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-6.0.2.tgz",
            "integrity": "sha512-8q3LsZjRezbFZ2PN+uP+Q7pnHUMmAOziU2vA2OwoFaKIXxlxl38IylhSSgUorWu/rf4er67w0ikBqjBFk/pomA==",
            "engines": {
                "node": ">=10.13.0"
            },
            "funding": {
                "url": "https://github.com/sponsors/mysticatea"
            }
        },

</code>```

Can someone help me in fixing these errors?

Body:
How to work with types of dependency required by two dependency having different version i.e

I ran this command ttsc -p tsconfig.sdk.json which gave following error

node_modules/react-native-webrtc/node_modules/event-target-shim/index.d.ts:377:34 - error TS1005: ']' expected.
377     [P in string & keyof TEventMap as `on${P}`]: EventTarget.CallbackFunction<TEventTarget, TEventMap[P]> | null;                                       ~~
node_modules/react-native-webrtc/node_modules/event-target-shim/index.d.ts:377:45 - error TS1005: ';' expected.
377     [P in string & keyof TEventMap as `on${P}`]: EventTarget.CallbackFunction<TEventTarget, TEventMap[P]> | null;                                               ~
node_modules/react-native-webrtc/node_modules/event-target-shim/index.d.ts:377:46 - error TS1128: Declaration or statement expected.
377     [P in string & keyof TEventMap as `on${P}`]: EventTarget.CallbackFunction<TEventTarget, TEventMap[P]> | null;
node_modules/react-native-webrtc/node_modules/event-target-shim/index.d.ts:377:105 - error TS1005: '(' expected.
377     [P in string & keyof TEventMap as `on${P}`]: EventTarget.CallbackFunction<TEventTarget, TEventMap[P]> | null;                                                                                ~

node_modules/react-native-webrtc/node_modules/event-target-shim/index.d.ts:377:111 - error TS1005: ')' expected.

Shimmer is used as a dependency by the two packages I am using

react-native-webrtc

react-native (react-native uses dependency abort-controller which uses event-target-shim

        "node_modules/abort-controller": {
            "version": "3.0.0",
            "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
            "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
            "dependencies": {
                "event-target-shim": "^5.0.0"
            },
            "engines": {
                "node": ">=6.5"
            }
        },
           "node_modules/react-native-webrtc": {
            "version": "1.100.1",
            "resolved": "https://registry.npmjs.org/react-native-webrtc/-/react-native-webrtc-1.100.1.tgz",
            "integrity": "sha512-2dF8HrZWdfrbm1NLso424xgNeGFf4WK5Jlqs7ecVDvCMWHTYVHVwyNt52zx1yiOMEqQWk4edOd4xhWJfUiOvMg==",
            "hasInstallScript": true,
            "dependencies": {
                "base64-js": "1.5.1",
                "event-target-shim": "6.0.2",
                "tar": "6.1.11"
            },
            "peerDependencies": {
                "react-native": ">=0.60.0"
            }
        },
        "node_modules/react-native-webrtc/node_modules/event-target-shim": {
            "version": "6.0.2",
            "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-6.0.2.tgz",
            "integrity": "sha512-8q3LsZjRezbFZ2PN+uP+Q7pnHUMmAOziU2vA2OwoFaKIXxlxl38IylhSSgUorWu/rf4er67w0ikBqjBFk/pomA==",
            "engines": {
                "node": ">=10.13.0"
            },
            "funding": {
                "url": "https://github.com/sponsors/mysticatea"
            }
        },

Can someone help me in fixing these errors?


问:
undefined reference to `SDL_Init'

I started using SDL today and had some trouble before, now I got it running but it won't let me init it.

```<code># **Code -->**

</code>```
```<code>#include <iostream>
#include <SDL2/SDL.h>
#undef main

using namespace std;

int main(){
    if(SDL_Init(SDL_INIT_EVERYTHING)<0){
        cout << "error starting sdl" << endl;
    }
    return 0;
}
</code>```

Output -->

PS C:\Users\aashi\OneDrive\CPP_Projects> cd "c:\Users\aashi\OneDrive\CPP_Projects" ; if ($?) { g++ hellDEmo.cpp -o hellDEmo } ; if ($?) { .\hellDEmo }
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\aashi\AppData\Local\Temp\cc8Ya8Za.o:hellDEmo.cpp:(.text+0x1e): undefined reference to `SDL_Init'
collect2.exe: error: ld returned 1 exit status*

what's the problem in code or compiler?

Title: undefined reference to `SDL_Init'

Body:
I started using SDL today and had some trouble before, now I got it running but it won't let me init it.

# **Code -->**

#include <iostream>
#include <SDL2/SDL.h>
#undef main

using namespace std;

int main(){
    if(SDL_Init(SDL_INIT_EVERYTHING)<0){
        cout << "error starting sdl" << endl;
    }
    return 0;
}

Output -->

PS C:\Users\aashi\OneDrive\CPP_Projects> cd "c:\Users\aashi\OneDrive\CPP_Projects" ; if ($?) { g++ hellDEmo.cpp -o hellDEmo } ; if ($?) { .\hellDEmo }
c:/mingw/bin/../lib/gcc/mingw32/9.2.0/../../../../mingw32/bin/ld.exe: C:\Users\aashi\AppData\Local\Temp\cc8Ya8Za.o:hellDEmo.cpp:(.text+0x1e): undefined reference to `SDL_Init'
collect2.exe: error: ld returned 1 exit status*

what's the problem in code or compiler?


问:
How to interrupt the awaiting in a `for-await` loop / Swift
I'm wondering how to stop a for-await loop from "awaiting".

Here's the loop. I use it to listen to new Transactions with storekit2:

```<code>    transactionListener = Task(priority: .background) { [self] in
        // wait for transactions and process them as they arrive
        for await verificationResult in Transaction.updates {
            if Task.isCancelled { print("canceled"); break }

            // --- do some funny stuff with the transaction here ---
            await transaction.finish()
        }
        print("done")
    }
</code>```

As you can see, Transaction.updates is awaited and returns a new transaction whenever one is created. When the App finishes, I cancel the loop with transactionListener.cancel() - but the cancel is ignored as the Transaction.updates is waiting for the next transaction to deliver and there's no direct way in the API to stop it (like, e.g. Task.sleep() does)

The issues starts, when I run unit-tests. The listener from a previous test is still listening while the next test is already running. This produces very unreliable test results and crashes our CI/CD pipeline. I nailed it down to the shown piece of code and the described issue.

So, question: Is it possible to interrupt a for-await loop from awaiting? I have something like the Unix/Linux command kill -1 in mind. Any ideas?

Body:
I'm wondering how to stop a for-await loop from "awaiting".

Here's the loop. I use it to listen to new Transactions with storekit2:

    transactionListener = Task(priority: .background) { [self] in
        // wait for transactions and process them as they arrive
        for await verificationResult in Transaction.updates {
            if Task.isCancelled { print("canceled"); break }

            // --- do some funny stuff with the transaction here ---
            await transaction.finish()
        }
        print("done")
    }

As you can see, Transaction.updates is awaited and returns a new transaction whenever one is created. When the App finishes, I cancel the loop with transactionListener.cancel() - but the cancel is ignored as the Transaction.updates is waiting for the next transaction to deliver and there's no direct way in the API to stop it (like, e.g. Task.sleep() does)

The issues starts, when I run unit-tests. The listener from a previous test is still listening while the next test is already running. This produces very unreliable test results and crashes our CI/CD pipeline. I nailed it down to the shown piece of code and the described issue.

So, question: Is it possible to interrupt a for-await loop from awaiting? I have something like the Unix/Linux command kill -1 in mind. Any ideas?


问:
How to change player displayname on fabric?

Don't know how to call this thing correctly, so I'll call it displayname, and by that I mean nametag that hovers above player

I'm new to fabric, and usually I use documentation for things I'm new to, but unfortunately fabric docs do not exist. So I ask help here.

So...

How can I change displayname? E.g change it's colour or the name text. I'm making a client-side mod
(and don't have access to server-side) for me and my friends. I understand that I need to use mixin, but have no idea how to do what I need.

Thanks in advance!

Tried to find some examples or docs in the Internet - completely failed.

Preferably some example function, but even name of method I should inject mixin into would be helpful


问:
GUI Branch Strategy w/ Submodules
I have a repo "repo1" with 2 branches "main" and "dev" with 3 submodules "submodule1", "submodule2" and "submodule3".

All 3 submodules can only be tested together in "repo1".

If i develop a feature in "submodule1", i create a branch from "main" in "submodule1".

When the feature from "submodule1" is ready to be tested, i want to checkout "dev" in "repo1", update all submodules (with something like "git update submodule") in their "dev" branches.

After testing "dev" in "repo1", i want to merge all "dev" from all submodules to their "main".

Then i want to checkout "main" in "repo1" and update all submodules in their "main" branches, so i can push it and have a working branch in "main" from "repo1" that i can pull in other machines.

I know, that i can do "git update submodule submodule1" after adding "branch = main" in .gitmodules, but how can i do it for "dev" and "main" without having to change it every time? Is there a way to do it or is there a better method for it?

What i want is basicaly to check out all submodules to "dev" in "repo1", test them, switch to every submodule and merge their "dev" into "main", then check out all submodules to "main" in "repo1" and push it.

Title: GUI Branch Strategy w/ Submodules


问:
codepen scroll function not working or console
My code project on codepen has no working Javascript. The console.logs are not running within my javascript. I have a Div with the id and class set to "text1"</p>
```<code>$(window).scroll(function(){
    $(".text1").css("color: red");
  });

const masterEl = document.getElementById('text1')
console.log(masterEl)
console.log("masterEl")
</code>```

Body:
My code project on codepen has no working Javascript. The console.logs are not running within my javascript. I have a Div with the id and class set to "text1"

$(window).scroll(function(){
    $(".text1").css("color: red");
  });

const masterEl = document.getElementById('text1')
console.log(masterEl)
console.log("masterEl")


问:
Laravel 9 : How to upload photo take with mobile camera using ajax
In my project I need the users take photos with their phone and then send this photos to the server,

I already configure the input file field to open the camera, take the photo and show them in the form, but when  tried to save the file to the server, don't work, don't save the file, but properties like, name and extension passed to the controller.

When I tried to do the same on PC, upload photos stored in the PC, work perfectly.

This is my file input

```<code><input type="file" name="imagen_upload" id="imagen_upload" capture="camera" accept="image/*"
              class="d-none">
</code>```

This is my JS (jQuery)

```<code>      var formData;

      $(document).on('submit', '#form', function(e) {
        e.preventDefault();
        formData = new FormData(this);
        return false;
      });

      $(document).on('click', '.btn-save', function(e) {
        $('#form').trigger('submit');
        var confirmation;
        foto = $('[name="imagen_upload"]').val();
        if (foto == null || foto == '') {
          toastr.error('Debe tomar una foto');
          return;
        }
        confirmation = confirm('¿Esta seguro que desea grabar esta foto?');
        if (confirmation) {
          $.post({
            url: '{{ route('subirFoto') }}',
            data: formData,
            contentType: false,
            processData: false,
            success: function(data) {
              alert(data);
              if (data.status) {
                alert('Se grabo la foto correctamente');
              } else {
                alert('No se pudo grabar la foto, por favor intente de nuevo');
              }
            },
            error: function(data) {
              alert('Hubo un error');
            }
          })
        }
      })
</code>```

This is the action at the controller

```<code>public function upload(Request $request)
    {
        $status = false;

        // Eliminar fotos previas
        $foto = Foto::whereInspeccionId($request->id)->whereTipo($request->tipo_foto)->first();
        if ($foto) {
            $foto->delete();
        }

        // Crear instacia de Foto
        $foto = new Foto();
        $foto->inspeccion_id = $request->id;
        if (Auth::user()) {
            $foto->autor = Auth::user()->id;
        } else {
            $foto->autor = $request->autor;
        }
        $foto->tipo = $request->tipo_foto;
        $img = $request->file('imagen_upload');
        $foto->asset = $img->getClientOriginalName();
        $save = $foto->save();

        // Cargar foto al servidor
        $dir = public_path() . '/../images/inspecciones/' . $foto->inspeccion_id . '/';
        $img->move($dir, $foto->asset);

        if ($save) {
            $status = true;
        }

        return response()->json(['status' => $status]);
    }
</code>```

I need that  the photos taked with de mobile camera stored at the server just like when I select files at the PC

Body:
In my project I need the users take photos with their phone and then send this photos to the server,

I already configure the input file field to open the camera, take the photo and show them in the form, but when  tried to save the file to the server, don't work, don't save the file, but properties like, name and extension passed to the controller.

When I tried to do the same on PC, upload photos stored in the PC, work perfectly.

This is my file input

<input type="file" name="imagen_upload" id="imagen_upload" capture="camera" accept="image/*"
              class="d-none">

This is my JS (jQuery)

      var formData;

      $(document).on('submit', '#form', function(e) {
        e.preventDefault();
        formData = new FormData(this);
        return false;
      });

      $(document).on('click', '.btn-save', function(e) {
        $('#form').trigger('submit');
        var confirmation;
        foto = $('[name="imagen_upload"]').val();
        if (foto == null || foto == '') {
          toastr.error('Debe tomar una foto');
          return;
        }
        confirmation = confirm('¿Esta seguro que desea grabar esta foto?');
        if (confirmation) {
          $.post({
            url: '{{ route('subirFoto') }}',
            data: formData,
            contentType: false,
            processData: false,
            success: function(data) {
              alert(data);
              if (data.status) {
                alert('Se grabo la foto correctamente');
              } else {
                alert('No se pudo grabar la foto, por favor intente de nuevo');
              }
            },
            error: function(data) {
              alert('Hubo un error');
            }
          })
        }
      })

This is the action at the controller

public function upload(Request $request)
    {
        $status = false;

        // Eliminar fotos previas
        $foto = Foto::whereInspeccionId($request->id)->whereTipo($request->tipo_foto)->first();
        if ($foto) {
            $foto->delete();
        }

        // Crear instacia de Foto
        $foto = new Foto();
        $foto->inspeccion_id = $request->id;
        if (Auth::user()) {
            $foto->autor = Auth::user()->id;
        } else {
            $foto->autor = $request->autor;
        }
        $foto->tipo = $request->tipo_foto;
        $img = $request->file('imagen_upload');
        $foto->asset = $img->getClientOriginalName();
        $save = $foto->save();

        // Cargar foto al servidor
        $dir = public_path() . '/../images/inspecciones/' . $foto->inspeccion_id . '/';
        $img->move($dir, $foto->asset);

        if ($save) {
            $status = true;
        }

        return response()->json(['status' => $status]);
    }

I need that  the photos taked with de mobile camera stored at the server just like when I select files at the PC


问:
Is there any wildcard character missing in over the given Given Ternary Condition Operator?
```<code>let output = []
for(let x = 0; x<appliances.length; x++){
    document.getElementById("parent").innerHTML += `<div class="card" style="width: 18rem;">
  <img src="${appliances[x].img_src}" class="card-img-top" alt="...">
  <div class="card-body">
    ${appliances[x].quantity >= 10 ?
        '<h5 class= "card-title" style = "color:blue">`${appliances[x].name}` - `₹${appliances[x].price}` </h5>' :
        '<h5 class="card-title" style = "color:green">{${appliances[x].name} - `₹${appliances[x].price}` </h5>'}
    <p class="card-text">Some quick example text to build on </p>
    <a href="#" class="btn btn-primary">Go somewhere</a>
  </div>
</div>`
</code>```

Kindly correct me to fix error over the ternary operator condition.Iam expecting to retrieve the name and price that was given in the array object.I am beginner so please help me with this.

Body:
let output = []
for(let x = 0; x<appliances.length; x++){
    document.getElementById("parent").innerHTML += `

    ${appliances[x].quantity >= 10 ?
        '
`${appliances[x].name}` - `₹${appliances[x].price}`
' :
        '
{${appliances[x].name} - `₹${appliances[x].price}`
'}

Some quick example text to build on

    Go somewhere

`

Kindly correct me to fix error over the ternary operator condition.Iam expecting to retrieve the name and price that was given in the array object.I am beginner so please help me with this.


问:
Failing to copy contents of an array of strings(a double char pointer returned from a function) into another array of strings? (C)
The function:

```<code>#define MAX_MATCHES 10
#define BUFFER_SIZE 100

char **search_regex(const char *string, const char *regex) {
    regex_t preg;
    int rv;
    size_t nmatch = MAX_MATCHES;
    regmatch_t pmatch[MAX_MATCHES];
    char **matches = malloc(MAX_MATCHES * sizeof(char *));

    // Compile the regular expression
    rv = regcomp(&preg, regex, REG_EXTENDED);
    if (rv != 0) {
        char error_message[BUFFER_SIZE];
        regerror(rv, &preg, error_message, BUFFER_SIZE);
        fprintf(stderr, "Could not compile regex '%s': %s\n", regex, error_message);
        return NULL;
    }

    // Match the regular expression against the string
    rv = regexec(&preg, string, nmatch, pmatch, 0);
    if (rv == 0) {
        // The regular expression matched. Extract the matched substrings and store them in the matches array.
        int i;
        for (i = 0; i < MAX_MATCHES; i++) {
            if (pmatch[i].rm_so == -1) {
                // No more matches
                break;
            }
            int start = pmatch[i].rm_so;
            int end = pmatch[i].rm_eo;
            int length = end - start;
            matches[i] = malloc((length + 1) * sizeof(char));
            strncpy(matches[i], &string[start], length);
            matches[i][length] = '\0';
        }
    }

    // Free the regular expression
    regfree(&preg);
    return matches;
}
</code>```

How do I copy it into an array of strings declared in main like

```<code>char hold[3][100];

memcpy(hold, search_regex(...,...),sizeof(char*)*10);
</code>```

How do I maneuver through this as this is an elementary problem of a program I am developing...
I have used tried using strcpy iteratively but to no avail

Body:
The function:

#define MAX_MATCHES 10
#define BUFFER_SIZE 100

char **search_regex(const char *string, const char *regex) {
    regex_t preg;
    int rv;
    size_t nmatch = MAX_MATCHES;
    regmatch_t pmatch[MAX_MATCHES];
    char **matches = malloc(MAX_MATCHES * sizeof(char *));

    // Compile the regular expression
    rv = regcomp(&preg, regex, REG_EXTENDED);
    if (rv != 0) {
        char error_message[BUFFER_SIZE];
        regerror(rv, &preg, error_message, BUFFER_SIZE);
        fprintf(stderr, "Could not compile regex '%s': %s\n", regex, error_message);
        return NULL;
    }

    // Match the regular expression against the string
    rv = regexec(&preg, string, nmatch, pmatch, 0);
    if (rv == 0) {
        // The regular expression matched. Extract the matched substrings and store them in the matches array.
        int i;
        for (i = 0; i < MAX_MATCHES; i++) {
            if (pmatch[i].rm_so == -1) {
                // No more matches
                break;
            }
            int start = pmatch[i].rm_so;
            int end = pmatch[i].rm_eo;
            int length = end - start;
            matches[i] = malloc((length + 1) * sizeof(char));
            strncpy(matches[i], &string[start], length);
            matches[i][length] = '\0';
        }
    }

    // Free the regular expression
    regfree(&preg);
    return matches;
}

How do I copy it into an array of strings declared in main like

char hold[3][100];

memcpy(hold, search_regex(...,...),sizeof(char*)*10);

How do I maneuver through this as this is an elementary problem of a program I am developing...
I have used tried using strcpy iteratively but to no avail


问:
Get data from _app.js in another server side page nextjs
Suppose our base url is example.com and someone immediately navigate to example.com/markets from outside so here is the flow:

Call api to get access token in _app.js in getInitialProps

In serverSideProps for /markets, call api with access token obtained at level 1

Because access token has not set by step 1 yet, step 2 fails because it has no access token yet.
I can't call access token's api at step 2 again because our level of abstraction is that all global data are taken from _app.js

What can I do to handle this with just nextjs functionalities?

_app.js:

```<code>MyApp.getInitialProps = async (appContext: AppContext) => {
  const access_token = await getAccessToken()

  return {
    accessToken: access_token
  };
};

</code>```

markets.js

```<code>export const getServerSideProps: GetServerSideProps<HouseMarketPageProps> = async (ctx) => {
  const market_data = await getMarketData(accessToken) //I can't access accessToken here

  return {
    props: {
      marketData: market_data
    }
  };
};
</code>```

Body:
Suppose our base url is example.com and someone immediately navigate to example.com/markets from outside so here is the flow:

Call api to get access token in _app.js in getInitialProps

In serverSideProps for /markets, call api with access token obtained at level 1

Because access token has not set by step 1 yet, step 2 fails because it has no access token yet.
I can't call access token's api at step 2 again because our level of abstraction is that all global data are taken from _app.js

What can I do to handle this with just nextjs functionalities?

_app.js:

MyApp.getInitialProps = async (appContext: AppContext) => {
  const access_token = await getAccessToken()

  return {
    accessToken: access_token
  };
};

markets.js

export const getServerSideProps: GetServerSideProps<HouseMarketPageProps> = async (ctx) => {
  const market_data = await getMarketData(accessToken) //I can't access accessToken here

  return {
    props: {
      marketData: market_data
    }
  };
};


问:
Giving props to other component React Native not working
I'm trying to give the data of a certain person to the other component but for some reason this only gives errors.
I tried doing that with the props method as it should but that does not work.

What can be the solution?

Parent:

```<code>
export default function EditFamily({ navigation, props, person, inheritors }) {
  const [shouldShowAdd, setShouldShowAdd] = useState(null);
  const [shouldShowAddChild, setShouldShowAddChild] = useState(null);

  function renderFamily(family, key) {
    return (
      <View key={key} style={styles.family}>
        <View style={styles.inheritors}>
          {family.inheritors.map((inheritor) => {
            return (
              <Add
                key={inheritor.id}
                person={inheritor}
                setShouldShowAdd={setShouldShowAdd}
              />
            );
          })}
        </View>
        {family.children && family.children.length ? (
          <View style={styles.children}>
            {family.children.map((child, index) => renderFamily(child, index))}
          </View>
        ) : null}
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <SafeAreaView style={styles.container}>
        {shouldShowAdd ? (
          <View style={styles.details}>
            <View style={styles.pressView}>
              <Pressable
                onPress={() => setShouldShowAdd(null)}
                style={styles.pressX}
              >
                <Text>X</Text>
              </Pressable>
            </View>
            <Pressable>
              <Text>Edit date of {shouldShowAdd.firstname}</Text>
            </Pressable>
            <Pressable
              onPress={() => setShouldShowAddChild(!shouldShowAddChild)}
            >
              <Text>Add child</Text>
            </Pressable>
            {shouldShowAddChild && <AddChild />}
            <Pressable>
              <Text>Add Partner</Text>
            </Pressable>
            <Pressable>
              <Text>Add Parent</Text>
            </Pressable>
          </View>
        ) : null}
        <ScrollView>
          <ScrollView horizontal={true}>{renderFamily(data)}</ScrollView>
        </ScrollView>
      </SafeAreaView>
      <StatusBar style="auto" />
    </View>
  );
}

</code>```

Component that gives data to the parent:

```<code>export default function Add({ person, setShouldShowAdd }) {
  let mijnFoto = 'http://192.168.1.36/CodingApp/assets/' + person.image;
  return (
    <TouchableOpacity
      style={styles.person}
      onPress={() => setShouldShowAdd(person)}
    >
      <Text style={styles.text}>
        {person.firstname} {person.lastname}
      </Text>
    </TouchableOpacity>
  );
}
</code>```

The component that should for example be able to show the Id of the person that's been clicked:

```<code>export default function AddChild({ setShouldShowAdd }) {

  return (
    <View>
      <Text>hoi id:{person.id}</Text>
   </View>
  );
}

</code>```

Body:
I'm trying to give the data of a certain person to the other component but for some reason this only gives errors.
I tried doing that with the props method as it should but that does not work.

What can be the solution?

Parent:

export default function EditFamily({ navigation, props, person, inheritors }) {
  const [shouldShowAdd, setShouldShowAdd] = useState(null);
  const [shouldShowAddChild, setShouldShowAddChild] = useState(null);

  function renderFamily(family, key) {
    return (
      <View key={key} style={styles.family}>
        <View style={styles.inheritors}>
          {family.inheritors.map((inheritor) => {
            return (
              <Add
                key={inheritor.id}
                person={inheritor}
                setShouldShowAdd={setShouldShowAdd}
              />
            );
          })}
        </View>
        {family.children && family.children.length ? (
          <View style={styles.children}>
            {family.children.map((child, index) => renderFamily(child, index))}
          </View>
        ) : null}
      </View>
    );
  }

  return (
    <View style={styles.container}>
      <SafeAreaView style={styles.container}>
        {shouldShowAdd ? (
          <View style={styles.details}>
            <View style={styles.pressView}>
              <Pressable
                onPress={() => setShouldShowAdd(null)}
                style={styles.pressX}
              >
                <Text>X</Text>
              </Pressable>
            </View>
            <Pressable>
              <Text>Edit date of {shouldShowAdd.firstname}</Text>
            </Pressable>
            <Pressable
              onPress={() => setShouldShowAddChild(!shouldShowAddChild)}
            >
              <Text>Add child</Text>
            </Pressable>
            {shouldShowAddChild && <AddChild />}
            <Pressable>
              <Text>Add Partner</Text>
            </Pressable>
            <Pressable>
              <Text>Add Parent</Text>
            </Pressable>
          </View>
        ) : null}
        <ScrollView>
          <ScrollView horizontal={true}>{renderFamily(data)}</ScrollView>
        </ScrollView>
      </SafeAreaView>
      <StatusBar style="auto" />
    </View>
  );
}

Component that gives data to the parent:

export default function Add({ person, setShouldShowAdd }) {
  let mijnFoto = 'http://192.168.1.36/CodingApp/assets/' + person.image;
  return (
    <TouchableOpacity
      style={styles.person}
      onPress={() => setShouldShowAdd(person)}
    >
      <Text style={styles.text}>
        {person.firstname} {person.lastname}
      </Text>
    </TouchableOpacity>
  );
}

The component that should for example be able to show the Id of the person that's been clicked:

export default function AddChild({ setShouldShowAdd }) {

  return (
    <View>
      <Text>hoi id:{person.id}</Text>
   </View>
  );
}


问:
Importing database from mysql dump file
I am trying to import a mysql database from here in Windows 10 workbench. I am trying to to that from the UI of Workbench. Navigating to server>data import i open the corresponding window and select the file i want to import( in my case attachments.sql). When i press data import i get:

```<code> Restoring C:\Users\..\attachments.sql
Running: mysql.exe --defaults-file="C:\Users...\tmpi16ntmjj.cnf"  --protocol=tcp --host=localhost --user=root --port=3306 --default-character-set=utf8 --comments  < "C:\\Users\\...ς\\attachments.sql"
ERROR 1046 (3D000) at line 22: No database selected

Operation failed with exitcode 1
14:28:12 Import of C:\Users\Kospsych..\attachmments.sql has finished with 1 errors
</code>```

which i don not understand. How could this be done properly?

Title: Importing database from mysql dump file

Body:
I am trying to import a mysql database from here in Windows 10 workbench. I am trying to to that from the UI of Workbench. Navigating to server>data import i open the corresponding window and select the file i want to import( in my case attachments.sql). When i press data import i get:

 Restoring C:\Users\..\attachments.sql
Running: mysql.exe --defaults-file="C:\Users...\tmpi16ntmjj.cnf"  --protocol=tcp --host=localhost --user=root --port=3306 --default-character-set=utf8 --comments  < "C:\\Users\\...ς\\attachments.sql"
ERROR 1046 (3D000) at line 22: No database selected

Operation failed with exitcode 1
14:28:12 Import of C:\Users\Kospsych..\attachmments.sql has finished with 1 errors

which i don not understand. How could this be done properly?


问:
Docker and Angular build cannot find file
I am preparing to release an angular application within Docker. My Docker file looks as follows

```<code>#step 1
FROM node:latest as node
WORKDIR /app
COPY . .
RUN npm install -g npm@9.2.0
run npm run build --prod

#step 2
FROM nginx:alpine
COPY --from=node /app/dist/taims /usr/share/nginx/html
</code>```

When I  run npm run build --prod outside of the Docker file I don't receive this error. What am I missing?
At the very end of the build, I receive the following error

```<code>Error: src/app/modules/internal/signals/signals.component.ts:11:29 - error TS2307: Cannot find module '../../../models/fundamentals/GeneralInfo' or its corresponding type declarations.
#13 51.57
#13 51.57 11 import { GeneralInfo } from '../../../models/fundamentals/GeneralInfo';

</code>```

When I run

Body:
I am preparing to release an angular application within Docker. My Docker file looks as follows

#step 1
FROM node:latest as node
WORKDIR /app
COPY . .
RUN npm install -g npm@9.2.0
run npm run build --prod

#step 2
FROM nginx:alpine
COPY --from=node /app/dist/taims /usr/share/nginx/html

When I  run npm run build --prod outside of the Docker file I don't receive this error. What am I missing?
At the very end of the build, I receive the following error

Error: src/app/modules/internal/signals/signals.component.ts:11:29 - error TS2307: Cannot find module '../../../models/fundamentals/GeneralInfo' or its corresponding type declarations.
#13 51.57
#13 51.57 11 import { GeneralInfo } from '../../../models/fundamentals/GeneralInfo';

When I run


问:
Why the ouput of nn.Embeddings(vocab_size, dim) chnages on re-running the code for same input string?
I am trying to understand how word embeddings are generated, I've been reading that 1-hot encoded vector is used and it servers as a lookup table but, I want to print that and see, how can I do that.  When I am doing the following:

```<code> self.embeddings = nn.Embedding(vocab_size, dim)
 print('embed',self.embeddings.weight)
</code>```

I am getting different results when I re-run the code for same input string/vocab_size and same dim.

I want to know why this happens and how are those weight values calulated? What equation/fucntions is used to get these values? Is any function like softmax etc used to get the weights?

Body:
I am trying to understand how word embeddings are generated, I've been reading that 1-hot encoded vector is used and it servers as a lookup table but, I want to print that and see, how can I do that.  When I am doing the following:

 self.embeddings = nn.Embedding(vocab_size, dim)
 print('embed',self.embeddings.weight)

I am getting different results when I re-run the code for same input string/vocab_size and same dim.

I want to know why this happens and how are those weight values calulated? What equation/fucntions is used to get these values? Is any function like softmax etc used to get the weights?


问:
AAChartModel-Swift / AAInfographics — trouble displaying a chart
I'm trying to figure out how to use the AAChartModel Swift library.

I imported it, and did import AAInfographics.

I can't manage to get a chart to display. I have the following code as an onAppear on a VStack:

.onAppear {
    let chartModel = AAChartModel()
        .chartType(.bar)
            .title("Polar Area Chart")
            .subtitle("A simple polar area chart")
            .dataLabelsEnabled(true)
            .categories(["Jan", "Feb", "Mar", "Apr", "May", "Jun"])
            .yAxisTitle("Y-axis Title")
            .series([
                AASeriesElement()
                    .name("Polar Area Chart")
                    .data([7.0, 6.9, 2.5, 14.5, 18.2, 21.5])
            ])

    let chartView = AAChartView()
    chartView.frame = CGRect(x: 0,
                            y: 60,
                            width: 200,
                            height: 200)
    chartView.aa_drawChartWithChartModel(chartModel)
}
```
<p>I get the following printed to console (ends with <code> AAChartView was destroyed!!!</code>):</p>
<pre class="lang-bash prettyprint-override"><code>----------- console log AAOptions JSON information of AAChartView -----------:
{
  "series" : [
    {
      "data" : [
        7,
        6.9000000000000004,
        2.5,
        14.5,
        18.199999999999999,
        21.5
      ],
      "name" : "Polar Area Chart"
    }
  ],
  "legend" : {
    "enabled" : true
  },
  "xAxis" : {
    "categories" : [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun"
    ],
    "visible" : true,
    "labels" : {
      "enabled" : true
    },
    "title" : {
      "text" : ""
    }
  },
  "tooltip" : {
    "shared" : true,
    "enabled" : true
  },
  "subtitle" : {
    "text" : "A simple polar area chart"
  },
  "chart" : {
    "pinchType" : "none",
    "panning" : true,
    "type" : "bar"
  },
  "colors" : [
    "#1e90ff",
    "#ef476f",
    "#ffd066",
    "#04d69f",
    "#25547c"
  ],
  "plotOptions" : {
    "series" : {
      "stacking" : "",
      "animation" : {
        "duration" : 800,
        "easing" : 0
      },
      "dataLabels" : {
        "enabled" : true
      }
    },
    "bar" : {
      "borderWidth" : 0,
      "borderRadius" : 0
    }
  },
  "credits" : {
    "enabled" : false
  },
  "yAxis" : {
    "title" : {
      "text" : "Y-axis Title"
    },
    "visible" : true,
    "lineWidth" : 0,
    "labels" : {
      "enabled" : true
    },
    "gridLineWidth" : 0.60000002384185791
  },
  "title" : {
    "text" : "Polar Area Chart"
  }
}
 AAChartView was destroyed!!!
</code>```

Body:
I'm trying to figure out how to use the AAChartModel Swift library.

I imported it, and did import AAInfographics.

I can't manage to get a chart to display. I have the following code as an onAppear on a VStack:

.onAppear {
    let chartModel = AAChartModel()
        .chartType(.bar)
            .title("Polar Area Chart")
            .subtitle("A simple polar area chart")
            .dataLabelsEnabled(true)
            .categories(["Jan", "Feb", "Mar", "Apr", "May", "Jun"])
            .yAxisTitle("Y-axis Title")
            .series([
                AASeriesElement()
                    .name("Polar Area Chart")
                    .data([7.0, 6.9, 2.5, 14.5, 18.2, 21.5])
            ])

    let chartView = AAChartView()
    chartView.frame = CGRect(x: 0,
                            y: 60,
                            width: 200,
                            height: 200)
    chartView.aa_drawChartWithChartModel(chartModel)
}

I get the following printed to console (ends with  AAChartView was destroyed!!!):

----------- console log AAOptions JSON information of AAChartView -----------:
{
  "series" : [
    {
      "data" : [
        7,
        6.9000000000000004,
        2.5,
        14.5,
        18.199999999999999,
        21.5
      ],
      "name" : "Polar Area Chart"
    }
  ],
  "legend" : {
    "enabled" : true
  },
  "xAxis" : {
    "categories" : [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun"
    ],
    "visible" : true,
    "labels" : {
      "enabled" : true
    },
    "title" : {
      "text" : ""
    }
  },
  "tooltip" : {
    "shared" : true,
    "enabled" : true
  },
  "subtitle" : {
    "text" : "A simple polar area chart"
  },
  "chart" : {
    "pinchType" : "none",
    "panning" : true,
    "type" : "bar"
  },
  "colors" : [
    "#1e90ff",
    "#ef476f",
    "#ffd066",
    "#04d69f",
    "#25547c"
  ],
  "plotOptions" : {
    "series" : {
      "stacking" : "",
      "animation" : {
        "duration" : 800,
        "easing" : 0
      },
      "dataLabels" : {
        "enabled" : true
      }
    },
    "bar" : {
      "borderWidth" : 0,
      "borderRadius" : 0
    }
  },
  "credits" : {
    "enabled" : false
  },
  "yAxis" : {
    "title" : {
      "text" : "Y-axis Title"
    },
    "visible" : true,
    "lineWidth" : 0,
    "labels" : {
      "enabled" : true
    },
    "gridLineWidth" : 0.60000002384185791
  },
  "title" : {
    "text" : "Polar Area Chart"
  }
}
 AAChartView was destroyed!!!


问:
Callback function's byte parameter has value out of bounds in project Panama function interface
I'm using the new Foreign function & memory API which is part of project Panama and available in preview in JAVA 19.

This is the complete callback function

```<code>public static byte addFive(byte t) {
    Byte test = (Byte) t;
    return (byte) (Long.valueOf(test) + 5);
}
</code>```

The native library function which is called with as paramater, the function addFive and (byte) -41.

```<code>uint8_t callback_test(uint8_t (*fn)(uint8_t), uint8_t arg) {
    uint8_t res = fn(arg + 1) * 2;
    return res;
}
</code>```

I expect t to have value -40, and this does show in the Intellij debugger. But when you print it, it prints 216 instead. In addition, casting to Byte gives an ArrayIndexOutOfBoundsException.

I do realize that the native function is an unsigned int, so the returned value of 216 makes sense. However, a java byte should not be allowed that value, so, I expect java to automatically convert it to -41.

Is this behavior expected?

What is the correct way to get the unsigned int from the native code passed to the java function as a byte in the range [-128, 127]?

Body:
I'm using the new Foreign function & memory API which is part of project Panama and available in preview in JAVA 19.

This is the complete callback function

public static byte addFive(byte t) {
    Byte test = (Byte) t;
    return (byte) (Long.valueOf(test) + 5);
}

The native library function which is called with as paramater, the function addFive and (byte) -41.

uint8_t callback_test(uint8_t (*fn)(uint8_t), uint8_t arg) {
    uint8_t res = fn(arg + 1) * 2;
    return res;
}

I expect t to have value -40, and this does show in the Intellij debugger. But when you print it, it prints 216 instead. In addition, casting to Byte gives an ArrayIndexOutOfBoundsException.

I do realize that the native function is an unsigned int, so the returned value of 216 makes sense. However, a java byte should not be allowed that value, so, I expect java to automatically convert it to -41.

Is this behavior expected?

What is the correct way to get the unsigned int from the native code passed to the java function as a byte in the range [-128, 127]?


问:
authorization key&value are in http header, but I can't use postman with google access token
In postman header, there are authorization key&value exactly. but url always redirect to google login page


问:
How to display the `test case name` in mobile device screen while flutter integration test is being executed
Currently when we run the flutter integration test by flutter test integration_test/app_test.dart, we are seeing Test Starting.. text in the mobile device/simulator screen(Screenshot Attached)

when we have multiple test cases in app_test.dart (Say 10 TCs)

In order to see which Test case is currently being executed, is there any way we can display the test case name in mobile device/simulator screen?

Or can we override Test Starting..?

Or can we add watermark?

Any help highly appreciated.!


问:
Unable to connect to backend on ec2 instance due to CORS issue
I am trying to access the backend using this query

```<code>fetch("<backend-server-link>", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Token: <token>,
      },
      body: JSON.stringify(payload),
    })
</code>```

But I get this error in my console.

Access to fetch at '< site-name>' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

The backend is hosted on a AWS server.
The backend code is in Python an Flask, and I have included CORS in the Flask app. How do I resolve this error?

I tried adding the 'no-cors' mode in the fetch query but it did not work.

Body:
I am trying to access the backend using this query

fetch("<backend-server-link>", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Token: <token>,
      },
      body: JSON.stringify(payload),
    })

But I get this error in my console.

Access to fetch at '< site-name>' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

The backend is hosted on a AWS server.
The backend code is in Python an Flask, and I have included CORS in the Flask app. How do I resolve this error?

I tried adding the 'no-cors' mode in the fetch query but it did not work.


问:
Execution failed for task ':firebase_core:mergeDebugShaders'. in flutter project
What is the problem in my futter project

```<code>dependencies:
  flutter:
    sdk: flutter
  cloud_firestore : ^4.3.1

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  bloc:
  flutter_bloc:
  equatable:
  http:
  flutter_svg: ^0.17.4
  firebase_core: ^2.4.1

</code>```

I have tried to change the cloud_firestore and firebase_core

Body:
What is the problem in my futter project

dependencies:
  flutter:
    sdk: flutter
  cloud_firestore : ^4.3.1

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  bloc:
  flutter_bloc:
  equatable:
  http:
  flutter_svg: ^0.17.4
  firebase_core: ^2.4.1

I have tried to change the cloud_firestore and firebase_core