问:
Tail-calls corrupted when compiled with __attribute__((musttail))
I was working a Lisp interpreter with a 'threaded' design, where it compiles to a VM where each instruction is a C function that calls the next instruction — if the compiler does tail call elimination, then it should only need a jmp between instructions.

It's a stack-oriented VM, with an Imm instructions that pushes an immediate to the stack.

When I manually call the first Imm instruction, it runs fine.  However, once the Imm instruction jumps to the next Imm instruction, it seems the call stack becomes corrupted as none of the parameter values are valid anymore.  However, this only occurs when I use clang with __attribute__((musttail)).  In fact, gcc -O3 and even clang -O3 compile it to a jmp just fine (but clang without musttail compiles to a call).  Anyone know what could be going on here?

A stripped-down version of the code that exhibits this behavior follows:

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

typedef enum { TypeInt = 0 } Tag;

typedef struct {
    int n; /* item count */
    int64_t *val; /* pointer */
} List;

typedef struct Block {
    struct Ins *ins;
    int n;
    struct Fn *fn;
    struct Scope *locals;
    struct Scope *mod;
} Block;

typedef struct Scope {
    int n;
    const char **names;
    int64_t *vals;
    Block first;
} Scope;

typedef struct Ins {
    char (*op)(int, Block);
    int64_t imm;
} Ins;

typedef struct Fn {
    Scope locals;
    Scope *mod;
} Fn;

int64_t *stack;
uint32_t sc; /* stack counter */
uint32_t fc; /* frame counter */
uint32_t cap = 128 * sizeof(int64_t);

#define F_INS(x) char x(int ic, Block b)
#define MUSTTAIL __attribute__((musttail))
#define INSRET MUSTTAIL return b.ins[ic + 1].op(ic + 1, b);

#define N_BUILTINS 1
const char *builtins[N_BUILTINS] = { "+" };

void vm_init(void) { stack = malloc(cap); }
F_INS(Done) { return 0; }

void stack_push(int64_t v)
{
    if (++sc >= cap) stack = realloc(stack, cap *= 2);
    stack[sc - 1] = v;
}

F_INS(Imm)
{
    printf("IC: %u\n", ic);
    stack_push(b.ins[ic].imm);
    INSRET;
}

F_INS(Add)
{
    int64_t y = stack[--sc];
    int64_t x = stack[--sc];
    stack_push(x + y);
    INSRET;
}

int main(int argc, char **argv)
{
    Block b = {0};
    vm_init();
    b.ins = realloc(b.ins, ++b.n * sizeof(Ins));
    b.ins[b.n - 1].op = &Imm;
    b.ins[b.n - 1].imm = 3;
    b.ins = realloc(b.ins, ++b.n * sizeof(Ins));
    b.ins[b.n - 1].op = &Imm;
    b.ins[b.n - 1].imm = 4;
    b.ins = realloc(b.ins, ++b.n * sizeof(Ins));
    b.ins[b.n - 1].op = &Add;
    b.ins = realloc(b.ins, ++b.n * sizeof(Ins));
    b.ins[b.n - 1].op = &Done;

    (*b.ins[0].op)(0, b);
}
</code>```

When I remove the structs for Fn and Scope, or when I turn optimizations on, it doesn't crash anymore.  Bizarrely, it works fine with fsanitize=memory.

The full code is at https://git.sr.ht/~euclaise/trent/tree/

```<code>clang version 14.0.6
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
</code>```

Body:
I was working a Lisp interpreter with a 'threaded' design, where it compiles to a VM where each instruction is a C function that calls the next instruction — if the compiler does tail call elimination, then it should only need a jmp between instructions.

It's a stack-oriented VM, with an Imm instructions that pushes an immediate to the stack.

When I manually call the first Imm instruction, it runs fine.  However, once the Imm instruction jumps to the next Imm instruction, it seems the call stack becomes corrupted as none of the parameter values are valid anymore.  However, this only occurs when I use clang with __attribute__((musttail)).  In fact, gcc -O3 and even clang -O3 compile it to a jmp just fine (but clang without musttail compiles to a call).  Anyone know what could be going on here?

A stripped-down version of the code that exhibits this behavior follows:

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

typedef enum { TypeInt = 0 } Tag;

typedef struct {
    int n; /* item count */
    int64_t *val; /* pointer */
} List;

typedef struct Block {
    struct Ins *ins;
    int n;
    struct Fn *fn;
    struct Scope *locals;
    struct Scope *mod;
} Block;

typedef struct Scope {
    int n;
    const char **names;
    int64_t *vals;
    Block first;
} Scope;

typedef struct Ins {
    char (*op)(int, Block);
    int64_t imm;
} Ins;

typedef struct Fn {
    Scope locals;
    Scope *mod;
} Fn;

int64_t *stack;
uint32_t sc; /* stack counter */
uint32_t fc; /* frame counter */
uint32_t cap = 128 * sizeof(int64_t);

#define F_INS(x) char x(int ic, Block b)
#define MUSTTAIL __attribute__((musttail))
#define INSRET MUSTTAIL return b.ins[ic + 1].op(ic + 1, b);

#define N_BUILTINS 1
const char *builtins[N_BUILTINS] = { "+" };

void vm_init(void) { stack = malloc(cap); }
F_INS(Done) { return 0; }

void stack_push(int64_t v)
{
    if (++sc >= cap) stack = realloc(stack, cap *= 2);
    stack[sc - 1] = v;
}

F_INS(Imm)
{
    printf("IC: %u\n", ic);
    stack_push(b.ins[ic].imm);
    INSRET;
}

F_INS(Add)
{
    int64_t y = stack[--sc];
    int64_t x = stack[--sc];
    stack_push(x + y);
    INSRET;
}

int main(int argc, char **argv)
{
    Block b = {0};
    vm_init();
    b.ins = realloc(b.ins, ++b.n * sizeof(Ins));
    b.ins[b.n - 1].op = &Imm;
    b.ins[b.n - 1].imm = 3;
    b.ins = realloc(b.ins, ++b.n * sizeof(Ins));
    b.ins[b.n - 1].op = &Imm;
    b.ins[b.n - 1].imm = 4;
    b.ins = realloc(b.ins, ++b.n * sizeof(Ins));
    b.ins[b.n - 1].op = &Add;
    b.ins = realloc(b.ins, ++b.n * sizeof(Ins));
    b.ins[b.n - 1].op = &Done;

    (*b.ins[0].op)(0, b);
}

When I remove the structs for Fn and Scope, or when I turn optimizations on, it doesn't crash anymore.  Bizarrely, it works fine with fsanitize=memory.

The full code is at https://git.sr.ht/~euclaise/trent/tree/

clang version 14.0.6
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin


来源: stackexchange

问:
Defining a variable inside `exec(...)` works in the global scope, but in the local scope
Consider the following code which uses Python's built-in funciton exec.

```<code>exec('a = 1')
print(a) # prints just fine

def foo():
    exec('b = 2')
    print(b) # NameError: name 'b' is not defined

foo()
</code>```

When exec is used in the global context to define a variable a, the variable is available (e.g. print(a) works); however, when exec is used to define a variable, b inside a function, the variable is not available (e.g. print(b) causes a NameError).

What's going on? Do I have to pass in the function's local context to exec?

ContentLicense: CC BY-SA 4.0

Body:
Consider the following code which uses Python's built-in funciton exec.

exec('a = 1')
print(a) # prints just fine

def foo():
    exec('b = 2')
    print(b) # NameError: name 'b' is not defined

foo()

When exec is used in the global context to define a variable a, the variable is available (e.g. print(a) works); however, when exec is used to define a variable, b inside a function, the variable is not available (e.g. print(b) causes a NameError).

What's going on? Do I have to pass in the function's local context to exec?


问:
Unable to center chart titles in python using custom function
The code below is the code I am using for a heart failure analysis project. But,

This method is not centering the values of each bar under the graph, pictured below.

I am not getting the percentage value above each bar in the graph

```<code>def plot_percentage(df, col, target):
x,y = col, target
temp_df = df.groupby(x)[y].value_counts(normalize=True)
temp_df = temp_df.mul(100).rename('percent').reset_index()
temp_df = temp_df[temp_df.HeartDisease != 0]
order_list = list(df[col].unique())
order_list.sort()
sns.set(font_scale=1.5)
g = sns.catplot(x=x, y='percent', hue=x,kind='bar', data=temp_df, height=8, aspect=2, order=order_list, legend_out=False)
g.ax.set_ylim(0,100)
plt.title(f'{col.title()} By Percent {target.title()}',
          fontdict={'fontsize': 30})
plt.xlabel(f'{col.title()}', fontdict={'fontsize': 20})
plt.ylabel(f'{target.title()} Percentage', fontdict={'fontsize': 20})
return g
</code>```

Body:
The code below is the code I am using for a heart failure analysis project. But,

This method is not centering the values of each bar under the graph, pictured below.

I am not getting the percentage value above each bar in the graph

def plot_percentage(df, col, target):
x,y = col, target
temp_df = df.groupby(x)[y].value_counts(normalize=True)
temp_df = temp_df.mul(100).rename('percent').reset_index()
temp_df = temp_df[temp_df.HeartDisease != 0]
order_list = list(df[col].unique())
order_list.sort()
sns.set(font_scale=1.5)
g = sns.catplot(x=x, y='percent', hue=x,kind='bar', data=temp_df, height=8, aspect=2, order=order_list, legend_out=False)
g.ax.set_ylim(0,100)
plt.title(f'{col.title()} By Percent {target.title()}',
          fontdict={'fontsize': 30})
plt.xlabel(f'{col.title()}', fontdict={'fontsize': 20})
plt.ylabel(f'{target.title()} Percentage', fontdict={'fontsize': 20})
return g


问:
TwinCAT system is launching Rexroth drives stright to OP when the final machine state is set to INIT
I am working on a TwinCAT system. We have TwinCAT booting and the Bosch Rexroth drives being powered simultaneously. The TwinCAT system is supposed to set the final state of each individual drive. However all 4 of the drives are booting and then going to OP as soon as they finish booting. We need to hold off on booting the second drive until the first drive has finished initializing as the second drive is slaved to the first through an encoder and the first drive needs to finish booting before the second drive as the emulator for the first drive isn't sending the appropriate signals yet and the second drive then presents an error and wont boot normally.

I have found a crude temporary fix for this in the form of applying control power to the drives and getting them to boot completely before booting the PLC. I have tried to set the Final Machine State for the drives in the I/O stack for the drives and then call out the transition change in the plc program itself. That has not been consistent though. I would like to find the reason why the drives are bypassing the Final Machine State setting in the PLC to begin with. Though any help or advice would be much appreciated.


问:
Azure WAF V2 false positive SQL Injection attacks on form entry data
We are using Azure ASE v3 to host our web app with Azure Application Gateway and WAF V2. We have been getting quite a lot of false positives on data our users enter into a form in the app.

For example

"Matched Data": in ( found within ARGS:medicationsList: Aspirin ( 81mg )

"Matched Data": t like t found within ARGS:supportPersonsAnswer: Support person felt like they take more aspirin.

Are there any standard approaches to addressing this problem apart from creating exclusions for medications? I understand those phrases were flagged due to combinations of SQL keywords but at the same time those are legitimate sentences a user would enter.


问:
Match month of outer query to month in subquery
I am attempting to get the total of a column (Amount) by Month:

```<code>SELECT
    Date,
    DATEPART(month, Date) AS Month,
    DATEPART(year, Date) AS year,
    (
        SELECT
            SUM(Amount)
        FROM Transactions AS T
        WHERE DATEPART(month, Date) = DATEPART(month, T.Date)
    ) AS Amount
FROM Transactions AS T
</code>```

I know that this could be done in a straightforward manner using a group by clause as follows:

```<code>SELECT
    DATEPART(month, Date) AS Month,
    SUM(Amount) AS Total
FROM Transactions AS T
GROUP BY DATEPART(month, Date)
</code>```

However I need to use subquery instead as the subquery will contain additional conditions and joins to assist in the calculation of a total based on rules from other tables.

I expected the first query to return all months and their respective totals, in the subquery I am matching Month of the transactions with the Month of the outer query row.  However it simply returns the full SUM of all months for each month.

My guess is that my attempt to match the month is not quite correct, but I can't see how to fix.

Body:
I am attempting to get the total of a column (Amount) by Month:

SELECT
    Date,
    DATEPART(month, Date) AS Month,
    DATEPART(year, Date) AS year,
    (
        SELECT
            SUM(Amount)
        FROM Transactions AS T
        WHERE DATEPART(month, Date) = DATEPART(month, T.Date)
    ) AS Amount
FROM Transactions AS T

I know that this could be done in a straightforward manner using a group by clause as follows:

SELECT
    DATEPART(month, Date) AS Month,
    SUM(Amount) AS Total
FROM Transactions AS T
GROUP BY DATEPART(month, Date)

However I need to use subquery instead as the subquery will contain additional conditions and joins to assist in the calculation of a total based on rules from other tables.

I expected the first query to return all months and their respective totals, in the subquery I am matching Month of the transactions with the Month of the outer query row.  However it simply returns the full SUM of all months for each month.

My guess is that my attempt to match the month is not quite correct, but I can't see how to fix.


问:
EJS cannot read variable in html page
I'm new at backend programming and having diffuculty with using EJS and routes. I'm using a database as well. The problem is , a dynamic js variable cannot displaying in ejs view file. I mean "message" like "the password does not match
<%= message %>
 Can you help me ? These are my codes. I've shortened them as much as i can do. I don't think database files are important for the solution so did not include them. Thanks !

This is my main index.js file :

```<code>const express = require("express");
const app = express();
const path = require('path');

const dotenv = require('dotenv') ;
dotenv.config({path:'./.env'})
app.set("view engine", "ejs");

app.use(express.static('public'));
app.use(express.static('node_modules'));
app.use(express.urlencoded({ extended: false })); //false yerine true da koyulabilir.
app.use(express.json());
//Define routes
app.use('/',require('./routes/pages'));
app.use('/auth',require('./routes/auth'));

app.listen(3000, () => {

    console.log("Listening on port 3000");

});
</code>```

This is my auth.js(controllers) file :

```<code>    const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

const db_kullanici_auth = require("../data/kullanici_auth_db"); //it's a database importing

exports.register = async (req, res) => {
    try {
    //         console.log(req.body) ;
    // res.send("Form submitted") ;
        // let query = "SELECT email FROM register;"
        // const allDB = await (db_kullanici_auth.execute(query));
        // const projeler_db = allDB[0];
        // console.log(projeler_db);

        const { company_name_reg, name_reg, surname_reg, department_name_reg, position_name_reg, password_reg, password_confirm_reg, adres_reg, adres2_reg, zip_reg, sehir_reg, ulke_reg, telefon_kodu_reg, telefon_numarasi_reg, email_reg } = req.body;

        await (db_kullanici_auth.execute('SELECT email FROM register WHERE email = ? ', [email_reg], (error, results) => {

            if (error) {
                console.log(error);
            }

            if (results.length > 0) {

                console.log(results);

                return res.render('kayit_ol', {

                    message: 'Email is already in use'

                });

            }
            else if (password_reg !== password_confirm_reg) {

                console.log(results);
                return res.render('kayit_ol', {
                    message: 'Passwords does not match'

                });

            }
            // let hashedPassword = await bcrypt.hash(password_reg,8) ;
            // console.log(hashedPassword) ;
        }));
    } catch (error) {
        console.log(error);
    }
}
</code>```

This is my auth.js(routes) file :

```<code>const express = require('express') ;
const router = express.Router() ;
const authController = require('../controllers/auth');

router.post("/kayit_ol",authController.register);

module.exports = router ;
</code>```

Title: EJS cannot read variable in html page

Body:
I'm new at backend programming and having diffuculty with using EJS and routes. I'm using a database as well. The problem is , a dynamic js variable cannot displaying in ejs view file. I mean "message" like "the password does not match
<%= message %>
 Can you help me ? These are my codes. I've shortened them as much as i can do. I don't think database files are important for the solution so did not include them. Thanks !

This is my main index.js file :

const express = require("express");
const app = express();
const path = require('path');

const dotenv = require('dotenv') ;
dotenv.config({path:'./.env'})
app.set("view engine", "ejs");

app.use(express.static('public'));
app.use(express.static('node_modules'));
app.use(express.urlencoded({ extended: false })); //false yerine true da koyulabilir.
app.use(express.json());
//Define routes
app.use('/',require('./routes/pages'));
app.use('/auth',require('./routes/auth'));

app.listen(3000, () => {

    console.log("Listening on port 3000");

});

This is my auth.js(controllers) file :

    const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

const db_kullanici_auth = require("../data/kullanici_auth_db"); //it's a database importing

exports.register = async (req, res) => {
    try {
    //         console.log(req.body) ;
    // res.send("Form submitted") ;
        // let query = "SELECT email FROM register;"
        // const allDB = await (db_kullanici_auth.execute(query));
        // const projeler_db = allDB[0];
        // console.log(projeler_db);

        const { company_name_reg, name_reg, surname_reg, department_name_reg, position_name_reg, password_reg, password_confirm_reg, adres_reg, adres2_reg, zip_reg, sehir_reg, ulke_reg, telefon_kodu_reg, telefon_numarasi_reg, email_reg } = req.body;

        await (db_kullanici_auth.execute('SELECT email FROM register WHERE email = ? ', [email_reg], (error, results) => {

            if (error) {
                console.log(error);
            }

            if (results.length > 0) {

                console.log(results);

                return res.render('kayit_ol', {

                    message: 'Email is already in use'

                });

            }
            else if (password_reg !== password_confirm_reg) {

                console.log(results);
                return res.render('kayit_ol', {
                    message: 'Passwords does not match'

                });

            }
            // let hashedPassword = await bcrypt.hash(password_reg,8) ;
            // console.log(hashedPassword) ;
        }));
    } catch (error) {
        console.log(error);
    }
}

This is my auth.js(routes) file :

const express = require('express') ;
const router = express.Router() ;
const authController = require('../controllers/auth');

router.post("/kayit_ol",authController.register);

module.exports = router ;


问:
Running a Python script to open MS Access through Task Scheduler returns an error, but running that script normally works fine. What's going on?
I have a script that essentially opens up an Access Database, exports a report as a PDF, then does a few other things. This script is scheduled to run daily at a certain time. The task succeeds, however the error reported in the logfile is the following:

(-2147352567, 'Exception occurred.', (0, None, "Microsoft Access can't save the output data to the file you've selected.", None, -1, -2146825986), None)

The big mystery isn't necessarily that issue because when I run the script normally in either Visual Studio, straight through the command line, or via a batch file, the script runs fine.

But for whatever reason, when it is triggered via Task Scheduler the task itself report that it runs successfully. However the script doesn't as an except condition is met in the Access Database portion of code, thus defeating the purpose of this script.

Note that I tried running it in Task Scheduler via Python and via .bat but neither method worked. Additionally I confirmed that I filled in the parameters for the task correctly and tried several different methods to run it.

An excerpt of the code is below. The 'try' block that fails (second one) has a comment. This runs fine when done manually, but not when run through task scheduler. Note that all paths in the script are UNC paths.

```<code>try:
    a = win32com.client.gencache.EnsureDispatch("Access.Application")

except AttributeError:
    f_loc = Path(r'...\gen_py')
    shutil.rmtree(f_loc)
    a = win32com.client.gencache.EnsureDispatch("Access.Application")

try:
    # This block fails and goes to the except block
    filename = r'access_database_file.accdb'
    db = a.OpenCurrentDatabase(filename)

    report_name = 'Test'
    report = r'export location.pdf'

    # I believe this is where the section fails.
    a.DoCmd.OutputTo(3, report_name, r'PDF Format (*.pdf)', str(report))

    a.Application.Quit()

except Exception as e:
    write(logfile,f'...')
    write(logfile,str(e))
</code>```

Body:
I have a script that essentially opens up an Access Database, exports a report as a PDF, then does a few other things. This script is scheduled to run daily at a certain time. The task succeeds, however the error reported in the logfile is the following:

(-2147352567, 'Exception occurred.', (0, None, "Microsoft Access can't save the output data to the file you've selected.", None, -1, -2146825986), None)

The big mystery isn't necessarily that issue because when I run the script normally in either Visual Studio, straight through the command line, or via a batch file, the script runs fine.

But for whatever reason, when it is triggered via Task Scheduler the task itself report that it runs successfully. However the script doesn't as an except condition is met in the Access Database portion of code, thus defeating the purpose of this script.

Note that I tried running it in Task Scheduler via Python and via .bat but neither method worked. Additionally I confirmed that I filled in the parameters for the task correctly and tried several different methods to run it.

An excerpt of the code is below. The 'try' block that fails (second one) has a comment. This runs fine when done manually, but not when run through task scheduler. Note that all paths in the script are UNC paths.

try:
    a = win32com.client.gencache.EnsureDispatch("Access.Application")

except AttributeError:
    f_loc = Path(r'...\gen_py')
    shutil.rmtree(f_loc)
    a = win32com.client.gencache.EnsureDispatch("Access.Application")

try:
    # This block fails and goes to the except block
    filename = r'access_database_file.accdb'
    db = a.OpenCurrentDatabase(filename)

    report_name = 'Test'
    report = r'export location.pdf'

    # I believe this is where the section fails.
    a.DoCmd.OutputTo(3, report_name, r'PDF Format (*.pdf)', str(report))

    a.Application.Quit()

except Exception as e:
    write(logfile,f'...')
    write(logfile,str(e))


问:
cmake GLOB filtered by files indexed by git
Cmake supports file(GLOB MY_SOURCES src/*) to select files with a wildcard.

This is generally bad: Is it better to specify source files with GLOB or each file individually in CMake?

For a simple example, git mergetool leaves backup files when resolving merge conflicts (In a git merge conflict, what are the BACKUP, BASE, LOCAL, and REMOTE files that are generated?) - with the original extension, not *.bak or something. If using globbing/wildcards in cmake, these will automatically just be included in the next build and it'll fail. There are other gotchas, but this is one.

Some people still insist on using globs/wildcards. Is there a way to filter globbed files to only those tracked by git?

Something like setting MY_SOURCES from shelling out to git ls-files src/*. Can this even be done at configure time?

This way, cmake would ignore random other files that happen to match the wildcard.

As a bonus, it'll help catch those times I forget to git add new source files before pushing :)

Sure, the project should still compile without the .git directory, so this will need to be a best effort/only-if-available approach that falls back to file(GLOB ...) if git fails. Also still to be frowned upon .


问:
Pin in swiftUI able to click and show small info text above it
I'm new to swiftUI and I made this view where you see a maps with different pins on it. I wanted it so when I click the pin it shows a little box above it with the info about the place (name, address)

I found other threads about it but I couldn't really find what I needed.

Anybody who could help me?

```<code>import SwiftUI
import MapKit
struct MyAnnotationItem: Identifiable {
    var coordinate: CLLocationCoordinate2D
    let id = UUID()
}

struct MapView: View {
    @State var coordinateRegion: MKCoordinateRegion = {
        var newRegion = MKCoordinateRegion()
        newRegion.center.latitude = 50.80580148204638
        newRegion.center.longitude = 3.2842106137743308
        newRegion.span.latitudeDelta = 0.2
        newRegion.span.longitudeDelta = 0.2
        return newRegion
    }()

    var annotationItems: [MyAnnotationItem] = [
        //castel motors
        MyAnnotationItem(coordinate: CLLocationCoordinate2D(latitude: 50.690042667142485, longitude: 3.1734146440963777)),
        //leon saggaert
        MyAnnotationItem(coordinate: CLLocationCoordinate2D(latitude: 50.94343953661561, longitude: 3.2940420541585396)),
        //R4 motos
        MyAnnotationItem(coordinate: CLLocationCoordinate2D(latitude: 51.09466176530236, longitude: 3.7763867274168774)),
        //garden tools
        MyAnnotationItem(coordinate: CLLocationCoordinate2D(latitude:  50.78567261592435, longitude: 3.2141870141679365)),
        //desmet roland
        MyAnnotationItem(coordinate: CLLocationCoordinate2D(latitude:  50.87668047058957, longitude: 3.442740743366995)),
        //r trac
        MyAnnotationItem(coordinate: CLLocationCoordinate2D(latitude:  50.853492889583116, longitude: 3.7401561581010645))
    ]
    var body: some View {
        VStack {
            Map(coordinateRegion: $coordinateRegion,
                annotationItems: annotationItems) {item in
                MapMarker(coordinate: item.coordinate)
            }
        }
        .ignoresSafeArea()
    }

}

struct Previews_SwiftUIMap_Previews: PreviewProvider {
    static var previews: some View {
    MapView()
        }
    }

</code>```

I made the view with the pins, now I only need them to be clickable
My app now

Body:
I'm new to swiftUI and I made this view where you see a maps with different pins on it. I wanted it so when I click the pin it shows a little box above it with the info about the place (name, address)

I found other threads about it but I couldn't really find what I needed.

Anybody who could help me?

import SwiftUI
import MapKit
struct MyAnnotationItem: Identifiable {
    var coordinate: CLLocationCoordinate2D
    let id = UUID()
}

struct MapView: View {
    @State var coordinateRegion: MKCoordinateRegion = {
        var newRegion = MKCoordinateRegion()
        newRegion.center.latitude = 50.80580148204638
        newRegion.center.longitude = 3.2842106137743308
        newRegion.span.latitudeDelta = 0.2
        newRegion.span.longitudeDelta = 0.2
        return newRegion
    }()

    var annotationItems: [MyAnnotationItem] = [
        //castel motors
        MyAnnotationItem(coordinate: CLLocationCoordinate2D(latitude: 50.690042667142485, longitude: 3.1734146440963777)),
        //leon saggaert
        MyAnnotationItem(coordinate: CLLocationCoordinate2D(latitude: 50.94343953661561, longitude: 3.2940420541585396)),
        //R4 motos
        MyAnnotationItem(coordinate: CLLocationCoordinate2D(latitude: 51.09466176530236, longitude: 3.7763867274168774)),
        //garden tools
        MyAnnotationItem(coordinate: CLLocationCoordinate2D(latitude:  50.78567261592435, longitude: 3.2141870141679365)),
        //desmet roland
        MyAnnotationItem(coordinate: CLLocationCoordinate2D(latitude:  50.87668047058957, longitude: 3.442740743366995)),
        //r trac
        MyAnnotationItem(coordinate: CLLocationCoordinate2D(latitude:  50.853492889583116, longitude: 3.7401561581010645))
    ]
    var body: some View {
        VStack {
            Map(coordinateRegion: $coordinateRegion,
                annotationItems: annotationItems) {item in
                MapMarker(coordinate: item.coordinate)
            }
        }
        .ignoresSafeArea()
    }

}

struct Previews_SwiftUIMap_Previews: PreviewProvider {
    static var previews: some View {
    MapView()
        }
    }

I made the view with the pins, now I only need them to be clickable
My app now


问:
Problem with functions not waiting for variable to be filled before progressing
Soo i am developing this app, and i cant seem to figure how to fix this issue that i am having,

the problem is that the first function is always throwing undefined on the "console.log(params)", i assume the problem is because the "const result" is not waiting for the promise to end filling all the data before being passed on.

What i need is some help figuring out how to make the rest wait for result to be field before moving on.

```<code>    export async function registar_compra(compra){

    const params = await create_params(compra)

    console.log(params)
}

async function create_params(compra) {

const {numero_socio, nome_tuna, nome_completo, produtos_selecionados} = compra

const result =  {
                RequestItems: {
                    ['HISTORICO']: produtos_selecionados.map(async (produto, index) => ({
                    PutRequest: {
                        Item: {
                            id: "compra",
                            data_dia: await get_data(index),
                            numero_socio: numero_socio,
                            nome_tuna: nome_tuna,
                            nome_completo: nome_completo,
                            quantidade: produto.quantidade,
                            nome_produto: produto.nome_produto,
                            preco_quantidade: produto.preço_quantidade
                        },
                    },
                    })),
                },
            }

return result

}

function get_data(index) {
    return new Promise(resolve=> {
      setTimeout(() => {
        resolve(new Date().toISOString());
      }, 12 * index);
    });
 }
</code>```

I have tryed debugging it too see where the problem is, just cant seem to find the way to make this work

Body:
Soo i am developing this app, and i cant seem to figure how to fix this issue that i am having,

the problem is that the first function is always throwing undefined on the "console.log(params)", i assume the problem is because the "const result" is not waiting for the promise to end filling all the data before being passed on.

What i need is some help figuring out how to make the rest wait for result to be field before moving on.

    export async function registar_compra(compra){

    const params = await create_params(compra)

    console.log(params)
}

async function create_params(compra) {

const {numero_socio, nome_tuna, nome_completo, produtos_selecionados} = compra

const result =  {
                RequestItems: {
                    ['HISTORICO']: produtos_selecionados.map(async (produto, index) => ({
                    PutRequest: {
                        Item: {
                            id: "compra",
                            data_dia: await get_data(index),
                            numero_socio: numero_socio,
                            nome_tuna: nome_tuna,
                            nome_completo: nome_completo,
                            quantidade: produto.quantidade,
                            nome_produto: produto.nome_produto,
                            preco_quantidade: produto.preço_quantidade
                        },
                    },
                    })),
                },
            }

return result

}

function get_data(index) {
    return new Promise(resolve=> {
      setTimeout(() => {
        resolve(new Date().toISOString());
      }, 12 * index);
    });
 }

I have tryed debugging it too see where the problem is, just cant seem to find the way to make this work


问:
Why can't I reproduce the results obtained with pycaret?
If I use the dataset transformed by pycaret and the best trained model why don't I get the same results I get with pycaret? I am trying to learn how to build regression models with datasets downloaded from the internet (boston dataset, iris, etc.) but with pycaret I get good results, if I write the program from scratch I don't.

First in pycaret I ran the setup() command.
Then after choosing the best model from compare_models() and finalize it with finalize_model() I download the dataset initially transformed by pycaret.
At this point if I use the transformed dataset and the tuned model parameters obtained from print(tuned_model) shouldn't I be able to do it myself? Of course as pycaret I divide the dataset into train, test and validation set.
Which step am I skipping?


问:
TensorFlow Lite Arduino IDE Library
I am working on using TF Lite to get a trained TF model onto my board via the Arduino IDE. I am using the Circuit Playground Bluefruit board (listed as supported on the TF website). When I try to run the hello-world from the cloned library, I get an "Error in compiling for baord" message.

Adafruit mentions I need only the NON pre-compiled library, but it seems the library was removed from the native library manager a few years ago, making it difficult to find the pre-compiled library. I tried to install using:

git clone https://github.com/tensorflow/tflite-micro-arduino-examples Arduino_TensorFlowLite

which, of course, gets a pre-compiled version. I think this is what is behind the aforementioned error message. Any guidance would be so appreciated!!

Title: TensorFlow Lite Arduino IDE Library


问:
Frozen modules warning and looping script when running multiprocessing pool
I'm trying to make a Python program iterate through pixels in parallel to speed up the process. The working version of my program calls GetPixelData() in a for loop with the arguments x_pos, x_size, y_size, pixel_number, pixel_number being incremented by the for loop so the program can process the next pixel.

This does the job, but slowly (even though the script only processes about 40 pixels at most). I'm using this to automate a very high-latency online game so every millisecond counts. My solution was to use a multiprocessing Pool to run a function on each pixel in parallel, while keeping an iteration variable to pass to the function so it knows which pixel it should process.

However, every time I run my script, I get this in the Python debugger:

```<code>0.02s - Debugger warning: It seems that frozen modules are being used, which may
0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off
0.00s - to python to disable frozen modules.
0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.
</code>```

After that, the script starts looping on top of itself, opening tab after tab on Chrome.

Here's the function code:

def GetPixelData(x_pos, x_size, y_size, pixel_number, pixels_obstacle, pixels_coffee):
    global coffee_amount

    x = pixel_number / x_size
    y = pixel_number % y_size

    if pixels_obstacle.getpixel((x, y))[2] < 240:
        Jump(driver, canvas)
        print("Object")
    elif pixels_coffee.getpixel((x, y))[1] < 50:
        Jump(driver, canvas)
        coffee_amount += 1
        print("+1 Coffee (" + str(coffee_amount) + " total)")

    return x, y
```
<p>And here's how I'm calling the function in parallel:</p>
<pre class="lang-python prettyprint-override"><code># Get pixels in bounds
bounds_obstacle = (x_pos, 830, x_pos + x_size, 830 + y_size) * screen_multiplier
bounds_coffee = (x_pos, 460, x_pos + x_size, 460 + y_size) * screen_multiplier
pixels_obstacle = ImageGrab.grab(bbox=bounds_obstacle)
pixels_coffee = ImageGrab.grab(bbox=bounds_coffee)

# Process pixels in parallel
args = [x_pos, x_size, y_size, pixels_obstacle, pixels_coffee]
iterable = ([args, pixel_number] for pixel_number in range(x_size * y_size))
pixel_pool = pool.Pool(os.cpu_count())
for r in pixel_pool.imap_unordered(GetPixelData, iterable):
    print(str(r))
</code>```

Body:
I'm trying to make a Python program iterate through pixels in parallel to speed up the process. The working version of my program calls GetPixelData() in a for loop with the arguments x_pos, x_size, y_size, pixel_number, pixel_number being incremented by the for loop so the program can process the next pixel.

This does the job, but slowly (even though the script only processes about 40 pixels at most). I'm using this to automate a very high-latency online game so every millisecond counts. My solution was to use a multiprocessing Pool to run a function on each pixel in parallel, while keeping an iteration variable to pass to the function so it knows which pixel it should process.

However, every time I run my script, I get this in the Python debugger:

0.02s - Debugger warning: It seems that frozen modules are being used, which may
0.00s - make the debugger miss breakpoints. Please pass -Xfrozen_modules=off
0.00s - to python to disable frozen modules.
0.00s - Note: Debugging will proceed. Set PYDEVD_DISABLE_FILE_VALIDATION=1 to disable this validation.

After that, the script starts looping on top of itself, opening tab after tab on Chrome.

Here's the function code:

def GetPixelData(x_pos, x_size, y_size, pixel_number, pixels_obstacle, pixels_coffee):
    global coffee_amount

    x = pixel_number / x_size
    y = pixel_number % y_size

    if pixels_obstacle.getpixel((x, y))[2] < 240:
        Jump(driver, canvas)
        print("Object")
    elif pixels_coffee.getpixel((x, y))[1] < 50:
        Jump(driver, canvas)
        coffee_amount += 1
        print("+1 Coffee (" + str(coffee_amount) + " total)")

    return x, y

And here's how I'm calling the function in parallel:

# Get pixels in bounds
bounds_obstacle = (x_pos, 830, x_pos + x_size, 830 + y_size) * screen_multiplier
bounds_coffee = (x_pos, 460, x_pos + x_size, 460 + y_size) * screen_multiplier
pixels_obstacle = ImageGrab.grab(bbox=bounds_obstacle)
pixels_coffee = ImageGrab.grab(bbox=bounds_coffee)

# Process pixels in parallel
args = [x_pos, x_size, y_size, pixels_obstacle, pixels_coffee]
iterable = ([args, pixel_number] for pixel_number in range(x_size * y_size))
pixel_pool = pool.Pool(os.cpu_count())
for r in pixel_pool.imap_unordered(GetPixelData, iterable):
    print(str(r))


问:
JQuery Autocomplete DIV Style Change?
I have a div that contains the Jquery autocomplete classes for a input that looks something like this:

[class*="ui-autocomplete-multiselect"][class*="form-control"] {
  border-radius: 5px;
  color: black;
  /* padding: 50x; this works */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-group">
  <div class="input-group input-group-sm flex-nowrap">
    <label for="test">Test Label</label>
    <div class="ui-autocomplete-multiselect ui-state-default ui-widget form-control">
      <input id="test" class="form control col-sm-12 ui-autocomplete-input">
    </div>
  </div>
</div></code>```

I'm trying modify the CSS border and color of the input div that contains the autocomplete class but nothing is changing. If I was to add padding, I see the padding changes but why aren't any of the color or border styles changing?

Title: JQuery Autocomplete DIV Style Change?

Body:
I have a div that contains the Jquery autocomplete classes for a input that looks something like this:

[class*="ui-autocomplete-multiselect"][class*="form-control"] {
  border-radius: 5px;
  color: black;
  /* padding: 50x; this works */
}

    Test Label

      <input id="test" class="form control col-sm-12 ui-autocomplete-input">

I'm trying modify the CSS border and color of the input div that contains the autocomplete class but nothing is changing. If I was to add padding, I see the padding changes but why aren't any of the color or border styles changing?


问:
Matlab - How to plot 2 different columns of data under 1 x-axis label?
I m trying to plot 2 different columns of excelsheet data (.xls) "Data1" & "Data2" under 1 x-axis label "Jan" to compare them side by side visually. How do i do it?

Excel Data:
Sample Excel Data

I m trying to do something like this for just 1 x-axis label for my
matlab boxplot

```<code>`tiledlayout(1,2)

ScoreS = [-3, -2, -1, 0, 1, 2, 3];
sceneOrder = ["Jan","Feb","Mar","Apr","May"];
surveyData.SceneCode = categorical(surveyData.SceneCode, sceneOrder);
surveyData.SceneQuestionCompare = categorical(surveyData.SceneCode, sceneOrder);

% Left axes
ax1 = nexttile
boxchart(surveyData.SceneCode, surveyData.Data1);
xlabel(ax1,'Scenes 1~12')
yt = get(gca, 'YTick');
ytx = linspace(min(yt), max(yt), numel(ScoreS));
ytl = sprintfc('%.0f',ScoreS);
ylabel(ax1,'Qn1 (Physical)')
legend('Physical (N=36)')

% Right axes
ax2 = nexttile
boxchart(surveyData.SceneCode, [surveyData.data3])
xlabel(ax2,'Scenes 1~12')
yt = get(gca, 'YTick');                                                         % Get Y-Tick Values
ytx = linspace(min(yt), max(yt), numel(ScoreS));                                     % New Y-Tick Values
ytl = sprintfc('%.0f',ScoreS);                                                       % New Y-Tick Labels
set(gca, 'YTick',ytx, 'YTickLabel',ytl)
ylabel(ax2,'Qn2 (VR)')
legend('VR (N=36)')`
</code>```

Body:
I m trying to plot 2 different columns of excelsheet data (.xls) "Data1" & "Data2" under 1 x-axis label "Jan" to compare them side by side visually. How do i do it?

Excel Data:
Sample Excel Data

I m trying to do something like this for just 1 x-axis label for my
matlab boxplot

`tiledlayout(1,2)

ScoreS = [-3, -2, -1, 0, 1, 2, 3];
sceneOrder = ["Jan","Feb","Mar","Apr","May"];
surveyData.SceneCode = categorical(surveyData.SceneCode, sceneOrder);
surveyData.SceneQuestionCompare = categorical(surveyData.SceneCode, sceneOrder);

% Left axes
ax1 = nexttile
boxchart(surveyData.SceneCode, surveyData.Data1);
xlabel(ax1,'Scenes 1~12')
yt = get(gca, 'YTick');
ytx = linspace(min(yt), max(yt), numel(ScoreS));
ytl = sprintfc('%.0f',ScoreS);
ylabel(ax1,'Qn1 (Physical)')
legend('Physical (N=36)')

% Right axes
ax2 = nexttile
boxchart(surveyData.SceneCode, [surveyData.data3])
xlabel(ax2,'Scenes 1~12')
yt = get(gca, 'YTick');                                                         % Get Y-Tick Values
ytx = linspace(min(yt), max(yt), numel(ScoreS));                                     % New Y-Tick Values
ytl = sprintfc('%.0f',ScoreS);                                                       % New Y-Tick Labels
set(gca, 'YTick',ytx, 'YTickLabel',ytl)
ylabel(ax2,'Qn2 (VR)')
legend('VR (N=36)')`


问:
How do I tigger the doOnError() in a Reactive Kakfa consumer?
```<code>private Flux<Record> consumeRecord() {
    return reactiveKafkaConsumerTemplate
            .receive()
            .doOnNext(consumerRecord -> {
                        Record record = consumerRecord.value();
                        recordWorkflowService.handleRecord(record);
                    }
            )
            .map(ConsumerRecord::value)
            .doOnError(throwable -> {
                log.error("something bad happened while consuming : {}", throwable.getMessage());
            });
}
</code>```

Currently this is the code I have in my consumer. When a record comes in I do see that my recordWorflowService.handleRecord is called and the record is processed successfully, however I cannot get the error case to trigger.

I have a use case where I am consumer records from a kafka topic and do some processing on them. However, if any part of that processing fails I do not want the kafka record to be committed so that it can get reprocessed. So if any error occurs in the recordWorkflowService I want .doOnError() to be triggered and to not commit the offset (So it can be reprocessed).

Am I on the right path here? I have tried manually throwing an exception within handleRecord() but .doOnError() never seems to get triggered.

Body:
private Flux<Record> consumeRecord() {
    return reactiveKafkaConsumerTemplate
            .receive()
            .doOnNext(consumerRecord -> {
                        Record record = consumerRecord.value();
                        recordWorkflowService.handleRecord(record);
                    }
            )
            .map(ConsumerRecord::value)
            .doOnError(throwable -> {
                log.error("something bad happened while consuming : {}", throwable.getMessage());
            });
}

Currently this is the code I have in my consumer. When a record comes in I do see that my recordWorflowService.handleRecord is called and the record is processed successfully, however I cannot get the error case to trigger.

I have a use case where I am consumer records from a kafka topic and do some processing on them. However, if any part of that processing fails I do not want the kafka record to be committed so that it can get reprocessed. So if any error occurs in the recordWorkflowService I want .doOnError() to be triggered and to not commit the offset (So it can be reprocessed).

Am I on the right path here? I have tried manually throwing an exception within handleRecord() but .doOnError() never seems to get triggered.


问:
JMnedict.xml file Trying to purge entries by xml tag?
JMnedict is a Japanese Name file that's free online in xml. I have not found another way it was stored. It is free to use as long as credit is given. Found here: https://www.edrdg.org/enamdict/enamdict_doc.html (I did not write the code below, I only copy-pasted it).

I get the principles of xml and why it exists, but nothing beyond that. I am not that savvy to specific programs that handle them besides text editors and maybe OpenOffice.

I downloaded it for the Japanese names. I want to filter the entries only to the fem, masc, given, surname, and unclass

I hope to make a Japanese name generator from the data and this is the best source material for it. (I made a Korean one already).

The thing is that the list of entities is:

character, company name, creature, deity, document, event, female given name or forename, fiction, given name, group, legend, male given name or forename, mythology, object, organization name, other, person, place , product name, religion, service, ship name, railway station, family or surname, unclassified name, work.

And the xml file is 152.3 MB.

I'd like to drop all of the entries that do not fall into the categories I want.

I'm looking for an efficient way to trim the file, so I can upload it to the online database.

Structure of the entries looks like this (Not sure if it helps):

```<code><entry>
<ent_seq>5000000</ent_seq>
<k_ele>
<keb>ゝ泉</keb>
</k_ele>
<r_ele>
<reb>ちゅせん</reb>
</r_ele>
<trans>
<name_type>&given;</name_type>
<trans_det>Chusen</trans_det>
</trans>
</entry>
</code>```

(as an example)

and trim out entries such as this:

```<code><entry>
<ent_seq>5000198</ent_seq>
<k_ele>
<keb>あかり博物館</keb>
</k_ele>
<r_ele>
<reb>あかりはくぶつかん</reb>
</r_ele>
<trans>
<name_type>&place;</name_type>
<trans_det>Akari Museum</trans_det>
</trans>
</entry>
</code>```

So is there an efficient way to purge all of the entries I don't want in BBedit, something similar or a method I'm not familiar with? I need to trim the file so I can upload it to my database (and hopefully it being shorter will help it upload.)

I'm on a Mac if you're suggesting applications.

OR is there a method I've not thought of to purge the entries in a different method?

What I've Tried:

I tried to upload the xml file to my database online directly, but it was too big, even when zipped. (And then I would do MySQL DROPS to remove the offending entries), but file was too big and phpMyAdmin gave up and spat out an error that the file was incomplete.

I did try trimming the file to a few entries for phpMyAdmin, and that uploaded successfully, but uploading it in sections seems inefficient, especially with the file so long and it having entries I don't want anyway.

I tried to convert it to a csv file, but it is too big and the automatic converters online can't handle it. (Converting it to JSON or similar has similar problems)

I tried OpenOffice, but again, it can't handle the file being that large and the application crashed on me. (I thought I could Sort then kill)

I can open it in BBEDIT and manually trim the file, but the file is very long and not organized, so it is super inefficient. I rather be able to sort the file by name_type. And kill the entries that don't belong.

Body:
JMnedict is a Japanese Name file that's free online in xml. I have not found another way it was stored. It is free to use as long as credit is given. Found here: https://www.edrdg.org/enamdict/enamdict_doc.html (I did not write the code below, I only copy-pasted it).

I get the principles of xml and why it exists, but nothing beyond that. I am not that savvy to specific programs that handle them besides text editors and maybe OpenOffice.

I downloaded it for the Japanese names. I want to filter the entries only to the fem, masc, given, surname, and unclass

I hope to make a Japanese name generator from the data and this is the best source material for it. (I made a Korean one already).

The thing is that the list of entities is:

character, company name, creature, deity, document, event, female given name or forename, fiction, given name, group, legend, male given name or forename, mythology, object, organization name, other, person, place , product name, religion, service, ship name, railway station, family or surname, unclassified name, work.

And the xml file is 152.3 MB.

I'd like to drop all of the entries that do not fall into the categories I want.

I'm looking for an efficient way to trim the file, so I can upload it to the online database.

Structure of the entries looks like this (Not sure if it helps):

<entry>
<ent_seq>5000000</ent_seq>
<k_ele>
<keb>ゝ泉</keb>
</k_ele>
<r_ele>
<reb>ちゅせん</reb>
</r_ele>
<trans>
<name_type>&given;</name_type>
<trans_det>Chusen</trans_det>
</trans>
</entry>

(as an example)

and trim out entries such as this:

<entry>
<ent_seq>5000198</ent_seq>
<k_ele>
<keb>あかり博物館</keb>
</k_ele>
<r_ele>
<reb>あかりはくぶつかん</reb>
</r_ele>
<trans>
<name_type>&place;</name_type>
<trans_det>Akari Museum</trans_det>
</trans>
</entry>

So is there an efficient way to purge all of the entries I don't want in BBedit, something similar or a method I'm not familiar with? I need to trim the file so I can upload it to my database (and hopefully it being shorter will help it upload.)

I'm on a Mac if you're suggesting applications.

OR is there a method I've not thought of to purge the entries in a different method?

What I've Tried:

I tried to upload the xml file to my database online directly, but it was too big, even when zipped. (And then I would do MySQL DROPS to remove the offending entries), but file was too big and phpMyAdmin gave up and spat out an error that the file was incomplete.

I did try trimming the file to a few entries for phpMyAdmin, and that uploaded successfully, but uploading it in sections seems inefficient, especially with the file so long and it having entries I don't want anyway.

I tried to convert it to a csv file, but it is too big and the automatic converters online can't handle it. (Converting it to JSON or similar has similar problems)

I tried OpenOffice, but again, it can't handle the file being that large and the application crashed on me. (I thought I could Sort then kill)

I can open it in BBEDIT and manually trim the file, but the file is very long and not organized, so it is super inefficient. I rather be able to sort the file by name_type. And kill the entries that don't belong.


问:
Proper way to store tab states in Compose Multiplatform
What is the proper way to store tab content state in Compose Multiplatform? "Remember" keeps state only during recompositions, not when one view replaces another. On Android ViewModel should be used, but in Compose Multiplatform there is no ViewModel class.</p>


问:
Why doesn't mx-auto center my div elements? (Bootstrap 5)
I try to use mx-auto to center my div elements. I used it a section before, and it does its job just fine. But in this scenario, it doesn't work.

No margin or padding added using m- or p- works.

Easy to use.

So easy to use, even your dog could do it.

Elite Clientele

We have all the dogs, the greatest dogs.

Guaranteed to work.

Find the love of your dog's life or your money back.

```


问:
Automatically connecting to OpenVPN with a script
I'm setting up an automated e-mail system that pulls queries from a MariaDB database and emails the outputs to my clients. I want these scripts to run daily, but they're being run from a server and I need to connect/log in to OpenVPN to connect to the MariaDB database. Is there a way for me to write a script that will connect to OpenVPN with my credentials so that these queries can be scheduled to run automatically?</p>


问:
Using HTTP API to build Grafana dashboard
I have been using influxDB as a datasource to build Grafana dashboard and now am trying to use an http api link that contain the below json file. The link is for example https://example:8080/cluster.  Or if possible to use telegraf to get the extracted data and send the metrics to the influxDB.

I would want to display the http display for example show the TEJD as Status UP and TECJ status as DOWN based on the json shown.

```<code>{ "status": "UP",  "TEJD": {"status":"UP", "count":"0", "minDateTime":"", "description":"Workbasket Jdmin"},  "TECJ":
     {"status":"DOWN", "count":"0", "minDateTime":"",
     "description":"Workbasket CreateJppWait"},  "TEDE": {"status":"UP",
     "count":"0", "minDateTime":"", "description":"Workbasket default"},
     "TEEW": {"status":"UP", "count":"0", "minDateTime":"",
     "description":"Workbasket eFormWriteFailure"},  "TEFB":
     {"status":"UP", "count":"0", "minDateTime":"",
     "description":"Workbasket BackgroundProcessing"},  "TEIC":
     {"status":"UP", "count":"0", "minDateTime":"",
     "description":"Workbasket IncompleteConnections"},  "TELB":
     {"status":"UP", "count":"18", "minDateTime":"20/12/2022 10:37",
     "description":"Workbasket LRBackgroundProcess"},   "JETE":
     {"status":"UP", "count":"0", "minDateTime":"",
     "description":"Jssignment errors for Jssign-WorkBasket"},  "JEWL":
     {"status":"DOWN", "count":"0", "minDateTime":"",
     "description":"Jssignment errors for Jssign-Worklist"},   "FETE":
     {"status":"UP", "count":"0", "minDateTime":"", "description":"Flow
     errors for Jssign-WorkBasket"},  "FEWL": {"status":"UP", "count":"0",
     "minDateTime":"", "description":"Flow errors for Jssign-Worklist"},
     "BQBP": {"status":"UP", "count":"0", "minDateTime":"",
     "description":"Broken queue System-Queue-BackgroundProcess"},  "BQDE":
     {"status":"UP", "count":"0", "minDateTime":"", "description":"Broken
     queue System-Queue-DefaultEntry"},   "CQCJ": {"status":"UP",
     "count":"0", "minDateTime":"", "description":"Custom query Create Jpp
     Requests"},   "JS02": {"status":"UP", "description":"Job Scheduler
     CaseDocumentDeletion (Jny one associated node:BackgroundProcessing)"},
     "JS21": {"status":"UP", "description":"Job Scheduler
     PurgeOldSIDExchangeRecords (Jll associated
     nodes:BackgroundProcessing)"},  "JS01": {"status":"UP",
     "description":"Job Scheduler UpdateReferenceData (Jny one associated
     node:BackgroundProcessing)"},   "package": { "name": "Pega Cluster",
     "elapsedTime": "819.0", "lastUpdated": "20/12/2022 10:52" } }
</code>```

UPDATE :   I found out that I can use telegraf http plugin however am still not able to pass the data.    I have used this plugin in telegraf

```<code>[[inputs.http]]
    urls = ["http://example:8080//Cluster"]
    tagexclude = ["url", "host"]
    #Overwrite measurement name from default `http` to `cluster`
    ### name_override = "httppegacluster"
    data_format = "json_v2"
    [[inputs.http.json_v2]]
        [[inputs.http.json_v2.object]]
             path = "test1"

        [[inputs.http.json_v2.object]]
             path = "test2"

        [[inputs.http.json_v2.object]]
            path = "test3"

        [[inputs.http.json_v2.object]]
            path = "test4"

        [[inputs.http.json_v2.object]]
            path = "test5"

</code>```

It is throwing this output but I would want the output to show test 1 test 2 and test 3 as I need to display the keys in the dashboard.

telegraf -config  http.conf -test

```<code>> http count="0",description="Workbasket Admin",minDateTime="",status="UP" 1671286903000000000
> http count="0",description="Workbasket eFormWriteFailure",minDateTime="",status="UP" 1671286903000000000
> http count="0",description="Workbasket CreateAppWait",minDateTime="",status="UP" 1671286903000000000
> http count="0",description="Workbasket default@RoS",minDateTime="",status="UP" 1671286903000000000
> http count="0",description="Workbasket BackgroundProcessing",minDateTime="",status="UP" 1671286903000000000
</code>```

I am following this example from this page link https://www.influxdata.com/blog/how-parse-json-telegraf-influxdb-cloud/   but seems the json format is different to mine

Body:
I have been using influxDB as a datasource to build Grafana dashboard and now am trying to use an http api link that contain the below json file. The link is for example https://example:8080/cluster.  Or if possible to use telegraf to get the extracted data and send the metrics to the influxDB.

I would want to display the http display for example show the TEJD as Status UP and TECJ status as DOWN based on the json shown.

{ "status": "UP",  "TEJD": {"status":"UP", "count":"0", "minDateTime":"", "description":"Workbasket Jdmin"},  "TECJ":
     {"status":"DOWN", "count":"0", "minDateTime":"",
     "description":"Workbasket CreateJppWait"},  "TEDE": {"status":"UP",
     "count":"0", "minDateTime":"", "description":"Workbasket default"},
     "TEEW": {"status":"UP", "count":"0", "minDateTime":"",
     "description":"Workbasket eFormWriteFailure"},  "TEFB":
     {"status":"UP", "count":"0", "minDateTime":"",
     "description":"Workbasket BackgroundProcessing"},  "TEIC":
     {"status":"UP", "count":"0", "minDateTime":"",
     "description":"Workbasket IncompleteConnections"},  "TELB":
     {"status":"UP", "count":"18", "minDateTime":"20/12/2022 10:37",
     "description":"Workbasket LRBackgroundProcess"},   "JETE":
     {"status":"UP", "count":"0", "minDateTime":"",
     "description":"Jssignment errors for Jssign-WorkBasket"},  "JEWL":
     {"status":"DOWN", "count":"0", "minDateTime":"",
     "description":"Jssignment errors for Jssign-Worklist"},   "FETE":
     {"status":"UP", "count":"0", "minDateTime":"", "description":"Flow
     errors for Jssign-WorkBasket"},  "FEWL": {"status":"UP", "count":"0",
     "minDateTime":"", "description":"Flow errors for Jssign-Worklist"},
     "BQBP": {"status":"UP", "count":"0", "minDateTime":"",
     "description":"Broken queue System-Queue-BackgroundProcess"},  "BQDE":
     {"status":"UP", "count":"0", "minDateTime":"", "description":"Broken
     queue System-Queue-DefaultEntry"},   "CQCJ": {"status":"UP",
     "count":"0", "minDateTime":"", "description":"Custom query Create Jpp
     Requests"},   "JS02": {"status":"UP", "description":"Job Scheduler
     CaseDocumentDeletion (Jny one associated node:BackgroundProcessing)"},
     "JS21": {"status":"UP", "description":"Job Scheduler
     PurgeOldSIDExchangeRecords (Jll associated
     nodes:BackgroundProcessing)"},  "JS01": {"status":"UP",
     "description":"Job Scheduler UpdateReferenceData (Jny one associated
     node:BackgroundProcessing)"},   "package": { "name": "Pega Cluster",
     "elapsedTime": "819.0", "lastUpdated": "20/12/2022 10:52" } }

UPDATE :   I found out that I can use telegraf http plugin however am still not able to pass the data.    I have used this plugin in telegraf

[[inputs.http]]
    urls = ["http://example:8080//Cluster"]
    tagexclude = ["url", "host"]
    #Overwrite measurement name from default `http` to `cluster`
    ### name_override = "httppegacluster"
    data_format = "json_v2"
    [[inputs.http.json_v2]]
        [[inputs.http.json_v2.object]]
             path = "test1"

        [[inputs.http.json_v2.object]]
             path = "test2"

        [[inputs.http.json_v2.object]]
            path = "test3"

        [[inputs.http.json_v2.object]]
            path = "test4"

        [[inputs.http.json_v2.object]]
            path = "test5"

It is throwing this output but I would want the output to show test 1 test 2 and test 3 as I need to display the keys in the dashboard.

telegraf -config  http.conf -test

> http count="0",description="Workbasket Admin",minDateTime="",status="UP" 1671286903000000000
> http count="0",description="Workbasket eFormWriteFailure",minDateTime="",status="UP" 1671286903000000000
> http count="0",description="Workbasket CreateAppWait",minDateTime="",status="UP" 1671286903000000000
> http count="0",description="Workbasket default@RoS",minDateTime="",status="UP" 1671286903000000000
> http count="0",description="Workbasket BackgroundProcessing",minDateTime="",status="UP" 1671286903000000000

I am following this example from this page link https://www.influxdata.com/blog/how-parse-json-telegraf-influxdb-cloud/   but seems the json format is different to mine


问:
I can't import simple c libraries
When I am trying to run cmake I get this error

```<code>fatal error: 'stdio.h' file not found
#include <stdio.h>
         ^~~~~~~~~
</code>```

I am using mac and people recommended me to run this command

```<code>xcode-select --install
</code>```

I get this in respond

```<code>command line tools are already installed, use "Software Update" in System Settings to install updates
</code>```

Then I checked my software update, but everything is up-to-date which is MacOS 13.1 (22C65).

Title: I can't import simple c libraries

Body:
When I am trying to run cmake I get this error

fatal error: 'stdio.h' file not found
#include <stdio.h>
         ^~~~~~~~~

I am using mac and people recommended me to run this command

xcode-select --install

I get this in respond

command line tools are already installed, use "Software Update" in System Settings to install updates

Then I checked my software update, but everything is up-to-date which is MacOS 13.1 (22C65).


问:
Display grid items onClick function not working react
I have made a grid that displays 4 grid items and onlick of the button I want it to display all grids items.

I have successfully set the items to not display but my function for them to display when the button is clicked is not working.
please see my code below.

```<code>
const Brands = () => {

  const divContainer = document.querySelectorAll("hidden");
  let showOrHide = function(){
    divContainer.style.display = "inline-block";
  }

  return (
 <>

 <div className={styles.brandcont}>
  <h2>Client Portfolio</h2>
 <div className={styles.cont}>
    <div className={styles.gucci}> <img alt="gucci logo" src={gucci}/></div>
    <div className={styles.fendi}> <img alt="fendi logo" src={fendi}/></div>
    <div className={styles.amq}> <img alt="alexander mcqueen logo" src={amq}/></div>
    <div className={styles.zegna}> <img alt="Zegna logo" src={zegna}/></div>
    <div className={styles.givenchy}> <img alt="Givenchy logo" src={givenchy}/></div>

    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={alfies}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={arije}/></div>

    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={bottega}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={breitling}/></div>

    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={brunello}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={louboutin}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={churchs}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={dolce}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={eden}/></div>

    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={grays}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={boss}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={kenzo}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={lacoste}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={loewe}/></div>

    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={longchamp}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={missoni}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={moschino}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={mulberry}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={prada}/></div>

    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={rimowa}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={ferragamo}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={stella}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={tg}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={time}/></div>

    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={ford}/></div>
    <div className={styles.gucci} id={styles.hidden}> <img alt="Givenchy logo" src={valentino}/></div>

 </div>

 <button onClick={showOrHide} className={styles.portbutton}>Full Portfolio</button>
 </div>

 </>
  )
}

export default Brands
</code>```

is there a simple way to correct this ?

I have removed the imports as it wouldnt let me post the question with too much code

Body:
I have made a grid that displays 4 grid items and onlick of the button I want it to display all grids items.

I have successfully set the items to not display but my function for them to display when the button is clicked is not working.
please see my code below.

const Brands = () => {

  const divContainer = document.querySelectorAll("hidden");
  let showOrHide = function(){
    divContainer.style.display = "inline-block";
  }

  return (
 <>

Client Portfolio

 <button onClick={showOrHide} className={styles.portbutton}>Full Portfolio</button>

 </>
  )
}

export default Brands

is there a simple way to correct this ?

I have removed the imports as it wouldnt let me post the question with too much code


问:
Use current Celery task in chord?
I'd like to run tasks in parallel that have a data dependency at the beginning of the first task. It seems that I should be able to start a chord with the current task in the header group that's used as the args for the body callback. I don't see a way to reference the signature of the current task in the documentation, but is there a way to do this?

I was thinking it would be something like this with the get_signature() being the missing piece:

```<code>@app.task(bind=True)
def chord_test(self, id_) -> int:
    data, next_id = get_data(id_)
    chord([self.get_signature(), chord_test.s(next_id)])(handle_results.s())

    return expensive_processing(data)
</code>```

Title: Use current Celery task in chord?

Body:
I'd like to run tasks in parallel that have a data dependency at the beginning of the first task. It seems that I should be able to start a chord with the current task in the header group that's used as the args for the body callback. I don't see a way to reference the signature of the current task in the documentation, but is there a way to do this?

I was thinking it would be something like this with the get_signature() being the missing piece:

@app.task(bind=True)
def chord_test(self, id_) -> int:
    data, next_id = get_data(id_)
    chord([self.get_signature(), chord_test.s(next_id)])(handle_results.s())

    return expensive_processing(data)


问:
Strange error with asynchronous code in Mutation Observer
I'm working on an third party addon for a WordPress page builder for which the code is based on Vue. Concretely, I'm working on an Emmet styled command line to add new elements to the UI with commands like: > section > container > button.

So far, so good. Since this Page Builder does not currently provide an API to interact inside the Vue context / state, I need to be creative. Currently it is a mixture between event dispatching and mutation observers. I manually go down each click path and thus create the elements as I need them.

This works, but only to a limited extent. I can't get any further at one point. The code you find below only goes up to the second layer.

section > container will work. The code will produce a section element with a nested container element inside. But: section > container > button will not work. The result here also is the same as before. The third element (button) is missing.

Here is the code:

```<code>async addElements(command) {
    try {
        // Split elements by one or more spaces
        let elements = command.split(">");

        // Remove items from array which are empty strings
        elements = elements.filter((item) => item);

        // Remove whitespace from all elements in the array
        elements = elements.map((item) => item.replace(/\s+/, ""));

        for (let i = 0; i < elements.length; i++) {
            // Remove whitespace
            elements[i] = elements[i].replace(" ", "");

            // Add Element
            await this.addElement({
                element: elements[i],
                index: i,
                elementsArray: elements,
            });
        }
    } catch (e) {
        console.log(e);
    }
}

async addElement({ element, elementsArray, index }) {
    // if is empty string, skip
    if (element == "") {
        return;
    }

    let newCreatedElement;
    let newCreatedElements = [];
    let mutationCountMax = elementsArray.length;

    // Add Mutation Observer to wait for the element to be created
    let observer = new MutationObserver(async (mutations) => {
        if (this.mutationCount >= mutationCountMax) {
            observer.disconnect();
            return;
        }

        this.mutationCount++;

        // Create a list from all li elements from the mutation.addedNodes
        let liList = [];
        mutations.forEach((mutation) => {
            if (mutation.addedNodes && mutation.addedNodes.length) {
                liList.push(
                    ...mutation.addedNodes[0].querySelectorAll("li")
                );
            }
        });

        // Remove mutations which have no added nodes
        mutations = mutations.filter(
            (mutation) => mutation.addedNodes.length > 0
        );

        // Remove mutations which have #builder-panel-header as parent
        mutations = mutations.filter(
            (mutation) =>
                mutation.addedNodes[0].parentElement.id !=
                "builder-panel-header"
        );

        // Remove mutations which target is not tag UL or tag LI
        mutations = mutations.filter(
            (mutation) =>
                mutation.addedNodes[0].tagName == "UL" ||
                mutation.addedNodes[0].tagName == "LI"
        );

        let addedNode = mutations[0].addedNodes[0];
        newCreatedElement = [addedNode];

        // if newCreatedElement is UL, get the first LI
        newCreatedElement = newCreatedElement[0].querySelectorAll("li");

        newCreatedElement.forEach((element) => {
            // Add click event to the element
            element
                .querySelector(".builder-draggable-handle")
                .dispatchEvent(new MouseEvent("click", { bubbles: true }));
        });

        /**
         * Wait for the nested LI Elements to be added to the page
         */

        let liObserver = new MutationObserver(async (liMutations) => {
            // Wait until the nested li elements have been added to the page
            if (
                liMutations.some(
                    (liMutation) => liMutation.addedNodes.length > 0
                )
            ) {
                // Get all of the nested li elements
                let liElements = addedNode.querySelectorAll("li li");

                console.log(liElements);

                console.log("Detected Nested LI Elements");

                liElements.forEach((element) => {
                    // Add click event to the element
                    element
                        .querySelector(".builder-draggable-handle")
                        .dispatchEvent(
                            new MouseEvent("click", { bubbles: true })
                        );
                });

                // Disconnect the observer once the li elements have been found
                liObserver.disconnect();
            }
        });

        // Observe the addedNode element for changes
        liObserver.observe(addedNode, {
            childList: true,
            subtree: true,
        });

        /**
         * Create Element
         */
        if (this.mutationCount != 1) {
            await this.createElement(element);
        }

        observer.disconnect();
    });

    // Observe the body
    observer.observe(document.querySelector("#builder-structure"), {
        childList: true,
        // Not observing attributes
        attributes: false,
        // Also deep elements
        subtree: true,
    });

    if (index == 0) {
        this.createElement(element);
    }
}

async createElement(element) {
    console.log("Create Element: " + element);

    // Code to add the element to the UI structure
    // ...
}
</code>```

The console.log output for the command section > container > button is the following:

```<code>Create Element: section
Create Element: container
Create Element: button
NodeList [li#element-aqtufh
Detected Nested LI Elements
NodeList [li#element-aqtufh
Detected Nested LI Elements
NodeList [li#element-aqtufh
Detected Nested LI Elements
</code>```

I think the problem lies in the asynchrony. The output in the console also seems to be not quite correct.

In that case I need the second mutation observer, because in the first one strangely the nested LI elements can't be found - I don't understand why. So it works, but only with the above mentioned problem.

Where is the error in my code?

Body:
I'm working on an third party addon for a WordPress page builder for which the code is based on Vue. Concretely, I'm working on an Emmet styled command line to add new elements to the UI with commands like: > section > container > button.

So far, so good. Since this Page Builder does not currently provide an API to interact inside the Vue context / state, I need to be creative. Currently it is a mixture between event dispatching and mutation observers. I manually go down each click path and thus create the elements as I need them.

This works, but only to a limited extent. I can't get any further at one point. The code you find below only goes up to the second layer.

section > container will work. The code will produce a section element with a nested container element inside. But: section > container > button will not work. The result here also is the same as before. The third element (button) is missing.

Here is the code:

async addElements(command) {
    try {
        // Split elements by one or more spaces
        let elements = command.split(">");

        // Remove items from array which are empty strings
        elements = elements.filter((item) => item);

        // Remove whitespace from all elements in the array
        elements = elements.map((item) => item.replace(/\s+/, ""));

        for (let i = 0; i < elements.length; i++) {
            // Remove whitespace
            elements[i] = elements[i].replace(" ", "");

            // Add Element
            await this.addElement({
                element: elements[i],
                index: i,
                elementsArray: elements,
            });
        }
    } catch (e) {
        console.log(e);
    }
}

async addElement({ element, elementsArray, index }) {
    // if is empty string, skip
    if (element == "") {
        return;
    }

    let newCreatedElement;
    let newCreatedElements = [];
    let mutationCountMax = elementsArray.length;

    // Add Mutation Observer to wait for the element to be created
    let observer = new MutationObserver(async (mutations) => {
        if (this.mutationCount >= mutationCountMax) {
            observer.disconnect();
            return;
        }

        this.mutationCount++;

        // Create a list from all li elements from the mutation.addedNodes
        let liList = [];
        mutations.forEach((mutation) => {
            if (mutation.addedNodes && mutation.addedNodes.length) {
                liList.push(
                    ...mutation.addedNodes[0].querySelectorAll("li")
                );
            }
        });

        // Remove mutations which have no added nodes
        mutations = mutations.filter(
            (mutation) => mutation.addedNodes.length > 0
        );

        // Remove mutations which have #builder-panel-header as parent
        mutations = mutations.filter(
            (mutation) =>
                mutation.addedNodes[0].parentElement.id !=
                "builder-panel-header"
        );

        // Remove mutations which target is not tag UL or tag LI
        mutations = mutations.filter(
            (mutation) =>
                mutation.addedNodes[0].tagName == "UL" ||
                mutation.addedNodes[0].tagName == "LI"
        );

        let addedNode = mutations[0].addedNodes[0];
        newCreatedElement = [addedNode];

        // if newCreatedElement is UL, get the first LI
        newCreatedElement = newCreatedElement[0].querySelectorAll("li");

        newCreatedElement.forEach((element) => {
            // Add click event to the element
            element
                .querySelector(".builder-draggable-handle")
                .dispatchEvent(new MouseEvent("click", { bubbles: true }));
        });

        /**
         * Wait for the nested LI Elements to be added to the page
         */

        let liObserver = new MutationObserver(async (liMutations) => {
            // Wait until the nested li elements have been added to the page
            if (
                liMutations.some(
                    (liMutation) => liMutation.addedNodes.length > 0
                )
            ) {
                // Get all of the nested li elements
                let liElements = addedNode.querySelectorAll("li li");

                console.log(liElements);

                console.log("Detected Nested LI Elements");

                liElements.forEach((element) => {
                    // Add click event to the element
                    element
                        .querySelector(".builder-draggable-handle")
                        .dispatchEvent(
                            new MouseEvent("click", { bubbles: true })
                        );
                });

                // Disconnect the observer once the li elements have been found
                liObserver.disconnect();
            }
        });

        // Observe the addedNode element for changes
        liObserver.observe(addedNode, {
            childList: true,
            subtree: true,
        });

        /**
         * Create Element
         */
        if (this.mutationCount != 1) {
            await this.createElement(element);
        }

        observer.disconnect();
    });

    // Observe the body
    observer.observe(document.querySelector("#builder-structure"), {
        childList: true,
        // Not observing attributes
        attributes: false,
        // Also deep elements
        subtree: true,
    });

    if (index == 0) {
        this.createElement(element);
    }
}

async createElement(element) {
    console.log("Create Element: " + element);

    // Code to add the element to the UI structure
    // ...
}

The console.log output for the command section > container > button is the following:

Create Element: section
Create Element: container
Create Element: button
NodeList [li#element-aqtufh
Detected Nested LI Elements
NodeList [li#element-aqtufh
Detected Nested LI Elements
NodeList [li#element-aqtufh
Detected Nested LI Elements

I think the problem lies in the asynchrony. The output in the console also seems to be not quite correct.

In that case I need the second mutation observer, because in the first one strangely the nested LI elements can't be found - I don't understand why. So it works, but only with the above mentioned problem.

Where is the error in my code?


问:
How can I use Readable() constructor to read from a text file and write it in a Writable() constructor?
I am trying to read from a text file using new Readable() constructor,but I don't know how to make the code receive it as a file path. I would like the result to be displayed in the console using new Writable() constructor.</p>
```<code>const fs = require('fs');
const {Readable} = require('stream');
const {Writable} = require('stream');

const userData = __dirname + '/files/data.txt';

const rStream = new Readable({
    read() {}
});

const wStream = new Writable({
    write(chunk, encoding, callback) {
        console.log("Readable data: ", chunk.toString());
        callback();
    }
});

rStream.pipe(wStream);
rStream.push(userData);

rStream.on('close', () =>
        wStream.end());

wStream.on('close', () =>
    console.log('No more data in file...')
);

rStream.on('error', (err) =>
    console.log('Readable error!', err.message)
);

wStream.on('error', (err) =>
    console.log('Writable error!', err.message)
);

rStream.destroy();
</code>```

Body:
I am trying to read from a text file using new Readable() constructor,but I don't know how to make the code receive it as a file path. I would like the result to be displayed in the console using new Writable() constructor.

const fs = require('fs');
const {Readable} = require('stream');
const {Writable} = require('stream');

const userData = __dirname + '/files/data.txt';

const rStream = new Readable({
    read() {}
});

const wStream = new Writable({
    write(chunk, encoding, callback) {
        console.log("Readable data: ", chunk.toString());
        callback();
    }
});

rStream.pipe(wStream);
rStream.push(userData);

rStream.on('close', () =>
        wStream.end());

wStream.on('close', () =>
    console.log('No more data in file...')
);

rStream.on('error', (err) =>
    console.log('Readable error!', err.message)
);

wStream.on('error', (err) =>
    console.log('Writable error!', err.message)
);

rStream.destroy();


问:
Redirect after form.submit()
I'm working with a large program and I need to add new functionality to an existing button. Previously when the button was clicked it's operations would be performed but the page would remain in place. I need the button to continue to perform it's action but then to redirect to a new page. Currently, when I add my window.location.href after the button's action the page does redirect successfully but the button's original actions is no longer being carried out. Ignore that fact that the URL is currently hard coded, that will change.

```<code>            },

    submitHandler: function (form)
    {
        $('#save').attr("disabled", true);
        form.submit();
        window.location.href = "{{ dealerDomain }}/gs-vehicle/viewMyVehicle?id={{ data['id'] }}";
    }
});
</code>```

This whole thing is inside a .validate( which is chained onto a .submit, and the only line I've added is the window.location.href. Does this help at all? window.location.href = "{{ dealerDomain }}/gs-vehicle/viewMyVehicle?id={{ data['id'] }}";

Thanks.

Title: Redirect after form.submit()

Body:
I'm working with a large program and I need to add new functionality to an existing button. Previously when the button was clicked it's operations would be performed but the page would remain in place. I need the button to continue to perform it's action but then to redirect to a new page. Currently, when I add my window.location.href after the button's action the page does redirect successfully but the button's original actions is no longer being carried out. Ignore that fact that the URL is currently hard coded, that will change.

            },

    submitHandler: function (form)
    {
        $('#save').attr("disabled", true);
        form.submit();
        window.location.href = "{{ dealerDomain }}/gs-vehicle/viewMyVehicle?id={{ data['id'] }}";
    }
});

This whole thing is inside a .validate( which is chained onto a .submit, and the only line I've added is the window.location.href. Does this help at all? window.location.href = "{{ dealerDomain }}/gs-vehicle/viewMyVehicle?id={{ data['id'] }}";

Thanks.


问:
generate all binary matrix with given rows sum and columns sum
I'm trying to program an algoritmn with python  which generate all the binary matrix (m row , n column) that we know sum of rows and sum of columns ... I tried few trials but I found that it was not valid . Someone can guide me please !

I tried to put all probabilities of each line with other lines and same for columns .. but it's unsuccesful way .


问:
iOS: List selection is reset to nil when app is sent to background
For some reason, a List will reset its selection to nil when the app is in the background.

Steps to reproduce the issue:

Run attached sample project

Once the app has launched, select a name in the sidebar

Move the app to the background

Wait a few seconds

Bring back the app to the foreground

Expected result:

The list selection should still be valid

Actual result:

The list selection is set to nil

Notes:

I’m using a StateObject, which should be the way to ensure that data isn’t regenerated when views are rendered. Is this a bug or something else needs to be taken care of?

class AppModel: ObservableObject {
    @Published var selectedPerson: Person?
}

@main

struct NilListSelectionApp: App {
    @StateObject var appModel = AppModel()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appModel)
        }
    }
}
```
<pre class="lang-swift prettyprint-override"><code>struct Person: Identifiable, Hashable {
    let id: UUID
    let firstname: String

    init(firstname: String) {
        id = UUID()
        self.firstname = firstname
    }
}

struct ContentView: View {
    @EnvironmentObject private var appModel: AppModel

    var body: some View {
        NavigationSplitView {
            SidebarView()
        } detail: {
            PersonView(person: appModel.selectedPerson)
        }
    }
}

struct SidebarView: View {
    @EnvironmentObject private var appModel: AppModel

    private let persons = [Person(firstname: "Joe"), Person(firstname: "Jane")]

    var body: some View {
        List(persons, id:\.self, selection: $appModel.selectedPerson) { person in
            Text(person.firstname).tag(person)
        }
        .listStyle(.sidebar)
    }
}

struct PersonView: View {
    let person: Person?

    var body: some View {
        if let person {
            Text(person.firstname)
        }
        else {
            Text("No Selection")
        }
    }
}
</code>```

Body:
For some reason, a List will reset its selection to nil when the app is in the background.

Steps to reproduce the issue:

Run attached sample project

Once the app has launched, select a name in the sidebar

Move the app to the background

Wait a few seconds

Bring back the app to the foreground

Expected result:

The list selection should still be valid

Actual result:

The list selection is set to nil

Notes:

I’m using a StateObject, which should be the way to ensure that data isn’t regenerated when views are rendered. Is this a bug or something else needs to be taken care of?

class AppModel: ObservableObject {
    @Published var selectedPerson: Person?
}

@main

struct NilListSelectionApp: App {
    @StateObject var appModel = AppModel()

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(appModel)
        }
    }
}

struct Person: Identifiable, Hashable {
    let id: UUID
    let firstname: String

    init(firstname: String) {
        id = UUID()
        self.firstname = firstname
    }
}

struct ContentView: View {
    @EnvironmentObject private var appModel: AppModel

    var body: some View {
        NavigationSplitView {
            SidebarView()
        } detail: {
            PersonView(person: appModel.selectedPerson)
        }
    }
}

struct SidebarView: View {
    @EnvironmentObject private var appModel: AppModel

    private let persons = [Person(firstname: "Joe"), Person(firstname: "Jane")]

    var body: some View {
        List(persons, id:\.self, selection: $appModel.selectedPerson) { person in
            Text(person.firstname).tag(person)
        }
        .listStyle(.sidebar)
    }
}

struct PersonView: View {
    let person: Person?

    var body: some View {
        if let person {
            Text(person.firstname)
        }
        else {
            Text("No Selection")
        }
    }
}


问:
Portainer keeps getting back with New Portainer installation
I am trying to run Portainer on Raspberry Pi 4.
After creating the admin user I can't get pass the time out warning.

our Portainer instance timed out for security purposes. To re-enable your Portainer instance, you will need to restart Portainer.

Tried:

stopping and starting Portainer

```<code> sudo docker restart portainer

</code>```

recreating the container

using another port

Anyone an idea of whats wrong here?
Thanks for yr effort in advance JB

Body:
I am trying to run Portainer on Raspberry Pi 4.
After creating the admin user I can't get pass the time out warning.

our Portainer instance timed out for security purposes. To re-enable your Portainer instance, you will need to restart Portainer.

Tried:

stopping and starting Portainer

 sudo docker restart portainer

recreating the container

using another port

Anyone an idea of whats wrong here?
Thanks for yr effort in advance JB


问:
"Remember Me" option when logging in with Django + DRF + Djoser + Nuxt
I've got a site that uses Django as a backend and Nuxt for frontend. I'd like to implement the commonly-seen "Remember Me" checkbox when a user logs in. If unchecked, the user should only be logged in for that session and has to log in again the next time they open their browser. If checked, they should stay logged in indefinitely unless they manually log out.

The backend is using Django, with Django Rest Framework and Djoser for authentication. Currently using DRF's TokenAuthentication, and not JWT stuff.

The frontend is using Nuxt, which is using the Nuxt Auth module with the local strategy for logging in. This is saving the token in localStorage, which never expires.

How would I go about adding this "Remember Me" functionality? I'm not even sure which part to modify - either the backend or the frontend.


问:
Rendering jsx:element for semantic-ui dropdown
I am new to using react.js, using a C# API, and trying to use the semantic-UI dropdown that allows HTML in the content of the dropdown items.

I'm having trouble returning the "content" field below.  It looks like a jsx:element type, not a string or number like the other types.

I can hardcode it, but I can't return it from the API.

Here is the example from the Semantic documentation which seems like an invalid JSON to me.  For now, I've given up on this, but still curious how JSON like this is supposed to be returned from c# .net core API.

```<code>const options = [
  {
    key: 1,
    text: 'Mobile',
    value: 1,
    content: (
      <Header icon='mobile' content='Mobile' subheader='The smallest size' />
    ),
  },
  {
    key: 2,
    text: 'Tablet',
    value: 2,
    content: (
      <Header
        icon='tablet'
        content='Tablet'
        subheader='The size in the middle'
      />
    ),
  },
  {
    key: 3,
    text: 'Desktop',
    value: 3,
    content: (
      <Header icon='desktop' content='Desktop' subheader='The largest size' />
    ),
  },
]
</code>```

This is my the code in the API that currently sends the dropdown items:

```<code>[HttpGet(Name = "GetCaseDropdown")]
public IEnumerable<CaseDropdownItem> Get()
{
    var db = new CaseDBContext();

    var records = (from x in db.Cases
                   select new CaseDropdownItem()
                   {
                       content = "<b>"+ x.StrCnCasenum + "</b>" + " " + x.StrCnName, // Does not render within parentheses which is required
                       text = x.StrCnName,
                       value = x.StrCnCasenum,
                       key = x.StrCnCasenum

                   }).ToArray();

    return records;

}
</code>```

And the react code that fetches the data:

```<code>fetch("casedropdown")
    .then((response) => response.json())
    .then((data) =>
        setCaseOptions(
            data.map((x) => {
                return { key: x.key, text: x.text, value: x.value, content: x.content };
            })
        )
    );
</code>```

Body:
I am new to using react.js, using a C# API, and trying to use the semantic-UI dropdown that allows HTML in the content of the dropdown items.

I'm having trouble returning the "content" field below.  It looks like a jsx:element type, not a string or number like the other types.

I can hardcode it, but I can't return it from the API.

Here is the example from the Semantic documentation which seems like an invalid JSON to me.  For now, I've given up on this, but still curious how JSON like this is supposed to be returned from c# .net core API.

const options = [
  {
    key: 1,
    text: 'Mobile',
    value: 1,
    content: (

    ),
  },
  {
    key: 2,
    text: 'Tablet',
    value: 2,
    content: (

    ),
  },
  {
    key: 3,
    text: 'Desktop',
    value: 3,
    content: (

    ),
  },
]

This is my the code in the API that currently sends the dropdown items:

[HttpGet(Name = "GetCaseDropdown")]
public IEnumerable<CaseDropdownItem> Get()
{
    var db = new CaseDBContext();

    var records = (from x in db.Cases
                   select new CaseDropdownItem()
                   {
                       content = ""+ x.StrCnCasenum + "" + " " + x.StrCnName, // Does not render within parentheses which is required
                       text = x.StrCnName,
                       value = x.StrCnCasenum,
                       key = x.StrCnCasenum

                   }).ToArray();

    return records;

}

And the react code that fetches the data:

fetch("casedropdown")
    .then((response) => response.json())
    .then((data) =>
        setCaseOptions(
            data.map((x) => {
                return { key: x.key, text: x.text, value: x.value, content: x.content };
            })
        )
    );


问:
VSCode: How to define unique includePaths for each core (sub-directories) in STM32h7 dual-core project within same git repo?
I have a git repository for a STM32 H7 dual-core project. Opening the repo-level folder my structure looks like the following:

```<code>
PARENT DIRECTORY (STM32H755)
├── .git
├── .vscode
│   └── c_cpp_properties.json
│
├── CM4
│   ├── Core
│   │   ├── Inc
│   │   │   └── .h files for CM4 only
│   │   └── Src
│   │       └── .c files for CM4 only
│   └── ...
│
├── CM7
│   ├── Core
│   │   ├── Inc
│   │   │   └── .h files for CM7 only
│   │   └── Src
│   │       └── .c files for CM7 only
│   └── ...
│
├── Common
│   ├── Core
│   │   ├── Inc
│   │   │   └── .h files for BOTH CM4 and CM7
│   │   └── Src
│   │       └── .c files for BOTH CM4 and CM7
│   └── ...
│

</code>```

I need to specify the includePath for each of the CM4 and CM7 cores independently, including that specific core's h files as well as the common h files.

How is this achieved?

The default path  within c_cpp_properties.json file:

```<code> "includePath": [
                "${workspaceFolder}/**",
            ],
</code>```

causes issues for similarly named files between the CM4 and CM7 (ie. main.h).

Conversely, using a core specific paths, such as the following for a CM4:

```<code> "includePath": [
                "${workspaceFolder}/CM4/**",
                "${workspaceFolder}/Common/**"
            ],
</code>```

causes issues for the other core's files (ie. CM7's main.h).

Body:
I have a git repository for a STM32 H7 dual-core project. Opening the repo-level folder my structure looks like the following:

PARENT DIRECTORY (STM32H755)
├── .git
├── .vscode
│   └── c_cpp_properties.json
│
├── CM4
│   ├── Core
│   │   ├── Inc
│   │   │   └── .h files for CM4 only
│   │   └── Src
│   │       └── .c files for CM4 only
│   └── ...
│
├── CM7
│   ├── Core
│   │   ├── Inc
│   │   │   └── .h files for CM7 only
│   │   └── Src
│   │       └── .c files for CM7 only
│   └── ...
│
├── Common
│   ├── Core
│   │   ├── Inc
│   │   │   └── .h files for BOTH CM4 and CM7
│   │   └── Src
│   │       └── .c files for BOTH CM4 and CM7
│   └── ...
│

I need to specify the includePath for each of the CM4 and CM7 cores independently, including that specific core's h files as well as the common h files.

How is this achieved?

The default path  within c_cpp_properties.json file:

 "includePath": [
                "${workspaceFolder}/**",
            ],

causes issues for similarly named files between the CM4 and CM7 (ie. main.h).

Conversely, using a core specific paths, such as the following for a CM4:

 "includePath": [
                "${workspaceFolder}/CM4/**",
                "${workspaceFolder}/Common/**"
            ],

causes issues for the other core's files (ie. CM7's main.h).


问:
Import LimeSurvey DB from data only
I backed up my Limesurvey data. Later my database got hosed by a virus.  Okay, good thing I have a backup! Except... When I backed up, I apparently neglected to "Save CREATE Schema", so my backup is data only.

So I figured I could set up a new install, remove the new data, and restore my data.

OOPS! It creates tables when you actually create a survey. Another table when you turn on tokens. Okay, I'll do those things too.  Change the new table names to match the ones in my data, aaaaaannnd...

No dice.  Mismatch in number of table fields.  At this point I'm at a loss -- does it alter the actual table field count during usage???

At any rate, I'm stuck. I'm just trying to get the danged survey back.  I have the data, but can't manage to create a table structure that matches the data structure.  Any suggestion as to how I might accomplish this?

Title: Import LimeSurvey DB from data only