问:
How to join two sheets based on calculated fields in Tableau?
UPDATE

Source example:

```<code>Company  yearA  yearB
A        2021   2022
B        2021   2021
C        2021   2023
D        2023   2024
E        2024   2022
</code>```

Table I want to get:

```<code>year  countA  countB
2021  3       1
2022  0       2
2023  1       1
2024  1       1
</code>```

I am new to Tableau and I find it diffcult to get the joined table based on two caculated fields.
Four fields in Table A and Table B are calculated fields obtained from the fields in one table in the data source. I want to get the “Count table”, which is joint by yearA in TableA == yearB in TableB.

I have tried two methods:

Create calculated fields in data source, but some calculated fields do not appear after I create it.

Drag four fields yearA, countA, yearB, countB together in one sheet, but I cannot get one(yearA)-to-all(yearB) relationship (Joint Table)since some entries do not appear  in the table in the data source. (For example, the entry “yearA=2022 and yearB=2022” do not appear in the original table)

```<code>TableA
yearA   countA
2021    1
2022    2
2023    3
</code>```
```<code>TableB
yearA   countA
2021    4
2022    5
2023    6
</code>```
```<code>Count table
year   countA  countB
2021   1       4
2022   2       5
2023   3       6
</code>```
```<code>Joint Table
yearA  countA   yearB  countB
2021     1      2021    4
                2022    5
2022     2      2021    4
                2023    6
2023     3      2021    4
                2022    5
                2023    6
</code>```

Body:
UPDATE

Source example:

Company  yearA  yearB
A        2021   2022
B        2021   2021
C        2021   2023
D        2023   2024
E        2024   2022

Table I want to get:

year  countA  countB
2021  3       1
2022  0       2
2023  1       1
2024  1       1

I am new to Tableau and I find it diffcult to get the joined table based on two caculated fields.
Four fields in Table A and Table B are calculated fields obtained from the fields in one table in the data source. I want to get the “Count table”, which is joint by yearA in TableA == yearB in TableB.

I have tried two methods:

Create calculated fields in data source, but some calculated fields do not appear after I create it.

Drag four fields yearA, countA, yearB, countB together in one sheet, but I cannot get one(yearA)-to-all(yearB) relationship (Joint Table)since some entries do not appear  in the table in the data source. (For example, the entry “yearA=2022 and yearB=2022” do not appear in the original table)

TableA
yearA   countA
2021    1
2022    2
2023    3

TableB
yearA   countA
2021    4
2022    5
2023    6

Count table
year   countA  countB
2021   1       4
2022   2       5
2023   3       6

Joint Table
yearA  countA   yearB  countB
2021     1      2021    4
                2022    5
2022     2      2021    4
                2023    6
2023     3      2021    4
                2022    5
                2023    6


来源: stackexchange

问:
I want to delete a message from a chat using messageKit
Use messageKit with Firebase
When I delete any message in the chat using long press, it gets deleted in front of me, but when I leave the chat and come back, it is not actually deleted.

```<code>    override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {

           if action == NSSelectorFromString("delete:") {
               return true
           } else {
               return super.collectionView(collectionView, canPerformAction: action, forItemAt: indexPath, withSender: sender)
           }
       }

   override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {

           if action == NSSelectorFromString("delete:") {
               // 1.) Remove from datasource
               // insert your code here
               self.mkMessages.remove(at: indexPath.section)  // Here it is deleted
               // 2.) Delete sections
               collectionView.deleteSections([indexPath.section])
           } else {
               super.collectionView(collectionView, performAction: action, forItemAt: indexPath, withSender: sender)
           }
       }
</code>```
```<code>extension MSGViewController: MessagesDataSource {
    func currentSender() -> SenderType {
        return currenUser
    }

    func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {
        return mkMessages[indexPath.section]
    }

    func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int {
        return mkMessages.count
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Use messageKit with Firebase
When I delete any message in the chat using long press, it gets deleted in front of me, but when I leave the chat and come back, it is not actually deleted.

    override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {

           if action == NSSelectorFromString("delete:") {
               return true
           } else {
               return super.collectionView(collectionView, canPerformAction: action, forItemAt: indexPath, withSender: sender)
           }
       }

   override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {

           if action == NSSelectorFromString("delete:") {
               // 1.) Remove from datasource
               // insert your code here
               self.mkMessages.remove(at: indexPath.section)  // Here it is deleted
               // 2.) Delete sections
               collectionView.deleteSections([indexPath.section])
           } else {
               super.collectionView(collectionView, performAction: action, forItemAt: indexPath, withSender: sender)
           }
       }

extension MSGViewController: MessagesDataSource {
    func currentSender() -> SenderType {
        return currenUser
    }

    func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {
        return mkMessages[indexPath.section]
    }

    func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int {
        return mkMessages.count
    }


问:
importrange not loading dynamic data
So I have two separate google sheets documents: one of them is a public document that only has the IMPORTRANGE that imports a bunch of rows and columns from a private document.

the problem is that the private doc has some custom app script functions and when I import the data to the public document it does not load dynamic data properly UNLESS the private doc is open on my computer.

so for example:

if the private doc is open on my computer

I open the public doc from the sheets app on my phone(diff google account)

the data loads properly everything works

BUT

if the private doc is closed on my computer

and I open the public doc on my phone again the data from the custom functions is gone

how im using the formula:
=IMPORTRANGE("https://docs.google.com/spreadsheets/d/id","A1:J64")

Is there a solution to this? is there a way to make importrange open the other google sheet in the server so it can run the script? I could not find anything in the docs

Title: importrange not loading dynamic data


问:
Property 'image_active_link' does not exist on type 'never'.ts(2339)

this script code

```<code><script lang="ts" setup>
let dataPriceFormSetting: any = await useGetDataPriceFormSetting()
const dataPaymentGateway: unknown = await useGetDataPaymentGateway()
</script>
</code>```

the error showing on template script of vuejs, so what should i do for this error?
everything is work fine and app run normally but vscode give me notice "Property 'image_active_link' does not exist on type 'never'"

Body:
this script code

the error showing on template script of vuejs, so what should i do for this error?
everything is work fine and app run normally but vscode give me notice "Property 'image_active_link' does not exist on type 'never'"


问:
Swapping an element from one column with that of another column
I'm currently working with Pandas dataframe and I found out there were some rows where values for 'id' and 'release dates' were switched. I'm trying to look through the columns and switch them back. However, when I check after I did my thing, I learn that nothing has changed. I've tried for loops, but if there is a better way to solve this problem, please enlighten me.</p>
```<code>ids= df_metadata['id']
rel_dates=df_metadata['release_date']
for i in range(len(rel_dates)):
    if '-' in ids[i]==True:
        id_rep=ids[i]
        date_rep=rel_dates[i]
        ids[i].replace({id_rep:date_rep})
    else:
        ids[i]=ids[i]
df_metadata['id']=ids
df_metadata['release_date']=rel_dates
</code>```

Body:
I'm currently working with Pandas dataframe and I found out there were some rows where values for 'id' and 'release dates' were switched. I'm trying to look through the columns and switch them back. However, when I check after I did my thing, I learn that nothing has changed. I've tried for loops, but if there is a better way to solve this problem, please enlighten me.

ids= df_metadata['id']
rel_dates=df_metadata['release_date']
for i in range(len(rel_dates)):
    if '-' in ids[i]==True:
        id_rep=ids[i]
        date_rep=rel_dates[i]
        ids[i].replace({id_rep:date_rep})
    else:
        ids[i]=ids[i]
df_metadata['id']=ids
df_metadata['release_date']=rel_dates


问:
Scala Maven plugin downloading multiple Scala versions
To use net.alchim31.maven:scala-maven-plugin:4.8.0, I add the following in pom.xml

<plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>scala-maven-plugin</artifactId>
                <version>4.8.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
```
<p>Now when I try to do mvn package, I get org.scala-lang:scala([0-9]?)-library is missing from project dependencies.</p>
<p>So now, I also add the following</p>
<pre class="lang-xml prettyprint-override"><code><configuration>
     <scalaVersion>2.12.17</scalaVersion>
</configuration>
</code>```

This downloads the dependency, and I can see in external libraries section

Now when I try to do mvn package, it runs but If I see the build console I see the following libraies being downloaded

```<code>Downloading from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.13.8/scala-library-2.13.8.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.13.8/scala-library-2.13.8.pom (1.6 kB at 4.6 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.13.0/scala-library-2.13.0.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.13.0/scala-library-2.13.0.pom (1.6 kB at 42 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.13.8/scala-library-2.13.8.jar
Downloaded from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.13.8/scala-library-2.13.8.jar (6.0 MB at 24 MB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.12.17/scala-library-2.12.17.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.12.17/scala-library-2.12.17.pom (1.6 kB at 42 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.12.17/scala-library-2.12.17.jar
Downloaded from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.12.17/scala-library-2.12.17.jar (5.4 MB at 32 MB/s)
</code>```

Why does it require 2.10.4 and 2.10.3?

[UPDATED]
My POM.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>scala-demo-1</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>${project.artifactId}</name>
  <description>My wonderfull scala app</description>
  <inceptionYear>2018</inceptionYear>

  <build>
    <sourceDirectory>src/main/scala</sourceDirectory>
    <testSourceDirectory>src/test/scala</testSourceDirectory>
    <plugins>
      <plugin>
        <!-- see http://davidb.github.com/scala-maven-plugin -->
        <groupId>net.alchim31.maven</groupId>
        <artifactId>scala-maven-plugin</artifactId>
        <version>4.8.0</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>testCompile</goal>
            </goals>
            <configuration>
              <args>
                <arg>-dependencyfile</arg>
                <arg>${project.build.directory}/.scala_dependencies</arg>
              </args>
              <scalaVersion>2.12.17</scalaVersion>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

</code>```

Body:
To use net.alchim31.maven:scala-maven-plugin:4.8.0, I add the following in pom.xml

<plugin>
                <groupId>net.alchim31.maven</groupId>
                <artifactId>scala-maven-plugin</artifactId>
                <version>4.8.0</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

Now when I try to do mvn package, I get org.scala-lang:scala([0-9]?)-library is missing from project dependencies.

So now, I also add the following

<configuration>
     <scalaVersion>2.12.17</scalaVersion>
</configuration>

This downloads the dependency, and I can see in external libraries section

Now when I try to do mvn package, it runs but If I see the build console I see the following libraies being downloaded

Downloading from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.13.8/scala-library-2.13.8.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.13.8/scala-library-2.13.8.pom (1.6 kB at 4.6 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.13.0/scala-library-2.13.0.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.13.0/scala-library-2.13.0.pom (1.6 kB at 42 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.13.8/scala-library-2.13.8.jar
Downloaded from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.13.8/scala-library-2.13.8.jar (6.0 MB at 24 MB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.12.17/scala-library-2.12.17.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.12.17/scala-library-2.12.17.pom (1.6 kB at 42 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.12.17/scala-library-2.12.17.jar
Downloaded from central: https://repo.maven.apache.org/maven2/org/scala-lang/scala-library/2.12.17/scala-library-2.12.17.jar (5.4 MB at 32 MB/s)

Why does it require 2.10.4 and 2.10.3?

[UPDATED]
My POM.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.example</groupId>
  <artifactId>scala-demo-1</artifactId>
  <version>1.0-SNAPSHOT</version>
  <name>${project.artifactId}</name>
  <description>My wonderfull scala app</description>
  <inceptionYear>2018</inceptionYear>

  <build>
    <sourceDirectory>src/main/scala</sourceDirectory>
    <testSourceDirectory>src/test/scala</testSourceDirectory>
    <plugins>
      <plugin>

        <groupId>net.alchim31.maven</groupId>
        <artifactId>scala-maven-plugin</artifactId>
        <version>4.8.0</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>testCompile</goal>
            </goals>
            <configuration>
              <args>
                <arg>-dependencyfile</arg>
                <arg>${project.build.directory}/.scala_dependencies</arg>
              </args>
              <scalaVersion>2.12.17</scalaVersion>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


问:
Image Manipulation With Certain Inputed Text
I have this code:

```<code>const { SlashCommandBuilder, MessageAttachment } = require('discord.js');
const { createCanvas, loadImage } = require('canvas');

module.exports = {
     data: new SlashCommandBuilder()
        .setName('image')
        .setDescription('Creates an image with the provided text')
                .addStringOption(option =>
        option.setName('text')
            .setDescription('The text to write on the image')
    ),
async execute(interaction) {
    const text = interaction.options.getString('text')

    // Create a canvas and get a drawing context
    const canvas = createCanvas(200, 100);
    const ctx = canvas.getContext('2d');

    // Load an image as a background for the canvas
    const background = await loadImage('./justdancememe.jpg');
    ctx.drawImage(background, 0, 0, canvas.width, canvas.height);

    // Write the text on the canvas
    ctx.font = '30px Impact';
    ctx.fillStyle = '#ffffff';
    ctx.textAlign = 'center';
    ctx.fillText(text, canvas.width / 2, canvas.height / 2);

    // Convert the canvas to a buffer and create a message attachment with it
    const attachment = new MessageAttachment(canvas.toBuffer(), 'justdancememe.jpg');

    // Reply with the image
    await interaction.reply({ files: [attachment] })
},
</code>```

};

I was expecting me to be able to input a value under text, say ‘example,’ and then that text would show up on the given image, but when the command is run, the bot doesn’t respond. Absolutely 0 errors as well.

Body:
I have this code:

const { SlashCommandBuilder, MessageAttachment } = require('discord.js');
const { createCanvas, loadImage } = require('canvas');

module.exports = {
     data: new SlashCommandBuilder()
        .setName('image')
        .setDescription('Creates an image with the provided text')
                .addStringOption(option =>
        option.setName('text')
            .setDescription('The text to write on the image')
    ),
async execute(interaction) {
    const text = interaction.options.getString('text')

    // Create a canvas and get a drawing context
    const canvas = createCanvas(200, 100);
    const ctx = canvas.getContext('2d');

    // Load an image as a background for the canvas
    const background = await loadImage('./justdancememe.jpg');
    ctx.drawImage(background, 0, 0, canvas.width, canvas.height);

    // Write the text on the canvas
    ctx.font = '30px Impact';
    ctx.fillStyle = '#ffffff';
    ctx.textAlign = 'center';
    ctx.fillText(text, canvas.width / 2, canvas.height / 2);

    // Convert the canvas to a buffer and create a message attachment with it
    const attachment = new MessageAttachment(canvas.toBuffer(), 'justdancememe.jpg');

    // Reply with the image
    await interaction.reply({ files: [attachment] })
},

};

I was expecting me to be able to input a value under text, say ‘example,’ and then that text would show up on the given image, but when the command is run, the bot doesn’t respond. Absolutely 0 errors as well.


问:
How to use INT 3 to execute code backward in DOS
I read from a blog post saying that back in the DOS days (not sure if it's possible under NT), there was a technique to execute code in backwards. It then went on to say that the idea was to execute say operation N, then use INT 3 to modify the instruction pointer to go backwards.

I'm trying to find more information regarding this but Googling so far didn't bring up anything close, and a lot of assembly code seems to target 32-bit and 64-bit architectures so I'm not sure if that's useful. I did find what INT 3 does:

Debuggers use this interrupt to establish breakpoints in a program
that is being debugged.  This is normally done by substituting an INT
3 instruction, which is one byte long, for a byte in the actual
program.  The original byte from the program is restored by the
debugger after it receives control through INT 3.

So my guess is, this "original byte" could be a JUMP instruction, and the second byte is the offset of the instruction (another post). The program maybe somehow modify the "stored" original byte and replaced it with a different offset. Does this make any sense?


问:
Form submit based on ajax response in jQuery
I'm using jQuery and am preventing the submission of a form, then based on an ajax response will submit the form.  The problem I'm finding is that I often have to submit the form twice.  The first time, it shows the loader, but it doesn't get seem to call any actions within the ajax's success function.  If I click it a second time, it submits (if it's been validated).  It also seems to work the first time, after I go through this.  So if I try again, it'll work the first time.  So maybe it's a cache issue? Here's the javascript I have:

```<code>            $('#submit_zipcode_frm').submit(function(event){
                    event.preventDefault();
                    var self = this;
                    $(".loader img").show();
                    z = $('#zipcode');
                    if(z.val() != '' && z.val().length == 5) {
                        var value = z.val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
                        var intRegex = /^\d+$/;
                        if(!intRegex.test(value)) {
                            $(".loader img").hide();
                            error($(".zipcode_field"));
                            return false;
                        }
                    } else {
                        $(".loader img").hide();
                        error($(".zipcode_field"));
                        return false;
                    }

                    $.ajax({
                        url: "/ajax/save/zipcode",
                        type: 'GET',
                        async: false,
                        cache: false,
                        dataType: 'html',
                        data:   {zipcode: $('.zipcode_field').val()},
                        success: function(data) {
                                if(data == 'false'){
                                    $(".loader img").hide();
                                    error($(".zipcode_field"));
                                    return false;
                                }else{
                                    self.submit();
                                    getList();
                                }
                        }
                    });
            });
</code>```

and here's the markup:

```<code>                        <form id="submit_zipcode_frm" class="submit_zipcode" method="post" action="/go" target="_blank">
                        <div class="zipcode_container">
                            <span class="loader">
                                <img src="/assets/img/loader.gif" style="display: none;"/>
                            </span>
                            <input type="text" class="zip_input zipcode_field ghost" id="zipcode" name="zipcode"  value="Enter your Zip"/>
                            <div class="start_btn">
                                <button type="submit">Submit</button>
                            </div>
                            <div class="clear"></div>
                        </div>
                        <div class="clear"></div>
                        </form>
</code>```

Any suggestions or ideas would be really appreciated.  Thank you!

EDIT:

Just to clarify the steps here:

User clicks the submit button

JavaScript show's the loader and validates the length and and type of the value entered

If that passes, an ajax lookup is used to truly validate it's a valid USPS zip code

If it is, the form is submitted and a function getList() is called

If it's not, error is thrown

ContentLicense: CC BY-SA 3.0

Body:
I'm using jQuery and am preventing the submission of a form, then based on an ajax response will submit the form.  The problem I'm finding is that I often have to submit the form twice.  The first time, it shows the loader, but it doesn't get seem to call any actions within the ajax's success function.  If I click it a second time, it submits (if it's been validated).  It also seems to work the first time, after I go through this.  So if I try again, it'll work the first time.  So maybe it's a cache issue? Here's the javascript I have:

            $('#submit_zipcode_frm').submit(function(event){
                    event.preventDefault();
                    var self = this;
                    $(".loader img").show();
                    z = $('#zipcode');
                    if(z.val() != '' && z.val().length == 5) {
                        var value = z.val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
                        var intRegex = /^\d+$/;
                        if(!intRegex.test(value)) {
                            $(".loader img").hide();
                            error($(".zipcode_field"));
                            return false;
                        }
                    } else {
                        $(".loader img").hide();
                        error($(".zipcode_field"));
                        return false;
                    }

                    $.ajax({
                        url: "/ajax/save/zipcode",
                        type: 'GET',
                        async: false,
                        cache: false,
                        dataType: 'html',
                        data:   {zipcode: $('.zipcode_field').val()},
                        success: function(data) {
                                if(data == 'false'){
                                    $(".loader img").hide();
                                    error($(".zipcode_field"));
                                    return false;
                                }else{
                                    self.submit();
                                    getList();
                                }
                        }
                    });
            });

and here's the markup:

                        <form id="submit_zipcode_frm" class="submit_zipcode" method="post" action="/go" target="_blank">

                            <input type="text" class="zip_input zipcode_field ghost" id="zipcode" name="zipcode"  value="Enter your Zip"/>

                                <button type="submit">Submit</button>

                        </form>

Any suggestions or ideas would be really appreciated.  Thank you!

EDIT:

Just to clarify the steps here:

User clicks the submit button

JavaScript show's the loader and validates the length and and type of the value entered

If that passes, an ajax lookup is used to truly validate it's a valid USPS zip code

If it is, the form is submitted and a function getList() is called

If it's not, error is thrown


问:
scrapy code 403 when running in AWS Lambda but works fine when running locally
I've set up an automated web-scraper that runs daily. All my spiders work perfectly except for 1 particular spider. It works fine when running locally with the command "scrapy crawl {spider} -O {spider.json}"

However, in the AWS CloudWatch, I can see this error
DEBUG:scrapy.core.engine:Crawled (403) <GET {WEBSITE URL}> (referer: None)

Any and all help would be greatly appreciated


问:
Conditional useEffect in Reactjs
I am developing a form with some number fields. The requirement is that some of the forms require special handling, for example: Volume will not be a user input but a product of surface area and height.

Currently Im using a useEffect Hook to capture the changes in surface area and height then update the disabled input field for Volume. I am trying to make the template generic so it could apply to other forms in the code. However, each of these templates shall have a distinct useEffect Hook since they are capturing different updates and responding in different way. Long story short, how do I dynamically|conditionally add useEffect to a functional component?

```<code>function Node(props: {
  nodeInfo: NodeInfo;
  // to return the state to the parent component
  submitNode: (nodeInfo: NodeInfo) => void;
}) {
  // mapping state to props
  const [nodeInfo, setNodeInfo] = useState(props.nodeInfo);

  // customize useEffect for each nodetype
  useEffect(() => {
    setNodeInfo({ ...nodeInfo, 'Volume (m^3)': nodeInfo['Area (m^2)'] * nodeInfo['Height (m)']});
  }, [nodeInfo['Area (m^2)', nodeInfo['Height (m)']]);

  const updateInfo = (paramName: string, value: number) => {
    setNodeInfo({ ...nodeInfo, [paramName]: value });
  };

  const validateInput = (paramName: string, value: number) => {
    const bounds = nodeBounds.find((nodeBound) => nodeBound.paramName === paramName);
    // no bounds found for validation
    if (bounds === undefined) return;

    if (value < bounds.minVal) {
      updateInfo(paramName, bounds.minVal);
      alert(
        bounds.errMsg ||
          `Input ${value} < ${bounds.minVal} is considered out of bound`,
      );
    } else if (value > (bounds.maxVal || 10000000)) {
      updateInfo(paramName, bounds.maxVal || 10000000);
      alert(
        bounds.errMsg ||
          `Input ${value} > ${
            bounds.maxVal || 10000000
          } is considered out of bound`,
      );
    }
  };

  return (
    <>
      {Object.keys(nodeInfo).map((key) => {
        return (
          <SingleInput
            key={`input-${key}`}
            inputType="number"
            inputName={key}
            inputValue={nodeInfo[key as keyof NodeInfo]}
            updateInfo={(val: number) => updateInfo(key, val)}
            validateInput={(val: number) => validateInput(key, val)}
            disabled={disableList.includes(key)}
          />
        );
      })}
      <input type="button" value="submit" onClick={() => props.submitNode(nodeInfo)} />
    </>
  );
}
</code>```

Title: Conditional useEffect in Reactjs

Body:
I am developing a form with some number fields. The requirement is that some of the forms require special handling, for example: Volume will not be a user input but a product of surface area and height.

Currently Im using a useEffect Hook to capture the changes in surface area and height then update the disabled input field for Volume. I am trying to make the template generic so it could apply to other forms in the code. However, each of these templates shall have a distinct useEffect Hook since they are capturing different updates and responding in different way. Long story short, how do I dynamically|conditionally add useEffect to a functional component?

function Node(props: {
  nodeInfo: NodeInfo;
  // to return the state to the parent component
  submitNode: (nodeInfo: NodeInfo) => void;
}) {
  // mapping state to props
  const [nodeInfo, setNodeInfo] = useState(props.nodeInfo);

  // customize useEffect for each nodetype
  useEffect(() => {
    setNodeInfo({ ...nodeInfo, 'Volume (m^3)': nodeInfo['Area (m^2)'] * nodeInfo['Height (m)']});
  }, [nodeInfo['Area (m^2)', nodeInfo['Height (m)']]);

  const updateInfo = (paramName: string, value: number) => {
    setNodeInfo({ ...nodeInfo, [paramName]: value });
  };

  const validateInput = (paramName: string, value: number) => {
    const bounds = nodeBounds.find((nodeBound) => nodeBound.paramName === paramName);
    // no bounds found for validation
    if (bounds === undefined) return;

    if (value < bounds.minVal) {
      updateInfo(paramName, bounds.minVal);
      alert(
        bounds.errMsg ||
          `Input ${value} < ${bounds.minVal} is considered out of bound`,
      );
    } else if (value > (bounds.maxVal || 10000000)) {
      updateInfo(paramName, bounds.maxVal || 10000000);
      alert(
        bounds.errMsg ||
          `Input ${value} > ${
            bounds.maxVal || 10000000
          } is considered out of bound`,
      );
    }
  };

  return (
    <>
      {Object.keys(nodeInfo).map((key) => {
        return (
          <SingleInput
            key={`input-${key}`}
            inputType="number"
            inputName={key}
            inputValue={nodeInfo[key as keyof NodeInfo]}
            updateInfo={(val: number) => updateInfo(key, val)}
            validateInput={(val: number) => validateInput(key, val)}
            disabled={disableList.includes(key)}
          />
        );
      })}
      <input type="button" value="submit" onClick={() => props.submitNode(nodeInfo)} />
    </>
  );
}


问:
How do I derive Copy and Deserialize on a struct with a Vec<>?
So I have a struct with a new method that makes a HTTP request and returns part of the response, which should deserialize into the struct that this method is for. The problem I'm having is that the part of the response I need is contained within a Vec<> in the response and using .first() gives a reference to it.

I tried dereferencing it, but my struct needs to have the Copy trait. So then I derived that, but my struct contains a field with a Vec<> type, and that needs to have the Copy trait. I learned about the error I was getting a bit and found out that references always have the Copy trait, so I should be able to just make my field &'a Vec<>. At this point I'm getting into named lifetimes territory, which I'm not very familiar with, being fairly new to Rust. It still doesn't work though, because:

```<code>error[E0277]: the trait bound `&'a Vec<f32>: Deserialize<'_>` is not satisfied
    --> src/embeddings.rs:26:14
     |
26   |     pub vec: &'a Vec<f32>,
     |              ^^^^^^^^^^^^ the trait `Deserialize<'_>` is not implemented for `&'a Vec<f32>`
     |
</code>```

And now I'm stuck. Here's hopefully enough of my code to find a solution:

#[derive(Deserialize)]
struct NewEmbeddingRequestResponse<'a> {
    data: Vec<Embedding<'a>>,
}

#[derive(Deserialize, Clone, Copy)]
pub struct Embedding<'a> {
    /* ... */
    pub vec: &'a Vec<f32>,
}

impl<'a> Embedding<'a> {
    pub async fn new(/* ... */) -> Result<Embedding<'a>, reqwest::Error> {
        /* ... */

        let response: NewEmbeddingRequestResponse = client.post(/* ... */)
            /* ... */
            .send().await?.json().await?;

        let embedding = *response.data.first().unwrap();

        Ok(embedding)
    }
}
```

Body:
So I have a struct with a new method that makes a HTTP request and returns part of the response, which should deserialize into the struct that this method is for. The problem I'm having is that the part of the response I need is contained within a Vec<> in the response and using .first() gives a reference to it.

I tried dereferencing it, but my struct needs to have the Copy trait. So then I derived that, but my struct contains a field with a Vec<> type, and that needs to have the Copy trait. I learned about the error I was getting a bit and found out that references always have the Copy trait, so I should be able to just make my field &'a Vec<>. At this point I'm getting into named lifetimes territory, which I'm not very familiar with, being fairly new to Rust. It still doesn't work though, because:

error[E0277]: the trait bound `&'a Vec<f32>: Deserialize<'_>` is not satisfied
    --> src/embeddings.rs:26:14
     |
26   |     pub vec: &'a Vec<f32>,
     |              ^^^^^^^^^^^^ the trait `Deserialize<'_>` is not implemented for `&'a Vec<f32>`
     |

And now I'm stuck. Here's hopefully enough of my code to find a solution:

#[derive(Deserialize)]
struct NewEmbeddingRequestResponse<'a> {
    data: Vec<Embedding<'a>>,
}

#[derive(Deserialize, Clone, Copy)]
pub struct Embedding<'a> {
    /* ... */
    pub vec: &'a Vec<f32>,
}

impl<'a> Embedding<'a> {
    pub async fn new(/* ... */) -> Result<Embedding<'a>, reqwest::Error> {
        /* ... */

        let response: NewEmbeddingRequestResponse = client.post(/* ... */)
            /* ... */
            .send().await?.json().await?;

        let embedding = *response.data.first().unwrap();

        Ok(embedding)
    }
}


问:
Angular on Linkedin
I am having trouble with css inheritance when injecting html generated with angular into linkedin through chrome extension, I had the same problem before when I used html, css, tried every single css reset but nothing worked until I hardcoded every single thing in my css with !important.

Is there any way around this, I want to use angular styles without any inheritance or if there is a way to somehow build angular with each style calculated and hardcoded/generated without too much work?

First tried without any modifications, every element get's twisted at least a bit, all margins, paddings, font-sizes just get messed up, then tried with css resets, still nothing. I expected same "look" as I get when I do ng serve.

Title: Angular on Linkedin


问:
Microsoft Voice Recorder Date, Time and Duration
Microsoft's Voice Recorder, in Windows 10, Stores recording in a Recordings File that is in Documents Folder. On the Voice Recorder app screen the Date, Time and Duration of recording is displayed.  Is there a way to get the Date, Time and Duration from the entries in the Voice Recorder File?

Want to get the timestamp of recordings saved by the Voice recorder programmatically for use in an ACCESS database, but the save records don't indicate a timestamp.  I can't find a way of getting that information.


问:
I'm having a syntax error writing a bash script
Writing a simple shell script to look at a specific file that will be added to in the future, and extract information from a name, formatted like {name};{info};{more info}, is pretty straightforward, but it gives me this error and I can't figure out why the hell there's an issue, I've tried adjusting it a million ways and can't figure it out.

Error:

```<code>./BBoiler.sh: line 6: syntax error near unexpected token `do'
./BBoiler.sh: line 6: `     for part in $parts; do'
</code>```

Code:

```<code>#! /bin/bash
name="Chloe"
echo clients.txt | while read line || [[ -n $line ]];
do
    parts=$(echo $line | tr ";" "\n")
    for part in $parts; do
        if[ $part == $name ]; then
            echo "$name"
        fi
    done
done

printf "$name test"
</code>```

Body:
Writing a simple shell script to look at a specific file that will be added to in the future, and extract information from a name, formatted like {name};{info};{more info}, is pretty straightforward, but it gives me this error and I can't figure out why the hell there's an issue, I've tried adjusting it a million ways and can't figure it out.

Error:

./BBoiler.sh: line 6: syntax error near unexpected token `do'
./BBoiler.sh: line 6: `     for part in $parts; do'

Code:

#! /bin/bash
name="Chloe"
echo clients.txt | while read line || [[ -n $line ]];
do
    parts=$(echo $line | tr ";" "\n")
    for part in $parts; do
        if[ $part == $name ]; then
            echo "$name"
        fi
    done
done

printf "$name test"


问:
PyTorch installation with conda 'setup.py': [Errno 2] No such file or directory
Trying to run import torch gives the following error:

```<code>Traceback (most recent call last):
  File "hello.py", line 1, in <module>
    import torch
  File "/Users/user/Desktop/art/torch/__init__.py", line 246, in <module>
    ''').strip()) from None
ImportError: Failed to load PyTorch C extensions:
    It appears that PyTorch has loaded the `torch/_C` folder
    of the PyTorch repository rather than the C extensions which
    are expected in the `torch._C` namespace. This can occur when
    using the `install` workflow. e.g.
        $ python setup.py install && python -c "import torch"

    This error can generally be solved using the `develop` workflow
        $ python setup.py develop && python -c "import torch"  # This should succeed
    or by running Python from a different directory.
</code>```

Then when I run the new command, I get this:

```<code>/Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'setup.py': [Errno 2] No such file or directory
</code>```

I have tried running the command in different folders and it still fails. My torch folder has no setup.py file when I manually check.

Body:
Trying to run import torch gives the following error:

Traceback (most recent call last):
  File "hello.py", line 1, in <module>
    import torch
  File "/Users/user/Desktop/art/torch/__init__.py", line 246, in <module>
    ''').strip()) from None
ImportError: Failed to load PyTorch C extensions:
    It appears that PyTorch has loaded the `torch/_C` folder
    of the PyTorch repository rather than the C extensions which
    are expected in the `torch._C` namespace. This can occur when
    using the `install` workflow. e.g.
        $ python setup.py install && python -c "import torch"

    This error can generally be solved using the `develop` workflow
        $ python setup.py develop && python -c "import torch"  # This should succeed
    or by running Python from a different directory.

Then when I run the new command, I get this:

/Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python: can't open file 'setup.py': [Errno 2] No such file or directory

I have tried running the command in different folders and it still fails. My torch folder has no setup.py file when I manually check.


问:
How to install program which published by VS2017 MVC project into folder
I publised my VS2017 MVC Project into a folder.
Then I copy all files in that folder into another Windows 10 PC IIS web page.

I try to run that page in IIS but show
HTTP Error 403.14 - Forbidden

I enable directoryBrowse which only show web file directory not my MVC web page.

How can I deploy my VS2017 MVC project or how to start web page which published by folder?


问:
Refresh token with authz-keycloak APISIX plugin
Plugin has option password_grant_token_generation_incoming_uri that allows user generates token using grant_type password, it works great but I don't know how to refresh token, can we do that with authz-keycloak plugin?

Thanks for your help!


问:
How to get the main window hwnd when it contains a QWebEngineWidget?
How to reproduce:

```<code>#include <QtWebEngineWidgets/QWebEngineView>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
       ui.setupUi(this);
       QWebEngineView* engine = new QWebEngineView(this);

       HWND hwnd = (HWND)this->winId();
       qDebug() << "\nhwnd: " << hwnd << "\n";
}
</code>```

The hwnd returned by windId() isn't the same as the main window.

When I search for any window which the given hwnd nothing is found, which means the window doesn't exist anymore?

Commenting the line:

```<code>QWebEngineView* engine = new QWebEngineView(this);
</code>```

It does return the hwnd of the main window correctly.

Im not sure if this can be called a bug, but how i can know the main window hwnd in this case?

Body:
How to reproduce:

#include <QtWebEngineWidgets/QWebEngineView>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
       ui.setupUi(this);
       QWebEngineView* engine = new QWebEngineView(this);

       HWND hwnd = (HWND)this->winId();
       qDebug() << "\nhwnd: " << hwnd << "\n";
}

The hwnd returned by windId() isn't the same as the main window.

When I search for any window which the given hwnd nothing is found, which means the window doesn't exist anymore?

Commenting the line:

QWebEngineView* engine = new QWebEngineView(this);

It does return the hwnd of the main window correctly.

Im not sure if this can be called a bug, but how i can know the main window hwnd in this case?


问:
WebAssembly - Out of memory: wasm memory - on a VPS with NodeJS, CPanel, O2Switch
I have a problem, I wanted to launch my bot on my VPS (hosted by O2Switch) but I'm getting this weird error that I never seen before.
This error don't occur when I remove the client.login() line.
Note that this code works indeed well on my personnal computer.
My VPS is using node JS version 16.17.1

```<code>TypeError: Cannot destructure property 'exports' of 'undefined' as it is undefined.
    at new Parser (/home/mzyu2532/test/node_modules/undici/lib/client.js:420:34)
    at connect (/home/mzyu2532/test/node_modules/undici/lib/client.js:1077:23)
/home/mzyu2532/test/node_modules/undici/lib/client.js:1184
        if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
                            ^

TypeError: Cannot read properties of undefined (reading 'timeoutType')
    at _resume (/home/mzyu2532/test/node_modules/undici/lib/client.js:1184:29)
    at resume (/home/mzyu2532/test/node_modules/undici/lib/client.js:1148:3)
    at connect (/home/mzyu2532/test/node_modules/undici/lib/client.js:1133:3)
</code>```

After catching the Client.login() (see above) with a .catch this seems to be provocated by :

```<code>RangeError: WebAssembly.instantiate(): Out of memory: wasm memory
    at lazyllhttp (/home/mzyu2532/test/node_modules/undici/lib/client.js:356:28)
</code>```

Reproducible By

on a O2Switch VPS, using cPanel interface, starting a node app with this code as index :

const { Client, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.once(Events.ClientReady, c => { console.log(`Ready! Logged in as ${c.user.tag}`); });

client.login(token);
```
<h2>Dependencies</h2>
<pre class="lang-json prettyprint-override"><code>  "dependencies": {
    "discord.js": "^14.7.1",
    "JSON": "^1.0.0"
  }
</code>```

Unsatisfactory Solution

Running this script from a ssh on my personnal computer.
I would rather like to understand where the problem comes from and if possible fix it

Environment

VPS : O2Switch
Node version : 16.17.1
Linux version : 4.18.0-372.19.1.lve.el7h.x86_64
got from uname -r
Heap Memory :

{
  total_heap_size: 4964352,
  total_heap_size_executable: 524288,
  total_physical_size: 3853632,
  total_available_size: 4342066688,
  used_heap_size: 4137768,
  heap_size_limit: 4345298944,
  malloced_memory: 254096,
  peak_malloced_memory: 91840,
  does_zap_garbage: 0,
  number_of_native_contexts: 1,
  number_of_detached_contexts: 0,
  total_global_handles_size: 8192,
  used_global_handles_size: 3040,
  external_memory: 314973
}
```

got from console.log(require('v8').getHeapStatistics())

Body:
I have a problem, I wanted to launch my bot on my VPS (hosted by O2Switch) but I'm getting this weird error that I never seen before.
This error don't occur when I remove the client.login() line.
Note that this code works indeed well on my personnal computer.
My VPS is using node JS version 16.17.1

TypeError: Cannot destructure property 'exports' of 'undefined' as it is undefined.
    at new Parser (/home/mzyu2532/test/node_modules/undici/lib/client.js:420:34)
    at connect (/home/mzyu2532/test/node_modules/undici/lib/client.js:1077:23)
/home/mzyu2532/test/node_modules/undici/lib/client.js:1184
        if (socket[kParser].timeoutType !== TIMEOUT_IDLE) {
                            ^

TypeError: Cannot read properties of undefined (reading 'timeoutType')
    at _resume (/home/mzyu2532/test/node_modules/undici/lib/client.js:1184:29)
    at resume (/home/mzyu2532/test/node_modules/undici/lib/client.js:1148:3)
    at connect (/home/mzyu2532/test/node_modules/undici/lib/client.js:1133:3)

After catching the Client.login() (see above) with a .catch this seems to be provocated by :

RangeError: WebAssembly.instantiate(): Out of memory: wasm memory
    at lazyllhttp (/home/mzyu2532/test/node_modules/undici/lib/client.js:356:28)

Reproducible By

on a O2Switch VPS, using cPanel interface, starting a node app with this code as index :

const { Client, Events, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');

const client = new Client({ intents: [GatewayIntentBits.Guilds] });

client.once(Events.ClientReady, c => { console.log(`Ready! Logged in as ${c.user.tag}`); });

client.login(token);

Dependencies

  "dependencies": {
    "discord.js": "^14.7.1",
    "JSON": "^1.0.0"
  }

Unsatisfactory Solution

Running this script from a ssh on my personnal computer.
I would rather like to understand where the problem comes from and if possible fix it

Environment

VPS : O2Switch
Node version : 16.17.1
Linux version : 4.18.0-372.19.1.lve.el7h.x86_64
got from uname -r
Heap Memory :

{
  total_heap_size: 4964352,
  total_heap_size_executable: 524288,
  total_physical_size: 3853632,
  total_available_size: 4342066688,
  used_heap_size: 4137768,
  heap_size_limit: 4345298944,
  malloced_memory: 254096,
  peak_malloced_memory: 91840,
  does_zap_garbage: 0,
  number_of_native_contexts: 1,
  number_of_detached_contexts: 0,
  total_global_handles_size: 8192,
  used_global_handles_size: 3040,
  external_memory: 314973
}

got from console.log(require('v8').getHeapStatistics())


问:
LoginAndEnrollAccount(emailText) does not prompts the email and password with updated Intune SDK
Ours is an Intune Application with Xamarin forms.
Authentication is handled default by Intune SDK.
Application does not use ADAL nor MSAL.

after the Intune SDK update, LoginAndEnrollAccount does not prompts the user for username and password.

when the Intune SDK 14.3.5 version is used it prompts for username and password and Login is successful.

Help is appreciated

When tried with 14.3.5 Login is successful.
When tried with 17.1.1 Login is unsuccessful.


问:
Save .docm to NEW .docx WITHOUT converting active document
I use this .docm file (quotation and advice) over and over again, this .docm file itself keeps getting better every day as I am adding new information to it. For every new project I copy the last one used so I always use the most updated version.

If I send this to a client I use a macro to save and convert to PDF. All safe and sound.

Some clients request having a MS Word file for easy copy/paste into their own MS Word files. This is where stuff goes wrong: sending the client the original .docm file means I am sending them the macro's as well. Of course I do use a password to protect the VBA project but still... I just would like to send only the contents of the .docm file, not the file itself.

Furthermore, I have edit the .docm file with an XML editor to have some ribbon buttons as well. Also this I do not want to send over to the client.

Last but not least: the original .docm file contains a .PNG image (a signature handwritten by pen) which I would like to remove from the .docx file that is to be sent.

To solve my first and second 'problem' I guess I need to create an empty .docx file first and then copy and paste all from one to another. But the third (remove the PNG file) I am unaware of any options to do so.

A bit of research brought me up to this StackOverflow item:
https://stackoverflow.com/questions/64160234/ms-word-vba-to-save-docm-to-docx-without-converting-active-document

```<code>InStrRev(ActiveDocument.FullName, ".") - 1) & ".docx"
</code>```

The line above does not use a new/blanc .docm file hence the ribbon items get copied.

The goal is that all dialogs may be passed, just save as .docx under the same name in the same folder.

I have record a macro to see if there would be any clou as to deleting the .PNG file but too bad that does not seem to give me any help.

```<code>Sub Macro1()
'
' Macro1 Macro
'
'
    Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0
    Windows("MyDocument.docm").Activate
    Selection.WholeStory
    Selection.Copy
    Windows("Document1").Activate
    Selection.PasteAndFormat (wdUseDestinationStylesRecovery)
    Selection.HomeKey Unit:=wdStory
    Windows("MyDocument.docm").Activate
    Windows("Document1").Activate
    Selection.WholeStory
    Selection.TypeText Text:=" "
    Selection.Delete Unit:=wdCharacter, Count:=1
    ActiveDocument.Save
    ChangeFileOpenDirectory "C:\MyPath\"
    ActiveDocument.SaveAs2 FileName:= _
        "C:\MyPath\MyDocument.docx", _
        FileFormat:=wdFormatXMLDocument, LockComments:=False, Password:="", _
        AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
        EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
        :=False, SaveAsAOCELetter:=False, CompatibilityMode:=15
    ActiveWindow.Close
End Sub
</code>```

But the code does allow me to have a clean/blanco .docx file without macro's and/or ribbon buttons.

Maybe the .PNG image does need to be named or given an ID of any kind? So it can be found by coding.

Any help would be much appreciated. Thanks!

Body:
I use this .docm file (quotation and advice) over and over again, this .docm file itself keeps getting better every day as I am adding new information to it. For every new project I copy the last one used so I always use the most updated version.

If I send this to a client I use a macro to save and convert to PDF. All safe and sound.

Some clients request having a MS Word file for easy copy/paste into their own MS Word files. This is where stuff goes wrong: sending the client the original .docm file means I am sending them the macro's as well. Of course I do use a password to protect the VBA project but still... I just would like to send only the contents of the .docm file, not the file itself.

Furthermore, I have edit the .docm file with an XML editor to have some ribbon buttons as well. Also this I do not want to send over to the client.

Last but not least: the original .docm file contains a .PNG image (a signature handwritten by pen) which I would like to remove from the .docx file that is to be sent.

To solve my first and second 'problem' I guess I need to create an empty .docx file first and then copy and paste all from one to another. But the third (remove the PNG file) I am unaware of any options to do so.

A bit of research brought me up to this StackOverflow item:
https://stackoverflow.com/questions/64160234/ms-word-vba-to-save-docm-to-docx-without-converting-active-document

InStrRev(ActiveDocument.FullName, ".") - 1) & ".docx"

The line above does not use a new/blanc .docm file hence the ribbon items get copied.

The goal is that all dialogs may be passed, just save as .docx under the same name in the same folder.

I have record a macro to see if there would be any clou as to deleting the .PNG file but too bad that does not seem to give me any help.

Sub Macro1()
'
' Macro1 Macro
'
'
    Documents.Add Template:="Normal", NewTemplate:=False, DocumentType:=0
    Windows("MyDocument.docm").Activate
    Selection.WholeStory
    Selection.Copy
    Windows("Document1").Activate
    Selection.PasteAndFormat (wdUseDestinationStylesRecovery)
    Selection.HomeKey Unit:=wdStory
    Windows("MyDocument.docm").Activate
    Windows("Document1").Activate
    Selection.WholeStory
    Selection.TypeText Text:=" "
    Selection.Delete Unit:=wdCharacter, Count:=1
    ActiveDocument.Save
    ChangeFileOpenDirectory "C:\MyPath\"
    ActiveDocument.SaveAs2 FileName:= _
        "C:\MyPath\MyDocument.docx", _
        FileFormat:=wdFormatXMLDocument, LockComments:=False, Password:="", _
        AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
        EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
        :=False, SaveAsAOCELetter:=False, CompatibilityMode:=15
    ActiveWindow.Close
End Sub

But the code does allow me to have a clean/blanco .docx file without macro's and/or ribbon buttons.

Maybe the .PNG image does need to be named or given an ID of any kind? So it can be found by coding.

Any help would be much appreciated. Thanks!


问:
Different datasets and different loss terms in pytorch
I am working on a problem where the input space has different regions: R1, R2, and R3, and I have three datasets (D1, D2, and D3) sampled from the corresponding regions. The trick is that the loss function has three loss terms as well: L1, L2, and L3 (corresponding to the three regions of the input space), where the definition of each loss term is different from the other two. The problem is to be solved in PyTorch.

I am not sure how to proceed with sampling/mini-batching. Any advice is appreciated.


问:
How to configure optional parameter for for you aws batch job defination and job submition?
How to configure optional parameter for for you aws batch job defination and job submition? Will it take default parameters if I do not want to pass any paramter?

How to configure optional parameter for for you aws batch job defination and job submition? Will it take default parameters if I do not want to pass any paramter?


问:
How can I get the calling query from within a Spark UDF?
Few years ago, writing a Hive UDF in a Hadoop environment, I could get the calling query like so:

```<code>public class MyHiveUDF extends GenericUDF {

    @Override
    public Object evaluate(DeferredObject[] arguments) throws CryptoException { ...stuff...}

    @Override
    public void configure(MapredContext context) {
        super.configure(context);
        Configuration conf = context.getJobConf();
        String myQuery = conf.get("hive.query.string","")
    }
</code>```

Now trying to do something similar in Spark/Scala (Databricks job/notebook), I want my UDF get hold of the calling query - is that possible? if so, how?
And as a more general question - can I get any of the Spark configuration inside a UDF code?

My platform is using Spark 3.3.0, Scala 2.12, Databricks version 11.x

It should look something like this:

```<code>def myCustomUdf: UserDefinedFunction = udf ( (colValue : String) => {
  val myQuery = ...get query string here?...
  stuffWithInput(colVal)
})
</code>```

Thanks

Body:
Few years ago, writing a Hive UDF in a Hadoop environment, I could get the calling query like so:

public class MyHiveUDF extends GenericUDF {

    @Override
    public Object evaluate(DeferredObject[] arguments) throws CryptoException { ...stuff...}

    @Override
    public void configure(MapredContext context) {
        super.configure(context);
        Configuration conf = context.getJobConf();
        String myQuery = conf.get("hive.query.string","")
    }

Now trying to do something similar in Spark/Scala (Databricks job/notebook), I want my UDF get hold of the calling query - is that possible? if so, how?
And as a more general question - can I get any of the Spark configuration inside a UDF code?

My platform is using Spark 3.3.0, Scala 2.12, Databricks version 11.x

It should look something like this:

def myCustomUdf: UserDefinedFunction = udf ( (colValue : String) => {
  val myQuery = ...get query string here?...
  stuffWithInput(colVal)
})

Thanks


问:
How to detect from client if rPyc server is successfully initialised and is running?
I have a fastapi project needs to connect to a rPyc server.

Since I need to start the rPyc server before I start the fastapi project, how could I know if the rPyc server is already successfully prepared from my fastapi end?

Any suggestion?

I have checked the Documentation about the ThreadedServer, except knowing start() function is blocking, I didn't find anything useful.

Now what I write in server:

```<code>t=ThreadedServer(Api,hostname,port)
t.start()
</code>```

What I am doing on client is just a simple connect without any other "detect-behavior":
conn=rpyc.connect(server_addr, server_port)

Body:
I have a fastapi project needs to connect to a rPyc server.

Since I need to start the rPyc server before I start the fastapi project, how could I know if the rPyc server is already successfully prepared from my fastapi end?

Any suggestion?

I have checked the Documentation about the ThreadedServer, except knowing start() function is blocking, I didn't find anything useful.

Now what I write in server:

t=ThreadedServer(Api,hostname,port)
t.start()

What I am doing on client is just a simple connect without any other "detect-behavior":
conn=rpyc.connect(server_addr, server_port)


问:
get SSL certificate details from web ui using selenium or playwright
Is there a way to get SSL certificate details from web UI using selenium or playwright? I know I can get them using openssl commands but I am looking to get from UI using selenium or playwright.</p>


问:
problem connecting to web server using users
i have a user with the following privilege.

```<code>CREATE USER admin IDENTIFIED BY '123';
GRANT SELECT on Person TO admin
GRANT SELECT on genders TO admin
GRANT SELECT on ages TO admin
GRANT SELECT on conditions TO admin
GRANT SELECT on countries TO admin
GRANT SELECT on company TO admin
</code>```

i then input the exact same details to connect to MySQL

```<code>  const express = require('express');
  const bodyParser = require('body-parser');
  const mysql = require('mysql');
  const mustacheExpress = require('mustache-express');
  const app = express();
  const webPort = 8088;

  const con = mysql.createConnection({
    host: "localhost",
    user: "admin",
    password: "123",
    database: "company"
  });
</code>```

I then tried connecting to the webserver using node index.js but got this error   i have already tried upgrading MySQL but the same error happens.

Body:
i have a user with the following privilege.

CREATE USER admin IDENTIFIED BY '123';
GRANT SELECT on Person TO admin
GRANT SELECT on genders TO admin
GRANT SELECT on ages TO admin
GRANT SELECT on conditions TO admin
GRANT SELECT on countries TO admin
GRANT SELECT on company TO admin

i then input the exact same details to connect to MySQL

  const express = require('express');
  const bodyParser = require('body-parser');
  const mysql = require('mysql');
  const mustacheExpress = require('mustache-express');
  const app = express();
  const webPort = 8088;

  const con = mysql.createConnection({
    host: "localhost",
    user: "admin",
    password: "123",
    database: "company"
  });

I then tried connecting to the webserver using node index.js but got this error   i have already tried upgrading MySQL but the same error happens.


问:
How to get pod IP address in helm template for hostAlias:
Im trying include podIP in Helm template using status.PodIP in hostAlias section. But hostAlias didn't accept status.PodIP and expect for a proper IP address.

How to put podIP in /etc/host through helm template.

Im trying include podIP in Helm template using status.PodIP in hostAlias section. But hostAlias didn't accept status.PodIP and expect for a proper IP address.

How to put podIP in /etc/host through helm template.


问:
Deploy to EC2 instance from Github Actions
Good night guys, I've been trying to find out this but it's the first time I'm doing it.

With Github OpenID connect I could to deploy the code to a S3 bucket, but now I need to pass these files from s3 to an EC2 instance in the deploy.yml file, but I can't use

```<code>access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
</code>```

Because the client doesn't want to give access to secrets.

There's any other way to do this?

I'm completely lost and I don't have administrator access or the enough permissions in AWS to work.

Thanks.

I have already the files in a S3 bucket with this code:

```<code>    - name: Copy to S3 bucket
      run: |
        aws s3 sync --delete ./my_path s3://${{ env.BUCKET_NAME }}/${{ steps.extract_branch.outputs.branch }}/${{steps.extract_hash.outputs.commit_hash }}

</code>```

And I've been trying to do something like this:

```<code>    - name: Deploy to EC2 instance
      uses: easingthemes/ssh-deploy@v2.1.5
      env:
        SSH_PRIVATE_KEY: "ALL PRIVATE KEY CODE PASTED"
        SOURCE: "./"
        REMOTE_HOST: "my host"
        REMOTE_USER: "my user"
        TARGET: "/path/to/copy/"
        EXCLUDE: "/dist/, /node_modules/, /venv/"
</code>```

This is the error:

```<code>Run easingthemes/ssh-deploy@v2.1.5
[general] GITHUB_WORKSPACE:  /home/runner/work/project
[SSH] Creating /home/runner/.ssh dir in  /home/runner/work/project
✅ [SSH] dir created.
[SSH] Creating /home/runner/.ssh/known_hosts file in  /home/runner/work/project
✅ [SSH] file created.
✅ Ssh key added to `.ssh` dir  /home/runner/.ssh/deploy_key
[Rsync] Starting Rsync Action: /home/runner/work/project/docker/ to ubuntu@ec2-server.com:/home/ubuntu/
⚠ [Rsync] error:  rsync exited with code 255
⚠ [Rsync] stderr:  Warning: Permanently added 'ec2-server.com' (ED25519) to the list of known hosts.
Load key "/home/runner/.ssh/deploy_key": error in libcrypto
ubuntu@ec2-server.com: Permission denied (publickey).
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: unexplained error (code 255) at io.c(228) [sender=3.2.3]

⚠ [Rsync] stdout:
⚠ [Rsync] cmd:  rsync /home/runner/work/project/docker/ ubuntu@ec2-server.com:/home/ubuntu/ --rsh "ssh -p 22 -i /home/runner/.ssh/deploy_key -o StrictHostKeyChecking=no" --recursive -rltgoDzvO
 1: 0xa1a640 node::Abort() [/home/runner/runners/2.299.1/externals/node12/bin/node]
 2: 0xa90649  [/home/runner/runners/2.299.1/externals/node12/bin/node]
 3: 0xc06599  [/home/runner/runners/2.299.1/externals/node12/bin/node]
 4: 0xc08387 v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) [/home/runner/runners/2.299.1/externals/node12/bin/node]
 5: 0x140dd19  [/home/runner/runners/2.299.1/externals/node12/bin/node]
</code>```

Body:
Good night guys, I've been trying to find out this but it's the first time I'm doing it.

With Github OpenID connect I could to deploy the code to a S3 bucket, but now I need to pass these files from s3 to an EC2 instance in the deploy.yml file, but I can't use

access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}

Because the client doesn't want to give access to secrets.

There's any other way to do this?

I'm completely lost and I don't have administrator access or the enough permissions in AWS to work.

Thanks.

I have already the files in a S3 bucket with this code:

    - name: Copy to S3 bucket
      run: |
        aws s3 sync --delete ./my_path s3://${{ env.BUCKET_NAME }}/${{ steps.extract_branch.outputs.branch }}/${{steps.extract_hash.outputs.commit_hash }}

And I've been trying to do something like this:

    - name: Deploy to EC2 instance
      uses: easingthemes/ssh-deploy@v2.1.5
      env:
        SSH_PRIVATE_KEY: "ALL PRIVATE KEY CODE PASTED"
        SOURCE: "./"
        REMOTE_HOST: "my host"
        REMOTE_USER: "my user"
        TARGET: "/path/to/copy/"
        EXCLUDE: "/dist/, /node_modules/, /venv/"

This is the error:

Run easingthemes/ssh-deploy@v2.1.5
[general] GITHUB_WORKSPACE:  /home/runner/work/project
[SSH] Creating /home/runner/.ssh dir in  /home/runner/work/project
✅ [SSH] dir created.
[SSH] Creating /home/runner/.ssh/known_hosts file in  /home/runner/work/project
✅ [SSH] file created.
✅ Ssh key added to `.ssh` dir  /home/runner/.ssh/deploy_key
[Rsync] Starting Rsync Action: /home/runner/work/project/docker/ to ubuntu@ec2-server.com:/home/ubuntu/
⚠ [Rsync] error:  rsync exited with code 255
⚠ [Rsync] stderr:  Warning: Permanently added 'ec2-server.com' (ED25519) to the list of known hosts.
Load key "/home/runner/.ssh/deploy_key": error in libcrypto
ubuntu@ec2-server.com: Permission denied (publickey).
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: unexplained error (code 255) at io.c(228) [sender=3.2.3]

⚠ [Rsync] stdout:
⚠ [Rsync] cmd:  rsync /home/runner/work/project/docker/ ubuntu@ec2-server.com:/home/ubuntu/ --rsh "ssh -p 22 -i /home/runner/.ssh/deploy_key -o StrictHostKeyChecking=no" --recursive -rltgoDzvO
 1: 0xa1a640 node::Abort() [/home/runner/runners/2.299.1/externals/node12/bin/node]
 2: 0xa90649  [/home/runner/runners/2.299.1/externals/node12/bin/node]
 3: 0xc06599  [/home/runner/runners/2.299.1/externals/node12/bin/node]
 4: 0xc08387 v8::internal::Builtin_HandleApiCall(int, unsigned long*, v8::internal::Isolate*) [/home/runner/runners/2.299.1/externals/node12/bin/node]
 5: 0x140dd19  [/home/runner/runners/2.299.1/externals/node12/bin/node]


问:
Python successfully imports a module in the parent directory without specifying a relative import
I'm working on "The Flask Mega-Tutorial" by Miguel Grinberg and in Part III there's a piece of code that I'm unsure as to why it compiles. This is the directory structure of the project

```<code>├── app
│   ├── forms.py
│   ├── __init__.py
│   ├── __init__.py~
│   ├── __pycache__
│   ├── routes.py
│   └── templates
├── config.py
├── LICENSE
├── microblog.py
├── README.md
└── venv

</code>```

In the file app/init.py it has the code

```<code>from config import Config
</code>```

in reference to config.py in the parent directory which has the following code

```<code>class Config(object):
</code>```

When I run

```<code>flask run
</code>```

everything seems to work but I'm unsure why this is permitted. Shouldn't app/init.py have the line

```<code>from ..config import Config
</code>```

instead?

I have an unfounded belief that microblog.py may have a role in this, where its code is

```<code>from app import app
</code>```

and so since the

```<code>FLASK_APP=microblog.py
</code>```

when running flask we are importing relative to the root level of the directory. Let me know if this is wrong.

I tried to replace the code

```<code>from config import Config
</code>```

with

```<code>from ..config import Config
</code>```

which didn't work.

Body:
I'm working on "The Flask Mega-Tutorial" by Miguel Grinberg and in Part III there's a piece of code that I'm unsure as to why it compiles. This is the directory structure of the project

├── app
│   ├── forms.py
│   ├── __init__.py
│   ├── __init__.py~
│   ├── __pycache__
│   ├── routes.py
│   └── templates
├── config.py
├── LICENSE
├── microblog.py
├── README.md
└── venv

In the file app/init.py it has the code

from config import Config

in reference to config.py in the parent directory which has the following code

class Config(object):

When I run

flask run

everything seems to work but I'm unsure why this is permitted. Shouldn't app/init.py have the line

from ..config import Config

instead?

I have an unfounded belief that microblog.py may have a role in this, where its code is

from app import app

and so since the

FLASK_APP=microblog.py

when running flask we are importing relative to the root level of the directory. Let me know if this is wrong.

I tried to replace the code

from config import Config

with

from ..config import Config

which didn't work.


问:
Components not rendering on screen react native expo
There are four components on a screen and only three out of four are rendering.  <popDown/>  is the component that isn't rendering. When I save the specific component's file the components get rendered. Note: I am saving an already fully updated file. It is running with no errors

The Screen

```<code>import react from 'react';
import {View,ScrollView} from 'react-native';
import { SafeAreaView,  } from 'react-navigation';
import { PrProvider } from '../appFunctions/PrContext';
import PopDown from '../Components/PRForm/popDown';
import RepsWeightTextInput from '../Components/PRForm/RepsWeightTextInput';
import NotesInput from '../Components/PRForm/NotesInput';
import SubmitPr from '../Components/PRForm/SubmitPr';

const PrEnteryScreen = ({}) => {

   return(
       <View style = {{height:'100%',width:'100%',backgroundColor:'#141212'}}>

       <SafeAreaView style = {{alignItems:'center'}}>
            {/**
             * use context for pr information
             */}
               <PrProvider>
               <PopDown />
               <RepsWeightTextInput/>
               <NotesInput/>
               <SubmitPr/>
               </PrProvider>

       </SafeAreaView>
       </View>

   );
   };

export default PrEnteryScreen;
</code>```

popdown component

```<code>import { useContext, useEffect, useState } from "react";
import { TouchableOpacity,StyleSheet,View,LayoutAnimation,UIManager,Platform,useFocusEffect } from "react-native";
import { Children } from "react/cjs/react.production.min";
import SelectExerciseButton, { setIsOpen } from "./SelectExerciseButton";
import SelectExerciseModal from "../../Screens/SelectExerciseModal";
import { EXERCISE_DATA } from "../../Screens/SelectExerciseModal";
import { PrContext, PrProvider } from "../../appFunctions/PrContext";

if (
    Platform.OS === "android" &&
    UIManager.setLayoutAnimationEnabledExperimental
  ) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
  }

  const PopDown = () => {
    const value = useContext(PrContext)
    const [isOpen,setIsOpen] = useState(false)
    const [listHeight,setListHeight] = useState(0)
    const [textName,setTextName] = useState(value.exercise);//eventually want to change text based on exercise state
    const toggleOpen = () => {
        setIsOpen(value => !value);
        LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
        setTextName(value.exercise);

        console.log(value.exercise);
    }
    useEffect(() =>{

        EXERCISE_DATA.forEach(()=>{
            setListHeight(value => value+50)
        })

    },[isOpen])
    return(
        <>
            <TouchableOpacity
                onPress = {toggleOpen}
            >
                <SelectExerciseButton  />
            </TouchableOpacity>
            <View>
                <SelectExerciseModal style = {isOpen ? styles.show: styles.hidden} listHeight = {listHeight} name = {textName}/>
            </View>
        </>
    )
  }

  const styles = StyleSheet.create({
    hidden:{
        height:0,
    },
    show:{ backgroundColor: '#9B9A9A', width: 200 }
  });
export default PopDown;

</code>```

What I tried

I changed the hidden style height to see if it would render the list that is supposed to pop out of the button. The list did render which means the <selectExerciseButton/> is the only thing not rendering in <popDown/>.

```<code>const styles = StyleSheet.create({
    hidden:{
        height:100,
    },
    show:{ backgroundColor: '#9B9A9A', width: 200 }
  });
</code>```

```<code><TouchableOpacity
                onPress = {toggleOpen}
            >
                {children}
            </TouchableOpacity>
            <View>
                <SelectExerciseModal style = {isOpen ? styles.show: styles.hidden} listHeight = {listHeight} name = {textName}/>
            </View>
</code>```
```<code><PrProvider>
                <PopDown>
                    <SelectExerciseButton/>
                </PopDown>
                <RepsWeightTextInput/>
                <NotesInput/>
                <SubmitPr/>
                </PrProvider>
</code>```

SelectExerciseButton

```<code>import { useNavigation,useFocusEffect } from "@react-navigation/native";
import { SafeAreaView, StyleSheet, Text, TouchableOpacity, View,LayoutAnimation } from "react-native";
import { useContext, useState,useEffect } from "react";
import { PrContext } from "../../appFunctions/PrContext";
/**
 *
 * @returns button that navigates to the a modal to select an exercise
 */
 if (
    Platform.OS === "android" &&
    UIManager.setLayoutAnimationEnabledExperimental
  ) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
  }

const SelectExerciseButton = () => {
    const value = useContext(PrContext)

    return(
        <>
            <View style = {styles.background}>
                <Text style = {styles.Text}> {value.exercise} </Text>
            </View>
        </>
    );
};

styles = StyleSheet.create({
    background:{
        backgroundColor: '#9B9A9A',
        width: 335,
        borderRadius:41,
        alignItems:'center',
        marginHorizontal:25,
        height:200,
        justifyContent:'center'
    },
    Text:{
        fontWeight:'bold',
        fontSize:40,
        color:'white',
        alignItems:'center'

    }
})
export default SelectExerciseButton;
</code>```

Body:
There are four components on a screen and only three out of four are rendering.  <popDown/>  is the component that isn't rendering. When I save the specific component's file the components get rendered. Note: I am saving an already fully updated file. It is running with no errors

The Screen

import react from 'react';
import {View,ScrollView} from 'react-native';
import { SafeAreaView,  } from 'react-navigation';
import { PrProvider } from '../appFunctions/PrContext';
import PopDown from '../Components/PRForm/popDown';
import RepsWeightTextInput from '../Components/PRForm/RepsWeightTextInput';
import NotesInput from '../Components/PRForm/NotesInput';
import SubmitPr from '../Components/PRForm/SubmitPr';

const PrEnteryScreen = ({}) => {

   return(
       <View style = {{height:'100%',width:'100%',backgroundColor:'#141212'}}>

       <SafeAreaView style = {{alignItems:'center'}}>
            {/**
             * use context for pr information
             */}
               <PrProvider>
               <PopDown />
               <RepsWeightTextInput/>
               <NotesInput/>
               <SubmitPr/>
               </PrProvider>

       </SafeAreaView>
       </View>

   );
   };

export default PrEnteryScreen;

popdown component

import { useContext, useEffect, useState } from "react";
import { TouchableOpacity,StyleSheet,View,LayoutAnimation,UIManager,Platform,useFocusEffect } from "react-native";
import { Children } from "react/cjs/react.production.min";
import SelectExerciseButton, { setIsOpen } from "./SelectExerciseButton";
import SelectExerciseModal from "../../Screens/SelectExerciseModal";
import { EXERCISE_DATA } from "../../Screens/SelectExerciseModal";
import { PrContext, PrProvider } from "../../appFunctions/PrContext";

if (
    Platform.OS === "android" &&
    UIManager.setLayoutAnimationEnabledExperimental
  ) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
  }

  const PopDown = () => {
    const value = useContext(PrContext)
    const [isOpen,setIsOpen] = useState(false)
    const [listHeight,setListHeight] = useState(0)
    const [textName,setTextName] = useState(value.exercise);//eventually want to change text based on exercise state
    const toggleOpen = () => {
        setIsOpen(value => !value);
        LayoutAnimation.configureNext(LayoutAnimation.Presets.spring);
        setTextName(value.exercise);

        console.log(value.exercise);
    }
    useEffect(() =>{

        EXERCISE_DATA.forEach(()=>{
            setListHeight(value => value+50)
        })

    },[isOpen])
    return(
        <>
            <TouchableOpacity
                onPress = {toggleOpen}
            >
                <SelectExerciseButton  />
            </TouchableOpacity>
            <View>
                <SelectExerciseModal style = {isOpen ? styles.show: styles.hidden} listHeight = {listHeight} name = {textName}/>
            </View>
        </>
    )
  }

  const styles = StyleSheet.create({
    hidden:{
        height:0,
    },
    show:{ backgroundColor: '#9B9A9A', width: 200 }
  });
export default PopDown;

What I tried

I changed the hidden style height to see if it would render the list that is supposed to pop out of the button. The list did render which means the <selectExerciseButton/> is the only thing not rendering in <popDown/>.

const styles = StyleSheet.create({
    hidden:{
        height:100,
    },
    show:{ backgroundColor: '#9B9A9A', width: 200 }
  });

<TouchableOpacity
                onPress = {toggleOpen}
            >
                {children}
            </TouchableOpacity>
            <View>
                <SelectExerciseModal style = {isOpen ? styles.show: styles.hidden} listHeight = {listHeight} name = {textName}/>
            </View>

<PrProvider>
                <PopDown>
                    <SelectExerciseButton/>
                </PopDown>
                <RepsWeightTextInput/>
                <NotesInput/>
                <SubmitPr/>
                </PrProvider>

SelectExerciseButton

import { useNavigation,useFocusEffect } from "@react-navigation/native";
import { SafeAreaView, StyleSheet, Text, TouchableOpacity, View,LayoutAnimation } from "react-native";
import { useContext, useState,useEffect } from "react";
import { PrContext } from "../../appFunctions/PrContext";
/**
 *
 * @returns button that navigates to the a modal to select an exercise
 */
 if (
    Platform.OS === "android" &&
    UIManager.setLayoutAnimationEnabledExperimental
  ) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
  }

const SelectExerciseButton = () => {
    const value = useContext(PrContext)

    return(
        <>
            <View style = {styles.background}>
                <Text style = {styles.Text}> {value.exercise} </Text>
            </View>
        </>
    );
};

styles = StyleSheet.create({
    background:{
        backgroundColor: '#9B9A9A',
        width: 335,
        borderRadius:41,
        alignItems:'center',
        marginHorizontal:25,
        height:200,
        justifyContent:'center'
    },
    Text:{
        fontWeight:'bold',
        fontSize:40,
        color:'white',
        alignItems:'center'

    }
})
export default SelectExerciseButton;


问:
Is cached Index page stored for all unauthorized users the same or every unauthorized user has its own cache?
I am using cache for my index page in Django project

```<code>from django.views.decorators.cache import cache_page

@cache_page(20, key_prefix='index_page')
def index(request):
    posts = Post.objects.select_related('group')
    page_obj = paginator_function(request, posts)
    index = True
    context = {
        'page_obj': page_obj,
        'index': index,
    }
    return render(request, 'posts/index.html', context)
</code>```

settings.py

```<code> CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        }
    }
</code>```

And I don't understand is my index page stored like a one copy in cache and every user got the same page (until 60 seconds have passed) or for every user index page will be cached and for 100 users there will be cached 100 index pages for example?

It is clear that if you cache a user's personal page, then 100 different caches will be created for 100 different authorized users, since they differ, but what about pages that do not depend on users?

Body:
I am using cache for my index page in Django project

from django.views.decorators.cache import cache_page

@cache_page(20, key_prefix='index_page')
def index(request):
    posts = Post.objects.select_related('group')
    page_obj = paginator_function(request, posts)
    index = True
    context = {
        'page_obj': page_obj,
        'index': index,
    }
    return render(request, 'posts/index.html', context)

settings.py

 CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        }
    }

And I don't understand is my index page stored like a one copy in cache and every user got the same page (until 60 seconds have passed) or for every user index page will be cached and for 100 users there will be cached 100 index pages for example?

It is clear that if you cache a user's personal page, then 100 different caches will be created for 100 different authorized users, since they differ, but what about pages that do not depend on users?


问:
Am having trouble opening a new activity in mainactivity. Kt
Here is My code

```<code>Val i = Intent (this@MainActivity,  secondActivity::class.java)

StartActivity(i)
</code>```

Every time the part ..::class.java has an error..i tried using application context instead of this and also imported the android intent but still the java part is still highlighted

Body:
Here is My code

Val i = Intent (this@MainActivity,  secondActivity::class.java)

StartActivity(i)

Every time the part ..::class.java has an error..i tried using application context instead of this and also imported the android intent but still the java part is still highlighted


问:
How do you change the server header returned by nginx?
I am using Nginx v1.23.3.
I was trying to hide the server header returned by Nginx. But I don't see any option to hide the server header for Nginx v1.23.3.

If I try to install Nginx-extras my Nginx version is downgraded to 1.18.  So is there any solution to hide/remove the server header in the response?


问:
Missing Google Cloud Container Image
I'm trying to solve a tutorial from the Google cloud platform, "Detecting anomalies in financial transactions by using AI Platform, Dataflow, and BigQuery"
But, the docker image required to run the data pipeline is not available in the Google Cloud Container Registry.

The link to the image was this as provided in the tutorial github repo.
But, when triggering the pipeline, it shows the following error.

Title: Missing Google Cloud Container Image


问:
How to build two targets for two language in Swift?
This question is almost the same as Two languages, two apps, but as the question and its answer both originated in 2011, I'm here to ask again.

I know the way to use Localization for different languages, but my situation is a little different. I have a large dictionary file in my App, for each language it's different. Besides that, everything is the same, the logic, the UI.

Is there any better idea than building a new app for each language?


问:
Is it possible to discover all types and functions in a package using reflection?
Is it possible to get all the types and functions defined in a package using reflection at runtime? To make the question clear, in C# we can do this by using a method called ExportedTypes on an assembly and it returns a list of classes.

To be particular, what I need to do is to obtain a list of methods that have a particular return type while being able to invoke them dynamically when required.

Edit: I already know about the AST package, but I am asking in particular about the reflection package.


问:
AttributeError: module 'pyAudioAnalysis.audioTrainTest' has no attribute 'featureAndTrain'
I am having having the error bellow while running my program. I believe there have been some updates on_ PyAudioAnalysis

AttributeError: module 'pyAudioAnalysis.audioTrainTest' has no attribute 'featureAndTrain'

I am wondering if there is a possibility to update this script:

from pyAudioAnalysis import audioTrainTest as aT
aT.featureAndTrain("...")

Thank you :)

Could not find an answer addressed to this issue online


问:
To create a review app, the pipeline owner must first authorize additional charges
I keep on getting an error with message whenever my heroku review app tries to build.

To create a review app, the pipeline owner must first authorize
additional charges

I have already configured my buildpacks, addons and image in the app.json.

Why is this happening and how to fix this?


问:
Facing error while training spacy ner model
I am trying to build Custom NER model using spacy. i have created config file but when i started to train model above error is coming.
============================= Training pipeline =============================
ℹ Pipeline: ['tok2vec', 'ner']
ℹ Initial learn rate: 0.001
E    #       LOSS TOK2VEC  LOSS NER  ENTS_F  ENTS_P  ENTS_R  SCORE

0       0          0.00    388.26    0.00    0.00    0.00    0.00
⚠ Aborting and saving the final best model. Encountered exception: ValueError()
Traceback (most recent call last):
File "C:\Users\Sumit.Mamidwar\Anaconda3\envs\mul_ner\lib\runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\Sumit.Mamidwar\Anaconda3\envs\mul_ner\lib\runpy.py", line 87, in run_code
exec(code, run_globals)
File "C:\Users\Sumit.Mamidwar\AppData\Roaming\Python\Python38\site-packages\spacy_main.py", line 4, in
setup_cli()
File "C:\Users\Sumit.Mamidwar\AppData\Roaming\Python\Python38\site-packages\spacy\cli_util.py", line 68, in setup_cli
command(prog_name=COMMAND)
File "C:\Users\Sumit.Mamidwar\Anaconda3\envs\mul_ner\lib\site-packages\click\core.py", line 829, in call
return self.main(*args, **kwargs)
File "C:\Users\Sumit.Mamidwar\Anaconda3\envs\mul_ner\lib\site-packages\click\core.py", line 782, in main
rv = self.invoke(ctx)
File "C:\Users\Sumit.Mamidwar\Anaconda3\envs\mul_ner\lib\site-packages\click\core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\Sumit.Mamidwar\Anaconda3\envs\mul_ner\lib\site-packages\click\core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Users\Sumit.Mamidwar\Anaconda3\envs\mul_ner\lib\site-packages\click\core.py", line 610, in invoke
return callback(*args, **kwargs)
File "C:\Users\Sumit.Mamidwar\Anaconda3\envs\mul_ner\lib\site-packages\typer\main.py", line 497, in wrapper
return callback(**use_params)  # type: ignore
File "C:\Users\Sumit.Mamidwar\AppData\Roaming\Python\Python38\site-packages\spacy\cli\train.py", line 59, in train_cli
train(nlp, output_path, use_gpu=use_gpu, stdout=sys.stdout, stderr=sys.stderr)
File "C:\Users\Sumit.Mamidwar\AppData\Roaming\Python\Python38\site-packages\spacy\training\loop.py", line 114, in train
raise e
File "C:\Users\Sumit.Mamidwar\AppData\Roaming\Python\Python38\site-packages\spacy\training\loop.py", line 98, in train
for batch, info, is_best_checkpoint in training_step_iterator:
File "C:\Users\Sumit.Mamidwar\AppData\Roaming\Python\Python38\site-packages\spacy\training\loop.py", line 194, in train_while_improving
nlp.update(
File "C:\Users\Sumit.Mamidwar\AppData\Roaming\Python\Python38\site-packages\spacy\language.py", line 1106, in update
proc.update(examples, sgd=None, losses=losses, **component_cfg[name])
File "spacy\pipeline\transition_parser.pyx", line 350, in spacy.pipeline.transition_parser.Parser.update
File "spacy\pipeline\transition_parser.pyx", line 609, in spacy.pipeline.transition_parser.Parser._init_gold_batch
File "spacy\pipeline_parser_internals\transition_system.pyx", line 85, in spacy.pipeline._parser_internals.transition_system.TransitionSystem.get_oracle_sequence_from_state
File "spacy\pipeline_parser_internals\ner.pyx", line 310, in spacy.pipeline._parser_internals.ner.BiluoPushDown.set_costs
ValueError


问:
Smart Banner not coming
I have published my app on iOS Appstore. To show smart banner I use following code on my webpage.

```<code><html>
<head>
<title>Kinjal's Games</title>
<meta name="apple-itunes-app" content="app-id=6444216110, app-clip-bundle-id=com.kinjal.brainbooster"/>
</head>
<body>
    Yo
</body>
</html>
</code>```

When I load webpage, it shows banner for 1 sec and then disappears immediately.

To verify, I tried by using other app's Appstore id. If I try using facebook's app id, it works.

```<code><meta name="apple-itunes-app" content="app-id=284882215, app-clip-bundle-id=com.kinjal.brainbooster"/>
</code>```

But it doesn't work only with my app id

```<code><meta name="apple-itunes-app" content="app-id=6444216110, app-clip-bundle-id=com.kinjal.brainbooster"/>
</code>```

Title: Smart Banner not coming

Body:
I have published my app on iOS Appstore. To show smart banner I use following code on my webpage.

<title>Kinjal's Games</title>
<meta name="apple-itunes-app" content="app-id=6444216110, app-clip-bundle-id=com.kinjal.brainbooster"/>

    Yo

When I load webpage, it shows banner for 1 sec and then disappears immediately.

To verify, I tried by using other app's Appstore id. If I try using facebook's app id, it works.

<meta name="apple-itunes-app" content="app-id=284882215, app-clip-bundle-id=com.kinjal.brainbooster"/>

But it doesn't work only with my app id

<meta name="apple-itunes-app" content="app-id=6444216110, app-clip-bundle-id=com.kinjal.brainbooster"/>


问:
Assimp multiple definition error in material.h when linking across multiple compilation units
I'm following the example provided at https://assimp.sourceforge.net/lib_html/usage.html to import a simple model using the assimp library. The first three lines in the example are the required include statements:

```<code>#include <assimp/cimport.h>        // Plain-C interface
#include <assimp/scene.h>          // Output data structure
#include <assimp/postprocess.h>    // Post processing flags
</code>```

Of these, scene.h seems to be problematic. If you include it AND link against a compilation unit that also includes it, it gives multiple definition errors for aiGetMaterialFloat and aiGetMaterialInteger. A stripped down example is given below:

main.c:

```<code>#include <assimp/cimport.h>        // Plain-C interface
#include <assimp/scene.h>          // Output data structure
#include <assimp/postprocess.h>    // Post processing flags
#include "model.h"
//...
</code>```

model.h:

```<code>#include <assimp/cimport.h>        // Plain-C interface
#include <assimp/scene.h>          // Output data structure
#include <assimp/postprocess.h>    // Post processing flags
//...
</code>```

model.c

```<code>#include "model.h"
</code>```

makefile:

```<code>main: main.c model
    gcc main.c model.o
model: model.c model.h
    gcc -c model.c
</code>```

I'm using MinGW to compile these.

Now this DOES seem to compile if:

main.c does not include model.h, OR

the include statements are removed from model.h, OR

model.o is not linked when compiling main.c, OR

the import for scene.h is removed from one or both files

It will also compile just fine if the #includes are all moved to main.c and the model compilation unit is removed entirely.

Note that if one of the above conditions are met, this compiles just fine without a DLL or static library linked. The problem seems to be exclusively from including the header files.

I've done a lot of research and the only thing I could find is that it might be the inline specifier on these functions that was causing the issue. However, after removing the inline specifiers from the function definitions in the library header file, I'm still getting the same errors. I've been trying to solve this issue for hours and nothing seems to be working. Any ideas?

Body:
I'm following the example provided at https://assimp.sourceforge.net/lib_html/usage.html to import a simple model using the assimp library. The first three lines in the example are the required include statements:

#include <assimp/cimport.h>        // Plain-C interface
#include <assimp/scene.h>          // Output data structure
#include <assimp/postprocess.h>    // Post processing flags

Of these, scene.h seems to be problematic. If you include it AND link against a compilation unit that also includes it, it gives multiple definition errors for aiGetMaterialFloat and aiGetMaterialInteger. A stripped down example is given below:

main.c:

#include <assimp/cimport.h>        // Plain-C interface
#include <assimp/scene.h>          // Output data structure
#include <assimp/postprocess.h>    // Post processing flags
#include "model.h"
//...

model.h:

#include <assimp/cimport.h>        // Plain-C interface
#include <assimp/scene.h>          // Output data structure
#include <assimp/postprocess.h>    // Post processing flags
//...

model.c

#include "model.h"

makefile:

main: main.c model
    gcc main.c model.o
model: model.c model.h
    gcc -c model.c

I'm using MinGW to compile these.

Now this DOES seem to compile if:

main.c does not include model.h, OR

the include statements are removed from model.h, OR

model.o is not linked when compiling main.c, OR

the import for scene.h is removed from one or both files

It will also compile just fine if the #includes are all moved to main.c and the model compilation unit is removed entirely.

Note that if one of the above conditions are met, this compiles just fine without a DLL or static library linked. The problem seems to be exclusively from including the header files.

I've done a lot of research and the only thing I could find is that it might be the inline specifier on these functions that was causing the issue. However, after removing the inline specifiers from the function definitions in the library header file, I'm still getting the same errors. I've been trying to solve this issue for hours and nothing seems to be working. Any ideas?


问:
How to take user to select appWidget to pin into screen From my App
I have developed a Widget for my Android App, and It can be added in following ways.

User can long press in the Home launcher and select Widgets and then drag and drop to Home Launcher Screen, like this -

and then

From the App, in a button click, If

```<code>Build.VERSION_CODES.O && appWidgetManager.isRequestPinAppWidgetSupported is true
</code>```

then we call

```<code> appWidgetManager.requestPinAppWidget
</code>```

And It works, for some devices It doesn't work even if isRequestPinAppWidgetSupported was true.

I am looking for a way to navigate user to 1st way ( going to select widget screen) from my app, whenever isRequestPinAppWidgetSupported was false.

I've used:

```<code>addWidgetActivityLauncher.launch(Intent(AppWidgetManager.ACTION_APPWIDGET_PICK).apply { putExtra(EXTRA_APPWIDGET_ID,requireActivity().appW.allocateAppWidgetId()) })
</code>```

But this opens up a screen like this

,

but clicking on my widget doesn't do anything. Just closes this dialog.

I want to automate the 1st way till the widget selection screen from my app.

PLease help me discover what I am missing.

Body:
I have developed a Widget for my Android App, and It can be added in following ways.

User can long press in the Home launcher and select Widgets and then drag and drop to Home Launcher Screen, like this -

and then

From the App, in a button click, If

Build.VERSION_CODES.O && appWidgetManager.isRequestPinAppWidgetSupported is true

then we call

 appWidgetManager.requestPinAppWidget

And It works, for some devices It doesn't work even if isRequestPinAppWidgetSupported was true.

I am looking for a way to navigate user to 1st way ( going to select widget screen) from my app, whenever isRequestPinAppWidgetSupported was false.

I've used:

addWidgetActivityLauncher.launch(Intent(AppWidgetManager.ACTION_APPWIDGET_PICK).apply { putExtra(EXTRA_APPWIDGET_ID,requireActivity().appW.allocateAppWidgetId()) })

But this opens up a screen like this

,

but clicking on my widget doesn't do anything. Just closes this dialog.

I want to automate the 1st way till the widget selection screen from my app.

PLease help me discover what I am missing.


问:
nginx server on ec2 instance not loading on browser but is running
when i use curl <ip> it shows the correct default nginx html, but it does not load when i try to access from my browser

Security rules

these are my inbound security rules on the ec2 instance