问:
Is there a way to add a box around an 'image()' in R without using segments?
I want to add (add=TRUE) images to a currently existing plot in R. The thing is that I'd like to add a line around my images, but can't find a way to do this without specifying a custom segment

```<code>x <- 10*(1:nrow(volcano))
y <- 10*(1:ncol(volcano))
image(x, y, volcano, col = hcl.colors(100, "terrain"), xlim = c(30,200), ylim = c(50,100))
x2 = 8*(1:nrow(volcano))+50
y2 = 8*(1:ncol(volcano))+50
image(x2, y2, volcano, col = hcl.colors(100, "terrain"), add = T)
box()
</code>```

Adding the black lines based on the minimum and maximum values in X and Y:

```<code>lwd = .5
# Left
segments(x0 = min(x2), y0 = min(y2), x1 = min(x2), y1 = max(y2), lwd = lwd)
# top
segments(x0 = min(x2), y0 = max(y2), x1 = max(x2), y1 = max(y2), lwd = lwd)
# right
segments(x0 = max(x2), y0 = max(y2), x1 = max(x2), y1 = min(y2), lwd = lwd)
# Bottom
segments(x0 = max(x2), y0 = min(y2), x1 = min(x2), y1 = min(y2), lwd = lwd)
</code>```

Custom segments around the image with some trial and error for the adjustment of the lines.

```<code># Left
xleft = -4
yleft = -4
segments(x0 = min(x2)+xleft, y0 = min(y2)+yleft, x1 = min(x2)+xleft, y1 = max(y2)+yleft, lwd = 2, col = "red")

# Bottom
xbot = -4
ybot = -4
segments(x0 = max(x2)+xbot, y0 = min(y2)+ybot, x1 = min(x2)+xbot, y1 = min(y2)+ybot, lwd = 2, col = "red")
</code>```

I added the red line, but I'd like to have a function that can add it for me automatically. Is there a function that does that in R? I want to do this because I have multiple images with multiple x and y corrections and don't want to tweak each image separately.

box() doesn't do it, and adding segments based on min and max doesn't either.

Body:
I want to add (add=TRUE) images to a currently existing plot in R. The thing is that I'd like to add a line around my images, but can't find a way to do this without specifying a custom segment

x <- 10*(1:nrow(volcano))
y <- 10*(1:ncol(volcano))
image(x, y, volcano, col = hcl.colors(100, "terrain"), xlim = c(30,200), ylim = c(50,100))
x2 = 8*(1:nrow(volcano))+50
y2 = 8*(1:ncol(volcano))+50
image(x2, y2, volcano, col = hcl.colors(100, "terrain"), add = T)
box()

Adding the black lines based on the minimum and maximum values in X and Y:

lwd = .5
# Left
segments(x0 = min(x2), y0 = min(y2), x1 = min(x2), y1 = max(y2), lwd = lwd)
# top
segments(x0 = min(x2), y0 = max(y2), x1 = max(x2), y1 = max(y2), lwd = lwd)
# right
segments(x0 = max(x2), y0 = max(y2), x1 = max(x2), y1 = min(y2), lwd = lwd)
# Bottom
segments(x0 = max(x2), y0 = min(y2), x1 = min(x2), y1 = min(y2), lwd = lwd)

Custom segments around the image with some trial and error for the adjustment of the lines.

# Left
xleft = -4
yleft = -4
segments(x0 = min(x2)+xleft, y0 = min(y2)+yleft, x1 = min(x2)+xleft, y1 = max(y2)+yleft, lwd = 2, col = "red")

# Bottom
xbot = -4
ybot = -4
segments(x0 = max(x2)+xbot, y0 = min(y2)+ybot, x1 = min(x2)+xbot, y1 = min(y2)+ybot, lwd = 2, col = "red")

I added the red line, but I'd like to have a function that can add it for me automatically. Is there a function that does that in R? I want to do this because I have multiple images with multiple x and y corrections and don't want to tweak each image separately.

box() doesn't do it, and adding segments based on min and max doesn't either.


来源: stackexchange

问:
Insert equation plugin of Zim does not find Latex
I have installed Zim on my MacBook. I already have Latex installed. When I try to add the "Insert Equation" plugin, the following errors are shown:

Dependencies

latex - Failed

dvipng - Failed

It is worth mentioning that when I type "latex" or "dvipng" in the terminal, I see that the corresponsing program is called. So, the installation of Latex seems fine.

How to solve this issue?

ContentLicense: CC BY-SA 4.0


问:
Storing relation in RavenDB without manually storing the related documents?

TLDR:

Is it possible to:

store a document (Article) with a relation (Tags) in one Store/StoreAsync call to RavenDB, but into separate collections?

then fetch the parent document (Article) including the related documents (Tags) in one query (without including/loading the tags separately)?

Explanation

AFAIK the only way to store data to RavenDB which have a relation into separate collections is to store them individually. When you read the data, you need to Include the related documents and call Load to get them.

I wonder if there is a way to simplify this by storing and querying Articles and related Tags in one go.

I have a idea how I wish it would work (but it does not), as well a working but cumbersome example.

The examples below are split into these steps

POCOs

Storing data

Index definition

Querying the index

I put the broken-but-I-wish-it-would-work and the working examples next to each other. I think it is easier to understand it that way.

POCOs

broken-but-I-wish-it-would-work

namespace Articles
{
    public class ArticlePersistance
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public List<TagPersistance> Tags { get; set; } // Specify TagPersistance here
    }

    [DearRavenDBStoreToSeparateCollectionPlease] // Does not exist
    public class TagPersistance
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
}
```
<p><strong>working</strong></p>
<pre class="lang-csharp prettyprint-override"><code>namespace Articles
{
    public class ArticlePersistance
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public List<string> Tags { get; set; } // Specify string here
    }

    public class TagPersistance
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
}
</code>```

Storing data

broken-but-I-wish-it-would-work

Storing ArticlePersistance and TagPersistance into their own collections with one call to StoreAsync. AFAIK this stores the Article and Tags into the same collection.

var tag = new TagPersistance() { Name = "Tag1" };
var article = new ArticlePersistance()
{
    Title = "aaa",
    Tags = new List<TagPersistance> { tag } // Embed the full Tag here
};
await session.StoreAsync(article); // Only one call to StoreAsync
await session.SaveChangesAsync();
```
<p><strong>working</strong><br />
Storing the Article and Tags separately:</p>
<pre class="lang-csharp prettyprint-override"><code>var tag = new TagPersistance() { Name = "Tag1" };
await session.StoreAsync(tag); // Store Tag separately

var article = new ArticlePersistance()
{
    Title = "aaa",
    Tags = new List<string> { tag.Id } // Embed only the tag id
};
await session.StoreAsync(article);

await session.SaveChangesAsync();
</code>```

Index definition

broken-but-I-wish-it-would-work

Index on ArticlePersistance which stores the full Tag objects

public class Articles_Test : AbstractIndexCreationTask<ArticlePersistance>
{
    public Articles_Test()
    {
        Map = articles =>
               from article in articles
               let tags = article.Tags.Select(t => LoadDocument<TagPersistance>(t)) // Load the related Tags
               select new
               {
                   Title = article.Title,
                   Tags = tags // Store the full Tag objects here
               };
    }
}
```
<p><strong>working</strong><br />
Index which holds only the Tag names, not the full Tag objects:</p>
<pre class="lang-csharp prettyprint-override"><code>public class Articles_Test : AbstractIndexCreationTask<ArticlePersistance>
{
    public Articles_Test()
    {
        Map = articles =>
               from article in articles
               let tags = article.Tags.Select(t => LoadDocument<TagPersistance>(t)) // Load the related Tags
               select new
               {
                   Title = article.Title,
                   Tags = tags.Select(t => t.Name) // Store only the Tag name
               };
    }
}
</code>```

Querying the index

broken-but-I-wish-it-would-work

Finally querying the index and getting the article with the tags back.
I hoped for fetching the Article and the Tags in one go here

// This does not work
var article = await session
    .Query<ArticlePersistance, Articles_Test>()
    .Where(a => a.Title == "aaa")
    .ToListAsync();
```
<p><strong>working</strong><br />
This is working, but cumbersome.
You need to care about the relation between Article and Tags which could already be specified in the Index definition.</p>
<pre class="lang-csharp prettyprint-override"><code>var article = await session
    .Query<ArticlePersistance, Articles_Test>()
    .Where(a => a.Title == "aaa")
    .Include(t => t.Tags) // Include the tags
    .ToListAsync();
// Query the tags separatelly
var tags = await session.LoadAsync<TagPersistance>(article.SelectMany(a => a.Tags));
</code>```

Body:
TLDR:

Is it possible to:

store a document (Article) with a relation (Tags) in one Store/StoreAsync call to RavenDB, but into separate collections?

then fetch the parent document (Article) including the related documents (Tags) in one query (without including/loading the tags separately)?

Explanation

AFAIK the only way to store data to RavenDB which have a relation into separate collections is to store them individually. When you read the data, you need to Include the related documents and call Load to get them.

I wonder if there is a way to simplify this by storing and querying Articles and related Tags in one go.

I have a idea how I wish it would work (but it does not), as well a working but cumbersome example.

The examples below are split into these steps

POCOs

Storing data

Index definition

Querying the index

I put the broken-but-I-wish-it-would-work and the working examples next to each other. I think it is easier to understand it that way.

POCOs

broken-but-I-wish-it-would-work

namespace Articles
{
    public class ArticlePersistance
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public List<TagPersistance> Tags { get; set; } // Specify TagPersistance here
    }

    [DearRavenDBStoreToSeparateCollectionPlease] // Does not exist
    public class TagPersistance
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
}

working

namespace Articles
{
    public class ArticlePersistance
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public List<string> Tags { get; set; } // Specify string here
    }

    public class TagPersistance
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
}

Storing data

broken-but-I-wish-it-would-work

Storing ArticlePersistance and TagPersistance into their own collections with one call to StoreAsync. AFAIK this stores the Article and Tags into the same collection.

var tag = new TagPersistance() { Name = "Tag1" };
var article = new ArticlePersistance()
{
    Title = "aaa",
    Tags = new List<TagPersistance> { tag } // Embed the full Tag here
};
await session.StoreAsync(article); // Only one call to StoreAsync
await session.SaveChangesAsync();

working

Storing the Article and Tags separately:

var tag = new TagPersistance() { Name = "Tag1" };
await session.StoreAsync(tag); // Store Tag separately

var article = new ArticlePersistance()
{
    Title = "aaa",
    Tags = new List<string> { tag.Id } // Embed only the tag id
};
await session.StoreAsync(article);

await session.SaveChangesAsync();

Index definition

broken-but-I-wish-it-would-work

Index on ArticlePersistance which stores the full Tag objects

public class Articles_Test : AbstractIndexCreationTask<ArticlePersistance>
{
    public Articles_Test()
    {
        Map = articles =>
               from article in articles
               let tags = article.Tags.Select(t => LoadDocument<TagPersistance>(t)) // Load the related Tags
               select new
               {
                   Title = article.Title,
                   Tags = tags // Store the full Tag objects here
               };
    }
}

working

Index which holds only the Tag names, not the full Tag objects:

public class Articles_Test : AbstractIndexCreationTask<ArticlePersistance>
{
    public Articles_Test()
    {
        Map = articles =>
               from article in articles
               let tags = article.Tags.Select(t => LoadDocument<TagPersistance>(t)) // Load the related Tags
               select new
               {
                   Title = article.Title,
                   Tags = tags.Select(t => t.Name) // Store only the Tag name
               };
    }
}

Querying the index

broken-but-I-wish-it-would-work

Finally querying the index and getting the article with the tags back.
I hoped for fetching the Article and the Tags in one go here

// This does not work
var article = await session
    .Query<ArticlePersistance, Articles_Test>()
    .Where(a => a.Title == "aaa")
    .ToListAsync();

working

This is working, but cumbersome.
You need to care about the relation between Article and Tags which could already be specified in the Index definition.

var article = await session
    .Query<ArticlePersistance, Articles_Test>()
    .Where(a => a.Title == "aaa")
    .Include(t => t.Tags) // Include the tags
    .ToListAsync();
// Query the tags separatelly
var tags = await session.LoadAsync<TagPersistance>(article.SelectMany(a => a.Tags));


问:
add files to root and access it within Android Studio Project
in java you could add the file within the project so you could use it on any device, i.e if the file is "data.dat" in java I could put the file in the project root and write this line

```<code>try (ObjectInputStream input = new ObjectInputStream(new FileInputStream("data.dat')))
</code>```

unfortunately I couldn't do this in android studio can someone please explain

in Android Studio it always gives me FileNotFoundException, I even tried using the absolute path but it didn't work, any Idea on how to do it?

Body:
in java you could add the file within the project so you could use it on any device, i.e if the file is "data.dat" in java I could put the file in the project root and write this line

try (ObjectInputStream input = new ObjectInputStream(new FileInputStream("data.dat')))

unfortunately I couldn't do this in android studio can someone please explain

in Android Studio it always gives me FileNotFoundException, I even tried using the absolute path but it didn't work, any Idea on how to do it?


问:
Test scroll inside select using react testing library
I am testing a select element from the "react-select" library

//SelectApi.js

```<code> <Select
                isClearable={false}
                value={value}
                options={options}
                className='react-select'
                classNamePrefix='select'
                theme={selectThemeColors}
                aria-label={ariaLabel}
                onMenuScrollToBottom={handleScroll}
                onInputChange={handleDBInputChange}
                onChange={handleChange}
            />
</code>```

But I don't know how to test the "onMenuScrollToBottom" part to activate the "handleScroll" function

```<code> const handleScroll = () => {
        let newSkip = skip + limit
        setSkip(newSkip)
    }
</code>```

For unit tests I am using the library "react-testing-library"

//SelectApi.test.js

```<code>    test("scroll in select", async () => {

        let value = jest.fn()
        let updateValue = jest.fn()
        let apiUrl = "/api/promoters/data"
        let ariaLabel = "selectPromoterFilter"

        const promotersOptions = [
            {
                id: 0,
                label: "Select Promoter",
                value: ""
            },
            {
                id: 1,
                label: "Ernesto Luna Hernández",
                value: 1
            },
            {
                id: 2,
                label: "María Fernanda Lopéz Barilla",
                value: 2
            },
            {
                id: 3,
                label: "Ricardo Gómez Robles",
                value: 3
            },
            {
                id: 4,
                label: "Ricardo Gómez Robles",
                value: 3
            },
            {
                id: 5,
                label: "Ricardo Gómez Robles",
                value: 5
            },
            {
                id: 6,
                label: "Ricardo Gómez Robles",
                value: 6
            },
            {
                id: 7,
                label: "Ricardo Gómez Robles",
                value: 7
            },
            {
                id: 8,
                label: "Ricardo Gómez Robles",
                value: 8
            },
            {
                id: 9,
                label: "Ricardo Gómez Robles",
                value: 9
            },
            {
                id: 10,
                label: "Final",
                value: 10
            }
        ]
        jest.spyOn(axios, 'get').mockResolvedValueOnce({ data: promotersOptions});

        let container
        await act(async () => {
            container = render(
                <Router>
                    <Provider store={store}>
                        <SelectApi
                            value={value}
                            updateValue={updateValue}
                            apiUrl={apiUrl}
                            ariaLabel={ariaLabel}
                        />
                    </Provider>
                </Router>
            )
        })

        const selectPromoter = container.queryByLabelText(ariaLabel)
        if (selectPromoter) {
            await act(async () => {
                fireEvent.click(selectPromoter)
                fireEvent.scroll(selectPromoter, { target: { scrollY: 400 } });

            })

        }

    })
</code>```

The solution of how I can activate the scroll inside the select to complete the coverage of the component

Body:
I am testing a select element from the "react-select" library

//SelectApi.js

 <Select
                isClearable={false}
                value={value}
                options={options}
                className='react-select'
                classNamePrefix='select'
                theme={selectThemeColors}
                aria-label={ariaLabel}
                onMenuScrollToBottom={handleScroll}
                onInputChange={handleDBInputChange}
                onChange={handleChange}
            />

But I don't know how to test the "onMenuScrollToBottom" part to activate the "handleScroll" function

 const handleScroll = () => {
        let newSkip = skip + limit
        setSkip(newSkip)
    }

For unit tests I am using the library "react-testing-library"

//SelectApi.test.js

    test("scroll in select", async () => {

        let value = jest.fn()
        let updateValue = jest.fn()
        let apiUrl = "/api/promoters/data"
        let ariaLabel = "selectPromoterFilter"

        const promotersOptions = [
            {
                id: 0,
                label: "Select Promoter",
                value: ""
            },
            {
                id: 1,
                label: "Ernesto Luna Hernández",
                value: 1
            },
            {
                id: 2,
                label: "María Fernanda Lopéz Barilla",
                value: 2
            },
            {
                id: 3,
                label: "Ricardo Gómez Robles",
                value: 3
            },
            {
                id: 4,
                label: "Ricardo Gómez Robles",
                value: 3
            },
            {
                id: 5,
                label: "Ricardo Gómez Robles",
                value: 5
            },
            {
                id: 6,
                label: "Ricardo Gómez Robles",
                value: 6
            },
            {
                id: 7,
                label: "Ricardo Gómez Robles",
                value: 7
            },
            {
                id: 8,
                label: "Ricardo Gómez Robles",
                value: 8
            },
            {
                id: 9,
                label: "Ricardo Gómez Robles",
                value: 9
            },
            {
                id: 10,
                label: "Final",
                value: 10
            }
        ]
        jest.spyOn(axios, 'get').mockResolvedValueOnce({ data: promotersOptions});

        let container
        await act(async () => {
            container = render(
                <Router>
                    <Provider store={store}>
                        <SelectApi
                            value={value}
                            updateValue={updateValue}
                            apiUrl={apiUrl}
                            ariaLabel={ariaLabel}
                        />
                    </Provider>
                </Router>
            )
        })

        const selectPromoter = container.queryByLabelText(ariaLabel)
        if (selectPromoter) {
            await act(async () => {
                fireEvent.click(selectPromoter)
                fireEvent.scroll(selectPromoter, { target: { scrollY: 400 } });

            })

        }

    })

The solution of how I can activate the scroll inside the select to complete the coverage of the component


问:
How do I sanitize/add prepared statements to my PHP website
I'm doing a school project writing a simple website (in this case, the theme is Harry Potter)
One page is supposed to display infomation from MySQL database about the different houses.

```<code><?php
    $dbname = 'hogwarts';
    $dbuser = 'Albus';
    $dbpass = 'SherbertLemon';
    $dbhost = 'localhost';

    $link = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
    mysqli_select_db($link, $dbname) or die("Could not open the db '$dbname'");
      $housename = '';
      if (isset($_GET['house'])) {
        $housename = $_GET['house'];
        $sql = "SELECT info FROM houses WHERE name='$housename'";
        $result = mysqli_query($link,$sql);

        if (!$result) { echo "Could not get data."; }
        else {
            $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
            $info = "{$row['info']}";
        }
      }
?>
</code>```

Now, as it were, the line  $sql = "SELECT info FROM houses WHERE name='$housename'"; allows for SQL-injections and my question is - how do I sanitize and/or turn this into prepared statements to prevent and better secure my site?

Kindest regards

EDIT
I tried query parameters as suggested and this is what I came up with. It works and SQLmap finds no injection points :)

```<code><?php
    $dbname = 'hogwarts';
    $dbuser = 'Albus';
    $dbpass = 'SherbertLemon';
    $dbhost = 'localhost';
    $info = "Not found";
    $link = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
    mysqli_select_db($link, $dbname) or die("Could not open the db '$dbname'");
      $housename = '';
      if (isset($_GET['house'])) {
        $housename = $_GET['house'];

        $stmt = $link->prepare("SELECT info FROM houses WHERE name=?");
        $stmt->bind_param("s",$housename);
        $stmt->execute();
        $result = $stmt->get_result();

        //$sql = "SELECT info FROM houses WHERE name='$housename'";
        //$result = mysqli_query($link,$sql);

        if (!$result) { echo "Could not get data."; }
        else {
            $row = mysqli_fetch_array($result,MYSQLI_ASSOC);

         if    ($row)
            $info = "{$row['info']}";
        }
      }
?>
</code>```

Body:
I'm doing a school project writing a simple website (in this case, the theme is Harry Potter)
One page is supposed to display infomation from MySQL database about the different houses.

<?php
    $dbname = 'hogwarts';
    $dbuser = 'Albus';
    $dbpass = 'SherbertLemon';
    $dbhost = 'localhost';

    $link = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
    mysqli_select_db($link, $dbname) or die("Could not open the db '$dbname'");
      $housename = '';
      if (isset($_GET['house'])) {
        $housename = $_GET['house'];
        $sql = "SELECT info FROM houses WHERE name='$housename'";
        $result = mysqli_query($link,$sql);

        if (!$result) { echo "Could not get data."; }
        else {
            $row = mysqli_fetch_array($result,MYSQLI_ASSOC);
            $info = "{$row['info']}";
        }
      }
?>

Now, as it were, the line  $sql = "SELECT info FROM houses WHERE name='$housename'"; allows for SQL-injections and my question is - how do I sanitize and/or turn this into prepared statements to prevent and better secure my site?

Kindest regards

EDIT
I tried query parameters as suggested and this is what I came up with. It works and SQLmap finds no injection points :)

<?php
    $dbname = 'hogwarts';
    $dbuser = 'Albus';
    $dbpass = 'SherbertLemon';
    $dbhost = 'localhost';
    $info = "Not found";
    $link = mysqli_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
    mysqli_select_db($link, $dbname) or die("Could not open the db '$dbname'");
      $housename = '';
      if (isset($_GET['house'])) {
        $housename = $_GET['house'];

        $stmt = $link->prepare("SELECT info FROM houses WHERE name=?");
        $stmt->bind_param("s",$housename);
        $stmt->execute();
        $result = $stmt->get_result();

        //$sql = "SELECT info FROM houses WHERE name='$housename'";
        //$result = mysqli_query($link,$sql);

        if (!$result) { echo "Could not get data."; }
        else {
            $row = mysqli_fetch_array($result,MYSQLI_ASSOC);

         if    ($row)
            $info = "{$row['info']}";
        }
      }
?>


问:
Render quasar components that came from outside with fetching, onMounted
I want to fetch data from my CMS and render Quasar Framework components inside of it in Quasar Cli

In quasar.config.js -> build:

```<code>extendViteConf(viteConf, {}) {
                viteConf.resolve.alias.vue = "vue/dist/vue.esm-bundler.js";
            },
</code>```

Boot file:

```<code>export default boot(({ app }) => {
    child_app = createApp({
        data() {
            return {
                message: "",
            };
        },
    });
    child_app.use(Quasar, {
        plugins: {}, // import Quasar plugins and add here
    });

    child_app.config.globalProperties = app.config.globalProperties;

    const { reload, ...appContext } = app._context;
    Object.assign(child_app._context, appContext);
});
</code>```

Getting this error:

```<code>runtime-core.esm-bundler.js:40 [Vue warn]: Failed to resolve component: q-carousel-slide
If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.
  at <App>
</code>```

I tried adding this but then, there is no rendering in the end;

```<code>child_app.config.compilerOptions.isCustomElement = (tag) => {
        return tag.startsWith("q-");
    };
</code>```

Only working solution I found is using Quasar UMD for mounted data :-/

I would prefer preventing double loading vue and quasar if possible.

Body:
I want to fetch data from my CMS and render Quasar Framework components inside of it in Quasar Cli

In quasar.config.js -> build:

extendViteConf(viteConf, {}) {
                viteConf.resolve.alias.vue = "vue/dist/vue.esm-bundler.js";
            },

Boot file:

export default boot(({ app }) => {
    child_app = createApp({
        data() {
            return {
                message: "",
            };
        },
    });
    child_app.use(Quasar, {
        plugins: {}, // import Quasar plugins and add here
    });

    child_app.config.globalProperties = app.config.globalProperties;

    const { reload, ...appContext } = app._context;
    Object.assign(child_app._context, appContext);
});

Getting this error:

runtime-core.esm-bundler.js:40 [Vue warn]: Failed to resolve component: q-carousel-slide
If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.
  at <App>

I tried adding this but then, there is no rendering in the end;

child_app.config.compilerOptions.isCustomElement = (tag) => {
        return tag.startsWith("q-");
    };

Only working solution I found is using Quasar UMD for mounted data :-/

I would prefer preventing double loading vue and quasar if possible.


问:
Importing data from Flat file into Teradata table
I have a tab delimited flat file(.txt) like below and i want to import data into one Teradata table whose datatype is mentioned:

```<code>CALENDAR_DATE NRDP_ETL_SCOPE_START_DATE FISCAL_PERIOD_WEEK
12/30/2022  12/22/2022  2022-01 W2
12/31/2022  12/22/2022  2022-01 W2
1/1/2023    12/22/2022  2022-01 W2
1/2/2023    12/22/2022  2022-01 W2
1/28/2023   1/22/2023   2023-02 W2
1/29/2023   1/22/2023   2023-02 W2

  CALENDAR_DATE DATE FORMAT 'YY/MM/DD' NOT NULL
  ETL_SCOPE_START_DATE DATE FORMAT 'YYYY-MM-DD' NOT NULL
  FISCAL_PERIOD_WEEK VARCHAR(10) CHARACTER SET LATIN NOT CASESPECIFIC
</code>```

I have tried something like below but that is failing:

```<code>insert into ABC.TABLENAME values (TO_DATE(?,'YY/MM/DD'),TO_DATE(?,'YYYY-MM-DD'),?);
</code>```

Can you please help me with that?

Thanks,
Debasis

Body:
I have a tab delimited flat file(.txt) like below and i want to import data into one Teradata table whose datatype is mentioned:

CALENDAR_DATE NRDP_ETL_SCOPE_START_DATE FISCAL_PERIOD_WEEK
12/30/2022  12/22/2022  2022-01 W2
12/31/2022  12/22/2022  2022-01 W2
1/1/2023    12/22/2022  2022-01 W2
1/2/2023    12/22/2022  2022-01 W2
1/28/2023   1/22/2023   2023-02 W2
1/29/2023   1/22/2023   2023-02 W2

  CALENDAR_DATE DATE FORMAT 'YY/MM/DD' NOT NULL
  ETL_SCOPE_START_DATE DATE FORMAT 'YYYY-MM-DD' NOT NULL
  FISCAL_PERIOD_WEEK VARCHAR(10) CHARACTER SET LATIN NOT CASESPECIFIC

I have tried something like below but that is failing:

insert into ABC.TABLENAME values (TO_DATE(?,'YY/MM/DD'),TO_DATE(?,'YYYY-MM-DD'),?);

Can you please help me with that?

Thanks,
Debasis


问:
GODOT : can get_string_from_utf8() work with other language?
var keytyped = PoolByteArray([typedevent.unicode]).getstringfrom_utf8()

code above is working fine with english language
but its dont work with Thai language

if i typed [A] its will recognize as [A]
but if i typed [ร] (locate at [I] key) its will recognize as [#] instead of [ร]

is it a way to make it work?

Godot version v3.5.1.stable.official [6fed1ffa3]


问:
Quantity field input on related products (woocommerce) doesn't appear
I'm using this hook to show a quantity input on all my woocommerce_loop_add_to_cart_link, but in the related products widget, is the only place that the woocommerce_quantity_input() (input element) doesn't even appear.
Do you know why?

```<code>add_filter( 'woocommerce_loop_add_to_cart_link', function( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
        $html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="wcb2b-quantity" method="post" enctype="multipart/form-data" >';
        $html .= woocommerce_quantity_input( array(), $product, false );
        $html .= '<button type="submit" class="button alt">' . esc_html( $product->add_to_cart_text() ) . '</button>';
        $html .= '</form>';

    }
    return $html;
</code>```

the woocommerce_quantity_input() is defined here

```<code>function woocommerce_quantity_input( $args = array(), $product = null, $echo = true ) {
    if ( is_null( $product ) ) {
        $product = $GLOBALS['product'];
    }

    $defaults = array(
        'input_id'     => uniqid( 'quantity_' ),
        'input_name'   => 'quantity',
        'input_value'  => '1',
        'classes'      => apply_filters( 'woocommerce_quantity_input_classes', array( 'input-text', 'qty', 'text' ), $product ),
        'max_value'    => apply_filters( 'woocommerce_quantity_input_max', -1, $product ),
        'min_value'    => apply_filters( 'woocommerce_quantity_input_min', 0, $product ),
        'step'         => apply_filters( 'woocommerce_quantity_input_step', 1, $product ),
        'pattern'      => apply_filters( 'woocommerce_quantity_input_pattern', has_filter( 'woocommerce_stock_amount', 'intval' ) ? '[0-9]*' : '' ),
        'inputmode'    => apply_filters( 'woocommerce_quantity_input_inputmode', has_filter( 'woocommerce_stock_amount', 'intval' ) ? 'numeric' : '' ),
        'product_name' => $product ? $product->get_title() : '',
        'placeholder'  => apply_filters( 'woocommerce_quantity_input_placeholder', '', $product ),
        // When autocomplete is enabled in firefox, it will overwrite actual value with what user entered last. So we default to off.
        // See @link https://github.com/woocommerce/woocommerce/issues/30733.
        'autocomplete' => apply_filters( 'woocommerce_quantity_input_autocomplete', 'off', $product ),
    );

    $args = apply_filters( 'woocommerce_quantity_input_args', wp_parse_args( $args, $defaults ), $product );

    // Apply sanity to min/max args - min cannot be lower than 0.
    $args['min_value'] = max( $args['min_value'], 0 );
    $args['max_value'] = 0 < $args['max_value'] ? $args['max_value'] : '';

    // Max cannot be lower than min if defined.
    if ( '' !== $args['max_value'] && $args['max_value'] < $args['min_value'] ) {
        $args['max_value'] = $args['min_value'];
    }

    ob_start();

    wc_get_template( 'global/quantity-input.php', $args );

    if ( $echo ) {
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo ob_get_clean();
    } else {
        return ob_get_clean();
    }
}
</code>```

Related product screenshot: https://ibb.co/vw6Rt4d
Other loops screenshot: https://ibb.co/pRcpBRp

```<code></code>```

Body:
I'm using this hook to show a quantity input on all my woocommerce_loop_add_to_cart_link, but in the related products widget, is the only place that the woocommerce_quantity_input() (input element) doesn't even appear.
Do you know why?

add_filter( 'woocommerce_loop_add_to_cart_link', function( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
        $html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="wcb2b-quantity" method="post" enctype="multipart/form-data" >';
        $html .= woocommerce_quantity_input( array(), $product, false );
        $html .= '<button type="submit" class="button alt">' . esc_html( $product->add_to_cart_text() ) . '</button>';
        $html .= '</form>';

    }
    return $html;

the woocommerce_quantity_input() is defined here

function woocommerce_quantity_input( $args = array(), $product = null, $echo = true ) {
    if ( is_null( $product ) ) {
        $product = $GLOBALS['product'];
    }

    $defaults = array(
        'input_id'     => uniqid( 'quantity_' ),
        'input_name'   => 'quantity',
        'input_value'  => '1',
        'classes'      => apply_filters( 'woocommerce_quantity_input_classes', array( 'input-text', 'qty', 'text' ), $product ),
        'max_value'    => apply_filters( 'woocommerce_quantity_input_max', -1, $product ),
        'min_value'    => apply_filters( 'woocommerce_quantity_input_min', 0, $product ),
        'step'         => apply_filters( 'woocommerce_quantity_input_step', 1, $product ),
        'pattern'      => apply_filters( 'woocommerce_quantity_input_pattern', has_filter( 'woocommerce_stock_amount', 'intval' ) ? '[0-9]*' : '' ),
        'inputmode'    => apply_filters( 'woocommerce_quantity_input_inputmode', has_filter( 'woocommerce_stock_amount', 'intval' ) ? 'numeric' : '' ),
        'product_name' => $product ? $product->get_title() : '',
        'placeholder'  => apply_filters( 'woocommerce_quantity_input_placeholder', '', $product ),
        // When autocomplete is enabled in firefox, it will overwrite actual value with what user entered last. So we default to off.
        // See @link https://github.com/woocommerce/woocommerce/issues/30733.
        'autocomplete' => apply_filters( 'woocommerce_quantity_input_autocomplete', 'off', $product ),
    );

    $args = apply_filters( 'woocommerce_quantity_input_args', wp_parse_args( $args, $defaults ), $product );

    // Apply sanity to min/max args - min cannot be lower than 0.
    $args['min_value'] = max( $args['min_value'], 0 );
    $args['max_value'] = 0 < $args['max_value'] ? $args['max_value'] : '';

    // Max cannot be lower than min if defined.
    if ( '' !== $args['max_value'] && $args['max_value'] < $args['min_value'] ) {
        $args['max_value'] = $args['min_value'];
    }

    ob_start();

    wc_get_template( 'global/quantity-input.php', $args );

    if ( $echo ) {
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        echo ob_get_clean();
    } else {
        return ob_get_clean();
    }
}

Related product screenshot: https://ibb.co/vw6Rt4d
Other loops screenshot: https://ibb.co/pRcpBRp


问:
App on Android emulator cannot connect to local API
I'm building a mobile app in React with Ionic and Capacitor.
I'm running a local server with a local API built with Strapi (a headless CMS) that is running on localhost:9000.

I'm having a hell of a time trying to connect my local API to my Ionic app on an Android emulator. The connection works fine on a development server on a web browser. My emulator can also access my local API on a web browser. My app, however, cannot connect to the API when it is running on an emulator.

Here's how I have proceeded so far:

in the .env file of my ionic-react app, I have set the URI to my local API. I have replaced "localhost" with my IP address :

REACT_APP_API_URL = "http://192.168.1.31:9000"

in the gradle.properties file of my app, I have added proxy settings:

```<code>systemProp.http.proxyHost=192.168.1.31
systemProp.http.proxyPort=9000
systemProp.https.proxyHost=192.168.1.31
systemProp.https.proxyPort=9000
</code>```

in the AndroidManifest.xml file of my app, I have added two permissions:

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</code>```

Observations:

(✔) When I run ionic serve to launch a development server in a browser on my local machine, the HTTP requests execute fine. I can fetch my data.

(❌) When I run the app in Android Studio on an emulator, the HTTP requests fail ("Type Error : fetch failed").

(✔) Yet, when I open a web browser on the aforementioned emulator and try to access my API on 192.168.1.31:9000/api/games, I get a valid response.

The emulator can access my local API, but my app running on the emulator, cannot. It baffles me. Does anyone have an idea what I'm doing wrong?

I have tried replacing my IP address with 10.0.2.2 in the config files, with no success.

From left to right:

my app in a web browser,

my app on an emulator (with an empty carousel because the HTTP request failed),

a web browser on the emulator trying to access the API and getting a valid response.

Body:
I'm building a mobile app in React with Ionic and Capacitor.
I'm running a local server with a local API built with Strapi (a headless CMS) that is running on localhost:9000.

I'm having a hell of a time trying to connect my local API to my Ionic app on an Android emulator. The connection works fine on a development server on a web browser. My emulator can also access my local API on a web browser. My app, however, cannot connect to the API when it is running on an emulator.

Here's how I have proceeded so far:

in the .env file of my ionic-react app, I have set the URI to my local API. I have replaced "localhost" with my IP address :

REACT_APP_API_URL = "http://192.168.1.31:9000"

in the gradle.properties file of my app, I have added proxy settings:

systemProp.http.proxyHost=192.168.1.31
systemProp.http.proxyPort=9000
systemProp.https.proxyHost=192.168.1.31
systemProp.https.proxyPort=9000

in the AndroidManifest.xml file of my app, I have added two permissions:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Observations:

(✔) When I run ionic serve to launch a development server in a browser on my local machine, the HTTP requests execute fine. I can fetch my data.

(❌) When I run the app in Android Studio on an emulator, the HTTP requests fail ("Type Error : fetch failed").

(✔) Yet, when I open a web browser on the aforementioned emulator and try to access my API on 192.168.1.31:9000/api/games, I get a valid response.

The emulator can access my local API, but my app running on the emulator, cannot. It baffles me. Does anyone have an idea what I'm doing wrong?

I have tried replacing my IP address with 10.0.2.2 in the config files, with no success.

From left to right:

my app in a web browser,

my app on an emulator (with an empty carousel because the HTTP request failed),

a web browser on the emulator trying to access the API and getting a valid response.


问:
WPF INotifyPropertyChanged from non-ui thread
I have a set of properties which are binding in my view, like:

```<code>private int _workDone;
public int WorkDone
{
   get{return _workDone;}
   set
   {
       _workDone = value;
       OnPropertyChanged();
   }

}
</code>```

Now, this property is binding to my progress bar and it's being changed from a non-ui thread, problem is the whole progress bar goes from 0 to 100 in a second, am I allowed to raise INotifyPropertyChanged from non-ui threads?

Body:
I have a set of properties which are binding in my view, like:

private int _workDone;
public int WorkDone
{
   get{return _workDone;}
   set
   {
       _workDone = value;
       OnPropertyChanged();
   }

}

Now, this property is binding to my progress bar and it's being changed from a non-ui thread, problem is the whole progress bar goes from 0 to 100 in a second, am I allowed to raise INotifyPropertyChanged from non-ui threads?


问:
How to fine tune VGG16 with ImageNet dataset without error?
I am new in computer vision, and I want to fine tune VGG16 with imagenet64 dataset. But after downloading imagenet64 dataset with below code and then fine tuning, I got an error. Please help me to solve this error. thank you very much.

```<code>import os
import shutil
from keras.preprocessing.image import ImageDataGenerator
from keras.applications import VGG16
from keras import models, layers, optimizers
import matplotlib.image as mpimg
import math

checkpoints = '/content/drive/MyDrive/colab_files/imagenet64/'
if not os.path.exists('imagenet64'):
  if not os.path.exists(checkpoints + 'imagenet64.tar'):
    print("Downloading archive...")
    os.chdir(checkpoints)
    !wget https://pjreddie.com/media/files/imagenet64.tar
    os.chdir('/content/')
  print("Copying to local runtime...")
  shutil.copy(checkpoints + 'imagenet64.tar', './imagenet64.tar')
  print("Uncompressing...")
  !tar -xf imagenet64.tar
print("Data ready!")
</code>```
```<code>train_dir='/content/imagenet64/train'
val_dir='/content/imagenet64/val'
batch_size=40
epochs=30
train_datagen= ImageDataGenerator()
val_datagen= ImageDataGenerator()
train_generator = train_datagen.flow_from_directory(
                    train_dir,
                    target_size = (224,224),
                    batch_size = batch_size,
                                        class_mode = 'categorical',
                    subset='training'
                  )

validation_generator = val_datagen.flow_from_directory(
                    val_dir,
                    target_size = (224,224),
                    batch_size = batch_size,
                                        class_mode = 'categorical',
                    subset='training'
                  )

model_fine=model_n
model_fine.trainable = True

set_trainable = False
for layer in model_fine.layers:
    if layer.name=='block5_conv1':
        set_trainable = True
    if set_trainable == True:
        layer.trainable = True
    else:
        layer.trainable = False

model_fine.compile(loss='categorical_crossentropy', optimizer=optimizers.Nadam(lr=1e-5), metrics=['acc'])
h = model_fine.fit(
                                train_generator,
                                steps_per_epoch = train_generator.samples // batch_size,
                                epochs = epochs,
                                validation_data = validation_generator,
                                validation_steps = validation_generator.samples // batch_size,
                             )

</code>```

I tried to fine tune VGG16 with imagenet64 dataset and I expect to fine tune model. But I got an error:

Found 1281166 images belonging to 1000 classes.

Found 50000 images belonging to 1000 classes.

/usr/local/lib/python3.8/dist-packages/keras/optimizers/optimizer_v2/nadam.py:78: UserWarning: The lr argument is deprecated, use learning_rate instead.
super(Nadam, self).init(name, **kwargs)

Epoch 1/30

StagingError                              Traceback (most recent call last)
 in

```<code> 34

 35 model_fine.compile(loss='categorical_crossentropy', optimizer=optimizers.Nadam(lr=1e-5), metrics=['acc'])
</code>```

---> 36 h = model_fine.fit(

```<code> 37                                 train_generator,

 38                                 steps_per_epoch = train_generator.samples // batch_size,
</code>```

1 frames
/usr/local/lib/python3.8/dist-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)

1125           except Exception as e:  # pylint:disable=broad-except

1126             if hasattr(e, "ag_error_metadata"):

-> 1127               raise e.ag_error_metadata.to_exception(e)
1128             else:
1129               raise

StagingError: in user code:

```<code>File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1051, in train_function  *
    return step_function(self, iterator)
File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1040, in step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1030, in run_step  **
    outputs = model.train_step(data)
File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 893, in train_step
    self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
File "/usr/local/lib/python3.8/dist-packages/keras/optimizers/optimizer_v2/optimizer_v2.py", line 539, in minimize
    return self.apply_gradients(grads_and_vars, name=name)
File "/usr/local/lib/python3.8/dist-packages/keras/optimizers/optimizer_v2/optimizer_v2.py", line 646, in apply_gradients
    self._create_all_weights(var_list)
File "/usr/local/lib/python3.8/dist-packages/keras/optimizers/optimizer_v2/optimizer_v2.py", line 860, in _create_all_weights
    self._create_slots(var_list)
File "/usr/local/lib/python3.8/dist-packages/keras/optimizers/optimizer_v2/nadam.py", line 87, in _create_slots
    var_dtype = var_list[0].dtype.base_dtype

IndexError: list index out of range
</code>```

Body:
I am new in computer vision, and I want to fine tune VGG16 with imagenet64 dataset. But after downloading imagenet64 dataset with below code and then fine tuning, I got an error. Please help me to solve this error. thank you very much.

import os
import shutil
from keras.preprocessing.image import ImageDataGenerator
from keras.applications import VGG16
from keras import models, layers, optimizers
import matplotlib.image as mpimg
import math

checkpoints = '/content/drive/MyDrive/colab_files/imagenet64/'
if not os.path.exists('imagenet64'):
  if not os.path.exists(checkpoints + 'imagenet64.tar'):
    print("Downloading archive...")
    os.chdir(checkpoints)
    !wget https://pjreddie.com/media/files/imagenet64.tar
    os.chdir('/content/')
  print("Copying to local runtime...")
  shutil.copy(checkpoints + 'imagenet64.tar', './imagenet64.tar')
  print("Uncompressing...")
  !tar -xf imagenet64.tar
print("Data ready!")

train_dir='/content/imagenet64/train'
val_dir='/content/imagenet64/val'
batch_size=40
epochs=30
train_datagen= ImageDataGenerator()
val_datagen= ImageDataGenerator()
train_generator = train_datagen.flow_from_directory(
                    train_dir,
                    target_size = (224,224),
                    batch_size = batch_size,
                                        class_mode = 'categorical',
                    subset='training'
                  )

validation_generator = val_datagen.flow_from_directory(
                    val_dir,
                    target_size = (224,224),
                    batch_size = batch_size,
                                        class_mode = 'categorical',
                    subset='training'
                  )

model_fine=model_n
model_fine.trainable = True

set_trainable = False
for layer in model_fine.layers:
    if layer.name=='block5_conv1':
        set_trainable = True
    if set_trainable == True:
        layer.trainable = True
    else:
        layer.trainable = False

model_fine.compile(loss='categorical_crossentropy', optimizer=optimizers.Nadam(lr=1e-5), metrics=['acc'])
h = model_fine.fit(
                                train_generator,
                                steps_per_epoch = train_generator.samples // batch_size,
                                epochs = epochs,
                                validation_data = validation_generator,
                                validation_steps = validation_generator.samples // batch_size,
                             )

I tried to fine tune VGG16 with imagenet64 dataset and I expect to fine tune model. But I got an error:

Found 1281166 images belonging to 1000 classes.

Found 50000 images belonging to 1000 classes.

/usr/local/lib/python3.8/dist-packages/keras/optimizers/optimizer_v2/nadam.py:78: UserWarning: The lr argument is deprecated, use learning_rate instead.
super(Nadam, self).init(name, **kwargs)

Epoch 1/30

StagingError                              Traceback (most recent call last)
 in

 34

 35 model_fine.compile(loss='categorical_crossentropy', optimizer=optimizers.Nadam(lr=1e-5), metrics=['acc'])

---> 36 h = model_fine.fit(

 37                                 train_generator,

 38                                 steps_per_epoch = train_generator.samples // batch_size,

1 frames
/usr/local/lib/python3.8/dist-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)

1125           except Exception as e:  # pylint:disable=broad-except

1126             if hasattr(e, "ag_error_metadata"):

-> 1127               raise e.ag_error_metadata.to_exception(e)
1128             else:
1129               raise

StagingError: in user code:

File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1051, in train_function  *
    return step_function(self, iterator)
File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1040, in step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 1030, in run_step  **
    outputs = model.train_step(data)
File "/usr/local/lib/python3.8/dist-packages/keras/engine/training.py", line 893, in train_step
    self.optimizer.minimize(loss, self.trainable_variables, tape=tape)
File "/usr/local/lib/python3.8/dist-packages/keras/optimizers/optimizer_v2/optimizer_v2.py", line 539, in minimize
    return self.apply_gradients(grads_and_vars, name=name)
File "/usr/local/lib/python3.8/dist-packages/keras/optimizers/optimizer_v2/optimizer_v2.py", line 646, in apply_gradients
    self._create_all_weights(var_list)
File "/usr/local/lib/python3.8/dist-packages/keras/optimizers/optimizer_v2/optimizer_v2.py", line 860, in _create_all_weights
    self._create_slots(var_list)
File "/usr/local/lib/python3.8/dist-packages/keras/optimizers/optimizer_v2/nadam.py", line 87, in _create_slots
    var_dtype = var_list[0].dtype.base_dtype

IndexError: list index out of range


问:
Kubernetes Jenkins Cluster restarts restarts how to persists Jenkins configuration
I'm trying to deploy jenkins onto a kubernetes cluster on my windows machine. My issue is that when I restart docker desktop, I lose all of my Jenkins data. This means that I need to set up the admin user and install plugins each time I restart docker desktop.

I would like for the data to persist onto a folder I have in the "D:" drive of my PC so that even when docker desktop is restarted I will not lose my data.

This is my current configuration but it is not working as expected:

pv-pvc.yaml:

```<code># PersistentVolume for Jenkins
apiVersion: v1
kind: PersistentVolume
metadata:
  name: jenkins-pv
  labels:
    type: local
spec:
  storageClassName: local-storage
  persistentVolumeReclaimPolicy: Retain
  capacity:
    storage: 10Gi
  volumeMode: Filesystem
  accessModes:
    - ReadWriteOnce
  local:
    path: /d/Kubernetes/storage/jenkins
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - docker-desktop
---
# PersistentVolumeClaim for Jenkins
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: jenkins-pvc
  namespace: jenkins
spec:
  storageClassName: local-storage
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
</code>```

service.yaml:

```<code>apiVersion: v1
kind: Service
metadata:
  name: jenkins
spec:
  type: NodePort
  ports:
    - port: 8080
      targetPort: 8080
      nodePort: 30000
  selector:
    app: jenkins

---

apiVersion: v1
kind: Service
metadata:
  name: jenkins-jnlp
spec:
  type: ClusterIP
  ports:
    - port: 50000
      targetPort: 50000
  selector:
    app: jenkins
</code>```

deployment.yaml:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: jenkins
spec:
  replicas: 1
  selector:
    matchLabels:
      app: jenkins
  template:
    metadata:
      labels:
        app: jenkins
    spec:
      securityContext:
        fsGroup: 1000
      containers:
      - name: jenkins
        image: jenkins/jenkins:lts
        ports:
          - name: http-port
            containerPort: 8080
          - name: jnlp-port
            containerPort: 50000
        volumeMounts:
          - name: jenkins-vol
            mountPath: /mnt/d/Kubernetes/storage/jenkins/var/jenkins_home
      volumes:
        - name: jenkins-vol
          persistentVolumeClaim:
            claimName: jenkins-pvc

</code>```

Body:
I'm trying to deploy jenkins onto a kubernetes cluster on my windows machine. My issue is that when I restart docker desktop, I lose all of my Jenkins data. This means that I need to set up the admin user and install plugins each time I restart docker desktop.

I would like for the data to persist onto a folder I have in the "D:" drive of my PC so that even when docker desktop is restarted I will not lose my data.

This is my current configuration but it is not working as expected:

pv-pvc.yaml:

# PersistentVolume for Jenkins
apiVersion: v1
kind: PersistentVolume
metadata:
  name: jenkins-pv
  labels:
    type: local
spec:
  storageClassName: local-storage
  persistentVolumeReclaimPolicy: Retain
  capacity:
    storage: 10Gi
  volumeMode: Filesystem
  accessModes:
    - ReadWriteOnce
  local:
    path: /d/Kubernetes/storage/jenkins
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - docker-desktop
---
# PersistentVolumeClaim for Jenkins
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: jenkins-pvc
  namespace: jenkins
spec:
  storageClassName: local-storage
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi

service.yaml:

apiVersion: v1
kind: Service
metadata:
  name: jenkins
spec:
  type: NodePort
  ports:
    - port: 8080
      targetPort: 8080
      nodePort: 30000
  selector:
    app: jenkins

---

apiVersion: v1
kind: Service
metadata:
  name: jenkins-jnlp
spec:
  type: ClusterIP
  ports:
    - port: 50000
      targetPort: 50000
  selector:
    app: jenkins

deployment.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: jenkins
spec:
  replicas: 1
  selector:
    matchLabels:
      app: jenkins
  template:
    metadata:
      labels:
        app: jenkins
    spec:
      securityContext:
        fsGroup: 1000
      containers:
      - name: jenkins
        image: jenkins/jenkins:lts
        ports:
          - name: http-port
            containerPort: 8080
          - name: jnlp-port
            containerPort: 50000
        volumeMounts:
          - name: jenkins-vol
            mountPath: /mnt/d/Kubernetes/storage/jenkins/var/jenkins_home
      volumes:
        - name: jenkins-vol
          persistentVolumeClaim:
            claimName: jenkins-pvc


问:
`pip install` under Ubuntu, works; fails under Windows
I've written a program and in order to help some colleagues of mine to install it in an easy way, I've built a python package.

In Ubuntu is fairly easy to install it. Just doing pip3 install taskAutom will do the job.

I've created myself a Win10 VM to test it under Windows, but I cannot install the package. I get an error which I still do not understand ... in the sense that I still don't know what to do to avoid it.

In my program I use python-docx which depends on lxml. Installing it using pip on windows, complains...

UPDATE:  I've found that using python3.8 solves the issue. For the original test, I used python3.11. Is not a bad workaround, but I'd like to be agnostic to the OS or Python Version.

Thanks.


问:
Options for adding/creating DND PTR record for domain-specific email address on a shared hosting plan
We have a website on a shared hosting plan. Email service is provided so we can send emails as info@domain.com.

We found that at least two email providers, gmx.net and IONOS, return emails with the error 554 Bad DNS PTR resource record. They require that we switch from a dynamically assigned IP address to a fixed IP address and assign our email server its own full domain name (FQDN).

Our web hosting provider said they cannot change the PTR of a shared server IP to our domain as it is a shared hosting package. However, it is possible to change the PTR record to our domain in private (VPS) hosting.

Is there an easier and more economical solution to satisfy the requirements of these email providers while still using a shared hosting plan?

I have already looked into email hosting with Titan and Gmail, but it is out of budget.


问:
Handling frames selenium vba
Hi guys i am trying to click an element in a frame but i cannot switch to the said frame. I tried everything but i get either :there is no such element or no such frame error.I cant see to figure out what i do wrong . Any help will be greatly appreciated. HTML below</p>
```<code>Option Explicit
Public Sub test()

Dim pause1, pause2, pause3, url, url2 As String

 pause1 = "00:00:08"

 pause2 = "00:00:30"

 pause3 = "00:00:40"

 url = "http://tra01:1000/"

 url2 = "https://TDMLogon.jsp"

Dim driver As New WebDriver

Dim rowc, cc, columnC As Integer

Dim tblent As Variant

Dim By As selenium.By

Set By = New selenium.By
driver.Start "Chrome"

driver.Get (url2)

Application.Wait Now + TimeValue(pause3)

driver.FindElementByXPath("/html/body/table[2]/tbody/tr/td/table[1]/tbody/tr/td/form/table/tbody/tr[2]/td/table/tbody/tr[1]/td[2]/select").AsSelect.SelectByText ("EMP ID")

driver.FindElementByXPath("/html/body/table[2]/tbody/tr/td/table[1]/tbody/tr/td/form/table/tbody/tr[2]/td/table/tbody/tr[2]/td[2]/select").AsSelect.SelectByText ("English")

driver.FindElementByXPath("/html/body/table[2]/tbody/tr/td/table[1]/tbody/tr/td/form/table/tbody/tr[2]/td/table/tbody/tr[4]/td/input").Click

Application.Wait Now + TimeValue(pause1)

driver.SwitchToParentFrame

driver.SwitchToFrame driver.FindElementByXPath("//*[@id=""frameset2""]")

Application.Wait Now + TimeValue(pause1)

driver.FindElementByXPath("//*[@id=""homeSearch""]").Click

End Sub
</code>```

Title: Handling frames selenium vba

Body:
Hi guys i am trying to click an element in a frame but i cannot switch to the said frame. I tried everything but i get either :there is no such element or no such frame error.I cant see to figure out what i do wrong . Any help will be greatly appreciated. HTML below

Option Explicit
Public Sub test()

Dim pause1, pause2, pause3, url, url2 As String

 pause1 = "00:00:08"

 pause2 = "00:00:30"

 pause3 = "00:00:40"

 url = "http://tra01:1000/"

 url2 = "https://TDMLogon.jsp"

Dim driver As New WebDriver

Dim rowc, cc, columnC As Integer

Dim tblent As Variant

Dim By As selenium.By

Set By = New selenium.By
driver.Start "Chrome"

driver.Get (url2)

Application.Wait Now + TimeValue(pause3)

driver.FindElementByXPath("/html/body/table[2]/tbody/tr/td/table[1]/tbody/tr/td/form/table/tbody/tr[2]/td/table/tbody/tr[1]/td[2]/select").AsSelect.SelectByText ("EMP ID")

driver.FindElementByXPath("/html/body/table[2]/tbody/tr/td/table[1]/tbody/tr/td/form/table/tbody/tr[2]/td/table/tbody/tr[2]/td[2]/select").AsSelect.SelectByText ("English")

driver.FindElementByXPath("/html/body/table[2]/tbody/tr/td/table[1]/tbody/tr/td/form/table/tbody/tr[2]/td/table/tbody/tr[4]/td/input").Click

Application.Wait Now + TimeValue(pause1)

driver.SwitchToParentFrame

driver.SwitchToFrame driver.FindElementByXPath("//*[@id=""frameset2""]")

Application.Wait Now + TimeValue(pause1)

driver.FindElementByXPath("//*[@id=""homeSearch""]").Click

End Sub


问:
Authentication middleware nodejs not working with localhost:3000 and hosted nodejs backend api
when i use localhost:3000 for frontend and localhost:5000 for backend , it is fine that authentication middleware working perfectly.when i host to render also fine that it is working .
but when i use localhost:3000 for frontend and hosted render api for backend , it shows "unauthorised no token provided". i cant set jwt token cookie . please help me.

i need solution that i need to use external api for login and authentication middleware. i cant use this to another server.


问:
Extension of vscode is deactivated somtimes
enter image description here

As the image shown above, some extensions (especially Remote - ssh and Python) are deactivated when I turn on my vscode.
I can activate them by re-installing but it is clumsy.
I cannot find the reason of it.
Thank you.

Tried to delete some extensions to avoid dependency problem or collision between extensions but they didn't work.


问:
How to push from Cloud VM to cloud repository?
I committed a model from google cloud source repo to cloud VM and trained on it. After training I would like to commit the changes back to the cloud repo. How to do that in the terminal?</p>


问:
Check when was Amazon S3 bucket last accessed
I want to get a list of buckets that are not used over a period of 1 year is there anyway to see the last read of the objects of s3 bucket

I tried using cli but it didnt work


问:
Chrome issues in Android 13
In Android 13 not open the chrome browser I can't open chrome using htm text

Error-unable to find explicit activity class{com.android.chrome/com.google.android.apps.chrome.Main} have you declared this activity in your Android Manifest.xml

I am trying to open chrome browser in Android 13
I want to open chrome browser using html text

Title: Chrome issues in Android 13


问:
Scientific notation can't be disabled in Rshiny
I don't want scientific notation in my R shiny. I tried to put options(scipen=999) in both UI and server. However, when display locally it shows non-scientific number while published to server it changed to scientific notation.

I'm using R 4.0.3 and try to display a R data.table in the app. Tried converting all numbers using format it failed as well. Thinking there may be a better way to handle this.

```<code> output$omop <- renderDataTable(
    labtable() %>% datatable(extensions = c("FixedHeader",'Buttons'),
                                        options = list(dom = 'Blfrtip',
                                        buttons = c('csv', 'excel', 'pdf', 'print'),
                                         lengthMenu = list(c(10,50,-1),
                                                           c(10,50,"All"))))
  )
</code>```

Are there options I can add or modify to prevent this unwanted display happen?

Thanks!

Body:
I don't want scientific notation in my R shiny. I tried to put options(scipen=999) in both UI and server. However, when display locally it shows non-scientific number while published to server it changed to scientific notation.

I'm using R 4.0.3 and try to display a R data.table in the app. Tried converting all numbers using format it failed as well. Thinking there may be a better way to handle this.

 output$omop <- renderDataTable(
    labtable() %>% datatable(extensions = c("FixedHeader",'Buttons'),
                                        options = list(dom = 'Blfrtip',
                                        buttons = c('csv', 'excel', 'pdf', 'print'),
                                         lengthMenu = list(c(10,50,-1),
                                                           c(10,50,"All"))))
  )

Are there options I can add or modify to prevent this unwanted display happen?

Thanks!


问:
WebStorm does not recognize npm module imports
For our web service we are creating a package (npm module). I been messing with the files and exports section of the package.json file and I can't see how to get my WebStorm IDE to recognize the import path correctly when importing the .js and .scss files.

Let me explain some more.

Here is the structure of our compiled npm module:

My issue is: WebStorm says this path is invalid to import when I try

```<code>import { Widget } from '@dev/test';
</code>```

and I see this

NOW the odd thing is, it DOES compile and works when our services webpack runs, however the IDE says its not there unless I do

```<code>import { Widget } from '@dev/test/lib/index';
</code>```

then the IDE says it's OK.

Now same goes for importing a SCSS file. Our goal is to have something like this in our services index.scss:

```<code>@use '~@dev/test';
</code>```

but webpack throws an error unless I do it this way

```<code>@use '~@ibm-cloud/feedback/lib/index';
</code>```

If I have to keep it that way, that's fine. But I want to at least fix the issue with the js import.

I tried using only files, or only using exports and vice versa, or both together but I seem to either break both or break one of the imports.

Does anyone have any ideas?

Body:
For our web service we are creating a package (npm module). I been messing with the files and exports section of the package.json file and I can't see how to get my WebStorm IDE to recognize the import path correctly when importing the .js and .scss files.

Let me explain some more.

Here is the structure of our compiled npm module:

My issue is: WebStorm says this path is invalid to import when I try

import { Widget } from '@dev/test';

and I see this

NOW the odd thing is, it DOES compile and works when our services webpack runs, however the IDE says its not there unless I do

import { Widget } from '@dev/test/lib/index';

then the IDE says it's OK.

Now same goes for importing a SCSS file. Our goal is to have something like this in our services index.scss:

@use '~@dev/test';

but webpack throws an error unless I do it this way

@use '~@ibm-cloud/feedback/lib/index';

If I have to keep it that way, that's fine. But I want to at least fix the issue with the js import.

I tried using only files, or only using exports and vice versa, or both together but I seem to either break both or break one of the imports.

Does anyone have any ideas?


问:
Setting rows display of Frame object from the static-frame library in jupyter
I am currently manipulating Frame objects from the static-frame library.
I am working in Jupyter, and it seems the default behavior is to display all rows when a Frame is printed in a cell. This makes my computer lag for large frames.

For instance, in pandas, all rows are by default displayed until 100 I guess, and that parameter can be set with the command pd.options.display.max_rows

Is there such a parameter for dataframes of the static-frame library ?


问:
Adding new column to dataframe with month extracted from date Spark

I am trying to add a new column to a dataframe in Spark. I have a clean dataset (dfClean) with a column called "Fecha ingreso" that has a date and I want to extract the month from this column and add a new column that only has the month.
I tried

```<code>from pyspark.sql.functions import month

dfCleanMonth = dfClean.withColumn('Month',month('Fecha ingreso'))
dfCleanMonth.display()
</code>```

but it's not adding any columns, even though it is not giving any errors. Does anybody know how I can fix it? I have looked online but can't seem to find the error.
Thank you!

Body:
I am trying to add a new column to a dataframe in Spark. I have a clean dataset (dfClean) with a column called "Fecha ingreso" that has a date and I want to extract the month from this column and add a new column that only has the month.
I tried

from pyspark.sql.functions import month

dfCleanMonth = dfClean.withColumn('Month',month('Fecha ingreso'))
dfCleanMonth.display()

but it's not adding any columns, even though it is not giving any errors. Does anybody know how I can fix it? I have looked online but can't seem to find the error.
Thank you!


问:
How to efficiently (referring to speed) group extremely large Numpy array?
I am working with a really large array of size (>10 Million x 2) that is in the following format

```<code>a = [[1, 1.3],
     [5, 56.3],
     [6, 6.4],
     [12, 18],
     .
     .
     .]
</code>```

type(a) = numpy.ndarray
Basically, column 1 is the index and column 2 is the associated value.
Now,  I would like to group this array based on a list of index I provide.

The groups are just a simple list/array of indices:

```<code>g1 = [6,1,...]
g2 = [12,5,...]
</code>```

Notice the indices within groups are not in the same order as the indices in my giant array. I could also have more than 2 groups.

Eventually, my goal is to sum up the values of the index in the provided group. But, right now, I am just trying to group this without aging a few years while my code runs.

Result for intermediate step should be

```<code>a1 = [[6, 6.4],
     [1, 1.3]]
</code>```
```<code>a2 = [[12, 18],
     [5, 56.3]]
</code>```

Finally the easy part, summing up the values (col 2) for all the indices in the group a1_sum = 7.7 and a2_sum = 74.3.

I am reading a from an HDF5 file. From my previous experiences --which is not a whole lot --working from HDF5 directly is slower so I just copy the entire array and work with it. This approach was perfectly fine when my data was smaller, ~500k rows. With this large array, making a copy takes 10 s. I am okay with it but then trying to do what I explained above is just painfully slow.

As you would expect, for loop-ing >10 million rows of the array will take whatever time I have left in this planet. And for-loop is the only way I can think of accomplishing this. I would have to loop through each entry in col_1 of a and compare it all lists to find out in which list the index exists and then group. I'm having really hard time to coming up with ways I vectorize my solution approach since vectorizing in Numpy is much faster than looping.

The end result is the sum value. So perhaps there is way to achieve that without grouping?

I would appreciate any help you can provide. Thank you!

Body:
I am working with a really large array of size (>10 Million x 2) that is in the following format

a = [[1, 1.3],
     [5, 56.3],
     [6, 6.4],
     [12, 18],
     .
     .
     .]

type(a) = numpy.ndarray
Basically, column 1 is the index and column 2 is the associated value.
Now,  I would like to group this array based on a list of index I provide.

The groups are just a simple list/array of indices:

g1 = [6,1,...]
g2 = [12,5,...]

Notice the indices within groups are not in the same order as the indices in my giant array. I could also have more than 2 groups.

Eventually, my goal is to sum up the values of the index in the provided group. But, right now, I am just trying to group this without aging a few years while my code runs.

Result for intermediate step should be

a1 = [[6, 6.4],
     [1, 1.3]]

a2 = [[12, 18],
     [5, 56.3]]

Finally the easy part, summing up the values (col 2) for all the indices in the group a1_sum = 7.7 and a2_sum = 74.3.

I am reading a from an HDF5 file. From my previous experiences --which is not a whole lot --working from HDF5 directly is slower so I just copy the entire array and work with it. This approach was perfectly fine when my data was smaller, ~500k rows. With this large array, making a copy takes 10 s. I am okay with it but then trying to do what I explained above is just painfully slow.

As you would expect, for loop-ing >10 million rows of the array will take whatever time I have left in this planet. And for-loop is the only way I can think of accomplishing this. I would have to loop through each entry in col_1 of a and compare it all lists to find out in which list the index exists and then group. I'm having really hard time to coming up with ways I vectorize my solution approach since vectorizing in Numpy is much faster than looping.

The end result is the sum value. So perhaps there is way to achieve that without grouping?

I would appreciate any help you can provide. Thank you!


问:
Regex - Find all spaces which are not between two characters
Example string

```<code>ffff7cp37wicb5.hui.com /images/xyz.jpg HTTP/1.1 HIT 103.195.71.140 image/jpeg "trace-id=3948b327-87d5-a6a0-15e5-3e20ef6d6333;parent-id=540089004159950400;span-id=540089004159950400" ^curl mozilla; haa/7.79.1^ ^max-age=2592000^ 0 NOT_DEFINED
</code>```

I need to match all spaces except the ones that lie between two carets (^) so that I can split the above line into tokens

Tried the solution from here using:

```<code>arr = str.split(/\s(?![^^]*\^)/g)
</code>```

Expectation

```<code>ffff7cp37wicb5.hui.com
/images/xyz.jpg
HTTP/1.1
HIT
103.195.71.140
image/jpeg
"trace-id=3948b327-87d5-a6a0-15e5-3e20ef6d6333;parent-id=540089004159950400;span-id=540089004159950400"
^curl mozilla; haa/7.79.1^
^max-age=2592000^
0
NOT_DEFINED
</code>```

Actual

```<code>ffff7cp37wicb5.hui.com /images/xyz.jpg HTTP/1.1 HIT 103.195.71.140 image/jpeg "trace-id=3948b327-87d5-a6a0-15e5-3e20ef6d6333;parent-id=540089004159950400;span-id=540089004159950400" ^curl mozilla; haa/7.79.1^ ^max-age=2592000^
0
NOT_DEFINED
</code>```

Body:
Example string

ffff7cp37wicb5.hui.com /images/xyz.jpg HTTP/1.1 HIT 103.195.71.140 image/jpeg "trace-id=3948b327-87d5-a6a0-15e5-3e20ef6d6333;parent-id=540089004159950400;span-id=540089004159950400" ^curl mozilla; haa/7.79.1^ ^max-age=2592000^ 0 NOT_DEFINED

I need to match all spaces except the ones that lie between two carets (^) so that I can split the above line into tokens

Tried the solution from here using:

arr = str.split(/\s(?![^^]*\^)/g)

Expectation

ffff7cp37wicb5.hui.com
/images/xyz.jpg
HTTP/1.1
HIT
103.195.71.140
image/jpeg
"trace-id=3948b327-87d5-a6a0-15e5-3e20ef6d6333;parent-id=540089004159950400;span-id=540089004159950400"
^curl mozilla; haa/7.79.1^
^max-age=2592000^
0
NOT_DEFINED

Actual

ffff7cp37wicb5.hui.com /images/xyz.jpg HTTP/1.1 HIT 103.195.71.140 image/jpeg "trace-id=3948b327-87d5-a6a0-15e5-3e20ef6d6333;parent-id=540089004159950400;span-id=540089004159950400" ^curl mozilla; haa/7.79.1^ ^max-age=2592000^
0
NOT_DEFINED


问:
Using ActiveMQ/JMS on Tomcat server?
We have a Spring based web application deployed in Tomcat. The web application uses Spring's JmsTemplate and DefaultMessageListenerContainer to produce and consume messages respectively. Our JMS provider is ActiveMQ "Classic" and we have used ActiveMQ client libraries to establish a connection with the native broker. We have used PooledConnectionFactory from the activemq-pool library. Since it's a Spring web application we have defined the connection factory bean and wired the connectionFactory into JmsTemplate and DefaultMessageListenerContainer beans respectively. We are assuming the pooling would be driven by Spring through the connection factory.

The behavior we are seeing is the JMS sessions are being created/destroyed continuously. Under load the application would stop consuming the messages.

After reading different articles we are trying to understand the role of JCA JMS. Can anybody suggest implementing JMS through JCA would resolve the issue and to enlist JMS as an XA resource to maintain the connections and sessions through JCA Adapters.

In our Spring JMS web application and Tomcat server we have used both the ActiveMQ PooledConnectionFactory and ActiveMQConnectionFactory from ActiveMQ client libraries. We see the sessions are being created/destroyed frequently and this stops the JMS client from consuming messages.

The below snippet of the Spring beans how we have configured the Spring JmsTemplate and DefaultMessageListenerContainer beans wired in with the connectionFactory.

<bean id="jmsQueueConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
   <property name="connectionFactory">
      <bean class="org.apache.activemq.ActiveMQConnectionFactory">
         <property name="brokerURL" value="ssl://localhost:61616"/>
         <property name="trustAllPackages" value="true"/>
      </bean>
   </property>
   <property name="maxConnections" value="5"/>
   <property name="maximumActiveSessionPerConnection" value="400"/>
</bean>

<bean id="dmDefaultMessageListenerContainer" class="com.crsoftwareinc.crs.core.jmsListener.DMDefaultMessageListenerContainer">
   <property name="autoStartup"       value="false"/>
   <property name="concurrentConsumers" value="1" />
   <property name="maxConcurrentConsumers" value="5" />
   <property name="cacheLevelName"      value="CACHE_NONE"/>
   <property name="connectionFactory"   ref="jmsQueueConnectionFactory" />
   <property name="sessionTransacted"     value="true"/>
</bean>

<bean id="jmsTemplate"  class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="jmsQueueConnectionFactory"/>
    <property name="sessionTransacted" value="true"/>
</bean>
```

We are looking for a work around how could we use JMS with ActiveMQ  in Spring Web application in production deployments where the connections and sessions are maintained seamlessly?

Title: Using ActiveMQ/JMS on Tomcat server?

Body:
We have a Spring based web application deployed in Tomcat. The web application uses Spring's JmsTemplate and DefaultMessageListenerContainer to produce and consume messages respectively. Our JMS provider is ActiveMQ "Classic" and we have used ActiveMQ client libraries to establish a connection with the native broker. We have used PooledConnectionFactory from the activemq-pool library. Since it's a Spring web application we have defined the connection factory bean and wired the connectionFactory into JmsTemplate and DefaultMessageListenerContainer beans respectively. We are assuming the pooling would be driven by Spring through the connection factory.

The behavior we are seeing is the JMS sessions are being created/destroyed continuously. Under load the application would stop consuming the messages.

After reading different articles we are trying to understand the role of JCA JMS. Can anybody suggest implementing JMS through JCA would resolve the issue and to enlist JMS as an XA resource to maintain the connections and sessions through JCA Adapters.

In our Spring JMS web application and Tomcat server we have used both the ActiveMQ PooledConnectionFactory and ActiveMQConnectionFactory from ActiveMQ client libraries. We see the sessions are being created/destroyed frequently and this stops the JMS client from consuming messages.

The below snippet of the Spring beans how we have configured the Spring JmsTemplate and DefaultMessageListenerContainer beans wired in with the connectionFactory.

<bean id="jmsQueueConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" destroy-method="stop">
   <property name="connectionFactory">
      <bean class="org.apache.activemq.ActiveMQConnectionFactory">
         <property name="brokerURL" value="ssl://localhost:61616"/>
         <property name="trustAllPackages" value="true"/>
      </bean>
   </property>
   <property name="maxConnections" value="5"/>
   <property name="maximumActiveSessionPerConnection" value="400"/>
</bean>

<bean id="dmDefaultMessageListenerContainer" class="com.crsoftwareinc.crs.core.jmsListener.DMDefaultMessageListenerContainer">
   <property name="autoStartup"       value="false"/>
   <property name="concurrentConsumers" value="1" />
   <property name="maxConcurrentConsumers" value="5" />
   <property name="cacheLevelName"      value="CACHE_NONE"/>
   <property name="connectionFactory"   ref="jmsQueueConnectionFactory" />
   <property name="sessionTransacted"     value="true"/>
</bean>

<bean id="jmsTemplate"  class="org.springframework.jms.core.JmsTemplate">
    <property name="connectionFactory" ref="jmsQueueConnectionFactory"/>
    <property name="sessionTransacted" value="true"/>
</bean>

We are looking for a work around how could we use JMS with ActiveMQ  in Spring Web application in production deployments where the connections and sessions are maintained seamlessly?


问:
Can't load pretrained model from local directory
I finetuned a huggingface model on google colab, saved it with trainer.save_model('./results/best_model') and downloaded the files in results/best_models (config.json, pytorch_model.bin, training_args.bin)from google colab and saved it in a local directory.

Now I am trying to load the model into a jupyter notebook with

```<code>from transformers import AutoTokenizer
from transformers import AutoModelForSequenceClassification, Trainer, TrainingArguments
import torch

import numpy as np
from sklearn.metrics import classification_report

path = 'models/yu'
tokenizer = AutoTokenizer.from_pretrained(path, local_files_only=True)
</code>```

The path (models/yu) leads to a directory which contains the files from above (config.json, pytorch_model.bin, training_args.bin), it is relative to the location of my .ipynb file. Yet when I try to load it I get the following error:

OSError: Can't load tokenizer for 'models/yu'. If you were trying to load it from 'https://huggingface.co/models', make sure you don't have a local directory with the same name. Otherwise, make sure 'models/yu' is the correct path to a directory containing all relevant files for a XLMRobertaTokenizerFast tokenizer.

What 'relevant files' could be missing? How do I load a pretrained model? Or should I have been saving the model in google colab differently in the first place?

What is also weird, is that the command produces the output

`

```<code>vocab_file sentencepiece.bpe.model
tokenizer_file tokenizer.json
added_tokens_file added_tokens.json
special_tokens_map_file special_tokens_map.json
tokenizer_config_file tokenizer_config.json

</code>```

`
which is the same as when I (successfully) load a pretrained model which I downloaded from the huggingface hub (and saved it locally).

Thank's for your help!

Body:
I finetuned a huggingface model on google colab, saved it with trainer.save_model('./results/best_model') and downloaded the files in results/best_models (config.json, pytorch_model.bin, training_args.bin)from google colab and saved it in a local directory.

Now I am trying to load the model into a jupyter notebook with

from transformers import AutoTokenizer
from transformers import AutoModelForSequenceClassification, Trainer, TrainingArguments
import torch

import numpy as np
from sklearn.metrics import classification_report

path = 'models/yu'
tokenizer = AutoTokenizer.from_pretrained(path, local_files_only=True)

The path (models/yu) leads to a directory which contains the files from above (config.json, pytorch_model.bin, training_args.bin), it is relative to the location of my .ipynb file. Yet when I try to load it I get the following error:

OSError: Can't load tokenizer for 'models/yu'. If you were trying to load it from 'https://huggingface.co/models', make sure you don't have a local directory with the same name. Otherwise, make sure 'models/yu' is the correct path to a directory containing all relevant files for a XLMRobertaTokenizerFast tokenizer.

What 'relevant files' could be missing? How do I load a pretrained model? Or should I have been saving the model in google colab differently in the first place?

What is also weird, is that the command produces the output

`

vocab_file sentencepiece.bpe.model
tokenizer_file tokenizer.json
added_tokens_file added_tokens.json
special_tokens_map_file special_tokens_map.json
tokenizer_config_file tokenizer_config.json

`
which is the same as when I (successfully) load a pretrained model which I downloaded from the huggingface hub (and saved it locally).

Thank's for your help!


问:
adding multiple angular apps on aspnet core using app.Map
I have tried to use two angular apps on single aspnet core 6.
using this code:

```<code>app.Map(@"/reports", app=>
            {
                app.UseSpa(spa =>
                {
                    spa.Options.SourcePath = "reportsApp";
                    if (env.IsDevelopment())
                    {
                        spa.Options.StartupTimeout = TimeSpan.FromSeconds(180); // Increase the timeout if angular app is taking longer to startup
                        spa.UseProxyToSpaDevelopmentServer("http://localhost:4201"); // Use this instead to use the angular cli server
                    }
                    else
                    {
                        app.UseSpaStaticFiles();
                    }
                });
            });
app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "App";
                if (env.IsDevelopment() )
                {
                    spa.Options.StartupTimeout = TimeSpan.FromSeconds(180); // Increase the timeout if angular app is taking longer to startup
                    spa.UseProxyToSpaDevelopmentServer("http://localhost:4200"); // Use this instead to use the angular cli server
                }
                else
                {
                    app.UseSpaStaticFiles();
                }
            });
</code>```

in development mode, ASP serve the index.html of reports app
but all reference from main page ignores 'reports' prefix.
for example:
localhost\reports => file:reports\index.html.
but this file call to locathost\style.css instead of  locathost\reports\style.css

in production mode same url's return main app.

what is the best way to handle two apps on same Host.

Body:
I have tried to use two angular apps on single aspnet core 6.
using this code:

app.Map(@"/reports", app=>
            {
                app.UseSpa(spa =>
                {
                    spa.Options.SourcePath = "reportsApp";
                    if (env.IsDevelopment())
                    {
                        spa.Options.StartupTimeout = TimeSpan.FromSeconds(180); // Increase the timeout if angular app is taking longer to startup
                        spa.UseProxyToSpaDevelopmentServer("http://localhost:4201"); // Use this instead to use the angular cli server
                    }
                    else
                    {
                        app.UseSpaStaticFiles();
                    }
                });
            });
app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "App";
                if (env.IsDevelopment() )
                {
                    spa.Options.StartupTimeout = TimeSpan.FromSeconds(180); // Increase the timeout if angular app is taking longer to startup
                    spa.UseProxyToSpaDevelopmentServer("http://localhost:4200"); // Use this instead to use the angular cli server
                }
                else
                {
                    app.UseSpaStaticFiles();
                }
            });

in development mode, ASP serve the index.html of reports app
but all reference from main page ignores 'reports' prefix.
for example:
localhost\reports => file:reports\index.html.
but this file call to locathost\style.css instead of  locathost\reports\style.css

in production mode same url's return main app.

what is the best way to handle two apps on same Host.


问:
Unable to add firebase_messaging to flutter module
I wanted to add firebase_messaging package to my flutter module and failing to build aar. I am using flutter 3.0.1. Steps to reproduce:

flutter create -t module --org com.example my_flutter_abc

cd my_flutter_abc

flutter pub add firebase_messaging

flutter build aar

Getting the following error

```<code>Running "flutter pub get" in my_flutter_abc...                   2,428ms

 Building with sound null safety

Running Gradle task 'assembleAarDebug'...                          33.6s
Warning: The plugin firebase_messaging requires Android SDK version 33.
For more information about build configuration, see https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.

One or more plugins require a higher Android SDK version.
Fix this issue by adding the following to C:\workspace\flutter-module\my_flutter_abc\.android\Flutter\build.gradle:
android {
  compileSdkVersion 33
  ...
}

c:\flutter_3_0_1\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_messaging-14.1.4\android\src\main\java\io\flutter\plugins\firebase\messaging\FlutterFirebaseMessagingPlugin.java:399: error: cannot find symbol
            .checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)
                                                    ^
  symbol:   variable POST_NOTIFICATIONS
  location: class permission
c:\flutter_3_0_1\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_messaging-14.1.4\android\src\main\java\io\flutter\plugins\firebase\messaging\FlutterFirebasePermissionManager.java:63: error: cannot find symbol
    permissions.add(Manifest.permission.POST_NOTIFICATIONS);
                                       ^
  symbol:   variable POST_NOTIFICATIONS
  location: class permission
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: c:\flutter_3_0_1\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_messaging-14.1.4\android\src\main\java\io\flutter\plugins\firebase\messaging\FlutterFirebaseMessagingPlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':firebase_messaging:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 32s

Gradle task assembleAarDebug failed with exit code 1.
</code>```

Modified my_flutter_abc.android\Flutter\build.gradle to use

```<code>android {
    compileSdkVersion 33
....
}
</code>```

then getting the following error when run flutter build aar again

```<code>
 Building with sound null safety

Running Gradle task 'assembleAarDebug'...                          15.8s

Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: c:\flutter_3_0_1\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_messaging-14.1.4\android\src\main\java\io\flutter\plugins\firebase\messaging\FlutterFirebaseMessagingPlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':firebase_messaging:uploadArchives'.
> Could not publish configuration 'archives'
   > Could not write to file 'c:\flutter_3_0_1\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_messaging-14.1.4\android\build\poms\pom-default.xml'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 14s

Gradle task assembleAarDebug failed with exit code 1.
</code>```

The gradle files are automatically generated when flutter build command is executed. There seems to be compatibility issues related to firebase_messaging package. When I remove this package from pubspec.yaml, everything works fine.

This issue is not seen when flutter app project is created.

Body:
I wanted to add firebase_messaging package to my flutter module and failing to build aar. I am using flutter 3.0.1. Steps to reproduce:

flutter create -t module --org com.example my_flutter_abc

cd my_flutter_abc

flutter pub add firebase_messaging

flutter build aar

Getting the following error

Running "flutter pub get" in my_flutter_abc...                   2,428ms

 Building with sound null safety

Running Gradle task 'assembleAarDebug'...                          33.6s
Warning: The plugin firebase_messaging requires Android SDK version 33.
For more information about build configuration, see https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.

One or more plugins require a higher Android SDK version.
Fix this issue by adding the following to C:\workspace\flutter-module\my_flutter_abc\.android\Flutter\build.gradle:
android {
  compileSdkVersion 33
  ...
}

c:\flutter_3_0_1\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_messaging-14.1.4\android\src\main\java\io\flutter\plugins\firebase\messaging\FlutterFirebaseMessagingPlugin.java:399: error: cannot find symbol
            .checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS)
                                                    ^
  symbol:   variable POST_NOTIFICATIONS
  location: class permission
c:\flutter_3_0_1\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_messaging-14.1.4\android\src\main\java\io\flutter\plugins\firebase\messaging\FlutterFirebasePermissionManager.java:63: error: cannot find symbol
    permissions.add(Manifest.permission.POST_NOTIFICATIONS);
                                       ^
  symbol:   variable POST_NOTIFICATIONS
  location: class permission
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: c:\flutter_3_0_1\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_messaging-14.1.4\android\src\main\java\io\flutter\plugins\firebase\messaging\FlutterFirebaseMessagingPlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
2 errors

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':firebase_messaging:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 32s

Gradle task assembleAarDebug failed with exit code 1.

Modified my_flutter_abc.android\Flutter\build.gradle to use

android {
    compileSdkVersion 33
....
}

then getting the following error when run flutter build aar again

 Building with sound null safety

Running Gradle task 'assembleAarDebug'...                          15.8s

Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: c:\flutter_3_0_1\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_messaging-14.1.4\android\src\main\java\io\flutter\plugins\firebase\messaging\FlutterFirebaseMessagingPlugin.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':firebase_messaging:uploadArchives'.
> Could not publish configuration 'archives'
   > Could not write to file 'c:\flutter_3_0_1\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_messaging-14.1.4\android\build\poms\pom-default.xml'.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 14s

Gradle task assembleAarDebug failed with exit code 1.

The gradle files are automatically generated when flutter build command is executed. There seems to be compatibility issues related to firebase_messaging package. When I remove this package from pubspec.yaml, everything works fine.

This issue is not seen when flutter app project is created.


问:
Rust Equivalent to Python scipy.interp1d?
I'm porting some scientific python code to Rust as a learning exercise. In the Python version, I make use of scipy.interp1d, which I'm using to do things like the following:

Given sorted array x and array y, calculate array new_y using new_x. (with some flexibility of algorithm, linear, cubic etc.).

https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d

Does anyone have nice Rust examples of this?  I found the 'enterpolate' crate, but it seems mostly suited to interpolating to fixed interval x data.  Is there anything in 'ndarray' that does interpolation?