问:
Rust cannot infer an appropriate lifetime for autoref due to conflicting requirements
I am trying (and struggling) to create a simple tree structure in Rust and a breadth-first iterator for it, however I've been stuck for hours trying to fix lifetimes. This is the closest I've got to a successful build, but the only error is the one in the title.

Here is the full code:

```<code>use std::{vec, vec::Vec};

pub struct Tree<K, V>
where K: PartialEq + Clone {
    subtrees: Vec<Tree<K, V>>,
    key: K,
    value: Option<V>,
}

impl<K, V> Tree<K, V>
where K: PartialEq + Clone {
    pub const fn new(root_key: K, root_value: Option<V>) -> Tree<K, V> {
        Tree {
            subtrees: Vec::new(),
            key: root_key,
            value: root_value,
        }
    }

    pub fn get_subtree(&mut self, key: K) -> Option<&mut Self> {
        for tree in &mut self.subtrees {
            if tree.key == key {
                return Some(tree);
            }
        }
        None
    }

    pub fn value(&mut self) -> Option<&mut V> {
        self.value.as_mut()
    }

    pub fn insert_subtree(&mut self, key: K, value: Option<V>) {
        self.subtrees.push(Tree::new(key, value));
    }

    pub fn iter_bfs(&mut self) -> BFSIterator<K, V> {
        BFSIterator {
            levels: vec![(0, vec![SearchState {
                tree: self,
                parent: None,
                visited: false,
            }])],
        }
    }
}

struct SearchState<'a, K: 'a, V: 'a>
where K: PartialEq + Clone {
    tree: &'a mut Tree<K, V>,
    parent: Option<&'a mut Tree<K, V>>,
    visited: bool,
}

struct BFSIterator<'a, K: 'a, V: 'a>
where K: PartialEq + Clone {
    levels: Vec<(usize, Vec<SearchState<'a, K, V>>)>,
}

impl<'a, K, V> BFSIterator<'a, K, V>
where K: PartialEq + Clone {
    fn current_level(&mut self) -> &mut (usize, Vec<SearchState<'a, K, V>>) {
        self.levels.last_mut().unwrap()
    }

    fn current_node(&mut self) -> &mut SearchState<'a, K, V> {
        let index = self.current_level().0;
        &mut self.current_level().1[index]
    }

    fn advance_vertical(&mut self) {
        // current node is parent
        let parent = &self.current_node().tree;
        // fill next level vec with children of current node
        let mut level_vec = Vec::new();
        let a_tree = self.current_node().tree;
        for tree in &mut a_tree.subtrees {
            level_vec.push(SearchState {
                tree,
                parent: Some(*parent),
                visited: false,
            });
        }
        // advance horizontally to get to the next one when we go back here
        self.current_level().0 += 1;
        // if it is a leaf, do not advance
        if level_vec.len() != 0 {
            self.levels.push((0, level_vec));
        }
    }
}

impl<'a, K: 'a, V: 'a> Iterator for BFSIterator<'a, K, V>
where K: PartialEq + Clone {
    type Item = &'a mut Tree<K, V>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.current_node().visited {
            if self.current_level().0 < self.current_level().1.len() {
                // we can go down if not at the end of the line
                self.advance_vertical();
                let junk_state = self.current_node().tree;
                return Some(junk_state);
            } else {
                if self.levels.len() > 0 {
                    // if everything on this line has been searched, go back
                    self.levels.pop();
                } else {
                    // got back to beginning, quit
                    return None;
                }
            }
        } else {
            let ret_ref = self.current_node().tree;
            self.current_node().visited = true;
            if self.current_level().0 < self.current_level().1.len() - 1 {
                // advance horizontally if we can
                self.current_level().0 += 1;
            } else {
                // last node visited on this level, let's advance horizontally from the beginning if we can
                // go back to node 0 horizontally
                self.current_level().0 = 0;
                self.advance_vertical();
                return Some(ret_ref);
            }

        }
        None
    }
}
</code>```

The problematic line is the following:

```<code>// current node is parent
        let parent = &self.current_node().tree;
</code>```

Here, it is apparent that the field tree of the struct SearchState is a mutable reference with lifetime 'a, but Rust struggles to realize, as shown in the full error message:

```<code>cannot infer an appropriate lifetime for autoref due to conflicting requirements
expected `Vec<SearchState<'a, _, _>>`
   found `Vec<SearchState<'_, _, _>>`
</code>```

What are your suggestions to fix it? I really don't want to end up just using raw pointers instead of references.

Body:
I am trying (and struggling) to create a simple tree structure in Rust and a breadth-first iterator for it, however I've been stuck for hours trying to fix lifetimes. This is the closest I've got to a successful build, but the only error is the one in the title.

Here is the full code:

use std::{vec, vec::Vec};

pub struct Tree<K, V>
where K: PartialEq + Clone {
    subtrees: Vec<Tree<K, V>>,
    key: K,
    value: Option<V>,
}

impl<K, V> Tree<K, V>
where K: PartialEq + Clone {
    pub const fn new(root_key: K, root_value: Option<V>) -> Tree<K, V> {
        Tree {
            subtrees: Vec::new(),
            key: root_key,
            value: root_value,
        }
    }

    pub fn get_subtree(&mut self, key: K) -> Option<&mut Self> {
        for tree in &mut self.subtrees {
            if tree.key == key {
                return Some(tree);
            }
        }
        None
    }

    pub fn value(&mut self) -> Option<&mut V> {
        self.value.as_mut()
    }

    pub fn insert_subtree(&mut self, key: K, value: Option<V>) {
        self.subtrees.push(Tree::new(key, value));
    }

    pub fn iter_bfs(&mut self) -> BFSIterator<K, V> {
        BFSIterator {
            levels: vec![(0, vec![SearchState {
                tree: self,
                parent: None,
                visited: false,
            }])],
        }
    }
}

struct SearchState<'a, K: 'a, V: 'a>
where K: PartialEq + Clone {
    tree: &'a mut Tree<K, V>,
    parent: Option<&'a mut Tree<K, V>>,
    visited: bool,
}

struct BFSIterator<'a, K: 'a, V: 'a>
where K: PartialEq + Clone {
    levels: Vec<(usize, Vec<SearchState<'a, K, V>>)>,
}

impl<'a, K, V> BFSIterator<'a, K, V>
where K: PartialEq + Clone {
    fn current_level(&mut self) -> &mut (usize, Vec<SearchState<'a, K, V>>) {
        self.levels.last_mut().unwrap()
    }

    fn current_node(&mut self) -> &mut SearchState<'a, K, V> {
        let index = self.current_level().0;
        &mut self.current_level().1[index]
    }

    fn advance_vertical(&mut self) {
        // current node is parent
        let parent = &self.current_node().tree;
        // fill next level vec with children of current node
        let mut level_vec = Vec::new();
        let a_tree = self.current_node().tree;
        for tree in &mut a_tree.subtrees {
            level_vec.push(SearchState {
                tree,
                parent: Some(*parent),
                visited: false,
            });
        }
        // advance horizontally to get to the next one when we go back here
        self.current_level().0 += 1;
        // if it is a leaf, do not advance
        if level_vec.len() != 0 {
            self.levels.push((0, level_vec));
        }
    }
}

impl<'a, K: 'a, V: 'a> Iterator for BFSIterator<'a, K, V>
where K: PartialEq + Clone {
    type Item = &'a mut Tree<K, V>;
    fn next(&mut self) -> Option<Self::Item> {
        if self.current_node().visited {
            if self.current_level().0 < self.current_level().1.len() {
                // we can go down if not at the end of the line
                self.advance_vertical();
                let junk_state = self.current_node().tree;
                return Some(junk_state);
            } else {
                if self.levels.len() > 0 {
                    // if everything on this line has been searched, go back
                    self.levels.pop();
                } else {
                    // got back to beginning, quit
                    return None;
                }
            }
        } else {
            let ret_ref = self.current_node().tree;
            self.current_node().visited = true;
            if self.current_level().0 < self.current_level().1.len() - 1 {
                // advance horizontally if we can
                self.current_level().0 += 1;
            } else {
                // last node visited on this level, let's advance horizontally from the beginning if we can
                // go back to node 0 horizontally
                self.current_level().0 = 0;
                self.advance_vertical();
                return Some(ret_ref);
            }

        }
        None
    }
}

The problematic line is the following:

// current node is parent
        let parent = &self.current_node().tree;

Here, it is apparent that the field tree of the struct SearchState is a mutable reference with lifetime 'a, but Rust struggles to realize, as shown in the full error message:

cannot infer an appropriate lifetime for autoref due to conflicting requirements
expected `Vec<SearchState<'a, _, _>>`
   found `Vec<SearchState<'_, _, _>>`

What are your suggestions to fix it? I really don't want to end up just using raw pointers instead of references.


来源: stackexchange

问:
Coverity reporting resource leaks that look like false positives
I'm getting a lot of resource leak issues identified by Coverity in a .NET project.

Here is an example:

The serializer is an instance of GraphQLSerializer and is configured as a singleton (in Startup.ConfigureServices()):

```<code>services.AddSingleton<IGraphQLSerializer, GraphQLSerializer>();
</code>```

GraphQLSerializer does not implement IDisposable:

```<code>public class GraphQLSerializer : IGraphQLTextSerializer
</code>```
```<code>public interface IGraphQLTextSerializer : IGraphQLSerializer
</code>```
```<code>public interface IGraphQLSerializer
</code>```

I don't get what resource is it leaked here. I have dozens of similar detected issues, with different types, but all on GetService(), with singleton objects of classes that don't implement IDisposable.

Is it safely to assume these are false positives? Or am I missing something here?

ContentLicense: CC BY-SA 4.0

Body:
I'm getting a lot of resource leak issues identified by Coverity in a .NET project.

Here is an example:

The serializer is an instance of GraphQLSerializer and is configured as a singleton (in Startup.ConfigureServices()):

services.AddSingleton<IGraphQLSerializer, GraphQLSerializer>();

GraphQLSerializer does not implement IDisposable:

public class GraphQLSerializer : IGraphQLTextSerializer

public interface IGraphQLTextSerializer : IGraphQLSerializer

public interface IGraphQLSerializer

I don't get what resource is it leaked here. I have dozens of similar detected issues, with different types, but all on GetService(), with singleton objects of classes that don't implement IDisposable.

Is it safely to assume these are false positives? Or am I missing something here?


问:
In flutter, how can I generate firebase token?
I want to generate a firebase token with device id with flutter mobile application. With this generated firebase token, I want to do with login function and other process. How can I generate firebase token with device id? Only for generating purpose, not for messaging and other purpose.

...........................

In detailedly, the the procedure I want to do is :

First : get device ID from device

Second : sent to firebase that previous getting device Id and want get back a firebase token to use in my API to login and other purpose. (!!! I asked this state. I am not familiar with firebase.)


问:
Get content from Consumer class object
Trying to verify content of Consumer<> class in unit test.

```<code>verify(customer, times(2)).setName(argumentCaptor.capture() as Consumer<Name>?)
println(argumentCaptor.allValues)
</code>```

The toString() also prints same string:
com.java.services.myClassName$MY_CONTENT$$Lambda$327/0x00000008004eeed0@590dea35

The setName method works like this:

```<code>myObject.setName { it.firstName = "firstName" }
</code>```

How do I get to MY_CONTENT so I can verify them with a list of string later?
How is the printout interpreted? What does Lambda present here.

Title: Get content from Consumer class object

Body:
Trying to verify content of Consumer<> class in unit test.

verify(customer, times(2)).setName(argumentCaptor.capture() as Consumer<Name>?)
println(argumentCaptor.allValues)

The toString() also prints same string:
com.java.services.myClassName$MY_CONTENT$$Lambda$327/0x00000008004eeed0@590dea35

The setName method works like this:

myObject.setName { it.firstName = "firstName" }

How do I get to MY_CONTENT so I can verify them with a list of string later?
How is the printout interpreted? What does Lambda present here.


问:
InfluxDB C# WritePoint write integer values shows as double
I'm trying to write a point into a influxdb bucket, using the code below C# inluxdb client, but when i look into influxdb the values have decimal places.

I saw examples with .Field("example", 10D), but how i do it with a variable?

```<code>point = PointData.Measurement(measurement)
                 .Field(name, Int32.Parse(value, CultureInfo.InvariantCulture))
                 .Timestamp(DateTime.UtcNow, WritePrecision.Ns);

writeApi.WritePoint(point, bucket, orgID);
</code>```

Body:
I'm trying to write a point into a influxdb bucket, using the code below C# inluxdb client, but when i look into influxdb the values have decimal places.

I saw examples with .Field("example", 10D), but how i do it with a variable?

point = PointData.Measurement(measurement)
                 .Field(name, Int32.Parse(value, CultureInfo.InvariantCulture))
                 .Timestamp(DateTime.UtcNow, WritePrecision.Ns);

writeApi.WritePoint(point, bucket, orgID);


问:
Mongoose function returning before Promise resolved
```<code>mongoCheckFile = async (fileData) => {
try {
 let offerIdsValues = [];
 //Extract all fileIds from CSV
 fileData.data.forEach((element, idx, fileData) => {
   fileIdsInCsv.push(`${element.fileId}`)
 });

fileData.fileOffers.forEach(element => {
  offerIdsValues.push(element.id);
});

let matchingClickDocs = [];

//The following functions are not waited for before returning
await Click.find({
  $and: [ {fileId: { $in: fileIdsInCsv} }, { fileId: {$in: offerIdsValues} } ]
}).populate('furtherInfo').exec(async (error, clicks) =>  {
  if (error) {
    console.log(error);
  } else {
     await Promise.all(clicks.map(async (click) => {
       const furtherDatas = await furtherData.findOne({ fileId: click.fileId });
       if (furtherDatas) {
         click.furtherInfo = furtherDatas;
         await click.save();
         matchingClickDocs.push(click);
        //this pushes correct values and creates correct array.
       }
     }));
     console.log(matchingClickDocs.length, 'first')
    // This returns after global function  with correct val
  }
  console.log(matchingClickDocs.length, 'second')
    // This returns after above  with correct val
  });
console.log( matchingClickDocs.length, 'third')
// Returns first with incorrect Val.
  }
  catch (err) {
    return (err);
  }
};
</code>```

This function returns before the promise returns its array.
I have console.logged the output as I run through and its all good until it comes to returning it.
I've hit a brick wall trying to return these values before the function returns.
I guess its a problem with the global function not awaiting the promises at the end.
I've tried a few different implementations but keep getting stuck on it.

Body:
mongoCheckFile = async (fileData) => {
try {
 let offerIdsValues = [];
 //Extract all fileIds from CSV
 fileData.data.forEach((element, idx, fileData) => {
   fileIdsInCsv.push(`${element.fileId}`)
 });

fileData.fileOffers.forEach(element => {
  offerIdsValues.push(element.id);
});

let matchingClickDocs = [];

//The following functions are not waited for before returning
await Click.find({
  $and: [ {fileId: { $in: fileIdsInCsv} }, { fileId: {$in: offerIdsValues} } ]
}).populate('furtherInfo').exec(async (error, clicks) =>  {
  if (error) {
    console.log(error);
  } else {
     await Promise.all(clicks.map(async (click) => {
       const furtherDatas = await furtherData.findOne({ fileId: click.fileId });
       if (furtherDatas) {
         click.furtherInfo = furtherDatas;
         await click.save();
         matchingClickDocs.push(click);
        //this pushes correct values and creates correct array.
       }
     }));
     console.log(matchingClickDocs.length, 'first')
    // This returns after global function  with correct val
  }
  console.log(matchingClickDocs.length, 'second')
    // This returns after above  with correct val
  });
console.log( matchingClickDocs.length, 'third')
// Returns first with incorrect Val.
  }
  catch (err) {
    return (err);
  }
};

This function returns before the promise returns its array.
I have console.logged the output as I run through and its all good until it comes to returning it.
I've hit a brick wall trying to return these values before the function returns.
I guess its a problem with the global function not awaiting the promises at the end.
I've tried a few different implementations but keep getting stuck on it.


问:
How can I force Selenium to control MiniBrowser?
I'm trying to automate some cross-browser website testing for my employer. Currently, we have a small C#-xUnit-Selenium testing suite for End-to-End tests. My goal is to run these tests locally on Windows using Google Chrome, Firefox, and Safari. The first two browsers I'm not worried about. Safari is giving me the trouble.

Since Safari doesn't support Win10, I've opted to use a WebKit-powered browser as a substitute. I know it won't be a 1-1 match, but I'm not concerned by the differences. My browser of choice is MiniBrowser, emulating Safari 15 with a very recent build of Webkit port WinCairo.

Here's my current problem: I don't know how to force Selenium to control MiniBrowser.

I would really like to have a class in Selenium that could parallel ChromeDriver() or SafariDriver() (WinCairoDriver(), I guess). But I don't know how to create it. I know that both WinCairo and MiniBrowser implement a WebDriver.exe file in their bin folders,
but I don't know how to translate that file into a driver class Selenium can recognize. I'm sure there are other requirements as well to get it working.

Any help would be appreciated.

Guide I used to build WinCairo browser

Link to my built WinCairo MiniBrowser

Here's where I would insert said WinCairoDriver() class if it existed:

```<code>namespace Project_Tests.Fixtures
{
    public class DriverSetup : IDisposable
    {
        public IWebDriver driver;

        public DriverSetup()
        {
            new DriverManager().SetUpDriver(new ChromeConfig());

            var chromeDriver = new ChromeDriver();
            // I need help here:
            //var wincairoDriver = new WinCairoDriver();

            driver = chromeDriver; // Where I want to pass wincairoDriver;
        }

        public void Dispose()
        {
            driver.Quit();
        }
    }
}
</code>```

Body:
I'm trying to automate some cross-browser website testing for my employer. Currently, we have a small C#-xUnit-Selenium testing suite for End-to-End tests. My goal is to run these tests locally on Windows using Google Chrome, Firefox, and Safari. The first two browsers I'm not worried about. Safari is giving me the trouble.

Since Safari doesn't support Win10, I've opted to use a WebKit-powered browser as a substitute. I know it won't be a 1-1 match, but I'm not concerned by the differences. My browser of choice is MiniBrowser, emulating Safari 15 with a very recent build of Webkit port WinCairo.

Here's my current problem: I don't know how to force Selenium to control MiniBrowser.

I would really like to have a class in Selenium that could parallel ChromeDriver() or SafariDriver() (WinCairoDriver(), I guess). But I don't know how to create it. I know that both WinCairo and MiniBrowser implement a WebDriver.exe file in their bin folders,
but I don't know how to translate that file into a driver class Selenium can recognize. I'm sure there are other requirements as well to get it working.

Any help would be appreciated.

Guide I used to build WinCairo browser

Link to my built WinCairo MiniBrowser

Here's where I would insert said WinCairoDriver() class if it existed:

namespace Project_Tests.Fixtures
{
    public class DriverSetup : IDisposable
    {
        public IWebDriver driver;

        public DriverSetup()
        {
            new DriverManager().SetUpDriver(new ChromeConfig());

            var chromeDriver = new ChromeDriver();
            // I need help here:
            //var wincairoDriver = new WinCairoDriver();

            driver = chromeDriver; // Where I want to pass wincairoDriver;
        }

        public void Dispose()
        {
            driver.Quit();
        }
    }
}


问:
Getting PHP Server / Live Server VS Code extensions to work for WordPress site
I am trying to get PHP Server/Live Server for a WordPress project in VS Code to work, but this last part has me puzzled and I'm unable to find an answer. My setup so far is as follows:

VS Code extensions: Installed PHP Server and Live Server extensions.

Added the following to settings.json:

```<code>"php.validate.enable": true,
"php.validate.run": "onType",
</code>```

Added the Live Server extension to Chrome

In the Live Server extension settings, I have: 'Actual Server: http://localhost:8080/', 'Live Server Address: http://127.0.0.1:5500/'. (I've also tried 'http://localhost:8080/sitename' for Actual Server)

Outcomes:

-If I manually browse to my WordPress site at http://localhost:8080/sitename, the site loads fine.

-In VS Code, when I click "Go Live" to run the live server, Chrome loads http://127.0.0.1:5500, but it is only displaying the WordPress theme directory, not the landing page for the site.

-If I right-click in the index.php file in VS Code and choose 'PHP Server: Serve Project", it loads a page with 'Fatal error: Uncaught Error: Call to undefined function get_header()..." because it isn't loading all of the other WordPress files with it so that basic functions like get_header() and get_footer() are recognized.

One solution I found for ensuring all WordPress files are loaded suggested adding the following to settings.json:

```<code>"php.validate.includePath: "wp-content",
</code>```

But VS Code is telling me that 'php.validate.includePath' is an unknown configuration option.

*PS - This is a simple wordpress testing environment, which is why I'm using index.php for the landing page.

Body:
I am trying to get PHP Server/Live Server for a WordPress project in VS Code to work, but this last part has me puzzled and I'm unable to find an answer. My setup so far is as follows:

VS Code extensions: Installed PHP Server and Live Server extensions.

Added the following to settings.json:

"php.validate.enable": true,
"php.validate.run": "onType",

Added the Live Server extension to Chrome

In the Live Server extension settings, I have: 'Actual Server: http://localhost:8080/', 'Live Server Address: http://127.0.0.1:5500/'. (I've also tried 'http://localhost:8080/sitename' for Actual Server)

Outcomes:

-If I manually browse to my WordPress site at http://localhost:8080/sitename, the site loads fine.

-In VS Code, when I click "Go Live" to run the live server, Chrome loads http://127.0.0.1:5500, but it is only displaying the WordPress theme directory, not the landing page for the site.

-If I right-click in the index.php file in VS Code and choose 'PHP Server: Serve Project", it loads a page with 'Fatal error: Uncaught Error: Call to undefined function get_header()..." because it isn't loading all of the other WordPress files with it so that basic functions like get_header() and get_footer() are recognized.

One solution I found for ensuring all WordPress files are loaded suggested adding the following to settings.json:

"php.validate.includePath: "wp-content",

But VS Code is telling me that 'php.validate.includePath' is an unknown configuration option.

*PS - This is a simple wordpress testing environment, which is why I'm using index.php for the landing page.


问:
An error when trying to post a photo on instagram using instagram-private-api
I've tried to post a photo on instagram, but I've got an Bad Request error. Is that package fault or mine?

Code:

```<code>// modules
const config = require("./config.json");
const createPost = require("./canvas");
const fs = require('fs');

// db
const { QuickDB } = require('quick.db');
const db = new QuickDB();

// instagram
const { IgApiClient } = require('instagram-private-api');
const { sample } = require('lodash');
const ig = new IgApiClient();
ig.state.generateDevice(config.instagramUsername);

// tellonym
const Tellonym = require('tellonym-api');
const client = new Tellonym.login(config.tellonymToken);

// variabls
let tells = [];

// main code
setInterval(async () => {
    client.getQuestions(20).then(response => {

        response.forEach(async tell => {
            if (tell.type === 'tell')
            {
                tells.push(tell.tell);
                if(JSON.parse(JSON.stringify(await db.get('tells'))).strings[0].includes(tell.tell)) return;
                await createPost(tell.tell);

                await ig.simulate.preLoginFlow();
                const loggedInUser = await ig.account.login(config.instagramUsername, config.instagramPassword);
                process.nextTick(async () => await ig.simulate.postLoginFlow());

                const post = await ig.publish.photo(
                    {
                        "file": fs.readFileSync("./output.png")
                    }
                );console.log(post)

            }
        });

        db.set("tells", {strings: [tells]});
    });
}, 0.1 * 1000 * 60);
</code>```

Error:

C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:126
return new errors_1.IgResponseError(response);
^

IgResponseError: POST /rupload_igphoto/1671729786445_0_4886961932 -
400 Bad Request;
at Request.handleResponseError (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:126:16)
at Request.send (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:54:28)
at async UploadRepository.photo (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\repositories\upload.repository.js:18:26)
at async PublishService.photo (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\services\publish.service.js:80:31)
at async C:\Users\PC\Desktop\spotted\index.js:38:30

Node.js v19.2.0

Body:
I've tried to post a photo on instagram, but I've got an Bad Request error. Is that package fault or mine?

Code:

// modules
const config = require("./config.json");
const createPost = require("./canvas");
const fs = require('fs');

// db
const { QuickDB } = require('quick.db');
const db = new QuickDB();

// instagram
const { IgApiClient } = require('instagram-private-api');
const { sample } = require('lodash');
const ig = new IgApiClient();
ig.state.generateDevice(config.instagramUsername);

// tellonym
const Tellonym = require('tellonym-api');
const client = new Tellonym.login(config.tellonymToken);

// variabls
let tells = [];

// main code
setInterval(async () => {
    client.getQuestions(20).then(response => {

        response.forEach(async tell => {
            if (tell.type === 'tell')
            {
                tells.push(tell.tell);
                if(JSON.parse(JSON.stringify(await db.get('tells'))).strings[0].includes(tell.tell)) return;
                await createPost(tell.tell);

                await ig.simulate.preLoginFlow();
                const loggedInUser = await ig.account.login(config.instagramUsername, config.instagramPassword);
                process.nextTick(async () => await ig.simulate.postLoginFlow());

                const post = await ig.publish.photo(
                    {
                        "file": fs.readFileSync("./output.png")
                    }
                );console.log(post)

            }
        });

        db.set("tells", {strings: [tells]});
    });
}, 0.1 * 1000 * 60);

Error:

C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:126
return new errors_1.IgResponseError(response);
^

IgResponseError: POST /rupload_igphoto/1671729786445_0_4886961932 -
400 Bad Request;
at Request.handleResponseError (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:126:16)
at Request.send (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:54:28)
at async UploadRepository.photo (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\repositories\upload.repository.js:18:26)
at async PublishService.photo (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\services\publish.service.js:80:31)
at async C:\Users\PC\Desktop\spotted\index.js:38:30

Node.js v19.2.0


问:
Get item in SkipListener onSkipInRead in Spring Batch
I'm following this post to do the same as the OP is asking, store in a table of a database the failed records while reading/processing/writing. The only issue I have is with the onSkipInRead that the item is not there, so I'm not able to post the skipped item to the database. How can I get the onSkipInRead item?

Below is my Step configuration and SkipListener:

```<code>public Step step() {
    return stepBuilderFactory.get("Step")
            .<Input, Output> chunk(100)
            .reader(reader()).faultTolerant().listener(recordSkipListener()).skipPolicy(fileVerificationSkipper())
            .processor(processor())
            .writer(writer())
            .listener(stepExecutionListener())
            .build();
}

public class RecordSkipListener implements SkipListener<Input, Output> {

    @Override
    public void onSkipInRead(Throwable t) {     // <-- item not available here
        log.info("Skipping record while reading");

    }

    @Override
    public void onSkipInWrite(Output item, Throwable t) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSkipInProcess(Input item, Throwable t) {
        log.info("Skipping record while process with Key: {}", item.getKey());
        // Here since I have the record (item) I can update the table in the database with the item details
    }
}
</code>```

Body:
I'm following this post to do the same as the OP is asking, store in a table of a database the failed records while reading/processing/writing. The only issue I have is with the onSkipInRead that the item is not there, so I'm not able to post the skipped item to the database. How can I get the onSkipInRead item?

Below is my Step configuration and SkipListener:

public Step step() {
    return stepBuilderFactory.get("Step")
            .<Input, Output> chunk(100)
            .reader(reader()).faultTolerant().listener(recordSkipListener()).skipPolicy(fileVerificationSkipper())
            .processor(processor())
            .writer(writer())
            .listener(stepExecutionListener())
            .build();
}

public class RecordSkipListener implements SkipListener<Input, Output> {

    @Override
    public void onSkipInRead(Throwable t) {     // <-- item not available here
        log.info("Skipping record while reading");

    }

    @Override
    public void onSkipInWrite(Output item, Throwable t) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSkipInProcess(Input item, Throwable t) {
        log.info("Skipping record while process with Key: {}", item.getKey());
        // Here since I have the record (item) I can update the table in the database with the item details
    }
}


问:
I am facing issue with Azure Pipeline with floating-ui package anyhow we are not using that package anywhere in Project
I am facing issue with Azure Pipeline . It is giving error with floating-ui even though we are not using it anywhere in React project.

I tries to find the solution but it not found anything.


问:
Can I put text outside ImageBackground in a ScrollView?
I am trying to have the text scroll with the image, like in this example:
https://reactnative.dev/docs/animations#scrollview-with-animated-event-example. But I want the text to be below of the image.

When I try to push the text outside with a margin or padding, the text disappears, and when I convert the image to have overflow visible, it still doesn't work(and I don't want to be able to drag the image to move around up/down.)

Here is the main code:

```<code>const images = new Array(6).fill('https://images.unsplash.com/photo-1556740749-887f6717d7e4');

const App = () => {
  const scrollX = useRef(new Animated.Value(0)).current;

  const { width: windowWidth } = useWindowDimensions();

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.scrollContainer}>
        <ScrollView
          horizontal={true}
          pagingEnabled
          showsHorizontalScrollIndicator={false}
          onScroll={Animated.event([
            {
              nativeEvent: {
                contentOffset: {
                  x: scrollX
                }
              }
            }
          ])}
          scrollEventThrottle={1}
        >
          {images.map((image, imageIndex) => {
            return (
              <View
                style={{ width: windowWidth, height: 250 }}
                key={imageIndex}
              >
                <ImageBackground source={{ uri: image }} style={styles.card}>
                  <View style={styles.textContainer}>
                    <Text style={styles.infoText}>
                      {"Image - " + imageIndex}
                    </Text>
                  </View>
                </ImageBackground>
              </View>
            );
          })}
        </ScrollView>
        <View style={styles.indicatorContainer}>
          {images.map((image, imageIndex) => {
            const width = scrollX.interpolate({
              inputRange: [
                windowWidth * (imageIndex - 1),
                windowWidth * imageIndex,
                windowWidth * (imageIndex + 1)
              ],
              outputRange: [8, 16, 8],
              extrapolate: "clamp"
            });
            return (
              <Animated.View
                key={imageIndex}
                style={[styles.normalDot, { width }]}
              />
            );
          })}
        </View>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  scrollContainer: {
    height: 300,
    alignItems: "center",
    justifyContent: "center"
  },
  card: {
    flex: 1,
    marginVertical: 4,
    marginHorizontal: 16,
    borderRadius: 5,
    overflow: "hidden",
    alignItems: "center",
    justifyContent: "center"
  },
  textContainer: {
    backgroundColor: "rgba(0,0,0, 0.7)",
    paddingHorizontal: 24,
    paddingVertical: 8,
    borderRadius: 5
  },
  infoText: {
    color: "white",
    fontSize: 16,
    fontWeight: "bold"
  },
  normalDot: {
    height: 8,
    width: 8,
    borderRadius: 4,
    backgroundColor: "silver",
    marginHorizontal: 4
  },
  indicatorContainer: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center"
  }
});
</code>```

Any help would be appreciated (:

Body:
I am trying to have the text scroll with the image, like in this example:
https://reactnative.dev/docs/animations#scrollview-with-animated-event-example. But I want the text to be below of the image.

When I try to push the text outside with a margin or padding, the text disappears, and when I convert the image to have overflow visible, it still doesn't work(and I don't want to be able to drag the image to move around up/down.)

Here is the main code:

const images = new Array(6).fill('https://images.unsplash.com/photo-1556740749-887f6717d7e4');

const App = () => {
  const scrollX = useRef(new Animated.Value(0)).current;

  const { width: windowWidth } = useWindowDimensions();

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.scrollContainer}>
        <ScrollView
          horizontal={true}
          pagingEnabled
          showsHorizontalScrollIndicator={false}
          onScroll={Animated.event([
            {
              nativeEvent: {
                contentOffset: {
                  x: scrollX
                }
              }
            }
          ])}
          scrollEventThrottle={1}
        >
          {images.map((image, imageIndex) => {
            return (
              <View
                style={{ width: windowWidth, height: 250 }}
                key={imageIndex}
              >
                <ImageBackground source={{ uri: image }} style={styles.card}>
                  <View style={styles.textContainer}>
                    <Text style={styles.infoText}>
                      {"Image - " + imageIndex}
                    </Text>
                  </View>
                </ImageBackground>
              </View>
            );
          })}
        </ScrollView>
        <View style={styles.indicatorContainer}>
          {images.map((image, imageIndex) => {
            const width = scrollX.interpolate({
              inputRange: [
                windowWidth * (imageIndex - 1),
                windowWidth * imageIndex,
                windowWidth * (imageIndex + 1)
              ],
              outputRange: [8, 16, 8],
              extrapolate: "clamp"
            });
            return (
              <Animated.View
                key={imageIndex}
                style={[styles.normalDot, { width }]}
              />
            );
          })}
        </View>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center"
  },
  scrollContainer: {
    height: 300,
    alignItems: "center",
    justifyContent: "center"
  },
  card: {
    flex: 1,
    marginVertical: 4,
    marginHorizontal: 16,
    borderRadius: 5,
    overflow: "hidden",
    alignItems: "center",
    justifyContent: "center"
  },
  textContainer: {
    backgroundColor: "rgba(0,0,0, 0.7)",
    paddingHorizontal: 24,
    paddingVertical: 8,
    borderRadius: 5
  },
  infoText: {
    color: "white",
    fontSize: 16,
    fontWeight: "bold"
  },
  normalDot: {
    height: 8,
    width: 8,
    borderRadius: 4,
    backgroundColor: "silver",
    marginHorizontal: 4
  },
  indicatorContainer: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center"
  }
});

Any help would be appreciated (:


问:
calling signalr on method from angular component
I am making web app with angular and @microsoft/signalr. I am able to read data and log it in the console but when i try to use incoming value in another component. data coming as null.

Here is my signal service:

```<code>@Injectable({
  providedIn: 'root'
})
export class SignalRService {

  private hubConnection: HubConnection;

  public data: BehaviorSubject<any>;

  constructor() {
    this.data = new BehaviorSubject([]);
  }

  public startConnection(): void {
    this.hubConnection = new HubConnectionBuilder()
      .withUrl('https://testServer.com:4301/notify', {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets
      })
      .build();

    this.hubConnection
      .start()
      .then(() => {
        console.log('Connection started succesfully');
        this.registerRealTimeEvents();
      })
      .catch(err => console.log('Error while starting connection: ' + err));
  }

  public registerRealTimeEvents(): void {
    this.data = new BehaviorSubject<any>([]); // create the subject

    this.hubConnection.on('ListTenorMessage', (data) => {
      console.log(data);
      this.data.next(data);
    });
  }

}
</code>```

here up I can see the incoming data when socket send message.

And here my init method when I call:

```<code>  this.signalRService.startConnection();
    this.signalRService.data.subscribe(res => {
      console.log(res);
    });
</code>```

Would someone has any idea?
Thanks!

Body:
I am making web app with angular and @microsoft/signalr. I am able to read data and log it in the console but when i try to use incoming value in another component. data coming as null.

Here is my signal service:

@Injectable({
  providedIn: 'root'
})
export class SignalRService {

  private hubConnection: HubConnection;

  public data: BehaviorSubject<any>;

  constructor() {
    this.data = new BehaviorSubject([]);
  }

  public startConnection(): void {
    this.hubConnection = new HubConnectionBuilder()
      .withUrl('https://testServer.com:4301/notify', {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets
      })
      .build();

    this.hubConnection
      .start()
      .then(() => {
        console.log('Connection started succesfully');
        this.registerRealTimeEvents();
      })
      .catch(err => console.log('Error while starting connection: ' + err));
  }

  public registerRealTimeEvents(): void {
    this.data = new BehaviorSubject<any>([]); // create the subject

    this.hubConnection.on('ListTenorMessage', (data) => {
      console.log(data);
      this.data.next(data);
    });
  }

}

here up I can see the incoming data when socket send message.

And here my init method when I call:

  this.signalRService.startConnection();
    this.signalRService.data.subscribe(res => {
      console.log(res);
    });

Would someone has any idea?
Thanks!


问:
"Invalid Host header" when visiting React app through domain - Rails backend with Nginx reverse proxy
I have a React app with a Ruby on Rails backend being served from a Linux machine I own (not a cloud provider). The React app is served using the serve application after being built with npm run build, and it makes several HTTP requests to a Ruby on Rails backend that I also run from the same machine. The requests are made using the Axios package. This is the first React app that I'm trying to build and host on my domain, so I'm a bit new to all of this.

I also use Google Domains so that the app can be reached via a domain I own. The app is reachable at http://bt_tokens.jzisser.com. Finally, I use Nginx Proxy Manager as a reverse proxy so I can easily route requests to my domain to different servers on my backend based on the subdomain.

The trouble is, when I try to navigate to the link above, the page simply displays an "Invalid Host header" message instead of loading. Looking in the network tab of my browser, the request results in a 400 "Bad Request" response.

I read up on this a bit and it seems I need to make sure that my request to the URL includes a "Host" header, with the value being the domain name that the request is going to. So for example, for the link above: Host: bt_tokens.jzisser.com. I added this to the request by going into the Proxy Host for bt_tokens.jzisser.com and adding a custom location as follows:

And looking at the network tab, the Host header is being added:

In researching how to fix this, I came across a solution involving editing the webpacker config to include allowedHosts:

```<code>module.exports = {
  //...
  devServer: {
    allowedHosts: 'all',
  },
};
</code>```

The catch here is that I don't have a custom webpacker config, and until now, have had no reason to consider a custom config. Other SO answers have pointed to the webpacker.config.js file in the node_modules folder, which feels really weird to me, but I went ahead and edited the config there to include this block. And I can confirm it's being picked up by npm run build, because at one point I accidentally created a syntax error there and the build failed. However, adding this did not fix the "Invalid Host header" issue.

Further Googling and searching SO hasn't turned up anything helpful, so I feel like I've hit a wall. Can anyone help me figure out how to fix this, or what I can do to debug this further on my own?

Body:
I have a React app with a Ruby on Rails backend being served from a Linux machine I own (not a cloud provider). The React app is served using the serve application after being built with npm run build, and it makes several HTTP requests to a Ruby on Rails backend that I also run from the same machine. The requests are made using the Axios package. This is the first React app that I'm trying to build and host on my domain, so I'm a bit new to all of this.

I also use Google Domains so that the app can be reached via a domain I own. The app is reachable at http://bt_tokens.jzisser.com. Finally, I use Nginx Proxy Manager as a reverse proxy so I can easily route requests to my domain to different servers on my backend based on the subdomain.

The trouble is, when I try to navigate to the link above, the page simply displays an "Invalid Host header" message instead of loading. Looking in the network tab of my browser, the request results in a 400 "Bad Request" response.

I read up on this a bit and it seems I need to make sure that my request to the URL includes a "Host" header, with the value being the domain name that the request is going to. So for example, for the link above: Host: bt_tokens.jzisser.com. I added this to the request by going into the Proxy Host for bt_tokens.jzisser.com and adding a custom location as follows:

And looking at the network tab, the Host header is being added:

In researching how to fix this, I came across a solution involving editing the webpacker config to include allowedHosts:

module.exports = {
  //...
  devServer: {
    allowedHosts: 'all',
  },
};

The catch here is that I don't have a custom webpacker config, and until now, have had no reason to consider a custom config. Other SO answers have pointed to the webpacker.config.js file in the node_modules folder, which feels really weird to me, but I went ahead and edited the config there to include this block. And I can confirm it's being picked up by npm run build, because at one point I accidentally created a syntax error there and the build failed. However, adding this did not fix the "Invalid Host header" issue.

Further Googling and searching SO hasn't turned up anything helpful, so I feel like I've hit a wall. Can anyone help me figure out how to fix this, or what I can do to debug this further on my own?


问:
Android Studio Dolphin
I can open and edit a project the first time. But when I try opening it a second time it shows no files. I tried to delete and rebuild, but with no luck. Also optimizing doesn't work either. My project doesn't use gradle, and I am using current release dolphin.

May someone help me with an advice?

Title: Android Studio Dolphin


问:
How do I use VBA to find out where a connection is being used if at all?
The issue is that, excel connections and queries can sometimes become unlinked, or fail to refresh due to one error or another.  The issue is when i am attempting to check for this disconnect, there doesn't appear to be a method to differentiate between connections with table and connection only.

I've attempted using source like this,

```<code>    Dim sourceConnection  As Object: Set sourceConnection = ActiveWorkbook.Connections(1)
    ThisWorkbook.RefreshAll
    Application.CalculateUntilAsyncQueriesDone
    Sheets(1).Activate

    ' Add code to determine the worksheet that is using the connection

    If sourceConnection.OLEDBConnection.Source = "" Then
        MsgBox "The sourceConnection is connected with only a connection."
    Else
        MsgBox "The sourceConnection is linked to a table somewhere on the workbook."
    End If

</code>```

Tablename

```<code>    Dim sourceConnection  As Object: Set sourceConnection = ActiveWorkbook.Connections(1)
    ThisWorkbook.RefreshAll
    Application.CalculateUntilAsyncQueriesDone
    Sheets(1).Activate

    ' Add code to determine the worksheet that is using the connection

    If sourceConnection.OLEDBConnection.Tablename = "" Then
        MsgBox "The sourceConnection is connected with only a connection."
    Else
        MsgBox "The sourceConnection is linked to a table somewhere on the workbook."
    End If

</code>```

or even command text

```<code>    Dim sourceConnection  As Object: Set sourceConnection = ActiveWorkbook.Connections(1)
    ThisWorkbook.RefreshAll
    Application.CalculateUntilAsyncQueriesDone
    Sheets(1).Activate

    ' Add code to determine the worksheet that is using the connection

    If sourceConnection.CommandText = "" Then
        MsgBox "The sourceConnection is connected with only a connection."
    Else
        MsgBox "The sourceConnection is linked to a table somewhere on the workbook."
    End If
</code>```

of the three, command text is the only one that compiles and runs, but fails to provide the desired information as the text only looks at the commands being followed by the connection, and does not reference anything regarding the tables it may be used by.

Body:
The issue is that, excel connections and queries can sometimes become unlinked, or fail to refresh due to one error or another.  The issue is when i am attempting to check for this disconnect, there doesn't appear to be a method to differentiate between connections with table and connection only.

I've attempted using source like this,

    Dim sourceConnection  As Object: Set sourceConnection = ActiveWorkbook.Connections(1)
    ThisWorkbook.RefreshAll
    Application.CalculateUntilAsyncQueriesDone
    Sheets(1).Activate

    ' Add code to determine the worksheet that is using the connection

    If sourceConnection.OLEDBConnection.Source = "" Then
        MsgBox "The sourceConnection is connected with only a connection."
    Else
        MsgBox "The sourceConnection is linked to a table somewhere on the workbook."
    End If

Tablename

    Dim sourceConnection  As Object: Set sourceConnection = ActiveWorkbook.Connections(1)
    ThisWorkbook.RefreshAll
    Application.CalculateUntilAsyncQueriesDone
    Sheets(1).Activate

    ' Add code to determine the worksheet that is using the connection

    If sourceConnection.OLEDBConnection.Tablename = "" Then
        MsgBox "The sourceConnection is connected with only a connection."
    Else
        MsgBox "The sourceConnection is linked to a table somewhere on the workbook."
    End If

or even command text

    Dim sourceConnection  As Object: Set sourceConnection = ActiveWorkbook.Connections(1)
    ThisWorkbook.RefreshAll
    Application.CalculateUntilAsyncQueriesDone
    Sheets(1).Activate

    ' Add code to determine the worksheet that is using the connection

    If sourceConnection.CommandText = "" Then
        MsgBox "The sourceConnection is connected with only a connection."
    Else
        MsgBox "The sourceConnection is linked to a table somewhere on the workbook."
    End If

of the three, command text is the only one that compiles and runs, but fails to provide the desired information as the text only looks at the commands being followed by the connection, and does not reference anything regarding the tables it may be used by.


问:
How can I transfer my python/kivy app to my Iphone?
I have been programming an app for my workout which is a total of 10 minutes. The app controls my Hue bridge light and also plays sound. The code of what the app has to do is in my python file, and the layout is on a Kivy file (I am using Floatlayout btw). Finally I am done with my app and would like to transfer it to my iOS Iphone. I have used all day researching only to find Terminal Error like: "local issuer certificate". I am new to programming so I really am stuck here.
I hope someone can help:)

Thank you,
Frederik

I have tried following numerous tutorials and since most of them are out of date I am stuck


问:
Material ui Datagrid get value on unchecking checkbox
I am using Material ui datagrid.  I want to get the value on uncheck of checkbox also.

I have an API which update the Datagrid, on selection I get the selected row data which then on button click I update the value into another array of object, Now when I close the datagrid and open again I want the data to be shown in table comparing if already present in array of object mark it as selected in checkbox, Now when i deselect the checkbox i need the ID and the row data which was removed so I can update the array again, but here on deselect the checkbox it shows empty, so how I can get the removed one so I can update my array

https://codesandbox.io/s/66424752get-row-item-on-checkbox-selection-in-react-material-ui-data-grid-wp4vl?file=/demo.tsx


问:
Get a CSV file from an EntityManager
My company asked me to improve one method from an older project.
The task is to create a csv file from a SQL table (select *) and download with a jsp, the main problem there aren't any Model class and there are a lot of table and I prefer don't create many one, my idea it was to get the list of rows and than for each entity get one row

The service class

```<code>public List<String> searchBersaniFile() {
        Query q = em.createNativeQuery(SQL_SELECT_REPNORM_BERSANI);
        List<String> resultList = (List<String>) q.getResultList(); //I get CastClassException here
        System.out.println(resultList);
        if (resultList == null) {
            resultList = new ArrayList<>();
        }
        return resultList;
    }
</code>```

The main class:

```<code>try (ServletOutputStream outServlet = response.getOutputStream()) {

            switch (flowType) {

            case STATO_BERSANI:
                listResult = awpSapNewRepository.searchBersaniFile();
                break;
            }

            StringBuffer buffer = new StringBuffer();
            String str;
            for (String result : listResult) {
                System.out.println(result);
                str = result.replaceAll("\\[|\\]", "").replaceAll(",", ";");
                System.out.println(str);
                buffer.append(str);
                buffer.append("\r\n");

            }

            String fileName = buildFileName(flowType);

            response.setContentType("text/csv");
            ;
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            outServlet.write(buffer.toString().getBytes());
            outServlet.flush();
        }
</code>```

I tried to get to get in String as you can see on top  (via debug I see it returns like this: [column1, column2, column3][column1,....])
Do you have any idea how can I get the csv without create any model?

Title: Get a CSV file from an EntityManager

Body:
My company asked me to improve one method from an older project.
The task is to create a csv file from a SQL table (select *) and download with a jsp, the main problem there aren't any Model class and there are a lot of table and I prefer don't create many one, my idea it was to get the list of rows and than for each entity get one row

The service class

public List<String> searchBersaniFile() {
        Query q = em.createNativeQuery(SQL_SELECT_REPNORM_BERSANI);
        List<String> resultList = (List<String>) q.getResultList(); //I get CastClassException here
        System.out.println(resultList);
        if (resultList == null) {
            resultList = new ArrayList<>();
        }
        return resultList;
    }

The main class:

try (ServletOutputStream outServlet = response.getOutputStream()) {

            switch (flowType) {

            case STATO_BERSANI:
                listResult = awpSapNewRepository.searchBersaniFile();
                break;
            }

            StringBuffer buffer = new StringBuffer();
            String str;
            for (String result : listResult) {
                System.out.println(result);
                str = result.replaceAll("\\[|\\]", "").replaceAll(",", ";");
                System.out.println(str);
                buffer.append(str);
                buffer.append("\r\n");

            }

            String fileName = buildFileName(flowType);

            response.setContentType("text/csv");
            ;
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            outServlet.write(buffer.toString().getBytes());
            outServlet.flush();
        }

I tried to get to get in String as you can see on top  (via debug I see it returns like this: [column1, column2, column3][column1,....])
Do you have any idea how can I get the csv without create any model?


问:
Tried to install PyQt5-tools via pip, didn't work
output from cmd.exe

```<code>Microsoft Windows [Version 10.0.19045.2251]
(c) Microsoft Corporation. All rights reserved.

C:\Users\cshang>pip install pyqt5-tools
Collecting pyqt5-tools
  Using cached pyqt5_tools-5.15.4.3.2-py3-none-any.whl (29 kB)
Collecting click
  Downloading click-8.1.3-py3-none-any.whl (96 kB)
     ---------------------------------------- 96.6/96.6 kB 2.8 MB/s eta 0:00:00
Collecting python-dotenv
  Using cached python_dotenv-0.21.0-py3-none-any.whl (18 kB)
Collecting pyqt5==5.15.4
  Using cached PyQt5-5.15.4.tar.gz (3.3 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [29 lines of output]
      Traceback (most recent call last):
        File "C:\Users\cshang\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 144, in prepare_metadata_for_build_wheel
          hook = backend.prepare_metadata_for_build_wheel
      AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

      During handling of the above exception, another exception occurred:

      Traceback (most recent call last):
        File "C:\Users\cshang\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 351, in <module>
          main()
        File "C:\Users\cshang\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 333, in main
          json_out['return_val'] = hook(**hook_input['kwargs'])
        File "C:\Users\cshang\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 148, in prepare_metadata_for_build_wheel
          whl_basename = backend.build_wheel(metadata_directory, config_settings)
        File "C:\Users\cshang\AppData\Local\Temp\pip-build-env-bb93u6by\overlay\Lib\site-packages\sipbuild\api.py", line 46, in build_wheel
          project = AbstractProject.bootstrap('wheel',
        File "C:\Users\cshang\AppData\Local\Temp\pip-build-env-bb93u6by\overlay\Lib\site-packages\sipbuild\abstract_project.py", line 87, in bootstrap
          project.setup(pyproject, tool, tool_description)
        File "C:\Users\cshang\AppData\Local\Temp\pip-build-env-bb93u6by\overlay\Lib\site-packages\sipbuild\project.py", line 585, in setup
          self.apply_user_defaults(tool)
        File "C:\Users\cshang\AppData\Local\Temp\pip-install-0_3wofg1\pyqt5_e15fce350c41410c985d7c48eeb1bfa0\project.py", line 63, in apply_user_defaults
          super().apply_user_defaults(tool)
        File "C:\Users\cshang\AppData\Local\Temp\pip-build-env-bb93u6by\overlay\Lib\site-packages\pyqtbuild\project.py", line 70, in apply_user_defaults
          super().apply_user_defaults(tool)
        File "C:\Users\cshang\AppData\Local\Temp\pip-build-env-bb93u6by\overlay\Lib\site-packages\sipbuild\project.py", line 236, in apply_user_defaults
          self.builder.apply_user_defaults(tool)
        File "C:\Users\cshang\AppData\Local\Temp\pip-build-env-bb93u6by\overlay\Lib\site-packages\pyqtbuild\builder.py", line 69, in apply_user_defaults
          raise PyProjectOptionException('qmake',
      sipbuild.pyproject.PyProjectOptionException
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

***end of output***
</code>```

tried installing pyqt5-tools, got this error message instead.
Can you please explain what I need to do to avoid those errors?

Body:
output from cmd.exe

Microsoft Windows [Version 10.0.19045.2251]
(c) Microsoft Corporation. All rights reserved.

C:\Users\cshang>pip install pyqt5-tools
Collecting pyqt5-tools
  Using cached pyqt5_tools-5.15.4.3.2-py3-none-any.whl (29 kB)
Collecting click
  Downloading click-8.1.3-py3-none-any.whl (96 kB)
     ---------------------------------------- 96.6/96.6 kB 2.8 MB/s eta 0:00:00
Collecting python-dotenv
  Using cached python_dotenv-0.21.0-py3-none-any.whl (18 kB)
Collecting pyqt5==5.15.4
  Using cached PyQt5-5.15.4.tar.gz (3.3 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Preparing metadata (pyproject.toml) ... error
  error: subprocess-exited-with-error

  × Preparing metadata (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [29 lines of output]
      Traceback (most recent call last):
        File "C:\Users\cshang\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 144, in prepare_metadata_for_build_wheel
          hook = backend.prepare_metadata_for_build_wheel
      AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

      During handling of the above exception, another exception occurred:

      Traceback (most recent call last):
        File "C:\Users\cshang\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 351, in <module>
          main()
        File "C:\Users\cshang\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 333, in main
          json_out['return_val'] = hook(**hook_input['kwargs'])
        File "C:\Users\cshang\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\pep517\in_process\_in_process.py", line 148, in prepare_metadata_for_build_wheel
          whl_basename = backend.build_wheel(metadata_directory, config_settings)
        File "C:\Users\cshang\AppData\Local\Temp\pip-build-env-bb93u6by\overlay\Lib\site-packages\sipbuild\api.py", line 46, in build_wheel
          project = AbstractProject.bootstrap('wheel',
        File "C:\Users\cshang\AppData\Local\Temp\pip-build-env-bb93u6by\overlay\Lib\site-packages\sipbuild\abstract_project.py", line 87, in bootstrap
          project.setup(pyproject, tool, tool_description)
        File "C:\Users\cshang\AppData\Local\Temp\pip-build-env-bb93u6by\overlay\Lib\site-packages\sipbuild\project.py", line 585, in setup
          self.apply_user_defaults(tool)
        File "C:\Users\cshang\AppData\Local\Temp\pip-install-0_3wofg1\pyqt5_e15fce350c41410c985d7c48eeb1bfa0\project.py", line 63, in apply_user_defaults
          super().apply_user_defaults(tool)
        File "C:\Users\cshang\AppData\Local\Temp\pip-build-env-bb93u6by\overlay\Lib\site-packages\pyqtbuild\project.py", line 70, in apply_user_defaults
          super().apply_user_defaults(tool)
        File "C:\Users\cshang\AppData\Local\Temp\pip-build-env-bb93u6by\overlay\Lib\site-packages\sipbuild\project.py", line 236, in apply_user_defaults
          self.builder.apply_user_defaults(tool)
        File "C:\Users\cshang\AppData\Local\Temp\pip-build-env-bb93u6by\overlay\Lib\site-packages\pyqtbuild\builder.py", line 69, in apply_user_defaults
          raise PyProjectOptionException('qmake',
      sipbuild.pyproject.PyProjectOptionException
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

***end of output***

tried installing pyqt5-tools, got this error message instead.
Can you please explain what I need to do to avoid those errors?


问:
Siebel incremental backups to a non Siebel DB
I have data in an Oracle Siebel data base and I want to move the data to the Azure Cloud over a VPN.

Is it possible to copy the database and then apply daily snapshots until I am ready to take the new Azure application live.

This reduces the risk of relying on a single big migration on the cutover weekend.

The destination DB is not Siebel, I will have to put the data into an Azure DB.

Just gathering ideas at the moment


问:
c# IOException with high baudrate, when opening Port - ONLY on COM1
I have some c# code, checking all available ports for a special connected external hardware.

The code works fine, finding the hardware for all standard baudrates AND all ports.

I my case I have to use ComPort.BaudRate = 250000 , which is no standard.

Starting with COM1, SerialPort.Open() then throws an IOException : "The parameter is incorrect.".(below 250000 works fine).

In contrast to this all other available ports, COM16, COM17 and COM3 where the hardware is connected, work fine with this high baudrate.

Any idea how avoid this exception or at least ignore it for COM1 (maybe on different hardware it might be a different port which fails)?

Edit:

OK, I tried it on different machines, connecting to all available USB-Ports (2.0/3.1) and also across USB-hubs. It works all the same: only COM1 throws an exception and the other ports work fine.

Btw. there is an FTDI-chip on the external hardware for UART communication.

Still don't know how to ignore the "System.IO.IOException: The parameter is incorrect" when trying to open a port, or would it be a viable way to ignore all exceptions on opening a port (maybe bad idea)?


问:
I've been trying to make a script that tells you how big your 3D model is
So I've been trying to make a script that analyses the dimensions in cm of your .stl 3D model, the problem is that I always get Not a number as output on my website. It shows Height: NaN cm. So I don't know what the problem is because it just has to look into the file get some data and use it but that's where I think it go's wrong because the data of the file is encrypted so I'd have to decrypt the data before I could use it in my script. Does anyone have a solution?

I tried to measure my 3D model by getting a script to analyse the code of the 3D model and find out what the dimensions are of that script.

Here's my script:

```<code><head>
  <title>3D Model Analyzer</title>
</head>
<body>
  <h1>3D Model Analyzer</h1>
  <p>Upload a .stl file to get the dimensions of your 3D model in centimeters.</p>
  <input type="file" id="fileInput" />
  <button onclick="analyzeModel()">Analyze Model</button>
  <p id="result"></p>

<script>
// START CODING IN JAVASCRIPT

// Function to analyze the 3D model
function analyzeModel() {
  // Get the file from the input
  const file = document.getElementById("fileInput").files[0];

  // Create a new FileReader object
  const reader = new FileReader();

  // Read the file as text
  reader.readAsText(file);

  // When the file is loaded, analyze it
  reader.onload = function() {
    // Get the contents of the file
    const contents = reader.result;

    // Split the contents by line
    const lines = contents.split("\n");

    // Initialize variables to store the min and max values
    let minX, minY, minZ, maxX, maxY, maxZ;

    // Loop through each line
    lines.forEach(line => {
      // Split the line by spaces
      const parts = line.split(" ");

      // If the line starts with "vertex", it contains a point
      if (parts[0] === "vertex") {
        // Get the x, y, and z coordinates of the point
        const x = parseFloat(parts[1]);
        const y = parseFloat(parts[2]);
        const z = parseFloat(parts[3]);

        // Update the min and max values
        if (minX === undefined || x < minX) minX = x;
        if (minY === undefined || y < minY) minY = y;
        if (minZ === undefined || z < minZ) minZ = z;
        if (maxX === undefined || x > maxX) maxX = x;
        if (maxY === undefined || y > maxY) maxY = y;
        if (maxZ === undefined || z > maxZ) maxZ = z;
      }
    });

    // Convert the min and max values to numbers
    minX = Number(minX);
    minY = Number(minY);
    minZ = Number(minZ);
    maxX = Number(maxX);
    maxY = Number(maxY);
    maxZ = Number(maxZ);

    // Calculate the dimensions of the 3D model
    const width = maxX - minX;
    const height = maxY - minY;
    const depth = maxZ - minZ;

    // Convert the dimensions from meters to centimeters
    const widthCm = width * 100;
    const heightCm = height * 100;
    const depthCm = depth * 100;

    // Display the result
    document.getElementById("result").innerHTML = `Width: ${widthCm} cm<br>Height: ${heightCm} cm<br>Depth: ${depthCm} cm`;
  };
}
</script>
</body>

</code>```

Body:
So I've been trying to make a script that analyses the dimensions in cm of your .stl 3D model, the problem is that I always get Not a number as output on my website. It shows Height: NaN cm. So I don't know what the problem is because it just has to look into the file get some data and use it but that's where I think it go's wrong because the data of the file is encrypted so I'd have to decrypt the data before I could use it in my script. Does anyone have a solution?

I tried to measure my 3D model by getting a script to analyse the code of the 3D model and find out what the dimensions are of that script.

Here's my script:

  <title>3D Model Analyzer</title>

3D Model Analyzer

Upload a .stl file to get the dimensions of your 3D model in centimeters.

  <input type="file" id="fileInput" />
  <button onclick="analyzeModel()">Analyze Model</button>


问:
Change mobile network mode (from 2G to 4G and vice versa) in react-native
I'm trying to create a simple react-native app that only does one thing, switches between 2G and 4G networks (and vice versa) with a click of a button. I've searched for this and found nothing so far. is this possible using react-native or expo?


问:
Wordpress metafields gone after edit post type
when i make a post/ad on my website i fill in meta fields from jetformbuilder. Then it shows my ad on the site. When i wanna edit the post/ad with jetengine post type 3 metafields are gone. Im trying to fix it for a day and cant find anything wrong. Is it a bug or can someone help me were to find my mistake.

I tried to check if all metafields are connected with the good names all good


问:
Jest: How to test an array containing complex objects
I'm trying to write assertions on arrays containing several DivHtmlElements (angular).

toMatchObject function in the Jest documentation allows to test array content based on element partial matching; but it requires to know the inner structures of each element...

Based on expect.objectContaining(object) matcher (which also requires to know about tested object inner structure), it would be nice to have a more generic matcher available; something like expect.objectMatching((object: any) => boolean) or like expect.objectMatching(jestMatcher).

It could be used like this:

```<code>  const fixture: ComponentFixture<MyComponent> = getFixtureUnderTest();

  fixture.detectChanges();

  const divs = fixture.debugElement.queryAll(By.css('.flex-row'));
  expect(divs).toMatchObject([
    expect.objectMatching((htmlElement) => htmlElement.nativeElement.textContent === 'foo'),
    expect.objectMatching((htmlElement) => htmlElement.nativeElement.getAttribute('class').includes('badge-info-light'))
  ]);

</code>```

Or is there another simple way to write such assertions?

Body:
I'm trying to write assertions on arrays containing several DivHtmlElements (angular).

toMatchObject function in the Jest documentation allows to test array content based on element partial matching; but it requires to know the inner structures of each element...

Based on expect.objectContaining(object) matcher (which also requires to know about tested object inner structure), it would be nice to have a more generic matcher available; something like expect.objectMatching((object: any) => boolean) or like expect.objectMatching(jestMatcher).

It could be used like this:

  const fixture: ComponentFixture<MyComponent> = getFixtureUnderTest();

  fixture.detectChanges();

  const divs = fixture.debugElement.queryAll(By.css('.flex-row'));
  expect(divs).toMatchObject([
    expect.objectMatching((htmlElement) => htmlElement.nativeElement.textContent === 'foo'),
    expect.objectMatching((htmlElement) => htmlElement.nativeElement.getAttribute('class').includes('badge-info-light'))
  ]);

Or is there another simple way to write such assertions?


问:
Can't use function when i run npm run start
Hello I wanted to be able to use a c code with electron, so I used node api but when i run the command npm run start, the require() function seems to get stuck since the other functions after it do not run. I also have no errors when running this command. I don't understand why the functions in the index.js file are blocked.

Here is my code:

index.js :

const server = require("./build/Release/server");

console.log(server.Server(12));

document.getElementById('h1-fs-s5').innerText = "12";

server.c :

```<code>#include<node_api.h>

napi_value Server(napi_env env, napi_callback_info info){
    size_t argc=1;
    napi_value args[1];
    int64_t upper_limit;
    int64_t largest_prime;
    napi_value output;

    napi_get_cb_info(env,info,&argc,args,NULL,NULL);

    napi_get_value_int64(env,args[0],&upper_limit);
    largest_prime=upper_limit;
    napi_create_double(env,largest_prime,&output);
    return output;
}

napi_value init(napi_env env, napi_value exports)
{
    napi_value server;
    napi_create_function(env,NULL,0,Server,NULL,&server);

    napi_set_named_property(env, exports, "Server",server);

    return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME,init);
</code>```

binding.gyp :

```<code>{
    "variables": {
        "openssl_fips" : "0"
    },
    "targets":[
        {
            "target_name":"server",
            "sources":[
                "server.c"
            ]
        }
    ]
}
</code>```

Body:
Hello I wanted to be able to use a c code with electron, so I used node api but when i run the command npm run start, the require() function seems to get stuck since the other functions after it do not run. I also have no errors when running this command. I don't understand why the functions in the index.js file are blocked.

Here is my code:

index.js :

const server = require("./build/Release/server");

console.log(server.Server(12));

document.getElementById('h1-fs-s5').innerText = "12";

server.c :

#include<node_api.h>

napi_value Server(napi_env env, napi_callback_info info){
    size_t argc=1;
    napi_value args[1];
    int64_t upper_limit;
    int64_t largest_prime;
    napi_value output;

    napi_get_cb_info(env,info,&argc,args,NULL,NULL);

    napi_get_value_int64(env,args[0],&upper_limit);
    largest_prime=upper_limit;
    napi_create_double(env,largest_prime,&output);
    return output;
}

napi_value init(napi_env env, napi_value exports)
{
    napi_value server;
    napi_create_function(env,NULL,0,Server,NULL,&server);

    napi_set_named_property(env, exports, "Server",server);

    return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME,init);

binding.gyp :

{
    "variables": {
        "openssl_fips" : "0"
    },
    "targets":[
        {
            "target_name":"server",
            "sources":[
                "server.c"
            ]
        }
    ]
}


问:
Limit the number of PHP API calls
I tried to create an API in PHP, I don't know if it's good, but it works.

I would like to secure the API with a key.

```<code>include 'src/callapi.php';
include 'src/variable.php';

$sortie = array('lat' => $lat, 'long' => $long, 'goodtosee' => $goodtosee);

echo json_encode($sortie);
</code>```

I tried this to secure access:

```<code>$key = "blablabla";

if ($_GET["key"] == $key) {
    $sortie = array('lat' => $lat, 'long' => $long, 'goodtosee' => $goodtosee);
    echo json_encode($sortie);
} else {
    echo "key not valid";
}
</code>```

If the key parameter in the url is equal to "blablabla" then it displays the data otherwise it displays "key not valid

How I can limit the number of calls per month?

Title: Limit the number of PHP API calls

Body:
I tried to create an API in PHP, I don't know if it's good, but it works.

I would like to secure the API with a key.

include 'src/callapi.php';
include 'src/variable.php';

$sortie = array('lat' => $lat, 'long' => $long, 'goodtosee' => $goodtosee);

echo json_encode($sortie);

I tried this to secure access:

$key = "blablabla";

if ($_GET["key"] == $key) {
    $sortie = array('lat' => $lat, 'long' => $long, 'goodtosee' => $goodtosee);
    echo json_encode($sortie);
} else {
    echo "key not valid";
}

If the key parameter in the url is equal to "blablabla" then it displays the data otherwise it displays "key not valid

How I can limit the number of calls per month?


问:
Android Talkback reads everything in the system language
I'm working on an application which supports 2 languages: dutch & french
If you have your device set in English, talkback reads all texts in the default talkback language
on iOS you have the "accessibilityLanguage" property, but I don't seem to find an equivalent in the android API
Things I've found and tried:

LocaleSpan: works, but I can't imagine it's the goal to wrap every single text manually in a LocaleSpan? I think it's rather meant for texts in a different language then your app language

TextView.textLocale: not sure what it does, didn't see/hear anything different

Is this behaviour of talkback normal? Seems "wrong" to me, but I'm not a TalkBack user myself so I'm not sure, but it's very difficult to listen to the dutch text in an english accent.


问:
Google Datastream doesn't show before-image with the RDS mysql source
https://cloud.google.com/datastream/docs/configure-your-source-mysql-database#rdsformysql

I followed the doc above building a datastram with RDS mysql. The stream was built successfully, but there is a problem, source_metadata.change_type only has INSERT and UPDATE-INSERT

I only can see the after-value (source_metadata.change_type = 'UPDATE-INSERT') for an UPDATE action.

https://cloud.google.com/datastream/docs/events-and-streams

According to this doc, I expected I can get a 1 UPDATE-DELETE and 1 UPDATE-INSERT for a UPDATE action.

I have tried to set the binlog_row_image=full in the parameters group of the rds-replica according to this doc: https://aws.amazon.com/blogs/database/enable-change-data-capture-on-amazon-rds-for-mysql-applications-that-are-using-xa-transactions/

Then I built a new datastream, but it no use. the result is the same.

How can I configure the RDS mysql and the google datastream for geting the before and after value?


问:
Boost static linking to custom library somehow broken (Windows)
I am trying to build a Library (MyLib) that has a static dependency to boost. However, when I am trying link MyLib to an Application I will get linking erorrs saying that boost functions cannot be found.

I did used the pointer to implementation idiom.
Conan installed the static lib of boost (I checked that).
The plattform is windows.

Does anyone has an idea what I am doing wrong?

Here is the CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.24)

set(TARGET_NAME MyLib)
project(${TARGET_NAME}Project)

include(${CMAKE_CURRENT_LIST_DIR}/build/conanbuildinfo.cmake)
conan_basic_setup()

set(
    SRC_FILES
    src/FileA.cpp
    src/FileB.cpp
    src/FileC.cpp
)

add_library(${TARGET_NAME} ${SRC_FILES})
target_include_directories(
    ${TARGET_NAME}
    PUBLIC ${CMAKE_CURRENT_LIST_DIR}/include/public
    PRIVATE ${CMAKE_CURRENT_LIST_DIR}/include/private
)

target_link_libraries(${TARGET_NAME} PRIVATE ${CONAN_LIBS_STATIC})
set_property(TARGET ${TARGET_NAME} PROPERTY CXX_STANDARD 17)

install(TARGETS ${TARGET_NAME} DESTINATION lib)
</code>```

This is the erorr I am getting:

```<code>Severity    Code    Description Project File    Line    Suppression State
Error   LNK2001 unresolved external symbol "public: class boost::log::v2s_mt_nt6::attribute_value_set::const_iterator __cdecl boost::log::v2s_mt_nt6::attribute_value_set::end(void)const " (?end@attribute_value_set@v2s_mt_nt6@log@boost@@QEBA?AVconst_iterator@1234@XZ)  Main    C:\dev\TestProjects\VSLog\Main\CppLogLib.lib(ConsoleLogWrapper.obj) 1

</code>```

Many thanks in advance.

I tried with CMake setting like
set(Boost_USE_STATIC_LIBS ON) or set_target_properties(${TARGET_NAME} PROPERTIES LINK_FLAGS "OPT:NOREF") but it did not help.

I also try to build MyLib using sln (and Boost downloaded from boost.org) and here I also get a linking error:

Error LNK1104 cannot open file 'libboost_log-vc143-mt-gd-x64-1_81.lib'

Body:
I am trying to build a Library (MyLib) that has a static dependency to boost. However, when I am trying link MyLib to an Application I will get linking erorrs saying that boost functions cannot be found.

I did used the pointer to implementation idiom.
Conan installed the static lib of boost (I checked that).
The plattform is windows.

Does anyone has an idea what I am doing wrong?

Here is the CMakeLists.txt

cmake_minimum_required(VERSION 3.24)

set(TARGET_NAME MyLib)
project(${TARGET_NAME}Project)

include(${CMAKE_CURRENT_LIST_DIR}/build/conanbuildinfo.cmake)
conan_basic_setup()

set(
    SRC_FILES
    src/FileA.cpp
    src/FileB.cpp
    src/FileC.cpp
)

add_library(${TARGET_NAME} ${SRC_FILES})
target_include_directories(
    ${TARGET_NAME}
    PUBLIC ${CMAKE_CURRENT_LIST_DIR}/include/public
    PRIVATE ${CMAKE_CURRENT_LIST_DIR}/include/private
)

target_link_libraries(${TARGET_NAME} PRIVATE ${CONAN_LIBS_STATIC})
set_property(TARGET ${TARGET_NAME} PROPERTY CXX_STANDARD 17)

install(TARGETS ${TARGET_NAME} DESTINATION lib)

This is the erorr I am getting:

Severity    Code    Description Project File    Line    Suppression State
Error   LNK2001 unresolved external symbol "public: class boost::log::v2s_mt_nt6::attribute_value_set::const_iterator __cdecl boost::log::v2s_mt_nt6::attribute_value_set::end(void)const " (?end@attribute_value_set@v2s_mt_nt6@log@boost@@QEBA?AVconst_iterator@1234@XZ)  Main    C:\dev\TestProjects\VSLog\Main\CppLogLib.lib(ConsoleLogWrapper.obj) 1

Many thanks in advance.

I tried with CMake setting like
set(Boost_USE_STATIC_LIBS ON) or set_target_properties(${TARGET_NAME} PROPERTIES LINK_FLAGS "OPT:NOREF") but it did not help.

I also try to build MyLib using sln (and Boost downloaded from boost.org) and here I also get a linking error:

Error LNK1104 cannot open file 'libboost_log-vc143-mt-gd-x64-1_81.lib'


问:
How to filter for rows with a particular key (not value) in a json column
I've been querying and filtering using a JSON column in sqlalchemy (not JSONB) on a postgres database by using

s.query(Model).filter(cast(Model.extra_data[key], String) == type_coerce(val, JSON)).all()
```

Which works fine, however, for some previous queries, I'd like to be able to query only rows that contain a particular key. That is to say, not all rows have key1, and I only want rows with that key in extra_data.

How do I filter such? I don't care what the value is, just that the key is there.

Body:
I've been querying and filtering using a JSON column in sqlalchemy (not JSONB) on a postgres database by using

s.query(Model).filter(cast(Model.extra_data[key], String) == type_coerce(val, JSON)).all()

Which works fine, however, for some previous queries, I'd like to be able to query only rows that contain a particular key. That is to say, not all rows have key1, and I only want rows with that key in extra_data.

How do I filter such? I don't care what the value is, just that the key is there.


问:
How to convert tibble data with various classes from long to wide format problem using ONLY base R package?
I am trying to convert my dataset from long to wide format only using base R packages and dplyr only due to university's project requirements. I have tried to use reshape function, but I have encountered problems with converting them using the reshape() function.
My data looks like this please note that in original dataset in geo column there are 27 countries and dates that go from 2000-02-01 to 2022-09-01:

```<code># A tibble: 8 × 3
  geo     time       values
  <chr>   <date>      <dbl>
1 Poland  2022-09-01   1.3
2 Germany 2022-09-01   2.1
3 Denmark 2022-09-01   3.2
4 Greece  2022-09-01   4.1
5 Poland  2022-08-01   1.1
6 Germany 2022-08-01   2.7
7 Denmark 2022-08-01   3.8
8 Greece  2022-08-01   4.12
</code>```

I want to convert that data into this format :

```<code># A tibble: 4 × 5
  time       Poland Germany Denmark Greece
  <date>      <dbl>   <dbl>   <dbl>  <dbl>
1 2022-09-01    1       2       3     4
2 2022-08-01    2.1     3.3     4.5   5.7
3 2022-07-01    7       8       5     8
4 2022-06-01   21.2     2.3     1.2   2.13
</code>```

You can reproduce these two datasets with this code

Long data:

```<code>library(dplyr)

datasample <- matrix(c("Poland","Germany","Denmark","Greece","Poland","Germany","Denmark","Greece",'2022-09-01','2022-09-01','2022-09-01','2022-09-01','2022-08-01','2022-08-01','2022-08-01','2022-08-01',1.3,2.1,3.2,4.1,1.1,2.7,3.8,4.12),
                     ncol = 3,
                     byrow = FALSE)
colnames(datasample) <- c("geo","time","values")
data_tibble <- as_tibble(datasample)
data_tibble <- data_tibble %>% mutate(geo = as.character(geo),
                                      time = as.Date(time),
                                      values = as.double(values))
</code>```

Wide data:

```<code>data_wide <- matrix(c("2022-09-01",1,2,3,4,"2022-08-01",2.1,3.3,4.5,5.7,"2022-07-01",7,8,5,8,"2022-06-01",21.2,2.3,1.2,2.13),ncol=5, byrow=TRUE)
colnames(data_wide) <- c("time", "Poland","Germany","Denmark","Greece")
data_wide <- as_tibble(data_wide)
data_wide <- data_wide %>%
  mutate(time = as.Date(time),
         Poland = as.double(Poland),
         Germany = as.double(Germany),
         Denmark = as.double(Denmark),
         Greece = as.double(Greece))
</code>```

I tried to use the simple reshape function from base R library:

```<code>data_wide <- reshape(original_data, idvar = "time", timevar = "geo", direction = "wide")
</code>```

and I get something like this:

```<code># A tibble: 272 × 2
   time       values.c("Austria", "Belgium", "Bulgaria", "Cyprus", "Czech Republi…¹
   <date>                                                                     <dbl>
 1 2022-09-01                                                                    NA
 2 2022-08-01                                                                    NA
 3 2022-07-01                                                                    NA
 4 2022-06-01                                                                    NA
 5 2022-05-01                                                                    NA
 6 2022-04-01                                                                    NA
 7 2022-03-01                                                                    NA
 8 2022-02-01                                                                    NA
 9 2022-01-01                                                                    NA
10 2021-12-01                                                                    NA
</code>```

This is something close to the result that I want but as you can see it is now divided into 2 columns
there should be time and seperate columns for each country but it is now a singular vector with country names.

How can i form that vector into seperate columns and insert the values to appropriate records?

Body:
I am trying to convert my dataset from long to wide format only using base R packages and dplyr only due to university's project requirements. I have tried to use reshape function, but I have encountered problems with converting them using the reshape() function.
My data looks like this please note that in original dataset in geo column there are 27 countries and dates that go from 2000-02-01 to 2022-09-01:

# A tibble: 8 × 3
  geo     time       values
  <chr>   <date>      <dbl>
1 Poland  2022-09-01   1.3
2 Germany 2022-09-01   2.1
3 Denmark 2022-09-01   3.2
4 Greece  2022-09-01   4.1
5 Poland  2022-08-01   1.1
6 Germany 2022-08-01   2.7
7 Denmark 2022-08-01   3.8
8 Greece  2022-08-01   4.12

I want to convert that data into this format :

# A tibble: 4 × 5
  time       Poland Germany Denmark Greece
  <date>      <dbl>   <dbl>   <dbl>  <dbl>
1 2022-09-01    1       2       3     4
2 2022-08-01    2.1     3.3     4.5   5.7
3 2022-07-01    7       8       5     8
4 2022-06-01   21.2     2.3     1.2   2.13

You can reproduce these two datasets with this code

Long data:

library(dplyr)

datasample <- matrix(c("Poland","Germany","Denmark","Greece","Poland","Germany","Denmark","Greece",'2022-09-01','2022-09-01','2022-09-01','2022-09-01','2022-08-01','2022-08-01','2022-08-01','2022-08-01',1.3,2.1,3.2,4.1,1.1,2.7,3.8,4.12),
                     ncol = 3,
                     byrow = FALSE)
colnames(datasample) <- c("geo","time","values")
data_tibble <- as_tibble(datasample)
data_tibble <- data_tibble %>% mutate(geo = as.character(geo),
                                      time = as.Date(time),
                                      values = as.double(values))

Wide data:

data_wide <- matrix(c("2022-09-01",1,2,3,4,"2022-08-01",2.1,3.3,4.5,5.7,"2022-07-01",7,8,5,8,"2022-06-01",21.2,2.3,1.2,2.13),ncol=5, byrow=TRUE)
colnames(data_wide) <- c("time", "Poland","Germany","Denmark","Greece")
data_wide <- as_tibble(data_wide)
data_wide <- data_wide %>%
  mutate(time = as.Date(time),
         Poland = as.double(Poland),
         Germany = as.double(Germany),
         Denmark = as.double(Denmark),
         Greece = as.double(Greece))

I tried to use the simple reshape function from base R library:

data_wide <- reshape(original_data, idvar = "time", timevar = "geo", direction = "wide")

and I get something like this:

# A tibble: 272 × 2
   time       values.c("Austria", "Belgium", "Bulgaria", "Cyprus", "Czech Republi…¹
   <date>                                                                     <dbl>
 1 2022-09-01                                                                    NA
 2 2022-08-01                                                                    NA
 3 2022-07-01                                                                    NA
 4 2022-06-01                                                                    NA
 5 2022-05-01                                                                    NA
 6 2022-04-01                                                                    NA
 7 2022-03-01                                                                    NA
 8 2022-02-01                                                                    NA
 9 2022-01-01                                                                    NA
10 2021-12-01                                                                    NA

This is something close to the result that I want but as you can see it is now divided into 2 columns
there should be time and seperate columns for each country but it is now a singular vector with country names.

How can i form that vector into seperate columns and insert the values to appropriate records?


问:
Kotlin generics of generics
I am facing a Kotlin generics limitation: IF a generic type is himself a generic, you have to provide his type parameter (or a projetction). Here is what I would like to do but is impossible:

```<code>interface Builder<T>
interface SpecializedBuilder<T>:Builder<T>

interface Definition<B:Builder> { //Not possible..., the T parameter must be provided
   fun <D> getBuilder(d:D) : B<D> // I Would like to provide the T parameter later here (is D)
}

and:

class SpecializedDefinition : Definition<SpecializedBuilder> {
  override fun <D> getBuilder(d:D): SpecializedBuilder<D> {...}
}
</code>```

The purpose is to keep the information of both builder B type and D type in the return type of getBuilder fun for later type inference. For example infer the type of the val builder as SpecializedBuilder<String> in the following code:

```<code>fun <D,DEF:Definition<*>> determineBuilder(d:D,def:DEF) = def.getBuilder(d)
or maybe
fun <D,B:Builder,DEF:Definition<B>> determineBuilder(d:D,def:DEF) : B = def.getBuilder(d)

val builder=determineBuilder("a string",SpecializedDefinition())

</code>```

Do you know if there is a known design pattern for this case?

Title: Kotlin generics of generics

Body:
I am facing a Kotlin generics limitation: IF a generic type is himself a generic, you have to provide his type parameter (or a projetction). Here is what I would like to do but is impossible:

interface Builder<T>
interface SpecializedBuilder<T>:Builder<T>

interface Definition { //Not possible..., the T parameter must be provided
   fun <D> getBuilder(d:D) : B<D> // I Would like to provide the T parameter later here (is D)
}

and:

class SpecializedDefinition : Definition<SpecializedBuilder> {
  override fun <D> getBuilder(d:D): SpecializedBuilder<D> {...}
}

The purpose is to keep the information of both builder B type and D type in the return type of getBuilder fun for later type inference. For example infer the type of the val builder as SpecializedBuilder<String> in the following code:

fun <D,DEF:Definition<*>> determineBuilder(d:D,def:DEF) = def.getBuilder(d)
or maybe
fun <D,B:Builder,DEF:Definition> determineBuilder(d:D,def:DEF) : B = def.getBuilder(d)

val builder=determineBuilder("a string",SpecializedDefinition())

Do you know if there is a known design pattern for this case?


问:
How do I get payload after ajax submitted the woocommerce checkout page
I am building a custom payment gateway and I want to support same page payment and not redirect the user after creating order.

normally your'll have a proceess_payment method in your gateway class which would return and array like

```<code>array('result' => 'success', 'redirect_url' => 'https://.......')
</code>```

I don't want to redirect the user after the order is created. So I would like to send a response like

```<code>array('result' => 'success', 'transactionId' => 'xxxxxxx')
</code>```

Such that I can start polling my server to get the status of that transactionId.

Please any hint on how I can listed to the AJAX call made by woocommerce after the checkout button is clicked.

Body:
I am building a custom payment gateway and I want to support same page payment and not redirect the user after creating order.

normally your'll have a proceess_payment method in your gateway class which would return and array like

array('result' => 'success', 'redirect_url' => 'https://.......')

I don't want to redirect the user after the order is created. So I would like to send a response like

array('result' => 'success', 'transactionId' => 'xxxxxxx')

Such that I can start polling my server to get the status of that transactionId.

Please any hint on how I can listed to the AJAX call made by woocommerce after the checkout button is clicked.


问:
Send push notification when user enters a specific designated area(even if app is closed). *Check Description*
In flutter is it possible to send push notification to user if he/she is near a designated area, let's suppose we have certain areas in our db with their latitudes and longitudes, and if a user walks through that area(lets say around 100 meters radius of any of those places) then the app will generate a push notification? How to implement it even if app is open or closed?

i read about this package flutter_background_geolocation: ^4.8.5 but it costs $349 for single app.


问:
VSCode always pushing same commit
I'm new to coding. Recently I started working with GitHub, with which I'm not familiar yet. I am on Mac.
So, I'm pushing my code to GitHub from VSCode. It all works. But then I realise that there's an error in my code, so I want to edit the code, make a new commit and push it again to be tested by my tutor. When I push it to GitHub though, it always pushes to original first commit, and not the one I just worked on.
What am I doing wrong?
I'm attaching a screenshot. As you can see there's a list of "First Commit" although I'm actually pushing other commits.
Thank you so much for your help!

I've been going back and forward with this problem for three days now.

enter image description here

Title: VSCode always pushing same commit