问:
Calling Fork for a subprocess
I am implementing a shell in C but when Im using fork() it creates too child process.
Here is my code :

```<code>int exec_simple_command(struct ast_node_simple_command *node)
{
    if (node == NULL)
        return 1;

    char **args = node->words;
    if (args == NULL)
        return 1;

    pid_t pid = fork();
    int status;

    /* Error handling */
    if (pid < 0)
        return -1;

    if (pid == 0) /* Child Process */
    {
        return exec_builtin(args);
    }
    else
    {
        if (waitpid(pid, &status, 0) < 0)
        {
            return 2;
        }

        return 0;

    }
}
</code>```

i have file with simple command to test my shell :

```<code>echo 1;
echo 2;
echo 3;
echo 4;

</code>```

And here is the output i get :

```<code>1
2
3
4
4
3
4
4
2
3
4
4
3
4
4

</code>```

every time I execute a new builtin it duplicates the number of child.
I just want to execute on child, wait before the child process terminated and then continue the rest of the program.
Thanks for your help.

Title: Calling Fork for a subprocess

Body:
I am implementing a shell in C but when Im using fork() it creates too child process.
Here is my code :

int exec_simple_command(struct ast_node_simple_command *node)
{
    if (node == NULL)
        return 1;

    char **args = node->words;
    if (args == NULL)
        return 1;

    pid_t pid = fork();
    int status;

    /* Error handling */
    if (pid < 0)
        return -1;

    if (pid == 0) /* Child Process */
    {
        return exec_builtin(args);
    }
    else
    {
        if (waitpid(pid, &status, 0) < 0)
        {
            return 2;
        }

        return 0;

    }
}

i have file with simple command to test my shell :

echo 1;
echo 2;
echo 3;
echo 4;

And here is the output i get :

1
2
3
4
4
3
4
4
2
3
4
4
3
4
4

every time I execute a new builtin it duplicates the number of child.
I just want to execute on child, wait before the child process terminated and then continue the rest of the program.
Thanks for your help.


来源: stackexchange

问:
Trying to insert image into Word Table using VBA
Im trying to use an input table and output table, where the inputs autofill the output using IF functions. For one of the Outputs, i need to the information in the cell to be in a table format. I thought inserting an image would be easier than embedding a table, so i tried that. Cant get it to function tho.

I have tried the following:

```<code>  If input6 = "putimagehere" Then
    Dim img As String
    img = "Image path"

    table2.Cell(18, 3).Select
    Selection.InlineShapes.AddPicture img

    End If
</code>```

It recognises the tables, all other putputs are correct, just the one that requires the image.

Any thoughts?

ContentLicense: CC BY-SA 4.0

Body:
Im trying to use an input table and output table, where the inputs autofill the output using IF functions. For one of the Outputs, i need to the information in the cell to be in a table format. I thought inserting an image would be easier than embedding a table, so i tried that. Cant get it to function tho.

I have tried the following:

  If input6 = "putimagehere" Then
    Dim img As String
    img = "Image path"

    table2.Cell(18, 3).Select
    Selection.InlineShapes.AddPicture img

    End If

It recognises the tables, all other putputs are correct, just the one that requires the image.

Any thoughts?


问:
karate: Accept = 'application/xml' header not working as expected
Even after setting the header, Accept = 'application/xml', when i am logging the response, it is showing json. My request is xml and i want to compare this xml request with the xml response. Can someone help.</p>
```<code>Given url testUrl
    And header Accept = 'application/xml'
    Then retry until responseStatus == 200
    When method GET
    Then status 200
    * karate.log("created: %s", response)
</code>```

Body:
Even after setting the header, Accept = 'application/xml', when i am logging the response, it is showing json. My request is xml and i want to compare this xml request with the xml response. Can someone help.

Given url testUrl
    And header Accept = 'application/xml'
    Then retry until responseStatus == 200
    When method GET
    Then status 200
    * karate.log("created: %s", response)


问:
How to get current live period from multi period dash stream
I 2 questions about Multi Period Dash how to get current live period from multi periods

For example :-

```<code>  <Period duration="PT394.04S" id="2405" start="PT1673258997.04S">
 <Period duration="PT15.0S" id="2405_1073741858_6" start="PT1673259457.56S">
 <Period id="2405_1073741858_7" start="PT1673259472.56S">
</code>```

is it (NOW(time) - Period start) < Period Duration) ? because some times its not working like that formula

Second question how get current segment number from timeline

For example :-
AUDIO:

```<code>      <SegmentTemplate initialization="D-$RepresentationID$.dash" media="D-$RepresentationID$-$Time$.dash" presentationTimeOffset="80292708174720" timescale="48000">
        <SegmentTimeline>
          <S d="184320" r="31" t="80292721037311" />
          <S d="178176" />
          </SegmentTimeline>
      </SegmentTemplate>
</code>```

VIDEO:

```<code>      <SegmentTemplate initialization="D-$RepresentationID$.dash" media="D-$RepresentationID$-$Time$.dash" presentationTimeOffset="1003658852184" timescale="600">
        <SegmentTimeline>
          <S d="2304" r="32" t="1003659011328" />
          <S d="1560" />
          </SegmentTimeline>
</code>```

You can see r on video template is higher than audio so video segments are more than audio if we assume t value is start time always sounds out sync and i cant really match them so how to get right current video and audio number regardless segments index number

Body:
I 2 questions about Multi Period Dash how to get current live period from multi periods

For example :-

  <Period duration="PT394.04S" id="2405" start="PT1673258997.04S">
 <Period duration="PT15.0S" id="2405_1073741858_6" start="PT1673259457.56S">
 <Period id="2405_1073741858_7" start="PT1673259472.56S">

is it (NOW(time) - Period start) < Period Duration) ? because some times its not working like that formula

Second question how get current segment number from timeline

For example :-
AUDIO:

      <SegmentTemplate initialization="D-$RepresentationID$.dash" media="D-$RepresentationID$-$Time$.dash" presentationTimeOffset="80292708174720" timescale="48000">
        <SegmentTimeline>
          <S d="184320" r="31" t="80292721037311" />
          <S d="178176" />
          </SegmentTimeline>
      </SegmentTemplate>

VIDEO:

      <SegmentTemplate initialization="D-$RepresentationID$.dash" media="D-$RepresentationID$-$Time$.dash" presentationTimeOffset="1003658852184" timescale="600">
        <SegmentTimeline>
          <S d="2304" r="32" t="1003659011328" />
          <S d="1560" />
          </SegmentTimeline>

You can see r on video template is higher than audio so video segments are more than audio if we assume t value is start time always sounds out sync and i cant really match them so how to get right current video and audio number regardless segments index number


问:
While running spring boot project getting error like NoClassDefFoundError org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
I have Spring boot project with the pom version 2.7.1 and while running getting below error.
I am using spring cloud dependency. My pom dependency like

org.springframework.boot
spring-boot-starter-parent
2.7.1

```<code><dependency>
    <groupId> org.springframework.boot </groupId>
    <artifactId>spring-boot-starter-cloud-connectors</artifactId>
    <version>2.2.13.RELEASE</version>
</dependency
</code>```

dependency Management:

```<code><dependencies>
  <dependency>
     <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-dependencies</artifactId>
    <version>2020.0.2</version>
    <type>pom</type>
   <scope>import</scope>
 </dependency>
</code>```

   Error:

   [enter image description here](https://i.stack.imgur.com/KwhUP.png)

Error Message::

Caused by: java.lang.NoClassDefFoundError:          org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadat

I need this pom version(2.7.1) not lower than this. Any solution?

Body:
I have Spring boot project with the pom version 2.7.1 and while running getting below error.
I am using spring cloud dependency. My pom dependency like

org.springframework.boot
spring-boot-starter-parent
2.7.1

<dependency>
    <groupId> org.springframework.boot </groupId>
    <artifactId>spring-boot-starter-cloud-connectors</artifactId>
    <version>2.2.13.RELEASE</version>
</dependency

dependency Management:

<dependencies>
  <dependency>
     <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-dependencies</artifactId>
    <version>2020.0.2</version>
    <type>pom</type>
   <scope>import</scope>
 </dependency>

   Error:

   [enter image description here](https://i.stack.imgur.com/KwhUP.png)

Error Message::

Caused by: java.lang.NoClassDefFoundError:          org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadat

I need this pom version(2.7.1) not lower than this. Any solution?


问:
Apache config to set POST field from URL variable
I have a old API where commands are selected with a POST field.
All data is going thru /api and then using COMMAND POST field to identify what it should actually do in the backend. COMMAND=CREATE_USER, COMMAND=LOGIN etc.

Is there a way to configure Apache to move this COMMAND to the request path?
So I could do /api/CREATE_USER or api/LOGIN and it would take the parameter out of the url and put it in the POST data and continue as usual?

I can't rewrite the API at the moment at it is pretty huge legacy code and this would be a good middle step for now.


问:
r code chunk is not presented properly under tab with xaringan template
I am preparing a presentation using a xaringan template.  I designed multiple tabs on one slide and included an R code chunk under one tab.  The code chunk was not presented properly.

[extra words to fill the whitespace.  I have nothing more to say]

Here are my codes:

```<code><!-- Tab links -->
<div class="tab">
  <button class="tablinks active" onclick="tablabel(event, 'tab11')">Tab 1</button>
</div>

<!-- Tab content -->
<div id="tab11" class="tabcontent" style="display:block">
   ```{r, eval=F}
BPPARAM <- SnowParam(detectCores()-1, progressbar = TRUE)
params <- list()
pks <- findChromPeaks([OnDiskMSnExp instant], param = params$CentWave, BPPARAM = BPPARAM)
```

```
```css
<style type ="text/css">
/* Style the tab */
.tab {
overflow: hidden;
/*border: 1px solid #ccc;*/
/*background-color: #f1f1f1;*/
}

/* Style the buttons that are used to open the tab content */
.tab tab_button {
text-align:left;
background-color: #f1e4ff;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
font-size: 17px;
margin-left:0.3em;
}

/* Change background color of buttons on hover */
.tab tab_button:hover {
background-color: #e4e5ff;
}

/* Create an active/current tablink class */
.tab tab_button.active {
background-color: #ffe4ff;
color: #fff;
background-color: #2b8cc4;
}

/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
/*border: 1px solid #ccc;*/
border-top: none;
/*text-align: left;*/
font-size: 20px;
/*font-style: normal;*/
/* background-color: #f2ffe4;*/
}

</style>
</code>```

Body:
I am preparing a presentation using a xaringan template.  I designed multiple tabs on one slide and included an R code chunk under one tab.  The code chunk was not presented properly.

[extra words to fill the whitespace.  I have nothing more to say]

Here are my codes:

  <button class="tablinks active" onclick="tablabel(event, 'tab11')">Tab 1</button>

   ```{r, eval=F}
BPPARAM <- SnowParam(detectCores()-1, progressbar = TRUE)
params <- list()
pks <- findChromPeaks([OnDiskMSnExp instant], param = params$CentWave, BPPARAM = BPPARAM)
</code></pre>

<pre><code>
```css


问:
How to create a sleep tracker using chartjs? (ng2charts)
Im currently trying to create a sleep tracking app using ng2 charts, but I cant seem to figure out how to correctly get it to work, and how to pass the data for it to display it correctly.

Just for example, if I slept from 18:00 o clock until 23:00 o clock, i want the bar to start at 18 and to end at 23. So i want to give the data like (x: 2023-01-10, y: 18:00, 23:00) for example.

Also, it should automatically stop at 24:00 at midnight and start again on the next day, like if i slept from 20:00 to 03:00 the next day. Is this even possible using ng2 charts?

I added my current chart and the relevant below.

```<code> scales: {
 x: {
 type: 'time',
 time:{
 unit: 'day',
         }
       },
 y:{
 min: '00:00:00',
 max: '23:59:59',
 suggestedMin: '00:00:00',
 suggestedMax: '23:59:59',
 type: 'time',
 time:{
 displayFormats:{
 hour: 'HH:00',
           },
 tooltipFormat: 'HH:MM',
         },
 stacked: true,
 min: 0,
 max: 24,
 ticks: {
 maxTicksLimit: 24,
         },
       },

 datasets: [
       {
 data: [
           {x: "2022-10-18", y:  "14:26:07" },
           {x: "2022-10-19", y:  "16:26:07" },
           {x: "2022-10-20", y:  "14:26:07" },
           {x: "2022-10-21", y:  "14:26:07" },
           {x: "2022-10-22", y:  "14:26:07" },
           {x: "2022-10-23", y:  "14:26:07" },
           {x: "2022-10-24", y:  "14:26:07" },
         ],
       },
     ],
</code>```

Current chart

I tried to pass a angular Time object as the y value, i also tried pretty much every variation of time strings i could think of.

Body:
Im currently trying to create a sleep tracking app using ng2 charts, but I cant seem to figure out how to correctly get it to work, and how to pass the data for it to display it correctly.

Just for example, if I slept from 18:00 o clock until 23:00 o clock, i want the bar to start at 18 and to end at 23. So i want to give the data like (x: 2023-01-10, y: 18:00, 23:00) for example.

Also, it should automatically stop at 24:00 at midnight and start again on the next day, like if i slept from 20:00 to 03:00 the next day. Is this even possible using ng2 charts?

I added my current chart and the relevant below.

 scales: {
 x: {
 type: 'time',
 time:{
 unit: 'day',
         }
       },
 y:{
 min: '00:00:00',
 max: '23:59:59',
 suggestedMin: '00:00:00',
 suggestedMax: '23:59:59',
 type: 'time',
 time:{
 displayFormats:{
 hour: 'HH:00',
           },
 tooltipFormat: 'HH:MM',
         },
 stacked: true,
 min: 0,
 max: 24,
 ticks: {
 maxTicksLimit: 24,
         },
       },

 datasets: [
       {
 data: [
           {x: "2022-10-18", y:  "14:26:07" },
           {x: "2022-10-19", y:  "16:26:07" },
           {x: "2022-10-20", y:  "14:26:07" },
           {x: "2022-10-21", y:  "14:26:07" },
           {x: "2022-10-22", y:  "14:26:07" },
           {x: "2022-10-23", y:  "14:26:07" },
           {x: "2022-10-24", y:  "14:26:07" },
         ],
       },
     ],

Current chart

I tried to pass a angular Time object as the y value, i also tried pretty much every variation of time strings i could think of.


问:
create-react-app with typescript failing to install dependencies
I have been trying to install create-react-app with typescript using the following command
npx create-react-app my-app --template typescript
and this is the output I get in the terminal
`Creating a new React app in D:\ecom\frontend\my-app.

npm WARN config global --global, --local are deprecated. Use --location=global instead.
Installing react, react-dom, and react-scripts with cra-template-typescript...

npm WARN config global --global, --local are deprecated. Use --location=global instead.

added 1414 packages in 10m

231 packages are looking for funding
run npm fund for details

Initialized a git repository.

Installing template dependencies using npm...
npm install --no-audit --save @testing-library/jest-dom@^5.14.1 @testing-library/react@^13.0.0 @testing-library/user-event@^13.2.1 @types/jest@^27.0.1 @types/node@^16.7.13 @types/react@^18.0.0 @types/react-dom@^18.0.0 typescript@^4.4.2  web-vitals@^2.1.0 failed`

Any other dependency I try to install inside create-react-app folder also fails to install

npm is successfully installing dependencies in my backend projects where I'm not using create-react-app so the issue seems to be with the create-react-app and not with npm

I've tried restarting create-react-app after uninstalling it globally but that does not work either

I've tried deleting the node-modules, package-lock.json and running npm install but that does not fix the issue either

It all started when I tried to install storybook (npm package). It got installed successfully but then for some reason I decided to delete entire project folder and I have not been able to set it up again, since.


问:
Connection string of MongoDB using TLS
I am a DBA. I have one setup of TLS mechanism based environment. Want to connect that DB using C# drivers of application. I am unable to connect the same. sharing the connection string for the same below. can some one help into that connectivity.

"mongodb://user:pass@hostname1:port,hostname2:port,hostname3:port/ibmclouddb?authSource=admin&replicaSet=replset&tls=true&tlsCAFile=/apps/Deploy/mongo/certificats/mg002i000589.pem"

Conf of TLS

Title: Connection string of MongoDB using TLS


问:
encountered with problem when install packages with npm
I need some help because I can't install any npm packages. When I try to install something I get this error.

This is my ERROR msg IMAGE

My node version is up to dated with v18.13.0 and npm version is 9.2.0

Please help me solve this problem.


问:
Oracle to show and hide value if meet two identical column in one table

I have data that show item, barcode and batch.

I want to show just one value and hide Item and Barcode after the one IF the Item and Barcode are not unique but has different batch.

the example on picture

This is what I expected.


问:
Hide 'about:blank' while printing a html form of an app which i developed
I wanna remove the 'about:blank' text that is being printed everytime I try printing a form of an app. Attached is the form(top) where 'about:blank' appears always.

Anything, we could do to remove it? btw, i use javascript to print

function printPageArea(areaID){
var printContent = document.getElementById(areaID); var WinPrint = window.open("http://myaddress.com/problem.html"); WinPrint.document.write(printContent.innerHTML); ``your textyour text WinPrint.document.close(); WinPrint.focus(); WinPrint.print(); WinPrint.close(); }

I'm not sure what to do and still exploring. My expectation is to remove about:blank through code


问:
image in ui.alert box on key event
In my adventure game I would like to implement some pictures in ui.alert boxes to show the player some things in the game. the alert function should be released on a key event. so, the content of the alert box should refer to a css.class (no html if possible).

I´m using Twine Sugarcube at the moment to code the game. with text it works.

how do i put an image(css.class) into the keyup event?

below you can find the js and the css code.

```<code>(function () {
  $(document).on('keyup', function (ev) {

    if (ev.key === 'a') {
      UI.alert("#no_panic");
    }
  });
}());

#no_panic {background-image: url("data/fotos/panic.png");width:800px;height: 583px;}

</code>```

Title: image in ui.alert box on key event

Body:
In my adventure game I would like to implement some pictures in ui.alert boxes to show the player some things in the game. the alert function should be released on a key event. so, the content of the alert box should refer to a css.class (no html if possible).

I´m using Twine Sugarcube at the moment to code the game. with text it works.

how do i put an image(css.class) into the keyup event?

below you can find the js and the css code.

(function () {
  $(document).on('keyup', function (ev) {

    if (ev.key === 'a') {
      UI.alert("#no_panic");
    }
  });
}());

#no_panic {background-image: url("data/fotos/panic.png");width:800px;height: 583px;}


问:
Google drive script
I am looking for a way to automatically rename files contained in specific Google Drive folders according to their original name. I would like this to be automated so when a new file is put into one of these folders, it is renamed with no outside action required.

For example in the "TEST" folder, files will be put, whose name follows this basic logic "[ID][name][yyyy-mm-dd][hhmmss]"
I am trying to ensure that when they are put in the "Test" folder their original name changes to [name][yyyy-mm-dd][hh"h"mm]
Example of changing the name using the original name:
Original name = _00869544_Item_2023-11-01_150726
New name = Item_2023-11-01_15:07

The files contained in the folders in question come from a synchronization, based on rules, and are therefore created / deleted automatically according to their, original name is also generated without this being able to be modified at the base.

Is it possible? How ?

Thank you very much !

I haven't been able to find any solution yet.

Title: Google drive script


问:
What are ppearson and spearson in datamash, and how do you use them?
When I look at the documentation, there is no "correlation", but there is "ppearson" and "spearson".  They are mentioned exactly once, as a "group-by statistical operation."  But .. how exactly are they defined?

Also, when I try to use one, there is an error message, but I don't understand how to fix it.  How do you use ppearson or spearson?

```<code>$ cat > foo.tsv
1^I2
2^I3
$ cat foo.tsv | datamash ppearson 1,2
datamash: operation ‘ppearson’ requires field pairs
</code>```

EDIT: This documentation section says

GNU Datamash is designed to closely follow R project’s (https://www.r-project.org/) statistical functions. See the files/operators.R file for the R equivalent code for each of datamash’s operators. When building datamash from source code on your local computer, operators are compared to known results of the equivalent R functions.

Looking in R, I don't see an spearson:

```<code>> ?spearson
No documentation for ‘spearson’ in specified packages and libraries:
you could try ‘??spearson’
</code>```

Body:
When I look at the documentation, there is no "correlation", but there is "ppearson" and "spearson".  They are mentioned exactly once, as a "group-by statistical operation."  But .. how exactly are they defined?

Also, when I try to use one, there is an error message, but I don't understand how to fix it.  How do you use ppearson or spearson?

$ cat > foo.tsv
1^I2
2^I3
$ cat foo.tsv | datamash ppearson 1,2
datamash: operation ‘ppearson’ requires field pairs

EDIT: This documentation section says

GNU Datamash is designed to closely follow R project’s (https://www.r-project.org/) statistical functions. See the files/operators.R file for the R equivalent code for each of datamash’s operators. When building datamash from source code on your local computer, operators are compared to known results of the equivalent R functions.

Looking in R, I don't see an spearson:

> ?spearson
No documentation for ‘spearson’ in specified packages and libraries:
you could try ‘??spearson’


问:
Userspace virtual address to kernel virtual address translation
I have an userspace process that allocates memory from the huge pages. This memory needs to be shared with kernel space threads and work queues. To do so I'm using ioctl to register the process memory.

In IOCTL:

take struct ring address from usersapce and do the vmap() the pages pages.

for memory blocks that can show up in the ring I pin_user_pages with LONG_TERM flag.

And here are the questions I have:

If I do the vmap on struct ring pointer can I (should I) unpin_user_page referring to it?

Should I vmap buffers that are going to be placed in the ring? Or pinning user pages is enough?

How to translate (remote to the kthread) userspace address to kernel address which can be accessed from kernel?

For second and third question:

So far I analyzed the code of the pin_user_pages_remote function. It ends up in the __get_user_pages_locked. In this function there is piece of code:

```<code>pages[i] = virt_to_page((void *)start);
  if (pages[i])
    get_page(pages[i]);
</code>```

Does this mean that when pages are pinned in ioctl then in kthread I can:

```<code>u64 offset = user_address & (PAGE_SIZE - 1);
struct page page = virt_to_page(user_address);
u64 phys = page_to_phys(page);
void *kva = phys_to_virt(phys) + offset;
</code>```

Does this need to be vmaped to do this trick?
Or there is much simpler method for doing so?

Body:
I have an userspace process that allocates memory from the huge pages. This memory needs to be shared with kernel space threads and work queues. To do so I'm using ioctl to register the process memory.

In IOCTL:

take struct ring address from usersapce and do the vmap() the pages pages.

for memory blocks that can show up in the ring I pin_user_pages with LONG_TERM flag.

And here are the questions I have:

If I do the vmap on struct ring pointer can I (should I) unpin_user_page referring to it?

Should I vmap buffers that are going to be placed in the ring? Or pinning user pages is enough?

How to translate (remote to the kthread) userspace address to kernel address which can be accessed from kernel?

For second and third question:

So far I analyzed the code of the pin_user_pages_remote function. It ends up in the __get_user_pages_locked. In this function there is piece of code:

pages[i] = virt_to_page((void *)start);
  if (pages[i])
    get_page(pages[i]);

Does this mean that when pages are pinned in ioctl then in kthread I can:

u64 offset = user_address & (PAGE_SIZE - 1);
struct page page = virt_to_page(user_address);
u64 phys = page_to_phys(page);
void *kva = phys_to_virt(phys) + offset;

Does this need to be vmaped to do this trick?
Or there is much simpler method for doing so?


问:
Failed to install phantonjs-2.1.1-linux-x86_64 on Ubuntu 22.04.1 LTS
After following the instruction on my Ubuntu 22.04.1 LTS, And finally when I do

phantomjs -v

I get the error:

```<code>Auto configuration failed
140111765546944:error:25066067:DSO support routines:DLFCN_LOAD:could not load the shared library:dso_dlfcn.c:185:filename(libproviders.so): libproviders.so: cannot open shared object file: No such file or directory
140111765546944:error:25070067:DSO support routines:DSO_load:could not load the shared library:dso_lib.c:244:
140111765546944:error:0E07506E:configuration file routines:MODULE_LOAD_DSO:error loading dso:conf_mod.c:285:module=providers, path=providers
140111765546944:error:0E076071:configuration file routines:MODULE_RUN:unknown module name:conf_mod.c:222:module=providers

</code>```

`

What's wrong with it?

Body:
After following the instruction on my Ubuntu 22.04.1 LTS, And finally when I do

phantomjs -v

I get the error:

Auto configuration failed
140111765546944:error:25066067:DSO support routines:DLFCN_LOAD:could not load the shared library:dso_dlfcn.c:185:filename(libproviders.so): libproviders.so: cannot open shared object file: No such file or directory
140111765546944:error:25070067:DSO support routines:DSO_load:could not load the shared library:dso_lib.c:244:
140111765546944:error:0E07506E:configuration file routines:MODULE_LOAD_DSO:error loading dso:conf_mod.c:285:module=providers, path=providers
140111765546944:error:0E076071:configuration file routines:MODULE_RUN:unknown module name:conf_mod.c:222:module=providers

`

What's wrong with it?


问:
Fixing position of particular bar after sorting - Plotly Bar Graph
I would like to know if it's possible to move the 'Total' Bar to the bottom or top of the figure after performing the sort using plotly.express bar.

Move 'Total' bar to the top or bottom after sorting:

The sorting is performed using the following:

```<code>import plotly.express as px
fig = px.bar(sheet, y=sheet.index, x=rows, orientation='h')
fig = fig.update_layout(yaxis={'categoryorder':'total ascending'})
</code>```

I have searched Stackoverflow and other platforms and could not find any related query.

Body:
I would like to know if it's possible to move the 'Total' Bar to the bottom or top of the figure after performing the sort using plotly.express bar.

Move 'Total' bar to the top or bottom after sorting:

The sorting is performed using the following:

import plotly.express as px
fig = px.bar(sheet, y=sheet.index, x=rows, orientation='h')
fig = fig.update_layout(yaxis={'categoryorder':'total ascending'})

I have searched Stackoverflow and other platforms and could not find any related query.


问:
Why Checking style borders in Word Vba is cousing "Memory out" Problem
I recently have been building a Word Macro to Comapre Styles From two different word documents and i am wondering why only borders as style propertie are cousing memory out problem when I'm just checking with If statment if they are visible.

for example:

```<code>dim isBorderAvailble as boolean

   if documents([name]).Styles([name]).Borders(wdBorderTop).visible = true then
       isBorderAvailble = true
   else
       isBorderAvailble = false
   end if
</code>```

Of course this is example of how checking procces works. There are 4 more types of border to check. Program has to check 762 styles (for my two test documents, each of them has 381 styles) so it return 3810 results. I dont know what to do bcs with if statment I dont save any data in any variable and not making new variables or collections so its impossible that some of the data are saved somewhere. I would appreciate, some advice. Thanks in advance :)

Body:
I recently have been building a Word Macro to Comapre Styles From two different word documents and i am wondering why only borders as style propertie are cousing memory out problem when I'm just checking with If statment if they are visible.

for example:

dim isBorderAvailble as boolean

   if documents([name]).Styles([name]).Borders(wdBorderTop).visible = true then
       isBorderAvailble = true
   else
       isBorderAvailble = false
   end if

Of course this is example of how checking procces works. There are 4 more types of border to check. Program has to check 762 styles (for my two test documents, each of them has 381 styles) so it return 3810 results. I dont know what to do bcs with if statment I dont save any data in any variable and not making new variables or collections so its impossible that some of the data are saved somewhere. I would appreciate, some advice. Thanks in advance :)


问:
The whole page reload when the usestate is updated
My goal is to make an element in which by clicking on the arrows you can set the time

so I used the useState hook

```<code>type Props = {
    placeholder?: string | number,
    time: number,
}

export function PetTimeSet(props: Props) {
    const {placeholder, time} = props
    // const [toggleClass, setToggleClass] = useState('inactive');
    const [currentTime, setCurrentTime] = useState(time)

    const getPadTime = (t:number) => t.toString().padStart(2, '0')

    const hours = getPadTime(Math.floor(currentTime / 60))
    // @ts-ignore
    const minutes = getPadTime(currentTime - hours * 60)

    useEffect(() => {
        if (Math.floor(currentTime / 60) >= 24) {
            setCurrentTime(0)
        }
    }, [currentTime])

    const handleTimeUncrease = () => setCurrentTime(prevTime => prevTime + 5)
    const handleTimeDecrease = () => setCurrentTime(prevTime => prevTime - 5)

    return (
        <div
            // onChange={() => setToggleClass('active')}
            //tslint:disable-next-line:typedef
            // onClick={() => {setToggleClass('active')}}
            className={`PetTimeSet `}>
            <span className="PetTimeSet-index">{placeholder}</span>
            <span className="PetTimeSet-choice">
                <button className="time-decrease">
                    <img src={arrow} alt="decrease" onClick={handleTimeDecrease} />
                </button>

                <span className="PetTimeSet-time">{`${hours}:${minutes}`}</span>

                <button className="time-uncrease" onClick={handleTimeUncrease}>
                    <img src={arrow} alt="uncrease" />
                </button>
            </span>
        </div>
    )
}
</code>```

However, each time you click on the button to increase or decrease the page, the action is triggered once, then the entire page is reloaded. I can't understand what could be the reason

I've tried passing functions to the element, I've tried using the useEffect hook differently, I've tried pushing everything to the root element of the page. The result is the same. Page reloads

Body:
My goal is to make an element in which by clicking on the arrows you can set the time

so I used the useState hook

type Props = {
    placeholder?: string | number,
    time: number,
}

export function PetTimeSet(props: Props) {
    const {placeholder, time} = props
    // const [toggleClass, setToggleClass] = useState('inactive');
    const [currentTime, setCurrentTime] = useState(time)

    const getPadTime = (t:number) => t.toString().padStart(2, '0')

    const hours = getPadTime(Math.floor(currentTime / 60))
    // @ts-ignore
    const minutes = getPadTime(currentTime - hours * 60)

    useEffect(() => {
        if (Math.floor(currentTime / 60) >= 24) {
            setCurrentTime(0)
        }
    }, [currentTime])

    const handleTimeUncrease = () => setCurrentTime(prevTime => prevTime + 5)
    const handleTimeDecrease = () => setCurrentTime(prevTime => prevTime - 5)

    return (

 setToggleClass('active')}
            //tslint:disable-next-line:typedef
            // onClick={() => {setToggleClass('active')}}
            className={`PetTimeSet `}>
            {placeholder}

                <button className="time-decrease">

                </button>

                {`${hours}:${minutes}`}

                <button className="time-uncrease" onClick={handleTimeUncrease}>

                </button>

    )
}

However, each time you click on the button to increase or decrease the page, the action is triggered once, then the entire page is reloaded. I can't understand what could be the reason

I've tried passing functions to the element, I've tried using the useEffect hook differently, I've tried pushing everything to the root element of the page. The result is the same. Page reloads


问:
How to implement prepared statement in array_push()
I'm trying to prevent my query from being injected with SQL injection by using a prepared statement. but how to implement prepared statement into array_push()?
here I use array push for custom search purposes.

Here is the code snippet that I have now.

```<code>public function getDataTable(Request $req) {
    $start = $req->start;
    $length = $req->length;
    $draw = $req->draw;
    $order = $req->order;
    $type = '';
    $where = $this->storeParams($req);

    $data = $this->getData($where, $start, $length, $order, $type);

    .
    .
    .
    .

    $output = [
        'draw' => (int) $draw,
        'recordsTotal' => $total,
        'recordsFiltered' => $filtered,
        'data' => $data,
    ];
    return json_encode($output);
}

public function storeParams(Request $req) {
    $param = [];

    $start_date = date('Y-m-d');
    $end_date = date('Y-m-d');

    if (!empty($req->studentid)) {
        array_push($param, 'studentid LIKE \'' . $req->studentid . '\'');
    }

    if (!empty($req->studentnm)) {
        array_push($param, 'studentnm LIKE \'' . $req->studentnm . '%\'');
    }

    if (!empty($start_date) && !empty($end_date)) {
        array_push($param, "entrydate between '" . $start_date . "' and '" . $end_date . "'");
    }

    if (count($param) > 0) {
        $where = implode(' and ', $param);
    } else {
        $where = "1";
    }
    return $where;
}

public function getData($where, $start = null, $length = null, $order = null, $type = null) {
    .
    .
    .
    .
    $dataSet = DB::connection('mysql5')->table('tbl_datastudent')
        ->selectRaw("studentid, stuidentnm, address, entrydate, payment, paymentdate")
        ->whereRaw($where);
    .
    .
    .
    .
}
</code>```

how do i apply the prepared statement into the storeParams() function? anybody can guide or help me?

updated

i'm already found the answer

```<code>->when($request->studentid, function ($q) use ($request) {
    $q->whereRaw('studentid LIKE ?', ['%'.$request->studentid.'%']);
})
</code>```

Body:
I'm trying to prevent my query from being injected with SQL injection by using a prepared statement. but how to implement prepared statement into array_push()?
here I use array push for custom search purposes.

Here is the code snippet that I have now.

public function getDataTable(Request $req) {
    $start = $req->start;
    $length = $req->length;
    $draw = $req->draw;
    $order = $req->order;
    $type = '';
    $where = $this->storeParams($req);

    $data = $this->getData($where, $start, $length, $order, $type);

    .
    .
    .
    .

    $output = [
        'draw' => (int) $draw,
        'recordsTotal' => $total,
        'recordsFiltered' => $filtered,
        'data' => $data,
    ];
    return json_encode($output);
}

public function storeParams(Request $req) {
    $param = [];

    $start_date = date('Y-m-d');
    $end_date = date('Y-m-d');

    if (!empty($req->studentid)) {
        array_push($param, 'studentid LIKE \'' . $req->studentid . '\'');
    }

    if (!empty($req->studentnm)) {
        array_push($param, 'studentnm LIKE \'' . $req->studentnm . '%\'');
    }

    if (!empty($start_date) && !empty($end_date)) {
        array_push($param, "entrydate between '" . $start_date . "' and '" . $end_date . "'");
    }

    if (count($param) > 0) {
        $where = implode(' and ', $param);
    } else {
        $where = "1";
    }
    return $where;
}

public function getData($where, $start = null, $length = null, $order = null, $type = null) {
    .
    .
    .
    .
    $dataSet = DB::connection('mysql5')->table('tbl_datastudent')
        ->selectRaw("studentid, stuidentnm, address, entrydate, payment, paymentdate")
        ->whereRaw($where);
    .
    .
    .
    .
}

how do i apply the prepared statement into the storeParams() function? anybody can guide or help me?

updated

i'm already found the answer

->when($request->studentid, function ($q) use ($request) {
    $q->whereRaw('studentid LIKE ?', ['%'.$request->studentid.'%']);
})


问:
is it possible to auto refresh alert without closing?
I want to refresh v-alert automatically after 1 sec without closing it so that value store in locaStorage can be reflected on v-alert after every 1 sec.

```<code><v-alert
    style="position: fixed;left: 35%;top: 7%;"
      border="left"
      close-text="Close Alert"
      color="deep-purple accent-4"
      dark
      dismissible
      text-align ='center'
      v-model="alert"
    >
      Yesterday's Leads: {{this.totalAndYetToCallCounts.previousLeads}} and Today's Leads: {{this.totalAndYetToCallCounts.TodaysLeads}}.
    </v-alert>
</code>```
```<code>export default {
  data () {
    return {
      totalAndYetToCallCounts: '',
      alert: true
    }
  },
  watch: {
    alert (newVal) {
      if (!newVal) {
        setTimeout(() => {
          this.alert = true
          this.totalAndYetToCallCounts = JSON.parse(localStorage.getItem('getTotalAndYetToCallCount'))
        }, 1000)
      }
    }

  },
}
</code>```

after writing it in created hook

```<code>  async created () {
    try {
      setInterval(() => {
        this.alert = true
        this.totalAndYetToCallCounts = JSON.parse(localStorage.getItem('getTotalAndYetToCallCount'))
      }, 1000)

  },
</code>```

Body:
I want to refresh v-alert automatically after 1 sec without closing it so that value store in locaStorage can be reflected on v-alert after every 1 sec.

<v-alert
    style="position: fixed;left: 35%;top: 7%;"
      border="left"
      close-text="Close Alert"
      color="deep-purple accent-4"
      dark
      dismissible
      text-align ='center'
      v-model="alert"
    >
      Yesterday's Leads: {{this.totalAndYetToCallCounts.previousLeads}} and Today's Leads: {{this.totalAndYetToCallCounts.TodaysLeads}}.
    </v-alert>

export default {
  data () {
    return {
      totalAndYetToCallCounts: '',
      alert: true
    }
  },
  watch: {
    alert (newVal) {
      if (!newVal) {
        setTimeout(() => {
          this.alert = true
          this.totalAndYetToCallCounts = JSON.parse(localStorage.getItem('getTotalAndYetToCallCount'))
        }, 1000)
      }
    }

  },
}

after writing it in created hook

  async created () {
    try {
      setInterval(() => {
        this.alert = true
        this.totalAndYetToCallCounts = JSON.parse(localStorage.getItem('getTotalAndYetToCallCount'))
      }, 1000)

  },


问:
Redux reducers on array items
My redux state looks like this:

```<code>user: {},
devices: [
  {name: "foo", ip: "192.168.0.1", settings: {
    isRunning: true
  }},
  {name: "bar", ip: "192.168.0.2", settings: {
    isRunning: true
  }},
  {name: "baz", ip: "192.168.0.3", settings: {
    isRunning: false
  }},
]
</code>```

The array is actually larger than this, which is why I need a way to update isRunning for the correct device (based on its IP). Is it possible to do this? I've previously only used redux actions where there is one key-value to map an action to.

Ideally I want just

```<code>const toggleIsRunning = (isRunning) => {

  return store.dispatch({
    type: 'TOGGLE_IS_RUNNING',
    value: isRunning
  });
}
</code>```

where this is a reducer to the settings object. But now I am forced to have one enormous reducer for devices and from there find the right index, then change the correct property, etc, which is quite cumbersome.

Title: Redux reducers on array items

Body:
My redux state looks like this:

user: {},
devices: [
  {name: "foo", ip: "192.168.0.1", settings: {
    isRunning: true
  }},
  {name: "bar", ip: "192.168.0.2", settings: {
    isRunning: true
  }},
  {name: "baz", ip: "192.168.0.3", settings: {
    isRunning: false
  }},
]

The array is actually larger than this, which is why I need a way to update isRunning for the correct device (based on its IP). Is it possible to do this? I've previously only used redux actions where there is one key-value to map an action to.

Ideally I want just

const toggleIsRunning = (isRunning) => {

  return store.dispatch({
    type: 'TOGGLE_IS_RUNNING',
    value: isRunning
  });
}

where this is a reducer to the settings object. But now I am forced to have one enormous reducer for devices and from there find the right index, then change the correct property, etc, which is quite cumbersome.


问:
Failed to load resource: the server responded with a status of 404 AxiosError
fetchFromAPI.jsx

import axios from "axios";

const BASE_URL = 'https://youtube-v31.p.rapidapi.com/captions'
const options = {
    params: {part: 'snippet', videoId: 'M7FIvfx5J10'},
    headers: {
      'X-RapidAPI-Key': process.env.REACT_APP_RAPID_API_KEY,
      'X-RapidAPI-Host': 'youtube-v31.p.rapidapi.com'
    }
  };
  export const fetchFromAPI = async(url) => {
    const {data} = await axios.get(`${BASE_URL}/${url}`,options);
    return data;
}```
</div>
</div>
</p>
<p>Feed.jsx</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> useEffect(() => {
    fetchFromAPI(`search?part=snippet&q=${selectedCategory}`)
      .then((data) => setVideos(data.items))
      .catch(function (error) {
        console.error(error);
      });
    },[selectedCategory])</code>```

I trying to fetch the data from rapidAPI for youtube.
I am getting this error in console.

Body:
fetchFromAPI.jsx

import axios from "axios";

const BASE_URL = 'https://youtube-v31.p.rapidapi.com/captions'
const options = {
    params: {part: 'snippet', videoId: 'M7FIvfx5J10'},
    headers: {
      'X-RapidAPI-Key': process.env.REACT_APP_RAPID_API_KEY,
      'X-RapidAPI-Host': 'youtube-v31.p.rapidapi.com'
    }
  };
  export const fetchFromAPI = async(url) => {
    const {data} = await axios.get(`${BASE_URL}/${url}`,options);
    return data;
}

Feed.jsx

 useEffect(() => {
    fetchFromAPI(`search?part=snippet&q=${selectedCategory}`)
      .then((data) => setVideos(data.items))
      .catch(function (error) {
        console.error(error);
      });
    },[selectedCategory])

I trying to fetch the data from rapidAPI for youtube.
I am getting this error in console.


问:
Py4JJavaError: An error occurred while calling o371.collectToPython
I am running a code using pyspark and get the following error:
Py4JJavaError: An error occurred while calling o215.collectToPython.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 3 in stage 0.0 failed 1 times, most recent failure: Lost task 3.0 in stage 0.0 (TID 3, localhost, executor driver): java.io.IOException: Cannot run program "C:\Users\i.florou\Anaconda\envs\satellite": CreateProcess error=5, Access is denied
at java.lang.ProcessBuilder.start(Unknown Source)

Windows 10
Python 3.6
Spark 2.4.5
Java "1.8.0_351"

Could anyone help me please?


问:
which OAuth Scope should my token have to just pull and push code?
I just found out git clone [url] doesnt work anymore
I want to be able to clone a project and make pull-push operations
only that,
is just 'repo' enough ?
I tried "reading more aboutOAuth scoped" but the page was not opening


问:
How can I webscrape Barchart.com pages
I use the following script to scrape this page: https://www.barchart.com/options/most-active/stocks

I would like to scrape other pages on barchart, but I am unable to find neither all the possible list names to fill the list parameter, nor the related datafields to be set in the fields
parameter.

I am particularly interested in pages about earnings and dividends announcements, and all pages related to options.

import requests
from urllib.parse import unquote
import pandas as pd

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0",
}

def main(url):
    with requests.Session() as req:
        req.headers.update(headers)
        r = req.get(url[:25])
        req.headers.update(
            {'X-XSRF-TOKEN': unquote(r.cookies.get_dict()['XSRF-TOKEN'])})
        params = {
            "list": "options.mostActive.us",
            "fields": "symbol,symbolType,symbolName,hasOptions,lastPrice,priceChange,percentChange,optionsImpliedVolatilityRank1y,optionsTotalVolume,optionsPutVolumePercent,optionsCallVolumePercent,optionsPutCallVolumeRatio,tradeTime,symbolCode",
            "orderBy": "optionsTotalVolume",
            "orderDir": "desc",
            "between(lastPrice,.10,)": "",
            "between(tradeTime,2021-08-03,2021-08-04)": "",
            "meta": "field.shortName,field.type,field.description",
            "hasOptions": "true",
            "page": "1",
            "limit": "500",
            "raw": "1"
        }
        r = req.get(url, params=params).json()
        df = pd.DataFrame(r['data']).iloc[:, :-1]
        print(df)

main('https://www.barchart.com/proxies/core-api/v1/quotes/get?')
```

I tried to guess the list parameter from the webpage name but have had no success.

Title: How can I webscrape Barchart.com pages

Body:
I use the following script to scrape this page: https://www.barchart.com/options/most-active/stocks

I would like to scrape other pages on barchart, but I am unable to find neither all the possible list names to fill the list parameter, nor the related datafields to be set in the fields
parameter.

I am particularly interested in pages about earnings and dividends announcements, and all pages related to options.

import requests
from urllib.parse import unquote
import pandas as pd

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0",
}

def main(url):
    with requests.Session() as req:
        req.headers.update(headers)
        r = req.get(url[:25])
        req.headers.update(
            {'X-XSRF-TOKEN': unquote(r.cookies.get_dict()['XSRF-TOKEN'])})
        params = {
            "list": "options.mostActive.us",
            "fields": "symbol,symbolType,symbolName,hasOptions,lastPrice,priceChange,percentChange,optionsImpliedVolatilityRank1y,optionsTotalVolume,optionsPutVolumePercent,optionsCallVolumePercent,optionsPutCallVolumeRatio,tradeTime,symbolCode",
            "orderBy": "optionsTotalVolume",
            "orderDir": "desc",
            "between(lastPrice,.10,)": "",
            "between(tradeTime,2021-08-03,2021-08-04)": "",
            "meta": "field.shortName,field.type,field.description",
            "hasOptions": "true",
            "page": "1",
            "limit": "500",
            "raw": "1"
        }
        r = req.get(url, params=params).json()
        df = pd.DataFrame(r['data']).iloc[:, :-1]
        print(df)

main('https://www.barchart.com/proxies/core-api/v1/quotes/get?')

I tried to guess the list parameter from the webpage name but have had no success.


问:
when i created billing account in gcp cloud it debited money but not created billing account
when i created billing account in GCP cloud it debited money but not created billing account. could you please tell me the solution?

linking billing to the project in GCP cloud


问:
Installing GDAL via python via a Script
I am trying to install python-gdal and gdal if it doesn't exist in the distribution. This is what I have:

```<code>try:
    from osgeo import gdal
    # gdalVersion = subprocess.check_output(['gdalinfo', '--version'])
    # print(gdalVersion)
except ImportError:
    raise ImportError("GDAL not installed. Let's make the installation")
    # Install GDAL if not available
    gdal_install = input("Install GDAL? Reply with Y or N. ")
    if gdal_install == "Y":
        subprocess.run(["sudo", "apt-get", "install","gdal-bin"])
        # gdalVersion = subprocess.check_output(['gdalinfo', '--version'])
        print(gdalVersion)
        pip.main(['install', '--user', "GDAL==3.0.4"])
        from osgeo import gdal
</code>```

Since python-gdal depends on the gdal --version you have, I tried working on it to know avail and that's why some of the statements are commented out. I would be happy to get on that help too.

Anyone know why this piece of code doesn't work?

Title: Installing GDAL via python via a Script

Body:
I am trying to install python-gdal and gdal if it doesn't exist in the distribution. This is what I have:

try:
    from osgeo import gdal
    # gdalVersion = subprocess.check_output(['gdalinfo', '--version'])
    # print(gdalVersion)
except ImportError:
    raise ImportError("GDAL not installed. Let's make the installation")
    # Install GDAL if not available
    gdal_install = input("Install GDAL? Reply with Y or N. ")
    if gdal_install == "Y":
        subprocess.run(["sudo", "apt-get", "install","gdal-bin"])
        # gdalVersion = subprocess.check_output(['gdalinfo', '--version'])
        print(gdalVersion)
        pip.main(['install', '--user', "GDAL==3.0.4"])
        from osgeo import gdal

Since python-gdal depends on the gdal --version you have, I tried working on it to know avail and that's why some of the statements are commented out. I would be happy to get on that help too.

Anyone know why this piece of code doesn't work?


问:
PyFlink: What's the best way to provide reference data and keep them uptated
I have a use case where I want to do comparisons between incoming data and some reference data provided by another service.

What's the best way in pyflink to fetch those data and update them regularly (in intervals of 1-2 hours)

Other considerations:

The reference data may contain hundreds of thousands of records


问:
Why does changing how a child object is looked up auto-validate said child object through it's parent?
Suppose you have the classes Client and Phone. A Client has_one Phone, and a Phone belongs_to a Client.

```<code>class Client < ApplicationRecord
  belongs_to :account

  has_one :default_phone, dependent: :destroy, class_name: "Phone"
end

class Phone < ApplicationRecord
  belongs_to :client
  belongs_to :account

  validates :number,
            format: { with: /\A\d{4,13}\z/ } # at least 4 digits
end
</code>```

I find that when assigning attributes to a Phone object with invalid values, depending on how said child Phone object variable is defined it may or may not render the parent Client object invalid.

For example, when defining @default_phone directly as the client's phone in #default_phone, this will render the Client parent object invalid after assigning invalid attributes to @default_phone:

```<code>@client = Client.find(1)
@account = @client.account

@fname = "Test"

def client_params
  {
    fname: @fname
  }
end

@number = "55" ## invalid. Minimum 4 digits

def default_phone_params
  {
    id: default_phone&.id,
    account_id: @client.account.id,
    number: @number
  }
end

def default_phone
  @default_phone ||= @client.default_phone&.presence
end

@client.assign_attributes(client_params)
@client.invalid?
#=> false

default_phone&.assign_attributes(default_phone_params)
@client.invalid?
#=> true
@client.errors.keys
#=> [:"default_phone.number"]
</code>```

Instead, if @default_phone is defined by looking up a Phone object by it's id, this does not happen.
Same example as above but changing how @default_phone is defined in #default_phone:

```<code>@client = Client.find(1)
@account = @client.account

@fname = "Test"

def client_params
  {
    fname: @fname
  }
end

@number = "55" ## invalid. Minimum 4 digits

def default_phone_params
  {
    id: default_phone&.id,
    account_id: @client.account.id,
    number: @number
  }
end

def default_phone
  @default_phone ||= @account.phones.find(@client.default_phone.id)
end

@client.assign_attributes(client_params)
default_phone&.assign_attributes(default_phone_params)

@client.invalid?
#=> false

default_phone.invalid?
#=> true
default_phone.errors.keys
#=> :number
</code>```

Why does assigning invalid attributes to @default_phone render the @client object invalid in the first example but not in the second?

I'd expect @client to be invalid if it's child Phone object attributes were assigned through nested attributes in client_params for example, but this is not the case as @default_phone is being assigned attributes independantly.  Still, the @client error key is default_phone.number.

Also, validates_associated :default_phone is not defined in the Client class either.

I've tried setting autosave: false on the Client default_phone association, to the same effects.

What am I missing here?

Body:
Suppose you have the classes Client and Phone. A Client has_one Phone, and a Phone belongs_to a Client.

class Client < ApplicationRecord
  belongs_to :account

  has_one :default_phone, dependent: :destroy, class_name: "Phone"
end

class Phone < ApplicationRecord
  belongs_to :client
  belongs_to :account

  validates :number,
            format: { with: /\A\d{4,13}\z/ } # at least 4 digits
end

I find that when assigning attributes to a Phone object with invalid values, depending on how said child Phone object variable is defined it may or may not render the parent Client object invalid.

For example, when defining @default_phone directly as the client's phone in #default_phone, this will render the Client parent object invalid after assigning invalid attributes to @default_phone:

@client = Client.find(1)
@account = @client.account

@fname = "Test"

def client_params
  {
    fname: @fname
  }
end

@number = "55" ## invalid. Minimum 4 digits

def default_phone_params
  {
    id: default_phone&.id,
    account_id: @client.account.id,
    number: @number
  }
end

def default_phone
  @default_phone ||= @client.default_phone&.presence
end

@client.assign_attributes(client_params)
@client.invalid?
#=> false

default_phone&.assign_attributes(default_phone_params)
@client.invalid?
#=> true
@client.errors.keys
#=> [:"default_phone.number"]

Instead, if @default_phone is defined by looking up a Phone object by it's id, this does not happen.
Same example as above but changing how @default_phone is defined in #default_phone:

@client = Client.find(1)
@account = @client.account

@fname = "Test"

def client_params
  {
    fname: @fname
  }
end

@number = "55" ## invalid. Minimum 4 digits

def default_phone_params
  {
    id: default_phone&.id,
    account_id: @client.account.id,
    number: @number
  }
end

def default_phone
  @default_phone ||= @account.phones.find(@client.default_phone.id)
end

@client.assign_attributes(client_params)
default_phone&.assign_attributes(default_phone_params)

@client.invalid?
#=> false

default_phone.invalid?
#=> true
default_phone.errors.keys
#=> :number

Why does assigning invalid attributes to @default_phone render the @client object invalid in the first example but not in the second?

I'd expect @client to be invalid if it's child Phone object attributes were assigned through nested attributes in client_params for example, but this is not the case as @default_phone is being assigned attributes independantly.  Still, the @client error key is default_phone.number.

Also, validates_associated :default_phone is not defined in the Client class either.

I've tried setting autosave: false on the Client default_phone association, to the same effects.

What am I missing here?


问:
Memory leak with malloc from Valgrind log
I'm doing the CS50 practice: license. This code is to read license plate from a txt file and print them out.
Could someone please help me to know why my code still has a memory leak?
I still receive this message from Valgrind:

```<code>==11625== 448 bytes in 8 blocks are definitely lost in loss record 1 of 1
==11625==    at 0x4848899: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==11625==    by 0x109227: main (license.c:29)
==11625==
==11625== LEAK SUMMARY:
==11625==    definitely lost: 448 bytes in 8 blocks
==11625==    indirectly lost: 0 bytes in 0 blocks
==11625==      possibly lost: 0 bytes in 0 blocks
==11625==    still reachable: 0 bytes in 0 blocks
==11625==         suppressed: 0 bytes in 0 blocks
==11625==
==11625== For lists of detected and suppressed errors, rerun with: -s
==11625== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
</code>```

I thought I already freed all the memory previously claimed by malloc with this piece of code:

```<code>while (idx < 8)
{
    free(plates[idx]);
    idx ++;
}
</code>```

Here is the full code

```<code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    // Check for command line args
    if (argc != 2)
    {
        printf("Usage: ./read infile\n");
        return 1;
    }

    // Create buffer to read into
    char buffer[7];

    // Create array to store plate numbers
    char *plates[8];

    FILE *infile = fopen(argv[1], "r");

    int idx = 0;

    while (fread(buffer, 1, 7, infile) == 7)
    {
        // Replace '\n' with '\0'
        buffer[6] = '\0';
        plates[idx] = malloc (7 * sizeof(char *));

        // Save plate number in array
        strcpy(plates[idx], buffer);
        idx++;
    }

    for (int i = 0; i < 8; i++)
    {
        printf("%s\n", plates[i]);
    }

    //free memory
    fclose(infile);
    while (idx < 8)
    {
    free(plates[idx]);
    idx ++;
    }
    return 0;
}
</code>```

Body:
I'm doing the CS50 practice: license. This code is to read license plate from a txt file and print them out.
Could someone please help me to know why my code still has a memory leak?
I still receive this message from Valgrind:

==11625== 448 bytes in 8 blocks are definitely lost in loss record 1 of 1
==11625==    at 0x4848899: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
==11625==    by 0x109227: main (license.c:29)
==11625==
==11625== LEAK SUMMARY:
==11625==    definitely lost: 448 bytes in 8 blocks
==11625==    indirectly lost: 0 bytes in 0 blocks
==11625==      possibly lost: 0 bytes in 0 blocks
==11625==    still reachable: 0 bytes in 0 blocks
==11625==         suppressed: 0 bytes in 0 blocks
==11625==
==11625== For lists of detected and suppressed errors, rerun with: -s
==11625== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

I thought I already freed all the memory previously claimed by malloc with this piece of code:

while (idx < 8)
{
    free(plates[idx]);
    idx ++;
}

Here is the full code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    // Check for command line args
    if (argc != 2)
    {
        printf("Usage: ./read infile\n");
        return 1;
    }

    // Create buffer to read into
    char buffer[7];

    // Create array to store plate numbers
    char *plates[8];

    FILE *infile = fopen(argv[1], "r");

    int idx = 0;

    while (fread(buffer, 1, 7, infile) == 7)
    {
        // Replace '\n' with '\0'
        buffer[6] = '\0';
        plates[idx] = malloc (7 * sizeof(char *));

        // Save plate number in array
        strcpy(plates[idx], buffer);
        idx++;
    }

    for (int i = 0; i < 8; i++)
    {
        printf("%s\n", plates[i]);
    }

    //free memory
    fclose(infile);
    while (idx < 8)
    {
    free(plates[idx]);
    idx ++;
    }
    return 0;
}


问:
Module not found: Error: Can't resolve 'net' in '/node_modules/express/lib'
I've been dealing with webpack > 5 bundling issues since yesterday.

Here's what my package.json looks like:

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "path-browserify": "^1.0.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.6.1",
    "react-scripts": "5.0.1",
    "socket.io-client": "^4.5.4",
    "stream-http": "^3.2.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "hola": "echo hola mundo"
  },
  "eslintConfig": {
    "extends": ["react-app", "react-app/jest"]
  },
  "browserslist": {
    "production": [">0.2%", "not dead", "not op_mini all"],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
```
<p>This is how it started:</p>
```jaime@jaime-Lenovo:~/gameapp$ npm run build

> react-scripts build

Creating an optimized production build...
Failed to compile.

Module not found: Error: Can't resolve 'path' in '/gameapp/frontend/node_modules/serve-static'
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: { "path": require.resolve("path-browserify") }'
        - install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "path": false }
```
<p>After reading answers (like this: i tried to Polyfill modules in webpack 5 but not working (Reactjs)) I tried:</p>
<p>1.- Adding <strong>resolve:{ fallback: { path: false }}</strong> on my /node_modules/react-scripts/config/webpack.config.js returns:</p>
```Module not found: Error: Can't resolve 'http' in '/node_modules/express/lib'

If you want to include a polyfill, you need to:
        - add a fallback 'resolve.fallback: { "http": require.resolve("stream-http") }'
        - install 'stream-http'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "http": false }
```
<p>2.- Adding <strong>resolve:{ fallback: { path: require.resolve('path-browserify') }}</strong> returns:</p>
```
Module not found: Error: Can't resolve 'http' in '/gameapp/frontend/node_modules/express/lib'

you need to:
        - add a fallback 'resolve.fallback: { "http": require.resolve("stream-http") }'
        - install 'stream-http'
or:
        resolve.fallback: { "http": false }
```
<p>3.- Using <strong>resolve.fallback: { "http": false }</strong> gives:</p>
```Failed to compile.

Module not found: Error: Can't resolve 'net' in '/gameapp/frontend/node_modules/express/lib'
```
<p>4.- Adding <strong>resolve:{ fallback: { path: require.resolve('stream-http') }}</strong> returns:</p>
```Failed to compile.

Module not found: Error: Can't resolve 'net' in '/home/jaime/gameapp/frontend/node_modules/express/lib'
```

And here's where I'm stuck. Is this last message part of the Webpack > 5 problem? and if so, what polyfill should I use? or should I just downgrade to webpack 4?

Body:
I've been dealing with webpack > 5 bundling issues since yesterday.

Here's what my package.json looks like:

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "path-browserify": "^1.0.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.6.1",
    "react-scripts": "5.0.1",
    "socket.io-client": "^4.5.4",
    "stream-http": "^3.2.0",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "hola": "echo hola mundo"
  },
  "eslintConfig": {
    "extends": ["react-app", "react-app/jest"]
  },
  "browserslist": {
    "production": [">0.2%", "not dead", "not op_mini all"],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

This is how it started:

jaime@jaime-Lenovo:~/gameapp$ npm run build

> react-scripts build

Creating an optimized production build...
Failed to compile.

Module not found: Error: Can't resolve 'path' in '/gameapp/frontend/node_modules/serve-static'
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: { "path": require.resolve("path-browserify") }'
        - install 'path-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "path": false }

After reading answers (like this: i tried to Polyfill modules in webpack 5 but not working (Reactjs)) I tried:

1.- Adding resolve:{ fallback: { path: false }} on my /node_modules/react-scripts/config/webpack.config.js returns:

Module not found: Error: Can't resolve 'http' in '/node_modules/express/lib'

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

2.- Adding resolve:{ fallback: { path: require.resolve('path-browserify') }} returns:

Module not found: Error: Can't resolve 'http' in '/gameapp/frontend/node_modules/express/lib'

you need to:
        - add a fallback 'resolve.fallback: { "http": require.resolve("stream-http") }'
        - install 'stream-http'
or:
        resolve.fallback: { "http": false }

3.- Using resolve.fallback: { "http": false } gives:

Failed to compile.

Module not found: Error: Can't resolve 'net' in '/gameapp/frontend/node_modules/express/lib'

4.- Adding resolve:{ fallback: { path: require.resolve('stream-http') }} returns:

Failed to compile.

Module not found: Error: Can't resolve 'net' in '/home/jaime/gameapp/frontend/node_modules/express/lib'

And here's where I'm stuck. Is this last message part of the Webpack > 5 problem? and if so, what polyfill should I use? or should I just downgrade to webpack 4?


问:
Leap Motion Hand Controller to touch object to turn particle on and off
I would like to create and C# script using a Leap Motion hand motion controller to turn tap on and off in Unity.
The Tap has 2 sides, hot and cold and 2 water particle system. If you touch the hot water, hot water will come out if you touch cold, cold water will come out and you can turn each off just by touching cold button sphere and hot button sphere.  you can also use the code to interact with other object just by touch.

I have research online for C# script for leap motion on how to trigger action an object and can find one. I have tried and replicate some of the VR tutorial but end up with 19 errors and now can't add script till fixed all of the error in the script.
I have tried some of basic tutorial on C# script YouTube.

if someone can help to write a basic generic code that can be used for multiple of objects.


问:
NetSuite Saved Search - Count Kit/Packages on Sales Order
I am creating a saved search of open sales orders and would like to have a column display the total number of 'kit/package' items on a given sales order. Often we have inventory items and kit/packages listed on an order, so I can't use the sum of the order quantity. Any help is appreciated!

I have tried formulas like the following with no luck:

```<code>Case when {transactionlinetype} = 'kit/package' then {quantity} Else null END
</code>```

Body:
I am creating a saved search of open sales orders and would like to have a column display the total number of 'kit/package' items on a given sales order. Often we have inventory items and kit/packages listed on an order, so I can't use the sum of the order quantity. Any help is appreciated!

I have tried formulas like the following with no luck:

Case when {transactionlinetype} = 'kit/package' then {quantity} Else null END


问:
How to consume messages from Kafka with Nifi with PlainLoginModule
I have to consume Messages from a thirth party Kafka.
For the security they are using the security protocol SASL_PLAINTEXT with the sasl mechanism PLAIN.
With a native Java-Application I am able to consume messages by setting following configurations:
**

```<code>sasl.mechanism: PLAIN
security.protocol: SASL_PLAINTEXT
sasl.jaas.config (if not using JAAS-Conf-file): org.apache.kafka.common.security.plain.PlainLoginModule required
username="myuser"
password="mypassword"
</code>```

**
How to setup these property in consume kafka 2 nifi processor ?

Body:
I have to consume Messages from a thirth party Kafka.
For the security they are using the security protocol SASL_PLAINTEXT with the sasl mechanism PLAIN.
With a native Java-Application I am able to consume messages by setting following configurations:
**

sasl.mechanism: PLAIN
security.protocol: SASL_PLAINTEXT
sasl.jaas.config (if not using JAAS-Conf-file): org.apache.kafka.common.security.plain.PlainLoginModule required
username="myuser"
password="mypassword"

**
How to setup these property in consume kafka 2 nifi processor ?


问:
'Application not responding' when running opencv imshow() in Jupyter notebook extension inside VSCode
Very simple code

```<code>import cv2
cap = cv2.VideoCapture('../data/videos/cat.mp4')
ret, frame = cap.read()

cv2.imshow('Hi', frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

It opens the first frame as expected and shows it. When I press a key however, python refuses to respond and I get Application not responding leading to a crash after a while or me having to manually force quit it.

I'm running it in a Jupyter notebook in VSCode (using the extension). Strange thing is that when I run this code in a .py file inside VSCode, it does work as expected. I see a million and one threads about this but they mostly give the advice add waitKey and destroyAllWindows but I haven't come across one using ipynb in VSCode. Anyone knows how to fix this?

Body:
Very simple code

import cv2
cap = cv2.VideoCapture('../data/videos/cat.mp4')
ret, frame = cap.read()

cv2.imshow('Hi', frame)
cv2.waitKey(0)
cv2.destroyAllWindows()

It opens the first frame as expected and shows it. When I press a key however, python refuses to respond and I get Application not responding leading to a crash after a while or me having to manually force quit it.

I'm running it in a Jupyter notebook in VSCode (using the extension). Strange thing is that when I run this code in a .py file inside VSCode, it does work as expected. I see a million and one threads about this but they mostly give the advice add waitKey and destroyAllWindows but I haven't come across one using ipynb in VSCode. Anyone knows how to fix this?


问:
How do I join the the tables related to the current user to retrieve the information from another table in a shortcode?
I have being trying to create a shortcode to retrieve the information from the csld_events and output in a certificate, but it turnout it is returning every event related to the course_id in the csld_events.

In this situation I could not find a way to only select the events related to the current user, i thought maybe i should try to retrieve it also with the group-id that the course and the student is registered, but until the moment i could not find any way to relate the three of them and be able to retrieve from csld_events the event with course id(object_id) and group id(ld_group).

In the wp_posts table i could find the posts related to group but nothing that would relate them to the course or the users in that group.

In the wp_learndash_user_activity i could find the activity_status with group-progress as meta-value with the post_id which is also the group ID but nothing that would relate it to the course.

Did anybody go through something like this in wordpress + learndash and have a solution for it?

```<code><?php

// Function to retrieve the dates of a course for a specific user
function get_course_dates( $user_id, $course_id ) {
    // Retrieve the dates of the course
    global $wpdb;
    $table_name = $wpdb->prefix . 'csld_events';
    $query = $wpdb->prepare( "SELECT start, end FROM $table_name WHERE object_id = %d", $course_id );
    $course_dates = $wpdb->get_results( $query, ARRAY_A );
    // Return the course dates
    return $course_dates;
  }

  // Register the shortcode to show the course dates
  add_shortcode( 'course_dates', 'course_dates_shortcode' );
  function course_dates_shortcode( $atts ) {
    // Extract the attributes
    $atts = shortcode_atts( array(
      'user_id' => 0,
      'course_id' => 0
    ), $atts, 'course_dates' );

    // If the user ID is not specified, use the current user
    $user_id = $atts['user_id'];
    if ( !$user_id ) {
      $user_id = get_current_user_id();
    }

    // Retrieve the course dates for the user
    $course_dates = get_course_dates( $user_id, $atts['course_id'] );

    // Build the output for the shortcode
    $output = '';
    if ( !empty( $course_dates ) ) {
      $output .= '<ul>';
      foreach ( $course_dates as $date ) {
        $start = date_create($date['start']);
        $end = date_create($date['end']);
        $output .= '<p>Start: ' . date_format($start,'d/m/Y') . '<br>Eind: ' . date_format($end,'d/m/Y') . '</p>';
      }
      $output .= '</p>';
    }

    // Return the output of the shortcode
    return $output;
  }
  ?>
</code>```

Body:
I have being trying to create a shortcode to retrieve the information from the csld_events and output in a certificate, but it turnout it is returning every event related to the course_id in the csld_events.

In this situation I could not find a way to only select the events related to the current user, i thought maybe i should try to retrieve it also with the group-id that the course and the student is registered, but until the moment i could not find any way to relate the three of them and be able to retrieve from csld_events the event with course id(object_id) and group id(ld_group).

In the wp_posts table i could find the posts related to group but nothing that would relate them to the course or the users in that group.

In the wp_learndash_user_activity i could find the activity_status with group-progress as meta-value with the post_id which is also the group ID but nothing that would relate it to the course.

Did anybody go through something like this in wordpress + learndash and have a solution for it?

<?php

// Function to retrieve the dates of a course for a specific user
function get_course_dates( $user_id, $course_id ) {
    // Retrieve the dates of the course
    global $wpdb;
    $table_name = $wpdb->prefix . 'csld_events';
    $query = $wpdb->prepare( "SELECT start, end FROM $table_name WHERE object_id = %d", $course_id );
    $course_dates = $wpdb->get_results( $query, ARRAY_A );
    // Return the course dates
    return $course_dates;
  }

  // Register the shortcode to show the course dates
  add_shortcode( 'course_dates', 'course_dates_shortcode' );
  function course_dates_shortcode( $atts ) {
    // Extract the attributes
    $atts = shortcode_atts( array(
      'user_id' => 0,
      'course_id' => 0
    ), $atts, 'course_dates' );

    // If the user ID is not specified, use the current user
    $user_id = $atts['user_id'];
    if ( !$user_id ) {
      $user_id = get_current_user_id();
    }

    // Retrieve the course dates for the user
    $course_dates = get_course_dates( $user_id, $atts['course_id'] );

    // Build the output for the shortcode
    $output = '';
    if ( !empty( $course_dates ) ) {
      $output .= '
';
      foreach ( $course_dates as $date ) {
        $start = date_create($date['start']);
        $end = date_create($date['end']);
        $output .= '
Start: ' . date_format($start,'d/m/Y') . '
Eind: ' . date_format($end,'d/m/Y') . '
';
      }
      $output .= '
';
    }

    // Return the output of the shortcode
    return $output;
  }
  ?>


问:
Expo auth Google provider: works on web but stopped working on iOS, no accessToken in success response
I've set up Google login in my React Native app using the Expo integration, as so:

```<code>import * as Google from 'expo-auth-session/providers/google';
...
const [request, response, promptAsync] = Google.useAuthRequest({
    expoClientId: 'web-token',
    iosClientId: 'ios-token',
    webClientId: 'another-web-token',
});

const onLoginPress = async () => {
    const response = await promptAsync();
    if (response?.type === "success") {
        const { authentication } = response;  // <- Note here
        const userData = await axios.get(GOOGLE_AUTH_USERINFO_STEM + authentication.accessToken);
    }
...
</code>```

Logging in via Google was working and is still working fine on web. However, logging in via Google on the iOS Simulator was working and is now not working.

The issue on iOS is that the response comes back as a success, but the authentication key is null, whereas in a proper response I should see an accessToken (and do see this on web).

Any tips on what to try for this?

Edit: I checked out an older commit in my repo where the iOS login was definitely working, and it's now not working either! This makes me think it's some issue on the Google side?

Body:
I've set up Google login in my React Native app using the Expo integration, as so:

import * as Google from 'expo-auth-session/providers/google';
...
const [request, response, promptAsync] = Google.useAuthRequest({
    expoClientId: 'web-token',
    iosClientId: 'ios-token',
    webClientId: 'another-web-token',
});

const onLoginPress = async () => {
    const response = await promptAsync();
    if (response?.type === "success") {
        const { authentication } = response;  // <- Note here
        const userData = await axios.get(GOOGLE_AUTH_USERINFO_STEM + authentication.accessToken);
    }
...

Logging in via Google was working and is still working fine on web. However, logging in via Google on the iOS Simulator was working and is now not working.

The issue on iOS is that the response comes back as a success, but the authentication key is null, whereas in a proper response I should see an accessToken (and do see this on web).

Any tips on what to try for this?

Edit: I checked out an older commit in my repo where the iOS login was definitely working, and it's now not working either! This makes me think it's some issue on the Google side?


问:
export pyplot figure to PNG without antialias
I'd like to generate high-resolution raster images from pyplot figures, without antialias (why? See below)

Some time ago, on Python 2.7 and Matplotlib 1.5, I worked out two processes for this:

plt.savefig() to PDF, and then manually import into GIMP at 1200dpi or higher, with anti-alias turned off, and export the result to a PNG.

plt.savefig() to EPS, and run a small ImageMagick script to convert the result to a non-antialiased png at very high resolution.

Drawback: These processes take either time, create new non-python dependencies or are somewhat awkward to implement (e.g.: the ImageMagick method had to be adapted for almost every machine it was running on).

Question:

Is there by now (Python 3.9, matplotlib 3.6) another way to produce a high-res, non-antialiased PNG from a Matplotlib/pyplot figure, that works entirely in Python, without external dependencies or manual labour involved? I haven't found any new suitable arguments for plt.savefig(), but maybe there is another way, like some global antialias switch for matplotlib, pyplot or one of the plotting backends?

In case you're wondering:

I'm generating lots of figures from pyplot, in SVG or PDF format. Such vector figures are ideal for printing, viewing at any scale, and even allow me to make manual adjustments or change the layout or labels later, in Inkscape.

Sometimes, however, I need to generate raster images for use in applications which can't deal with vector images. I still want them to print sharply (antialiased images don't) and to scale nicely to most reasonable sizes (anti-aliased images don't scale up well). I also find that a 1200dpi non-antialiased image of line art, which produces a 4x antialiased image at 300dpi when scaled down by a factor of 4, actually produces a smaller PNG file than the antialiased scaled-down version -- even in jpeg format[1] -- because it needs a much smaller colour palette.

[1]: please don't use jpeg for line art, it hurts my eyes!


问:
Error on Windows with Docker : SSL routines:ssl3 alert handshake failure
I am running an API Platform (Symfony 6, php 8.1) app using Docker on Windows 10.

In my php container, in the console, when I try :

```<code>`curl https_url`
</code>```

I am getting the following error :

```<code>`curl: (35) error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure`
</code>```

I am getting the similar exception inside my php code (in the Docker container) for the command:

```<code>`file_get_contents(https_url);`
</code>```

I have tried to pass additional arguments, for example:

```<code>`$arrContextOptions = array(
        "ssl" => array(
            "verify_peer" => false,
            "verify_peer_name" => false
        ),
    );
file_get_contents('https_url', false, $arrContextOptions);`
</code>```

but I am still getting the same SSL error.

The error appears only on Windows OS (colleagues with Linux don’t have it).

Does anyone see how to fix it ?

Thanks!

Marko

Body:
I am running an API Platform (Symfony 6, php 8.1) app using Docker on Windows 10.

In my php container, in the console, when I try :

`curl https_url`

I am getting the following error :

`curl: (35) error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure`

I am getting the similar exception inside my php code (in the Docker container) for the command:

`file_get_contents(https_url);`

I have tried to pass additional arguments, for example:

`$arrContextOptions = array(
        "ssl" => array(
            "verify_peer" => false,
            "verify_peer_name" => false
        ),
    );
file_get_contents('https_url', false, $arrContextOptions);`

but I am still getting the same SSL error.

The error appears only on Windows OS (colleagues with Linux don’t have it).

Does anyone see how to fix it ?

Thanks!

Marko


问:
How do I write a Python Dictionary to a csv file, without getting an empty row between each key:value pair?
I'm fairly new to programming. I'm trying to make a basic chatbot, which can take in new acronym's and their definitions, store them in a dictionary and then write them out to a csv file. I have got this working, however, the second function of the chatbot is to convert the csv file into a dictionary so that it can search for an acronym and return the definition (I also have a working version of this).

Currently the csv file output is all the acronyms and their definitions, but with a blank row in between each entry. Is there a way to stop this happening? (as when I try to read this back in as a dictionary it no longer works)

Or a way to read in a csv file, with these empty rows, to a dictionary?

So in an ideal world I will have a csv file which can be updated with new entries, so in one session a user could add a new entry and then search the updated csv file to check their new entry.

```<code>import csv

filename ="input.csv"

acronyms = {}

with open(filename, 'r') as inp:
    reader = csv.reader(inp)
    acronyms = {rows[0]:rows[1] for rows in reader}

new_acronym = input("What is the acronym you would like to add?   ")
new_definition = input("What is the definition of this new acronym?   ")

acronyms.update({new_acronym:new_definition})

with open('output.csv','w') as f:
    w = csv.writer(f)
    w.writerows(acronyms.items())
</code>```

So this is my working code. At the moment the input csv and output csv are different documents, but as mentioned above, in an ideal world they would be the same document.

Body:
I'm fairly new to programming. I'm trying to make a basic chatbot, which can take in new acronym's and their definitions, store them in a dictionary and then write them out to a csv file. I have got this working, however, the second function of the chatbot is to convert the csv file into a dictionary so that it can search for an acronym and return the definition (I also have a working version of this).

Currently the csv file output is all the acronyms and their definitions, but with a blank row in between each entry. Is there a way to stop this happening? (as when I try to read this back in as a dictionary it no longer works)

Or a way to read in a csv file, with these empty rows, to a dictionary?

So in an ideal world I will have a csv file which can be updated with new entries, so in one session a user could add a new entry and then search the updated csv file to check their new entry.

import csv

filename ="input.csv"

acronyms = {}

with open(filename, 'r') as inp:
    reader = csv.reader(inp)
    acronyms = {rows[0]:rows[1] for rows in reader}

new_acronym = input("What is the acronym you would like to add?   ")
new_definition = input("What is the definition of this new acronym?   ")

acronyms.update({new_acronym:new_definition})

with open('output.csv','w') as f:
    w = csv.writer(f)
    w.writerows(acronyms.items())

So this is my working code. At the moment the input csv and output csv are different documents, but as mentioned above, in an ideal world they would be the same document.


问:
Uncaught ReferenceError: monaco is not defined
I am trying to run Monaco Editor but it gives an error. Uncaught ReferenceError: monaco is not defined.

I'm running a local web server and I can see the loader.js is being loaded in the Firefox Developer Tools. Also when I type monaco into the Firefox's console it says that it is not defined.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="node_modules/monaco-editor/min/vs/loader.js"></script>
</head>
<body>

<div id="container" style="height: 100%"></div>

<script>
    monaco.editor.create(document.getElementById('container'), {
        value: "function hello() {\n\talert('Hello world!');\n}",
        language: 'javascript'
    });
</script>

</body>
</html>
</code>```

Body:
I am trying to run Monaco Editor but it gives an error. Uncaught ReferenceError: monaco is not defined.

I'm running a local web server and I can see the loader.js is being loaded in the Firefox Developer Tools. Also when I type monaco into the Firefox's console it says that it is not defined.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>


问:
How to override coo matrix (scipy sparse) with values from a dataframe (pandas)
I have a sparse coo matrix built in python using the scipy library. An example data set looks something like this:

```<code>  (100981, 0)   0.015
  (100982, 0)   0.016
  (100983, 0)   0.016
  (100981, 1)   0.023
  (100982, 1)   0.024
  (100983, 1)   0.025
  (100981, 2)   0.019
  (100982, 2)   0.018
  (100983, 2)   0.017
</code>```

I have pandas dataframe which looks like this:

```<code>   site_0   site_1   site_2    site
0  0.0140  0.02313  0.01020  100981
1  0.0130  0.02200  0.01370  100982
2  0.0162  0.02510  0.01479  100983

</code>```

I have written a pandas apply method statement (see below) to override the values in the matrix according to the "site" column value. However I am struggling how on how to use numpy vectorization instead of the apply statement.

```<code># where v_coo is my matrix defined above
# where df is my dataframe defined above
def override_sites(row):
    v_coo[row['site'], 0] = row['site_0']
    v_coo[row['site'], 1] = row['site_1']
    v_coo[row['site'], 2] = row['site_2']
    return v_coo
df.apply(override_sites, axis=1)

</code>```

Body:
I have a sparse coo matrix built in python using the scipy library. An example data set looks something like this:

  (100981, 0)   0.015
  (100982, 0)   0.016
  (100983, 0)   0.016
  (100981, 1)   0.023
  (100982, 1)   0.024
  (100983, 1)   0.025
  (100981, 2)   0.019
  (100982, 2)   0.018
  (100983, 2)   0.017

I have pandas dataframe which looks like this:

   site_0   site_1   site_2    site
0  0.0140  0.02313  0.01020  100981
1  0.0130  0.02200  0.01370  100982
2  0.0162  0.02510  0.01479  100983

I have written a pandas apply method statement (see below) to override the values in the matrix according to the "site" column value. However I am struggling how on how to use numpy vectorization instead of the apply statement.

# where v_coo is my matrix defined above
# where df is my dataframe defined above
def override_sites(row):
    v_coo[row['site'], 0] = row['site_0']
    v_coo[row['site'], 1] = row['site_1']
    v_coo[row['site'], 2] = row['site_2']
    return v_coo
df.apply(override_sites, axis=1)


问:
How to use docker secrets in docker-compose and python app?
I'm trying to use docker secret to store username and password. I did the following:

Step 1: Initiate docker swarm

docker swarm init

Step 2: Create docker secrets

echo "username" | docker secret create app_username -

echo "password" | docker secret create app_password -

Step 3: Update the docker-compose

```<code>version: "3.8"

secrets:
  app_username:
    external: true
  app_password:
    external: true

services:
  backend:
    container_name: lxd-backend
    build:
      context: ./backend
      dockerfile: backend.dockerfile
    image: lce-backend:latest
    env_file:
      - .env
    ports:
      - 8085:80
    secrets:
      - app_username
      - app_password
    environment:
      - SERVER_NAME=localhost
      - SERVER_HOST=https://localhost
      - APP_USER_FILE=/run/secrets/app_username
      - APP_PW_FILE=/run/secrets/app_password
</code>```

Then in my python script,

```<code>print("file: ", os.listdir('/run/secrets/'),flush=True)
</code>```

I get cannot access /run/secrets: no such file or directory error. What am I doing wrong?

Body:
I'm trying to use docker secret to store username and password. I did the following:

Step 1: Initiate docker swarm

docker swarm init

Step 2: Create docker secrets

echo "username" | docker secret create app_username -

echo "password" | docker secret create app_password -

Step 3: Update the docker-compose

version: "3.8"

secrets:
  app_username:
    external: true
  app_password:
    external: true

services:
  backend:
    container_name: lxd-backend
    build:
      context: ./backend
      dockerfile: backend.dockerfile
    image: lce-backend:latest
    env_file:
      - .env
    ports:
      - 8085:80
    secrets:
      - app_username
      - app_password
    environment:
      - SERVER_NAME=localhost
      - SERVER_HOST=https://localhost
      - APP_USER_FILE=/run/secrets/app_username
      - APP_PW_FILE=/run/secrets/app_password

Then in my python script,

print("file: ", os.listdir('/run/secrets/'),flush=True)

I get cannot access /run/secrets: no such file or directory error. What am I doing wrong?


问:
TypeScript & a p5js "journal" website, asking TypeScript to treat every folder as its own namespace/module

TL;DR - Is there an EASY way to tell TypeScript that every folder is its own namespace? Destination folder has html files that do that for the produced .js files.

Hi There,

I don't normally work in JavaScript, but I thought I'd try TypeScript, which is GREAT. Love it. Seems like possibly the best of both worlds, thumbs up.

My current use case is a little odd ball though. I am doing a 30 day journal of creative coding with p5js, which itself is a little odd ball, I realize.

I set up TypeScript, sees the p5j types just fine, etc.

The problem is that my code is "badly structured" by design. I want to have multiple sketches (mini code experiments) in the same main source folder, src, each in their own subfolder.

I would like each subfolder to be a complete thought, so it means duplicate files in some of the sub folders. Which works fine in the docs folder, because each index.html only loads its own files.

TypeScript doesn't know about the the index.html files, so it's sensibly warning me that I have redefined a lot of stuff.

I am going to start out by changing the "include": ["src/dayNum/just_the_current_sketch"] in the .tsconfig change every time I start a new sketch, which means a new copy of global.d.ts in every folder, too, it would seem? (I tried ["global","src/dayNum/just_the_current_sketch"] and that didn't seem to work.) Or maybe by just moving folders in and out of the ts "stage", as not every sketch is so complicated it needs TypeScript.

Is there an EASY way to tell TypeScript that every folder is its own namespace? I would like to avoid creating modules, A) because I've never used them and I'm supposed to be focusing on the p5js part, B) the JavaScript code in docs doesn't need them.

Thank you.

link to offending repo: https://github.com/carlynorama/2023January-30DaysNatureOfCode


问:
Lavaan Mediation
I am trying to Conduct a mediation analysis via SEM (using lavaan). The model should be specified as follows: mediator is Sexual Disgust, the predictor is Gender, and the outcome variable is Political views with regards to social views.

I am doing the code placed below and I keep on getting the error for the fit<-sem line. I am overall confused on what I am doing wrong as this is my first lavaan I have ever done.

```<code>modal<-'PolOri_Social ~ b*Sexual_Disgust+c*Gender~a*Gender
# indirect effect (a*b)
             ab := a*b
           # total effect
             total := c + (a*b)'

fit <- sem(model, data = Tyburdata)
summary(fit)```

'''Error in lavaan::lavaan(model = model, data = Tyburdata, model.type = "sem", :
lavaan ERROR: missing observed variables in dataset: Y M;;```
</code>```

Title: Lavaan Mediation

Body:
I am trying to Conduct a mediation analysis via SEM (using lavaan). The model should be specified as follows: mediator is Sexual Disgust, the predictor is Gender, and the outcome variable is Political views with regards to social views.

I am doing the code placed below and I keep on getting the error for the fit<-sem line. I am overall confused on what I am doing wrong as this is my first lavaan I have ever done.

modal<-'PolOri_Social ~ b*Sexual_Disgust+c*Gender~a*Gender
# indirect effect (a*b)
             ab := a*b
           # total effect
             total := c + (a*b)'

fit <- sem(model, data = Tyburdata)
summary(fit)```

'''Error in lavaan::lavaan(model = model, data = Tyburdata, model.type = "sem", :
lavaan ERROR: missing observed variables in dataset: Y M;;```


问:
Jupyter, Jupyterlab: memory usage of each cell, how to plot a memory usage cumsum chart for all executed cells of a notebook?
To make short :

At the end of a jupyter (or jupyterlab) notebook, how to generate a plot showing cumsum of memory usage for every executed cells ?

Context :

A jupyter notebook is run. Each executed cell uses some memory. The addition of the memory usage of executed cells, grow up all along the notebook execution, or decrease when some variables are deleted.

At the end of the notebook execution, some people may want to have a look to the evolution of memory usage, showing its up and down.

A cumsum plot of this memory usage could help to visualize these up and downs

Simple code for reproducible example :

Here bellow, 4 cells of a notebook. The first 3 cells create 3 list of numbers, and the last cell delete the first list.

Cell 1:

```<code>a=[1]*10000
</code>```

Cell 2:

```<code>b=[2]*100000
</code>```

Cell 3:

```<code>c=[3]*40000
</code>```

Cell 4:

```<code>del a
</code>```

What is expected :

A sort of plot like this one :

Question :

How to draw a plot like the above one, showing the cumsum of memory usage of each executed cell of a note book ?

Body:
To make short :

At the end of a jupyter (or jupyterlab) notebook, how to generate a plot showing cumsum of memory usage for every executed cells ?

Context :

A jupyter notebook is run. Each executed cell uses some memory. The addition of the memory usage of executed cells, grow up all along the notebook execution, or decrease when some variables are deleted.

At the end of the notebook execution, some people may want to have a look to the evolution of memory usage, showing its up and down.

A cumsum plot of this memory usage could help to visualize these up and downs

Simple code for reproducible example :

Here bellow, 4 cells of a notebook. The first 3 cells create 3 list of numbers, and the last cell delete the first list.

Cell 1:

a=[1]*10000

Cell 2:

b=[2]*100000

Cell 3:

c=[3]*40000

Cell 4:

del a

What is expected :

A sort of plot like this one :

Question :

How to draw a plot like the above one, showing the cumsum of memory usage of each executed cell of a note book ?