问:
How to select all data before current_state in history data in Oracle SQL?
So I have data look like in Picture.
Column name Track is to show the step of the state.
Column name Current_state is the status of the app right now.
Column name Current_state_hist is the history of the status.

So right now the current status now is AP.
I want to Select all the status before the last status right now (AP in Track 13 & 14) without remove the status AP in track 5 - 8.

Can somebody help me for this case? Thank you
Example of the data

答:
You can find the latest status without having to query the table twice using the ROW_NUMBER analytic function:

SELECT id, track, current_state, current_state_hist, total_unit
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER (ORDER BY track DESC)
           - ROW_NUMBER() OVER (
               PARTITION BY current_state_hist ORDER BY track DESC
             ) AS rn
  FROM   table_name t
)
WHERE rn > 0;
```
<p>Or, from Oracle 12:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM   table_name
MATCH_RECOGNIZE(
  ORDER BY track DESC
  ALL ROWS PER MATCH
  PATTERN ( ^ {- same_hist+ -} any_hist* )
  DEFINE
    same_hist AS FIRST(current_state_hist) = current_state_hist
)
</code>```

Which, for the sample data:

CREATE TABLE table_name (id, track, current_state, current_state_hist, total_unit) AS
SELECT 1,  1, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1,  2, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1,  3, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1,  4, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1,  5, 'AP', 'AP', 1 FROM DUAL UNION ALL
SELECT 1,  6, 'AP', 'AP', 1 FROM DUAL UNION ALL
SELECT 1,  7, 'AP', 'AP', 1 FROM DUAL UNION ALL
SELECT 1,  8, 'AP', 'AP', 1 FROM DUAL UNION ALL
SELECT 1,  9, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1, 10, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1, 11, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1, 12, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1, 13, 'AP', 'AP', 1 FROM DUAL UNION ALL
SELECT 1, 14, 'AP', 'AP', 1 FROM DUAL;
```
<p>Both output:</p>
<blockquote>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: right;">ID</th>
<th style="text-align: right;">TRACK</th>
<th style="text-align: left;">CURRENT_STATE</th>
<th style="text-align: left;">CURRENT_STATE_HIST</th>
<th style="text-align: right;">TOTAL_UNIT</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">12</td>
<td style="text-align: left;">AP</td>
<td style="text-align: left;">OD</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">11</td>
<td style="text-align: left;">AP</td>
<td style="text-align: left;">OD</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">10</td>
<td style="text-align: left;">AP</td>
<td style="text-align: left;">OD</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">9</td>
<td style="text-align: left;">AP</td>
<td style="text-align: left;">OD</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">8</td>
<td style="text-align: left;">AP</td>
<td style="text-align: left;">AP</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">7</td>
<td style="text-align: left;">AP</td>
<td style="text-align: left;">AP</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">6</td>
<td style="text-align: left;">AP</td>
<td style="text-align: left;">AP</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">5</td>
<td style="text-align: left;">AP</td>
<td style="text-align: left;">AP</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">4</td>
<td style="text-align: left;">AP</td>
<td style="text-align: left;">OD</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">3</td>
<td style="text-align: left;">AP</td>
<td style="text-align: left;">OD</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">2</td>
<td style="text-align: left;">AP</td>
<td style="text-align: left;">OD</td>
<td style="text-align: right;">1</td>
</tr>
<tr>
<td style="text-align: right;">1</td>
<td style="text-align: right;">1</td>
<td style="text-align: left;">AP</td>
<td style="text-align: left;">OD</td>
<td style="text-align: right;">1</td>
</tr>
</tbody>
</table>
</div></blockquote>
<hr />
<blockquote>
<p>I want the ouput is to select all except the last 2 row... because it's current status...</p>
</blockquote>
<p>If you just want to ignore the last 2 rows then: order the rows, then assign a <code>ROWNUM</code> pseudo-column to the ordered rows, then filter on the <code>ROWNUM</code> to exclude the latest two rows:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM   (
  SELECT t.*,
         ROWNUM AS rn
  FROM   (
    SELECT *
    FROM   table_name
    ORDER BY track DESC
  ) t
)
WHERE  rn >= 3;
</code>```

Or, using the ROW_NUMBER analytic function:

SELECT *
FROM   (
  SELECT t.*,
         ROW_NUMMBER() OVER (ORDER BY track DESC) AS rn
  FROM   table_name t
)
WHERE  rn >= 3;
```
<p>Or, from Oracle 12:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT *
FROM   table_name
ORDER BY track DESC
OFFSET 2 ROWS
FETCH FIRST 100 PERCENT ONLY;
</code>```

db<>fiddle here

Body:
You can find the latest status without having to query the table twice using the ROW_NUMBER analytic function:

SELECT id, track, current_state, current_state_hist, total_unit
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER (ORDER BY track DESC)
           - ROW_NUMBER() OVER (
               PARTITION BY current_state_hist ORDER BY track DESC
             ) AS rn
  FROM   table_name t
)
WHERE rn > 0;

Or, from Oracle 12:

SELECT *
FROM   table_name
MATCH_RECOGNIZE(
  ORDER BY track DESC
  ALL ROWS PER MATCH
  PATTERN ( ^ {- same_hist+ -} any_hist* )
  DEFINE
    same_hist AS FIRST(current_state_hist) = current_state_hist
)

Which, for the sample data:

CREATE TABLE table_name (id, track, current_state, current_state_hist, total_unit) AS
SELECT 1,  1, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1,  2, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1,  3, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1,  4, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1,  5, 'AP', 'AP', 1 FROM DUAL UNION ALL
SELECT 1,  6, 'AP', 'AP', 1 FROM DUAL UNION ALL
SELECT 1,  7, 'AP', 'AP', 1 FROM DUAL UNION ALL
SELECT 1,  8, 'AP', 'AP', 1 FROM DUAL UNION ALL
SELECT 1,  9, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1, 10, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1, 11, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1, 12, 'AP', 'OD', 1 FROM DUAL UNION ALL
SELECT 1, 13, 'AP', 'AP', 1 FROM DUAL UNION ALL
SELECT 1, 14, 'AP', 'AP', 1 FROM DUAL;

Both output:

ID
TRACK
CURRENT_STATE
CURRENT_STATE_HIST
TOTAL_UNIT

1
12
AP
OD
1

1
11
AP
OD
1

1
10
AP
OD
1

1
9
AP
OD
1

1
8
AP
AP
1

1
7
AP
AP
1

1
6
AP
AP
1

1
5
AP
AP
1

1
4
AP
OD
1

1
3
AP
OD
1

1
2
AP
OD
1

1
1
AP
OD
1

I want the ouput is to select all except the last 2 row... because it's current status...

If you just want to ignore the last 2 rows then: order the rows, then assign a ROWNUM pseudo-column to the ordered rows, then filter on the ROWNUM to exclude the latest two rows:

SELECT *
FROM   (
  SELECT t.*,
         ROWNUM AS rn
  FROM   (
    SELECT *
    FROM   table_name
    ORDER BY track DESC
  ) t
)
WHERE  rn >= 3;

Or, using the ROW_NUMBER analytic function:

SELECT *
FROM   (
  SELECT t.*,
         ROW_NUMMBER() OVER (ORDER BY track DESC) AS rn
  FROM   table_name t
)
WHERE  rn >= 3;

Or, from Oracle 12:

SELECT *
FROM   table_name
ORDER BY track DESC
OFFSET 2 ROWS
FETCH FIRST 100 PERCENT ONLY;

db<>fiddle here


来源: stackexchange

问:
SQLSTATE and SQLCODE usage in SQLRPGLE
In SQLRPGLE programming I have seen that the SQLSTATE and SQLCODE being used in several areas in order to catch an error in the sql statement. My query is what is the difference between SQLSTATE and SQLCODE because I see them to be used for similar purpose. Is there any special scenario where SQLSTATE or SQLCODE is used or are they the same?</p>

答:
Short version, SQLCODE is DB2 for IBM i specific, SQLSTATE is standard

See here

SQLSTATE is the preferred standard return code. It provides
application programs with return codes for common error conditions
found among the DB2® products.

SQLSTATE values are consistent with the SQLSTATE specifications that
are contained in the SQL 1999 standard.

ContentLicense: CC BY-SA 4.0

Title: SQLSTATE and SQLCODE usage in SQLRPGLE


问:
ImageMagick: lay a partly transparent tile over an image
I have a wallpaper.jpg (size: 1920x1280) and a partly transparent tile.gif (size: 16x16).

On a website I want to have the tile as a x- and y-repeated overlay over the wallpaper.

Right now, this overlay is realized using CSS. I want to save one request and merge the (repeated) tile.png with the wallpaper.jpg using ImageMagick. The wallpaper.jpg is generated via ImageMagick anyway.

Following the Documentation of the -tile option, I came up with the following command:

```<code>convert wallpaper.jpg -size 1920x1280 tile:tile.gif -compose over -composite result.jpg
</code>```

The result, however, is a 1920x1280 jpg filled with the tile, but no wallpaper shining through. Instead, the transparent part of the tile seem to be white.

The documentation says:

If the tile image is partially transparent then a 'Over' "-compose" method will need to be specified.

So what's wrong?

I also tried -flatten instead of -composite... same result.

edit:
I realize, there is also another -tile option documentation. It seems to follow the concept of overloading. Unfortunately, I cannot figure out how to use it correctly.

答:
Not sure if it will help, but have you tried converting your tile.gif to a 24-bit PNG file with Alpha/Transparency? - Scratch that....

I found some example showing but am unsure about the full command line:

```<code>composite -tile tile.gif netscape: wallpaper.jpg
</code>```

Source: http://www.imagemagick.org/Usage/compose/#tile

ContentLicense: CC BY-SA 3.0

Body:
I have a wallpaper.jpg (size: 1920x1280) and a partly transparent tile.gif (size: 16x16).

On a website I want to have the tile as a x- and y-repeated overlay over the wallpaper.

Right now, this overlay is realized using CSS. I want to save one request and merge the (repeated) tile.png with the wallpaper.jpg using ImageMagick. The wallpaper.jpg is generated via ImageMagick anyway.

Following the Documentation of the -tile option, I came up with the following command:

convert wallpaper.jpg -size 1920x1280 tile:tile.gif -compose over -composite result.jpg

The result, however, is a 1920x1280 jpg filled with the tile, but no wallpaper shining through. Instead, the transparent part of the tile seem to be white.

The documentation says:

If the tile image is partially transparent then a 'Over' "-compose" method will need to be specified.

So what's wrong?

I also tried -flatten instead of -composite... same result.

edit:
I realize, there is also another -tile option documentation. It seems to follow the concept of overloading. Unfortunately, I cannot figure out how to use it correctly.

Body:
Not sure if it will help, but have you tried converting your tile.gif to a 24-bit PNG file with Alpha/Transparency? - Scratch that....

I found some example showing but am unsure about the full command line:

composite -tile tile.gif netscape: wallpaper.jpg

Source: http://www.imagemagick.org/Usage/compose/#tile


问:
when exactly missing credentials error created in passport.js login cycle
I have decided to use passport.js for authentication of my node app. I implemented local strategies for login and signup and they works fine but there is a problem that confuses me. I have built a module in the past that generates and returns http errors using http-error package. I use it for standardizing error generation. For example if some credentials are missing or invalid I call
Errors.ValidationError({name:"password",reason:"password field is missing in your request"})

this creates and returns a proper http error and I send it to the users. It is useful for error generation. I want to use this logic with passport so I opted to create my own callbacks. Here is some code:

local login strategy definition

```<code>/**
 * User login
 * @param {*} request
 * @param {*} response
 * @return {*} logged existant user or error
 */
passport.use('login',
    new localStrategy(
        {
            usernameField: 'email',
            passwordField: 'password',
        },
        async (email, password, done)=> {
            if(email==null||password==null)
            {
                AppLogger.debug(21)
                return done(null, false);
            }
            User.findOne({ email: email }).
            then(async(user)=>{
                if (!user) {
                    AppLogger.debug(22)
                    return done(null, false);
                }
                if (!(await user.verifyPassword(password))) {
                    AppLogger.debug(23)
                    return done(null, false);
                }
                return done(null, user);
            }).
            catch((err)=>{
                AppLogger.debug(24)
                return done(err);
            });
        }
    )
);
</code>```

login route

```<code>/**
 * Login an existant user
 */
AuthRouter.post('/login', (req, res, next)=> {
    passport.authenticate('login', (err, user, info) =>{
        if (err) {
            AppLogger.debug(1)
            return next(err);
        }
        if (!user) {
            AppLogger.debug(2)
            return next(info);
        }
        req.login(user,(err)=>{
            if(err){
                AppLogger.debug(3)
                return next(err);
            }
            res.send({
                success:true,
                message:"logged in"
            })
        })
    })(req, res, next);
});
</code>```

considering all the debug lines on the code I get this output:
logs

My log lines prints 2 which means there is no exception but user is null and  I am trying to understand where exactly the missing credentials error is created in login strategy so I can generate my custom http error. Oddly enough none of the debugs in the strategy is not getting executed. Note that there is a middleware that catches all the errors and logs so the error log comes from there. And also keep in kind the app works as expected but I can't spot where this error is generated. I assume some method in passport middleware throws an error and my log middleware catches it but how can I interact with it and generate my http error in a meaningful way? Any suggestions are appreciated.

答:
Here is the work around I came up with:

router

```<code>/**
 * Login an existant user
 */
AuthRouter.post('/login', (req, res, next)=> {
    if(!req.body.email || !req.body.password){
        const subErrors = []
        if(!req.body.email){
            subErrors.push({
                name:"email",
                reason:"login request must contain email"
            })
        }
        if(!req.body.password){
            subErrors.push({
                name:"password",
                reason:"login request must contain password"
            })
        }
        const httpError = Errors.ValidationError(subErrors);
        return next(httpError);
    }
    passport.authenticate('login', (err, user, info) =>{
        if (err) {
            return next(err);
        }
        if (!user) {
            return next(info);
        }
        req.login(user,(err)=>{
            if(err){
                return next(err);
            }
            res.send({
                success:true,
                message:"logged in"
            })
        })
    })(req, res, next);
});
</code>```

Since the ultimate goal was replacing passport's default missing credentials error with my custom http error and I couldn't find a way within passportjs strategy, I check the request body before calling the passport.authenticate()
I can successfully create and return my custom error but this means although I check manually, passportjs also checks if the credentials are there. So its not optimal for performance.

Also I know that using

```<code>if(x===null)
</code>```

causes some problems in some cases and I also used '==' instead of '===' in the original code. It has nothing to do with main problem but its not the best practice.

finally here are the default and custom error responses:

this is what passportjs returns

```<code>{"message":"Missing credentials"}
</code>```

this is my custom error

```<code>{
"statusCode":400,
"error":"Bad Request",
"invalid_params":[
   {
       "name":"password",
       "reason":"login request must contain password"
   }
],
"type":"about:blank",
"title":"invalid parameters"}
</code>```

I hope I explained well what I was trying to achieve. Now it all works as desired but as I said with this logic I am checking twice for the same thing so any better solution is appreciated.

Body:
I have decided to use passport.js for authentication of my node app. I implemented local strategies for login and signup and they works fine but there is a problem that confuses me. I have built a module in the past that generates and returns http errors using http-error package. I use it for standardizing error generation. For example if some credentials are missing or invalid I call
Errors.ValidationError({name:"password",reason:"password field is missing in your request"})

this creates and returns a proper http error and I send it to the users. It is useful for error generation. I want to use this logic with passport so I opted to create my own callbacks. Here is some code:

local login strategy definition

/**
 * User login
 * @param {*} request
 * @param {*} response
 * @return {*} logged existant user or error
 */
passport.use('login',
    new localStrategy(
        {
            usernameField: 'email',
            passwordField: 'password',
        },
        async (email, password, done)=> {
            if(email==null||password==null)
            {
                AppLogger.debug(21)
                return done(null, false);
            }
            User.findOne({ email: email }).
            then(async(user)=>{
                if (!user) {
                    AppLogger.debug(22)
                    return done(null, false);
                }
                if (!(await user.verifyPassword(password))) {
                    AppLogger.debug(23)
                    return done(null, false);
                }
                return done(null, user);
            }).
            catch((err)=>{
                AppLogger.debug(24)
                return done(err);
            });
        }
    )
);

login route

/**
 * Login an existant user
 */
AuthRouter.post('/login', (req, res, next)=> {
    passport.authenticate('login', (err, user, info) =>{
        if (err) {
            AppLogger.debug(1)
            return next(err);
        }
        if (!user) {
            AppLogger.debug(2)
            return next(info);
        }
        req.login(user,(err)=>{
            if(err){
                AppLogger.debug(3)
                return next(err);
            }
            res.send({
                success:true,
                message:"logged in"
            })
        })
    })(req, res, next);
});

considering all the debug lines on the code I get this output:
logs

My log lines prints 2 which means there is no exception but user is null and  I am trying to understand where exactly the missing credentials error is created in login strategy so I can generate my custom http error. Oddly enough none of the debugs in the strategy is not getting executed. Note that there is a middleware that catches all the errors and logs so the error log comes from there. And also keep in kind the app works as expected but I can't spot where this error is generated. I assume some method in passport middleware throws an error and my log middleware catches it but how can I interact with it and generate my http error in a meaningful way? Any suggestions are appreciated.

Body:
Here is the work around I came up with:

router

/**
 * Login an existant user
 */
AuthRouter.post('/login', (req, res, next)=> {
    if(!req.body.email || !req.body.password){
        const subErrors = []
        if(!req.body.email){
            subErrors.push({
                name:"email",
                reason:"login request must contain email"
            })
        }
        if(!req.body.password){
            subErrors.push({
                name:"password",
                reason:"login request must contain password"
            })
        }
        const httpError = Errors.ValidationError(subErrors);
        return next(httpError);
    }
    passport.authenticate('login', (err, user, info) =>{
        if (err) {
            return next(err);
        }
        if (!user) {
            return next(info);
        }
        req.login(user,(err)=>{
            if(err){
                return next(err);
            }
            res.send({
                success:true,
                message:"logged in"
            })
        })
    })(req, res, next);
});

Since the ultimate goal was replacing passport's default missing credentials error with my custom http error and I couldn't find a way within passportjs strategy, I check the request body before calling the passport.authenticate()
I can successfully create and return my custom error but this means although I check manually, passportjs also checks if the credentials are there. So its not optimal for performance.

Also I know that using

if(x===null)

causes some problems in some cases and I also used '==' instead of '===' in the original code. It has nothing to do with main problem but its not the best practice.

finally here are the default and custom error responses:

this is what passportjs returns

{"message":"Missing credentials"}

this is my custom error

{
"statusCode":400,
"error":"Bad Request",
"invalid_params":[
   {
       "name":"password",
       "reason":"login request must contain password"
   }
],
"type":"about:blank",
"title":"invalid parameters"}

I hope I explained well what I was trying to achieve. Now it all works as desired but as I said with this logic I am checking twice for the same thing so any better solution is appreciated.


问:
Flutter using choice chips to filter array in firebase
I am trying to use Flutter choice chips to act as a filter for firebase but I cannot seem to work out how to achieve this. It doesn't seem to present any errors, but it doesn't present any data so I am confused what I haven't done right here</p>
```<code>_setupTasks(currentUserId, filters) async {
    if (kDebugMode) {
      print("Tasker Browsing: $currentUserId");
    }
    List<Task> tasks =
        await DatabaseService.getTasks(currentUserId, 'Posted', filters);
    if (mounted) {
      setState(() {
        _tasks = tasks;
      });
    }
  }

FilterChip(
                            showCheckmark: false,
                            checkmarkColor: Colors.white,
                            backgroundColor: Colors.grey[300],
                            label: Text(cat['name']),
                            selected: _filters.contains(cat.id),
                            labelStyle: TextStyle(
                              color: _filters.contains(cat.id)
                                  ? Colors.white
                                  : Colors.black,
                            ),
                            selectedColor:
                                Theme.of(context).colorScheme.primary,
                            onSelected: (bool value) {
                              setState(() {
                                if (value) {
                                  _filters.add(cat.id);
                                  _setupTasks(widget.currentUserId, _filters);
                                } else {
                                  _filters.removeWhere((String name) {
                                    return name == cat.id;
                                  });
                                  _setupTasks(widget.currentUserId, _filters);
                                }
                                if (kDebugMode) {
                                  print(_filters);
                                }
                              });
                            }),

static Future<List<Task>> getTasks(
      String userId, String status, List<String> filter) async {
    QuerySnapshot userTasksSnapshot = await tasksRef
        .where('status', isEqualTo: status)
        .where('ownerId', isNotEqualTo: userId)
        .where('typeId', arrayContains: filter)

        // .orderBy('timestamp', descending: true)
        .get();
    List<Task> tasks =
        userTasksSnapshot.docs.map((doc) => Task.fromDoc(doc)).toList();
    return tasks;
  }
</code>```

答: So turns out that the Filter Chips weren't sending an array like I had assumed from the logs. When I changed the arrayContains to whereIn this resolved the issue for anyone else looking to achieve a similar result

Body:
I am trying to use Flutter choice chips to act as a filter for firebase but I cannot seem to work out how to achieve this. It doesn't seem to present any errors, but it doesn't present any data so I am confused what I haven't done right here

_setupTasks(currentUserId, filters) async {
    if (kDebugMode) {
      print("Tasker Browsing: $currentUserId");
    }
    List<Task> tasks =
        await DatabaseService.getTasks(currentUserId, 'Posted', filters);
    if (mounted) {
      setState(() {
        _tasks = tasks;
      });
    }
  }

FilterChip(
                            showCheckmark: false,
                            checkmarkColor: Colors.white,
                            backgroundColor: Colors.grey[300],
                            label: Text(cat['name']),
                            selected: _filters.contains(cat.id),
                            labelStyle: TextStyle(
                              color: _filters.contains(cat.id)
                                  ? Colors.white
                                  : Colors.black,
                            ),
                            selectedColor:
                                Theme.of(context).colorScheme.primary,
                            onSelected: (bool value) {
                              setState(() {
                                if (value) {
                                  _filters.add(cat.id);
                                  _setupTasks(widget.currentUserId, _filters);
                                } else {
                                  _filters.removeWhere((String name) {
                                    return name == cat.id;
                                  });
                                  _setupTasks(widget.currentUserId, _filters);
                                }
                                if (kDebugMode) {
                                  print(_filters);
                                }
                              });
                            }),

static Future<List<Task>> getTasks(
      String userId, String status, List<String> filter) async {
    QuerySnapshot userTasksSnapshot = await tasksRef
        .where('status', isEqualTo: status)
        .where('ownerId', isNotEqualTo: userId)
        .where('typeId', arrayContains: filter)

        // .orderBy('timestamp', descending: true)
        .get();
    List<Task> tasks =
        userTasksSnapshot.docs.map((doc) => Task.fromDoc(doc)).toList();
    return tasks;
  }


问:
jest.fn() value must be a mock function or spy
I have a function in a module called button-actions that is called when a user clicks a back button. I want to test the backButtonActions method directly but need to mock up the leaveApp and displayById methods inside backButtonActions that get called.

Here is my button-actions.js file method.

```<code>export function backButtonActions( label, page ){      //, page
    console.log("LABEL = ", label, "  page = ", page);
    switch( label ){
        case 'step1':
            page.leaveApp();
            break;
        case 'step2':
            page.displayById();
            break;
    }
}
</code>```

I'm new to tests so I might be missing something very simple.
Below is my test.js file

```<code>   window.$ = require('jquery');
    import {backButtonActions} from '../button-actions';

    describe('Button Actions', () => {

        const page = {}

        beforeEach(() => {

            page.leaveApp = jest.fn(() => "leave");
            page.displayById = jest.fn(() => "Display");

            document.body.innerHTML =
                '<div>' +
                '  <button class="btn-back" />' +
                '</div>';

                 $('.btn-back').click((event, label) =>{
                     backButtonActions( label, page );
                 });

    });
    it('backButtonActions requires a string of either "step1" or "step2"', () => {

        $('.btn-back').trigger('click', 'step1');

         expect(backButtonActions).toBeCalled();
         expect(backButtonActions).toBeCalledWith("step1" || "step2");
    });
})
</code>```

When I run the above test I get the following error.

● Button Actions › backButtonActions requires a string of either
  "step 1" or "step 2"

```<code>expect(jest.fn())[.not].toBeCalled()

jest.fn() value must be a mock function or spy.
Received:
  function: [Function backButtonActions]

  at Object.<anonymous> (test/js/spec/create/button-actions.test.js:64:50)
</code>```

Is there something else I should be running to get this to work ?

答:
An example, as it took me a while as well to figure out:</p>
```<code>const wrapper = shallowMount(XYZComponent, {
  global: {
    mocks: {
      ...,
    },
  },
});
...

test('it should ...', () => {
  jest.spyOn(wrapper.vm.$refs.refOnElement, 'customElementMethodToBeMocked').mockImplementation();
  wrapper.vm.componentMethodWhereYouCallCustomElementMethodToBeMocked();
  expect(wrapper.vm.$refs.refOnElement.customElementMethodToBeMocked).toHaveBeenCalled();
});
</code>```

Body:
I have a function in a module called button-actions that is called when a user clicks a back button. I want to test the backButtonActions method directly but need to mock up the leaveApp and displayById methods inside backButtonActions that get called.

Here is my button-actions.js file method.

export function backButtonActions( label, page ){      //, page
    console.log("LABEL = ", label, "  page = ", page);
    switch( label ){
        case 'step1':
            page.leaveApp();
            break;
        case 'step2':
            page.displayById();
            break;
    }
}

I'm new to tests so I might be missing something very simple.
Below is my test.js file

   window.$ = require('jquery');
    import {backButtonActions} from '../button-actions';

    describe('Button Actions', () => {

        const page = {}

        beforeEach(() => {

            page.leaveApp = jest.fn(() => "leave");
            page.displayById = jest.fn(() => "Display");

            document.body.innerHTML =
                '
' +
                '  <button class="btn-back" />' +
                '
';

                 $('.btn-back').click((event, label) =>{
                     backButtonActions( label, page );
                 });

    });
    it('backButtonActions requires a string of either "step1" or "step2"', () => {

        $('.btn-back').trigger('click', 'step1');

         expect(backButtonActions).toBeCalled();
         expect(backButtonActions).toBeCalledWith("step1" || "step2");
    });
})

When I run the above test I get the following error.

● Button Actions › backButtonActions requires a string of either
  "step 1" or "step 2"

expect(jest.fn())[.not].toBeCalled()

jest.fn() value must be a mock function or spy.
Received:
  function: [Function backButtonActions]

  at Object.<anonymous> (test/js/spec/create/button-actions.test.js:64:50)

Is there something else I should be running to get this to work ?

Body:
An example, as it took me a while as well to figure out:

const wrapper = shallowMount(XYZComponent, {
  global: {
    mocks: {
      ...,
    },
  },
});
...

test('it should ...', () => {
  jest.spyOn(wrapper.vm.$refs.refOnElement, 'customElementMethodToBeMocked').mockImplementation();
  wrapper.vm.componentMethodWhereYouCallCustomElementMethodToBeMocked();
  expect(wrapper.vm.$refs.refOnElement.customElementMethodToBeMocked).toHaveBeenCalled();
});


问:
jQuery Ajax Call to asp.net webmethod
Can any one say
How we can specify a Success Function in Jquery Ajax call.
Suppose I have function like below `function

```<code>getComments(data,url,SucessFunction,FailurFunction) {

    var list = [data];
    var jsonData = JSON.stringify({ list: list });

$.ajax({
    type: "POST",
    url: url,
    data: jsonData,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(response, status) {
        var List = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
        $.each(List, function() {
            if (this['Cid'] != "1000")
                $('#' + ddlCities).append('<option value="' + this['Cid'] + '">' + this['CityCode'] + '</option>');
            else ($('#outerDiv').html(this['City']));

        });
    }
});
</code>```

}
`

In this how can  define the success function ,error function

Like

```<code>getComments(data,url,SucessFunction,FailurFunction) {

var list = [data];
var jsonData = JSON.stringify({ list: list });

$.ajax({
    type: "POST",
    url: url,
    data: jsonData,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: SucessFunction

    }
});
</code>```

}

Thanks in advance.

答:
I have found using Web Method to be flaky, your might want to take a slightly different  approach, instead of using a webmethod, take a look at using ajax enabled WCF service?

Here is a blog post on how to set it up using wcf to build fast and lean web apps

Title: jQuery Ajax Call to asp.net webmethod

Body:
Can any one say
How we can specify a Success Function in Jquery Ajax call.
Suppose I have function like below `function

getComments(data,url,SucessFunction,FailurFunction) {

    var list = [data];
    var jsonData = JSON.stringify({ list: list });

$.ajax({
    type: "POST",
    url: url,
    data: jsonData,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(response, status) {
        var List = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
        $.each(List, function() {
            if (this['Cid'] != "1000")
                $('#' + ddlCities).append('<option value="' + this['Cid'] + '">' + this['CityCode'] + '</option>');
            else ($('#outerDiv').html(this['City']));

        });
    }
});

}
`

In this how can  define the success function ,error function

Like

getComments(data,url,SucessFunction,FailurFunction) {

var list = [data];
var jsonData = JSON.stringify({ list: list });

$.ajax({
    type: "POST",
    url: url,
    data: jsonData,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: SucessFunction

    }
});

}

Thanks in advance.


问:
Can I use cv.imencode in Opencv.js to export webp images?
I want to transform the format of images from any extension(ex. png, jpg) to webp.
So I checked the OpenCV.js but I couldn't find cv.imencode method to create webp images.
Does it support cv.imencode method?
If not, I will use other server side languages, java, python, etc.
Thank you.

答:
no, sadly you cannot do this. there are no image codecs wrapped into opencv.js at all (and the only builtin method to read an image is by grabbing one from a pre-filled canvas)

however, there are 3rdparty js libs like Jimp for this


问:
Fill an input function to the right dynamically
I have a table of values, lets say:

And I want to achieve this:

the number of rows I manually select, but the columns could vary, and I input the function and number of columns into a another function, in this case =SUM(A1:A5) and 4 for the function below:

```<code>Sub FunctionFill()

    Dim myFunction As String: myFunction = "=SUM(A1:A5)"
    Dim Numvendors As Integer: Numvendors = 4
    Cells(Application.ActiveCell.Row, Application.ActiveCell.Column).Resize(, Numvendors).Formula = myFunction

End Sub
</code>```

This works as a macro.

How do I change this sub into a function that takes Numvendors and myFunction as inputs and outputs the range.

答:
Try this...

You don't really need range as well as cells.
You can fill all the cells at once using Resize rather than using a loop

.Formula tells it you want to set the cell formula.

```<code>Function FunctionFill(myFunction As String, NumVendors As Integer)

    Cells(Application.ActiveCell.Row, Application.ActiveCell.Column).Resize(, NumVendors + 1).Formula = myFunction

End Function
</code>```

Body:
I have a table of values, lets say:

And I want to achieve this:

the number of rows I manually select, but the columns could vary, and I input the function and number of columns into a another function, in this case =SUM(A1:A5) and 4 for the function below:

Sub FunctionFill()

    Dim myFunction As String: myFunction = "=SUM(A1:A5)"
    Dim Numvendors As Integer: Numvendors = 4
    Cells(Application.ActiveCell.Row, Application.ActiveCell.Column).Resize(, Numvendors).Formula = myFunction

End Sub

This works as a macro.

How do I change this sub into a function that takes Numvendors and myFunction as inputs and outputs the range.

Body:
Try this...

You don't really need range as well as cells.
You can fill all the cells at once using Resize rather than using a loop

.Formula tells it you want to set the cell formula.

Function FunctionFill(myFunction As String, NumVendors As Integer)

    Cells(Application.ActiveCell.Row, Application.ActiveCell.Column).Resize(, NumVendors + 1).Formula = myFunction

End Function


问:
ERROR: gcloud crashed (ModuleNotFoundError): No module named 'distutils.spawn'
I have been deploying my service on App Engine for a long time now and never had an issue until today.

Command to Deploy

```<code>gcloud app deploy app.yaml
</code>```

Output

```<code>Beginning deployment of service [default]...
Building and pushing image for service [default]
ERROR: gcloud crashed (ModuleNotFoundError): No module named 'distutils.spawn'
</code>```

I just deployed this morning with no issues and randomly when I tried to redeploy now I get the above error. Hopefully someone can help figure out what caused this issue.

For info:

app.yaml

```<code>runtime: custom
env: flex
manual_scaling:
  instances: 1
resources:
  cpu: 1
  memory_gb: 4
  disk_size_gb: 10
</code>```

Gcloud version

```<code>$ gcloud --version
Google Cloud SDK 341.0.0
alpha 2021.05.14
beta 2021.05.14
bq 2.0.68
core 2021.05.14
gsutil 4.62
minikube 1.20.0
skaffold 1.23.0
</code>```

答:
I had a similar issue, on my case this was the solution:</p>
```<code>sudo apt-get install python3-distutils
</code>```

Body:
I have been deploying my service on App Engine for a long time now and never had an issue until today.

Command to Deploy

gcloud app deploy app.yaml

Output

Beginning deployment of service [default]...
Building and pushing image for service [default]
ERROR: gcloud crashed (ModuleNotFoundError): No module named 'distutils.spawn'

I just deployed this morning with no issues and randomly when I tried to redeploy now I get the above error. Hopefully someone can help figure out what caused this issue.

For info:

app.yaml

runtime: custom
env: flex
manual_scaling:
  instances: 1
resources:
  cpu: 1
  memory_gb: 4
  disk_size_gb: 10

Gcloud version

$ gcloud --version
Google Cloud SDK 341.0.0
alpha 2021.05.14
beta 2021.05.14
bq 2.0.68
core 2021.05.14
gsutil 4.62
minikube 1.20.0
skaffold 1.23.0

Body:
I had a similar issue, on my case this was the solution:

sudo apt-get install python3-distutils


问:
perl tk fileevent fail on the second event
This simple excerpt, run on Perl 5.16.3, at open forks a sub-process which send data to the main one.

```<code>#!/usr/bin/perl
use Tk;
my $mainWindow = MainWindow->new();
$mainWindow->Button(-text => "Run", -command => \&run)->pack();
MainLoop;
my $fh;
sub receiver()
{
    print "$_" while <$fh>;
    print "End\n";
    close $fh;
}
sub run()
{
    print "run\n";
    my $pid = open $fh, '-|';
    die "Failed to start\n" unless defined $pid;
    print "pid=$pid\n";
    exec "echo Hello" unless $pid;
    $mainWindow->fileevent($fh, 'readable', \&receiver);
}
</code>```

It works as expected the first time only, at the second click on the button the open produce:

Tk::Error: Can't locate object method "OPEN" via package "Tk::Event::IO" at fe.pl line 16.
Tk callback for .button
Tk::ANON at /usr/lib64/perl5/vendor_perl/Tk.pm line 251
Tk::Button::butUp at /usr/lib64/perl5/vendor_perl/Tk/Button.pm line 175

(command bound to event)

I'm struggling to understand the reason, without success. Any idea?

答:
```<code>#!/usr/bin/perl
use Tk;
my $mainWindow = MainWindow->new();
$mainWindow->Button(-text => "Run", -command => \&run)->pack();
MainLoop;
sub run()
{
    my $fh;
    my $pid;
    $SIG{CHLD} = sub
    {
        my $kid = waitpid(-1, WNOHANG);
        print "$kid exited with $? ${^CHILD_ERROR_NATIVE}\n"
    };
    my $receiver = sub
    {
        print "$_" while <$fh>;
        print "End\n";
        close $fh;
        # delete handler since $fh is no longer used
        $mainWindow->fileevent($fh, 'readable', '');
    };
    print "run\n";
    $pid = open $fh, '-|';
    die "Failed to start\n" unless defined $pid;
    print "pid=$pid\n";
    exec "echo Hello" unless $pid;
    $mainWindow->fileevent($fh, 'readable', $receiver);
}
</code>```

Body:
This simple excerpt, run on Perl 5.16.3, at open forks a sub-process which send data to the main one.

#!/usr/bin/perl
use Tk;
my $mainWindow = MainWindow->new();
$mainWindow->Button(-text => "Run", -command => \&run)->pack();
MainLoop;
my $fh;
sub receiver()
{
    print "$_" while <$fh>;
    print "End\n";
    close $fh;
}
sub run()
{
    print "run\n";
    my $pid = open $fh, '-|';
    die "Failed to start\n" unless defined $pid;
    print "pid=$pid\n";
    exec "echo Hello" unless $pid;
    $mainWindow->fileevent($fh, 'readable', \&receiver);
}

It works as expected the first time only, at the second click on the button the open produce:

Tk::Error: Can't locate object method "OPEN" via package "Tk::Event::IO" at fe.pl line 16.
Tk callback for .button
Tk::ANON at /usr/lib64/perl5/vendor_perl/Tk.pm line 251
Tk::Button::butUp at /usr/lib64/perl5/vendor_perl/Tk/Button.pm line 175

(command bound to event)

I'm struggling to understand the reason, without success. Any idea?


问:
Switch a Gradle-based Vaadin 22 app to Vaadin 23 beta
I am a Gradle newbie, having used Maven in the past.

I successfully established a Vaadin 22.0.5 project using the Vaadin Latest - Gradle starter project downloaded from Hello World Starters page. The project successfully builds and runs using gretty > apprun in IntelliJ 2021.1 EAP Ultimate edition.

 How do I alter the project to use the current beta version of the next version, Vaadin 23.0.0.beta2, as listed on the Vaadin releases page?

First attempt

I changed the gradle.properties file which consists of this single line:

vaadinVersion=22.0.5
```
<p>… to this:</p>
<pre class="lang-none prettyprint-override"><code>vaadinVersion=23.0.0.beta2
</code>```

I clicked the floating windoid, Load Gradle Changes.

I immediately see this error appear in the IDE’s Build pane:

Build file '/Users/my_user/IdeaProjects/GetJava/build.gradle' line: 11

Plugin [id: 'com.vaadin', version: '23.0.0.beta2'] was not found in any of the following sources:

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
```
<h1>Second attempt</h1>
<p>After receiving Answer by cfrick, I did the following.</p>
<p>If found this at the top of the <code>build.gradle</code> file:</p>
<pre class="lang-java prettyprint-override"><code>buildscript {
    repositories {
        maven { setUrl("https://maven.vaadin.com/vaadin-prereleases") }
        maven { url "https://plugins.gradle.org/m2/" }
    }
}
</code>```

So I made no edits there, as seemed to be accomplishing the same thing as the first part of the Answer.

I changed the entirety of the settings.gradle file from this:

pluginManagement {
    plugins {
        id 'com.vaadin' version "${vaadinVersion}"
    }
}
```
<p>… to this:</p>
<pre class="lang-java prettyprint-override"><code>pluginManagement {
    repositories {
        gradlePluginPortal()
        maven {
            url = "https://maven.vaadin.com/vaadin-prereleases"
        }
    }
    plugins {
        id 'com.vaadin' version "${vaadinVersion}"
    }
}
</code>```

I changed the gradle.properties file which consists of this single line:

vaadinVersion=22.0.5
```
<p>… to this, using <code>beta1</code> rather than <code>beta2</code> seen above.</p>
<pre class="lang-none prettyprint-override"><code>vaadinVersion=23.0.0.beta1
</code>```

After executing Tasks > build > clean, I get a BUILD SUCCESSFUL message.

But when I execute Gretty > apprun, I get the following error message.

Execution failed for task ':compileJava'.
> Could not resolve all files for configuration ':compileClasspath'.
   > Could not find com.vaadin:vaadin-bom:23.0.0.beta1.
     Searched in the following locations:
       - https://repo.maven.apache.org/maven2/com/vaadin/vaadin-bom/23.0.0.beta1/vaadin-bom-23.0.0.beta1.pom
     If the artifact you are trying to retrieve can be found in the repository but without metadata in 'Maven POM' format, you need to adjust the 'metadataSources { ... }' of the repository declaration.
     Required by:
         project :
   > Could not find com.vaadin:vaadin-core:.
     Required by:
         project :

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html
```

答:
Pre-release versions are released first in Vaadins own pre-release
repository.  You would have to add the repository if you need access to
releases, that have not yet hit the public repos:

In build.gradle expand repositories by:

```<code>repositories {
    // ...
    maven {
        url = "https://maven.vaadin.com/vaadin-prereleases"
    }
}
</code>```

In the settings.gradle add a repositories block too:

```<code>pluginManagement {
    repositories {
        gradlePluginPortal()
        maven {
            url = "https://maven.vaadin.com/vaadin-prereleases"
        }
    }
    plugins {
        id 'com.vaadin' version "${vaadinVersion}"
    }
}
</code>```

Body:
I am a Gradle newbie, having used Maven in the past.

I successfully established a Vaadin 22.0.5 project using the Vaadin Latest - Gradle starter project downloaded from Hello World Starters page. The project successfully builds and runs using gretty > apprun in IntelliJ 2021.1 EAP Ultimate edition.

 How do I alter the project to use the current beta version of the next version, Vaadin 23.0.0.beta2, as listed on the Vaadin releases page?

First attempt

I changed the gradle.properties file which consists of this single line:

vaadinVersion=22.0.5

… to this:

vaadinVersion=23.0.0.beta2

I clicked the floating windoid, Load Gradle Changes.

I immediately see this error appear in the IDE’s Build pane:

Build file '/Users/my_user/IdeaProjects/GetJava/build.gradle' line: 11

Plugin [id: 'com.vaadin', version: '23.0.0.beta2'] was not found in any of the following sources:

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

Second attempt

After receiving Answer by cfrick, I did the following.

If found this at the top of the build.gradle file:

buildscript {
    repositories {
        maven { setUrl("https://maven.vaadin.com/vaadin-prereleases") }
        maven { url "https://plugins.gradle.org/m2/" }
    }
}

So I made no edits there, as seemed to be accomplishing the same thing as the first part of the Answer.

I changed the entirety of the settings.gradle file from this:

pluginManagement {
    plugins {
        id 'com.vaadin' version "${vaadinVersion}"
    }
}

… to this:

pluginManagement {
    repositories {
        gradlePluginPortal()
        maven {
            url = "https://maven.vaadin.com/vaadin-prereleases"
        }
    }
    plugins {
        id 'com.vaadin' version "${vaadinVersion}"
    }
}

I changed the gradle.properties file which consists of this single line:

vaadinVersion=22.0.5

… to this, using beta1 rather than beta2 seen above.

vaadinVersion=23.0.0.beta1

After executing Tasks > build > clean, I get a BUILD SUCCESSFUL message.

But when I execute Gretty > apprun, I get the following error message.

Execution failed for task ':compileJava'.
> Could not resolve all files for configuration ':compileClasspath'.
   > Could not find com.vaadin:vaadin-bom:23.0.0.beta1.
     Searched in the following locations:
       - https://repo.maven.apache.org/maven2/com/vaadin/vaadin-bom/23.0.0.beta1/vaadin-bom-23.0.0.beta1.pom
     If the artifact you are trying to retrieve can be found in the repository but without metadata in 'Maven POM' format, you need to adjust the 'metadataSources { ... }' of the repository declaration.
     Required by:
         project :
   > Could not find com.vaadin:vaadin-core:.
     Required by:
         project :

Possible solution:
 - Declare repository providing the artifact, see the documentation at https://docs.gradle.org/current/userguide/declaring_repositories.html

Body:
Pre-release versions are released first in Vaadins own pre-release
repository.  You would have to add the repository if you need access to
releases, that have not yet hit the public repos:

In build.gradle expand repositories by:

repositories {
    // ...
    maven {
        url = "https://maven.vaadin.com/vaadin-prereleases"
    }
}

In the settings.gradle add a repositories block too:

pluginManagement {
    repositories {
        gradlePluginPortal()
        maven {
            url = "https://maven.vaadin.com/vaadin-prereleases"
        }
    }
    plugins {
        id 'com.vaadin' version "${vaadinVersion}"
    }
}


问:
get object response value
I got a response from the backend the response is an object how can I get the arrays from the object I tried to use Object entries but I can't get the arrays can you please help me

答:
You are looking for the Object.values to retrieve just the value part of your object.

Example:

const object = {
  "20-01-22": ['a', 'b', 'c'],
  "21-01-22": ['b', 'c'],
  "22-01-22": ['d', 'f']
};

const arrays = Object.values(object)

// => [['a', 'b', 'c'], ['b', 'c'], ['d', 'f']];
```

Title: get object response value


问:
How can I use string instead of char* buffer to read the file data into string?
I am using standard file-handler API to read the file , currently I have used a char* buffer to read the data, but I want to use string so I can avoid calloc() use. I tried to pass the string address to the ReadFile() function, but it's not working. Could you please help me???

```<code>l_FileHandle = CreateFileA(inputFilePath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

l_FileSize = GetFileSize(l_FileHandle, NULL);

char * l_FileBuffer = NULL;

l_FileBuffer = (char *)calloc(l_FileSize, sizeof(char));

ReadFile(l_FileHandle,(void *)(l_FileBuffer), l_FileSize, &lpNumberOfBytesRead, lpOverlapped);
</code>```

答:
You can't pass in the address of the string itself, but you can pass in the address of its internal character buffer. Just make sure it has been allocated first.

```<code>l_FileHandle = CreateFileA(inputFilePath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

l_FileSize = GetFileSize(l_FileHandle, NULL);

string l_FileBuffer(l_FileSize, '\0');

ReadFile(l_FileHandle, l_FileBuffer.data(), l_FileSize, &lpNumberOfBytesRead, lpOverlapped);
</code>```

Note that the non-const version of data() requires C++17 or later. For C++11..14, you can use &l_FileBuffer[0] instead. Prior to C++11, that is not guaranteed to work, but in practice it will work in most implementations.

For a more standard way to read a file into a string, see How do I read an entire file into a std::string in C++?

Body:
I am using standard file-handler API to read the file , currently I have used a char* buffer to read the data, but I want to use string so I can avoid calloc() use. I tried to pass the string address to the ReadFile() function, but it's not working. Could you please help me???

l_FileHandle = CreateFileA(inputFilePath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

l_FileSize = GetFileSize(l_FileHandle, NULL);

char * l_FileBuffer = NULL;

l_FileBuffer = (char *)calloc(l_FileSize, sizeof(char));

ReadFile(l_FileHandle,(void *)(l_FileBuffer), l_FileSize, &lpNumberOfBytesRead, lpOverlapped);

Body:
You can't pass in the address of the string itself, but you can pass in the address of its internal character buffer. Just make sure it has been allocated first.

l_FileHandle = CreateFileA(inputFilePath.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);

l_FileSize = GetFileSize(l_FileHandle, NULL);

string l_FileBuffer(l_FileSize, '\0');

ReadFile(l_FileHandle, l_FileBuffer.data(), l_FileSize, &lpNumberOfBytesRead, lpOverlapped);

Note that the non-const version of data() requires C++17 or later. For C++11..14, you can use &l_FileBuffer[0] instead. Prior to C++11, that is not guaranteed to work, but in practice it will work in most implementations.

For a more standard way to read a file into a string, see How do I read an entire file into a std::string in C++?


答:
A standard integer is 4 bytes in width, meaning that, in memory, your 500 will look like this (assuming Big endian): 0x00 0x00 0x01 0xF4.

If you do c + 1, with c being an int * you are actually moving the pointer by these four bytes.

By casting c to a char *, you change the step width of the pointer to 1, meaning that it will now point to this location: 0x00 0x00 0x01 0xF4

By writing your 500 to that value, the same four bytes will now look like this: 0x00 0x00 0x00 0x01 (the remaining 0xF4 will be written to the next integer).

I am now assuming that your machine is little endian, meaning the bytes are 'reversed'.

0x90 0xF4 0x01 0x00
The 0x90 is leftover from the assignment of 400 in the previous iteration and by putting them all together, you get 0x01f490 or 128144.

Title: About the adress arithmetic in C

Body:
It's from a elementary question from the very beginning of MIT6.s081, Why does the fifth
printf's result is:

5: a[0] = 200, a[1] = 128144, a[2] = 256, a[3] = 302

I really can't imagine how 128144 comes!

Here is the code:

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

void f(void)
{
    int a[4];
    int *b = malloc(16);
    int *c;
    int i;

    printf("1: a = %p, b = %p, c = %p\n", a, b, c);

    c = a;
    for (i = 0; i < 4; i++)
        a[i] = 100 + i;
    c[0] = 200;
    printf("2: a[0] = %d, a[1] = %d, a[2] = %d, a[3] = %d\n",
           a[0], a[1], a[2], a[3]);

    c[1] = 300;
    *(c + 2) = 301;
    c[3] = 302;
    printf("3: a[0] = %d, a[1] = %d, a[2] = %d, a[3] = %d\n",
           a[0], a[1], a[2], a[3]);

    c = c + 1;
    *c = 400;
    printf("4: a[0] = %d, a[1] = %d, a[2] = %d, a[3] = %d\n",
           a[0], a[1], a[2], a[3]);

    c = (int *)((char *)c + 1);
    *c = 500;
    printf("5: a[0] = %d, a[1] = %d, a[2] = %d, a[3] = %d\n",
           a[0], a[1], a[2], a[3]);

    b = (int *)a + 1;
    c = (int *)((char *)a + 1);
    printf("6: a = %p, b = %p, c = %p\n", a, b, c);
}

int main(int ac, char **av)
{
    f();
    return 0;
}


问:
How to apply accuracy_score function to two columns in group by
I have the following data frame:

```<code>wn  Ground_truth   Prediction
A        1              1
A        1              1
A        1              0
A        1              1
B        0              1
B        1              1
B        0              0
</code>```

for each group ( A , B) i would like to calculate the accuracy_score(Ground_truth, Prediction)

答:
Specifically for accuracy you can actually do something simpler:

df.assign(x=df['Ground_truth']==df['Prediction']).groupby('wn').mean()
```

Body:
I have the following data frame:

wn  Ground_truth   Prediction
A        1              1
A        1              1
A        1              0
A        1              1
B        0              1
B        1              1
B        0              0

for each group ( A , B) i would like to calculate the accuracy_score(Ground_truth, Prediction)


问:
ARM templates and validation of mandatory tag values against AAD
I want to create policies using an ARM template for newly created resources that have automatically pre-populated or validated tags such as CreatedBy or BusinessOwner, and their values will include the names of the users who created them or who are responsible for the budget allocated to the Azure resource.

I would like the policy to specify that if a resource is created and a tag value is set, that value is validated against AAD users. It would be best if the ARM buildin function existed and the template looked something like this:

```<code>    CreatedBy
    {
      "mode": "All",
      "policyRule": {
        "if": {
          "allOf": [
            {
              "field": "tags['CreatedBy']",
              "exists": "false"
            }
          ]
        },
        "then": {
          "effect": "append",
          "details": [
            {
              "field": "tags['CreatedBy']",
              "value": "[GetAADUsername()]"
            }
          ]
        }
      },
      "parameters": {}
    }
</code>```

According to the list of functions that are currently supported for ARM templates, this is not possible, see. https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions.

But I want to ask if anyone has solved it and does not have a solution for defining policies for these basic tags and that their values are not just ad hoc strings, but verified values against real objects in AAD.

Thank you.

答:
Currently , Its not possible to add Created by or Updated by based on Azure AD UPN using Azure Policy.

As an alternative you can use Azure Event Hubs and Azure Functions to create the tags in order to manage the subscription resources based on who created it or modified it .

You can follow this Azure Community Blog by Anthony Watherston on how to tag resourced with a creator tag or you can refer this Github Repo created by Tom Hollander on how to add tags like createdBy, ModifiedBy, createdDate and ModifiedDate.

Body:
I want to create policies using an ARM template for newly created resources that have automatically pre-populated or validated tags such as CreatedBy or BusinessOwner, and their values will include the names of the users who created them or who are responsible for the budget allocated to the Azure resource.

I would like the policy to specify that if a resource is created and a tag value is set, that value is validated against AAD users. It would be best if the ARM buildin function existed and the template looked something like this:

    CreatedBy
    {
      "mode": "All",
      "policyRule": {
        "if": {
          "allOf": [
            {
              "field": "tags['CreatedBy']",
              "exists": "false"
            }
          ]
        },
        "then": {
          "effect": "append",
          "details": [
            {
              "field": "tags['CreatedBy']",
              "value": "[GetAADUsername()]"
            }
          ]
        }
      },
      "parameters": {}
    }

According to the list of functions that are currently supported for ARM templates, this is not possible, see. https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions.

But I want to ask if anyone has solved it and does not have a solution for defining policies for these basic tags and that their values are not just ad hoc strings, but verified values against real objects in AAD.

Thank you.


问:
Can scripts be inserted with innerHTML?
I tried to load some scripts into a page using innerHTML on a
. It appears that the script loads into the DOM, but it is never executed (at least in Firefox and Chrome). Is there a way to have scripts execute when inserting them with innerHTML?

Sample code:

<!DOCTYPE html>

  <body onload="document.getElementById('loader').innerHTML = '

答:
simple, no eval, no functions:</p>
```<code>    fetch('/somepage')
    .then(x=>x.text())
    .then(x=>{
      divDestination.innerHTML=x;
        divDestination.querySelectorAll("script")
        .forEach(x=>{
          var sc=document.createElement("script");
          sc.appendChild(document.createTextNode(x.innerText));
          divDestination.appendChild(sc)
      })
  })
</code>```

Title: Can scripts be inserted with innerHTML?

Body:
simple, no eval, no functions:

    fetch('/somepage')
    .then(x=>x.text())
    .then(x=>{
      divDestination.innerHTML=x;
        divDestination.querySelectorAll("script")
        .forEach(x=>{
          var sc=document.createElement("script");
          sc.appendChild(document.createTextNode(x.innerText));
          divDestination.appendChild(sc)
      })
  })


问:
While loop on a mysql call is throwing unknown PDO exception 'General Error'
I use the following (or similar) code on hundreds of pages I have built:

```<code>$stmt = $db->prepare("SELECT * FROM table");
$stmt->execute();

while($row = $stmt->fetch()) {

    $id = $row['id'];
    $name = $row['name'];

    do something with data returned...

    $id = NULL;
    $name = NULL;

}
</code>```

Out of nowwhere, I started receiving the following error on a few pages:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[HY000]: General error' in C:....page.php:28 Stack trace: #0
  C:..page.php(28): PDOStatement->fetch() #1 {main} thrown

The first loop will run (with no problem) but gives an error AFTER the first loop. The error code (line 28) references the line:

```<code>while($row = $stmt->fetch()) {
</code>```

I have never seen this before. As a test, I modified the code to store all returned results as:

```<code>$stmt = $db->prepare("SELECT * FROM table");
$stmt->execute();

$rows = $stmt->fetchALL();

foreach($rows as $row) {

    $id = $row['id'];
    $name = $row['name'];

    do something with data returned...

    $id = NULL;
    $name = NULL;

}
</code>```

and the system works. Any idea as to why?

答:
```<code>$stmt>execute();
</code>```

Shouldn't that be:

```<code>$stmt->execute();
</code>```

Body:
I use the following (or similar) code on hundreds of pages I have built:

$stmt = $db->prepare("SELECT * FROM table");
$stmt->execute();

while($row = $stmt->fetch()) {

    $id = $row['id'];
    $name = $row['name'];

    do something with data returned...

    $id = NULL;
    $name = NULL;

}

Out of nowwhere, I started receiving the following error on a few pages:

Fatal error: Uncaught exception 'PDOException' with message
  'SQLSTATE[HY000]: General error' in C:....page.php:28 Stack trace: #0
  C:..page.php(28): PDOStatement->fetch() #1 {main} thrown

The first loop will run (with no problem) but gives an error AFTER the first loop. The error code (line 28) references the line:

while($row = $stmt->fetch()) {

I have never seen this before. As a test, I modified the code to store all returned results as:

$stmt = $db->prepare("SELECT * FROM table");
$stmt->execute();

$rows = $stmt->fetchALL();

foreach($rows as $row) {

    $id = $row['id'];
    $name = $row['name'];

    do something with data returned...

    $id = NULL;
    $name = NULL;

}

and the system works. Any idea as to why?

Body:
$stmt>execute();

Shouldn't that be:

$stmt->execute();


问:
What does the underscore(_) do in for loop Golang?
I am just getting started learning the Golang language!
In for loop, I saw sometimes adding an underscore or without underscore.

Whatever add _ or not, I got the same result.

```<code>package main

import (
    "fmt"
)

func main() {
    doSomething()
    sum := addValues(5, 8)
    fmt.Println("The sum is", sum)

    multiSum, multiCount := addAllValues(4, 7, 9)
    fmt.Println("multisum", multiSum)
    fmt.Println("multiCount", multiCount)
}

func doSomething() {
    fmt.Println("Doing Something")
}

func addValues(value1 int, value2 int) int {
    return value1 + value2
}

func addAllValues(values ...int) (int, int) {
    total := 0
    for _, v := range values {
        total += v
    }
    return total, len(values)
}
</code>```
```<code>func addAllValues(values ...int) (int, int) {
    total := 0
    for v := range values {
        total += v
    }
    return total, len(values)
}
</code>```

All I know is I don't care about the index. Is that all? or there is something more what I have to know??

I really appreciate your help!

答:
By placing underscore you are telling the compiler this:
Ok, I'm aware that this function is returning something but I don't care! For example:</p>
```<code>package main

import "fmt"

func main() {
    mul1, add1 := test_function(2, 3)
    fmt.Println(mul1, add1)

    mul2, _ := test_function(4, 5)
    fmt.Println(mul2)

    _, add3 := test_function(7, 8)
    fmt.Println(add3)
}

func test_function(a int, b int) (mul int, add int) {
    return a * b, a + b
}
</code>```

Body:
I am just getting started learning the Golang language!
In for loop, I saw sometimes adding an underscore or without underscore.

Whatever add _ or not, I got the same result.

package main

import (
    "fmt"
)

func main() {
    doSomething()
    sum := addValues(5, 8)
    fmt.Println("The sum is", sum)

    multiSum, multiCount := addAllValues(4, 7, 9)
    fmt.Println("multisum", multiSum)
    fmt.Println("multiCount", multiCount)
}

func doSomething() {
    fmt.Println("Doing Something")
}

func addValues(value1 int, value2 int) int {
    return value1 + value2
}

func addAllValues(values ...int) (int, int) {
    total := 0
    for _, v := range values {
        total += v
    }
    return total, len(values)
}

func addAllValues(values ...int) (int, int) {
    total := 0
    for v := range values {
        total += v
    }
    return total, len(values)
}

All I know is I don't care about the index. Is that all? or there is something more what I have to know??

I really appreciate your help!

Body:
By placing underscore you are telling the compiler this:
Ok, I'm aware that this function is returning something but I don't care! For example:

package main

import "fmt"

func main() {
    mul1, add1 := test_function(2, 3)
    fmt.Println(mul1, add1)

    mul2, _ := test_function(4, 5)
    fmt.Println(mul2)

    _, add3 := test_function(7, 8)
    fmt.Println(add3)
}

func test_function(a int, b int) (mul int, add int) {
    return a * b, a + b
}


问:
Flask SocketI) need to detect duplicate connections on opening new tab
I need to detect the duplicate session when user opens a new tab. Since I am using it for survey, I am not having any of the user's data. I am working on anonymous users.

Reading through documentation and various other thread I understood that I need to send client a session data which will be a uuid and check if the user is already authenticated for new connection.

My code is below -

```<code>from flask import Flask, render_template, session
from flask_session import Session
from flask_socketio import SocketIO, send, emit
from flask_login import LoginManager, UserMixin, current_user, login_user, logout_user, AnonymousUserMixin
import time, json, uuid, os

app = Flask(__name__)
app.config['SECRET_KEY'] = 'top-secret!'
app.config['SESSION_TYPE'] = 'filesystem'
login_manager = LoginManager(app)
login_manager.init_app(app)
Session(app)
socketio = SocketIO(app, cors_allowed_origins="*", logger=True, manage_session=False)

class User(UserMixin, object):
    def __init__(self, id=None):
        self.id = id

@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)

time_now = 0
msg = "Hello User. Please wait other users to join. Survey will start once minimum users will join. Max waiting time " \
      "is 5 min "

# connected_msg_json = json.dumps(connected_msg, indent=4)
client_count = 0

@socketio.on('message')
def handle_message(msg):
    print("Connected with the client with data " + msg)

@socketio.on('connect')
def test_connect():
    print("Connected")
    f = open('data.json')
    data = json.load(f)
    minUserCount = data['minimumNoOfUser']
    global client_count, time_now
    if current_user.is_authenticated:
        pass
    else:
        client_count += 1
        login_user(User(id=uuid.uuid1()))
    if client_count == 0:
        time_now = int(time.time())

    print("Total no of connected client " + str(client_count))
    print("About to send the time when first user connected " + str(time_now))
    send(time_now)
    if client_count > minUserCount:
        send("Continue", broadcast=True)

@socketio.on('disconnect')
def test_disconnect():
    print('Client disconnected')
    logout_user()
    global client_count
    client_count -= 1
    print("Total no of connected client " + str(client_count))
</code>```

Since I need to make sure that survey opens when there are minimum no of unique users, I decided to login the users upon connection. And if the user is already authenticated then I believe it means it's the new connection via tab.

Now I am not sure if my code is okay but the packages are incorrect or both. I have tried to resolved the error but I am stuck with this error -

```<code>ImportError: cannot import name 'ContextVar' from 'werkzeug.local' (/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/werkzeug/local.py)
</code>```

This appears when I put line

```<code>app.config['SESSION_TYPE'] = 'filesystem'
</code>```

else I get different error about secret key not being set.

My requirements.txt are:

```<code>Flask==2.0.2
Flask-Cors==3.0.10
Flask-SocketIO==4.3.1
gevent==21.8.0
gevent-websocket==0.10.1
greenlet==1.1.2
gunicorn==20.1.0
python-engineio==3.13.2
python-socketio==4.6.0
simple-websocket==0.5.0
websocket-client==1.2.1
websockets==10.1
Werkzeug==0.14.1

</code>```

答: you need to update werkzeug to 2.0 +</p>

Body:
I need to detect the duplicate session when user opens a new tab. Since I am using it for survey, I am not having any of the user's data. I am working on anonymous users.

Reading through documentation and various other thread I understood that I need to send client a session data which will be a uuid and check if the user is already authenticated for new connection.

My code is below -

from flask import Flask, render_template, session
from flask_session import Session
from flask_socketio import SocketIO, send, emit
from flask_login import LoginManager, UserMixin, current_user, login_user, logout_user, AnonymousUserMixin
import time, json, uuid, os

app = Flask(__name__)
app.config['SECRET_KEY'] = 'top-secret!'
app.config['SESSION_TYPE'] = 'filesystem'
login_manager = LoginManager(app)
login_manager.init_app(app)
Session(app)
socketio = SocketIO(app, cors_allowed_origins="*", logger=True, manage_session=False)

class User(UserMixin, object):
    def __init__(self, id=None):
        self.id = id

@login_manager.user_loader
def load_user(user_id):
    return User.get(user_id)

time_now = 0
msg = "Hello User. Please wait other users to join. Survey will start once minimum users will join. Max waiting time " \
      "is 5 min "

# connected_msg_json = json.dumps(connected_msg, indent=4)
client_count = 0

@socketio.on('message')
def handle_message(msg):
    print("Connected with the client with data " + msg)

@socketio.on('connect')
def test_connect():
    print("Connected")
    f = open('data.json')
    data = json.load(f)
    minUserCount = data['minimumNoOfUser']
    global client_count, time_now
    if current_user.is_authenticated:
        pass
    else:
        client_count += 1
        login_user(User(id=uuid.uuid1()))
    if client_count == 0:
        time_now = int(time.time())

    print("Total no of connected client " + str(client_count))
    print("About to send the time when first user connected " + str(time_now))
    send(time_now)
    if client_count > minUserCount:
        send("Continue", broadcast=True)

@socketio.on('disconnect')
def test_disconnect():
    print('Client disconnected')
    logout_user()
    global client_count
    client_count -= 1
    print("Total no of connected client " + str(client_count))

Since I need to make sure that survey opens when there are minimum no of unique users, I decided to login the users upon connection. And if the user is already authenticated then I believe it means it's the new connection via tab.

Now I am not sure if my code is okay but the packages are incorrect or both. I have tried to resolved the error but I am stuck with this error -

ImportError: cannot import name 'ContextVar' from 'werkzeug.local' (/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/werkzeug/local.py)

This appears when I put line

app.config['SESSION_TYPE'] = 'filesystem'

else I get different error about secret key not being set.

My requirements.txt are:

Flask==2.0.2
Flask-Cors==3.0.10
Flask-SocketIO==4.3.1
gevent==21.8.0
gevent-websocket==0.10.1
greenlet==1.1.2
gunicorn==20.1.0
python-engineio==3.13.2
python-socketio==4.6.0
simple-websocket==0.5.0
websocket-client==1.2.1
websockets==10.1
Werkzeug==0.14.1

Body: you need to update werkzeug to 2.0 +


问:
do I use Krb5LoginModule or LdapLoginModule
Sorry if this is a silly question.
Do I use LdapLoginModule when I want to check if user exist or authorized?
Do I use Krb5LoginMoudle when I want to check if user has a ticket to do work?

Regards,
JemRug

答: I'm guessing they are both forms of logging in , but the underline protocols they are manipulating  is the key. One is talking Kerberos, the other LDAP.</p>


问:
Having number above 60 in "ss" format
```<code>Global time As Date

Sub countdown()
time = Now()
time = DateAdd("s", 120, time)

Do Until time < Now()
DoEvents
oSh.TextFrame.TextRange = Format((time - Now()), "ss")
Loop
End Sub
</code>```

The timer starts from 60 and ends at 00. Then the same repeats. Is it possible to start the timer from 120 directly? How can we go about it?

答:
Use DateDiff:

Global StopTime As Date

Sub countdown()

    StopTime = DateAdd("s", 120, Now)

    Do Until StopTime < Now
        DoEvents
        oSh.TextFrame.TextRange = DateDiff("s", Now, StopTime)
    Loop

End Sub
```

Title: Having number above 60 in "ss" format

Body:
Global time As Date

Sub countdown()
time = Now()
time = DateAdd("s", 120, time)

Do Until time < Now()
DoEvents
oSh.TextFrame.TextRange = Format((time - Now()), "ss")
Loop
End Sub

The timer starts from 60 and ends at 00. Then the same repeats. Is it possible to start the timer from 120 directly? How can we go about it?


问:
Git merge branch delete all my change file
Me and my co-worker usually merge each other branchs before we create merge request .But lastime when he merge my branch i found out there some errors so he do revert his code.

The problem right now is that when i merge his branch, all my changes file are being deleted and even when he merge my branch, my code still get delete. I really need some help in here

答:
If your coworker has merged your branch first, and then removed your changes (during the "undo all the change from merge and then commit" step), then it is expected that merging his branch result in your work being removed.

I would prefer for the coworker to reset his branch to before the first merge, re-do the merge properly, force push (git push --force)

Same for you: reset before the last merge (the one which removed your work), fetch, and then merge the branch.


问:
OnbackPrees to return home always in react stack navigation
I am do do navigation in react native where all the back arrow or back press return to initial route. On last on option is to list to onBackPreessed event and passs call to init route which is home.
I am hoping their will be props for allowing the Screen to return to init   Screen in stack navigations

What is happening

On home:
go details then go A
back arrow press in A, it  return  back to  details

Need actions

On home:
go details then go A
back arrow press in A  return  back to home instead of details

The code I try

```<code>import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}

function DetailsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <Button
        title="Go to A"
        onPress={() => navigation.navigate('A')}
      />

    </View>
  );
}
function A({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>AAAAAAAAAAAAAAAAAAA Screen</Text>

    </View>
  );
}
const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home" detachInactiveScreens={true}
        detachPreviousScreen={true}>
        <Stack.Screen name="Home" component={HomeScreen} />

        <Stack.Group screenOptions={{ presentation: 'modal' }}>
          <Stack.Screen name="Details" component={DetailsScreen}
            options={{ presentation: 'transparentModal' }}
          />
          <Stack.Screen name="A" component={A} />
        </Stack.Group>
      </Stack.Navigator>

    </NavigationContainer>
  );
}

export default App;
</code>```

答:
The default behaviour of React Navigation is this only, it takes you to the last visited stack on pressing back but if you want to update it, you can you this line of code:

```<code>useFocusEffect( //imported from @react-navigation/native-stack
React.useCallback(() => {
  const onBackPress = () => {
    navigation.navigate('InitialRouteName');
  };

  BackHandler.addEventListener('hardwareBackPress', onBackPress);

  return () =>
    BackHandler.removeEventListener('hardwareBackPress', onBackPress);
}, [])
</code>```

);

For reference, you can check this out - https://reactnavigation.org/docs/custom-android-back-button-handling/

Body:
I am do do navigation in react native where all the back arrow or back press return to initial route. On last on option is to list to onBackPreessed event and passs call to init route which is home.
I am hoping their will be props for allowing the Screen to return to init   Screen in stack navigations

What is happening

On home:
go details then go A
back arrow press in A, it  return  back to  details

Need actions

On home:
go details then go A
back arrow press in A  return  back to home instead of details

The code I try

import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}

function DetailsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <Button
        title="Go to A"
        onPress={() => navigation.navigate('A')}
      />

    </View>
  );
}
function A({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>AAAAAAAAAAAAAAAAAAA Screen</Text>

    </View>
  );
}
const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home" detachInactiveScreens={true}
        detachPreviousScreen={true}>
        <Stack.Screen name="Home" component={HomeScreen} />

        <Stack.Group screenOptions={{ presentation: 'modal' }}>
          <Stack.Screen name="Details" component={DetailsScreen}
            options={{ presentation: 'transparentModal' }}
          />
          <Stack.Screen name="A" component={A} />
        </Stack.Group>
      </Stack.Navigator>

    </NavigationContainer>
  );
}

export default App;

Body:
The default behaviour of React Navigation is this only, it takes you to the last visited stack on pressing back but if you want to update it, you can you this line of code:

useFocusEffect( //imported from @react-navigation/native-stack
React.useCallback(() => {
  const onBackPress = () => {
    navigation.navigate('InitialRouteName');
  };

  BackHandler.addEventListener('hardwareBackPress', onBackPress);

  return () =>
    BackHandler.removeEventListener('hardwareBackPress', onBackPress);
}, [])

);

For reference, you can check this out - https://reactnavigation.org/docs/custom-android-back-button-handling/


问:
How to find Xpath of any "city" of variable dropdown?

I installed Chrome addon "Selectors Hub".

I opened site: spicejet.com

I choose some random city of "from" dropdown.

With help of "Selectors Hub" chrome addon, I grabbed the Xpath code of
that city:

//div[@class='css-1dbjc4n r-14lw9ot r-z2wwpe r-vgw6uq r-156q2ks r-urutk0 r-8uuktl r-136ojw6']//div[11]

While validating this Xpath code in console, it shows 0 matches.

答:
This website is built on ReactJs as front-end, if I am not wrong, and finding the elements of a ReactJs website is a bit challenging; adding to that, if you rely on some locator finding tool, it's gets more difficult. It's always better you build your own locator strategy than rely on tools, especially for websites built with React, Vue, etc.

Having said that, the strategy here is to find the relatively narrowed down relative locator, and then since you are looking for a random selection of city, collect all the cities first, then apply random to it. Here is what it figured:

I collected cities, but along with it came some unwanted items (courtesy my relative locator), and I check them and if they are picked up, I pass them out, and only when a city is selected by random, I click on it. Check this code:

```<code>import random

driver.get("https://www.spicejet.com/")
time.sleep(10)
driver.find_element(By.XPATH, "//div[@data-testid='to-testID-destination']").click()
time.sleep(2)
cities = driver.find_elements(By.XPATH, "//div[@data-testid='to-testID-destination']//div[@data-focusable='true']")
print(len(cities))
x = random.choice(cities)
if x.text in ['To', 'India', 'International']:
    pass
else:
    print(x.text)
    x.click()
time.sleep(5)
driver.quit()
</code>```

Output:

```<code>Pakyong
Pakyong Airport
PYG

Process finished with exit code 0
</code>```

Body:
This website is built on ReactJs as front-end, if I am not wrong, and finding the elements of a ReactJs website is a bit challenging; adding to that, if you rely on some locator finding tool, it's gets more difficult. It's always better you build your own locator strategy than rely on tools, especially for websites built with React, Vue, etc.

Having said that, the strategy here is to find the relatively narrowed down relative locator, and then since you are looking for a random selection of city, collect all the cities first, then apply random to it. Here is what it figured:

I collected cities, but along with it came some unwanted items (courtesy my relative locator), and I check them and if they are picked up, I pass them out, and only when a city is selected by random, I click on it. Check this code:

import random

driver.get("https://www.spicejet.com/")
time.sleep(10)
driver.find_element(By.XPATH, "//div[@data-testid='to-testID-destination']").click()
time.sleep(2)
cities = driver.find_elements(By.XPATH, "//div[@data-testid='to-testID-destination']//div[@data-focusable='true']")
print(len(cities))
x = random.choice(cities)
if x.text in ['To', 'India', 'International']:
    pass
else:
    print(x.text)
    x.click()
time.sleep(5)
driver.quit()

Output:

Pakyong
Pakyong Airport
PYG

Process finished with exit code 0


问:
How to apply styles for v-slot?

<template>

 <app-tabs  class="w-11/12 lg:w-10/12 mx-auto" :tabList="contentList"  variant="horizontal">
 <template  v-for="content in contentList" v-slot:[content.SID]="">

{{ content.id }}
 //not breaking line and giving error
 {{ content.name }}{{ content.val}}

 </template>
</app-tabs>

</template>```

Unable to add css  class inside of vuejs slots. I am getting error as,

error  Elements in iteration expect to have 'v-bind:key' directives  vue/require-v-for-key

Is there any way to add css class, or any other alternative ways to do it?
With internet resources, I found the way to do it by Deep Selectors like >>> but not sure how to proceed.

答:
Your error occurs because the key (:key="uniqueID") is missing. Add in your loop a key like :

```<code><template  v-for="content in contentList" v-slot:[content.SID]="">
   <div :key="content.id" class="align-items">{{ content.id }}<br/>
 {{ content.name }} {{ content.val }}</div>
</template>
</code>```

Title: How to apply styles for v-slot?

Body:
<template>

 <app-tabs  class="w-11/12 lg:w-10/12 mx-auto" :tabList="contentList"  variant="horizontal">
 <template  v-for="content in contentList" v-slot:[content.SID]="">

{{ content.id }}
 //not breaking line and giving error
 {{ content.name }}{{ content.val}}

 </template>
</app-tabs>

</template>

Unable to add css  class inside of vuejs slots. I am getting error as,

error  Elements in iteration expect to have 'v-bind:key' directives  vue/require-v-for-key

Is there any way to add css class, or any other alternative ways to do it?
With internet resources, I found the way to do it by Deep Selectors like >>> but not sure how to proceed.

Body:
Your error occurs because the key (:key="uniqueID") is missing. Add in your loop a key like :

<template  v-for="content in contentList" v-slot:[content.SID]="">
   <div :key="content.id" class="align-items">{{ content.id }}<br/>
 {{ content.name }} {{ content.val }}</div>
</template>


问:
MinGW 32 "undefined reference to `ExitProcess@4'"
for learning purposes I wrote a small assembler program (test.asm):

```<code>global _main

extern _ExitProcess@4

section .text

    _main:

        mov     ebx,0
        push    ebx
        call    _ExitProcess@4
</code>```

Than I assembled it with NASM (test.obj):

```<code>nasm -f win32 test.asm
</code>```

Now I am trying to link it to an "Portable Executable" (Windows 10 32 Bit):

```<code>ld test.obj
</code>```

But I am always getting this error message:

```<code>undefined reference to `ExitProcess@4'
</code>```

As far as I understand this message it means, that my program is not linked to "Kernel32.dll".
But I thought "ld" is linking with "Kernel32.dll" automatically so I don't have to add some flags for that.
Moreover if I add this flag:

```<code>ld test.obj -lkernel32
</code>```

I am getting the following error message:

```<code>cannot find -lkernel32
</code>```

I am sure I did a dumb mistake so maybe someone can tell me what's wrong.

EDIT:

If I am using "gcc" instead it work's:

```<code>gcc test.obj -nostdlib -lkernel32
</code>```

So now I am wondering why "gcc" knows "-lkernel32" and "ld" not.

答:
You can also put the kernel32.dll in the same folder of test.obj. Then you call :

ld -o test test.obj kernel32.dll

Body:
for learning purposes I wrote a small assembler program (test.asm):

global _main

extern _ExitProcess@4

section .text

    _main:

        mov     ebx,0
        push    ebx
        call    _ExitProcess@4

Than I assembled it with NASM (test.obj):

nasm -f win32 test.asm

Now I am trying to link it to an "Portable Executable" (Windows 10 32 Bit):

ld test.obj

But I am always getting this error message:

undefined reference to `ExitProcess@4'

As far as I understand this message it means, that my program is not linked to "Kernel32.dll".
But I thought "ld" is linking with "Kernel32.dll" automatically so I don't have to add some flags for that.
Moreover if I add this flag:

ld test.obj -lkernel32

I am getting the following error message:

cannot find -lkernel32

I am sure I did a dumb mistake so maybe someone can tell me what's wrong.

EDIT:

If I am using "gcc" instead it work's:

gcc test.obj -nostdlib -lkernel32

So now I am wondering why "gcc" knows "-lkernel32" and "ld" not.


问:
How to pass textview value from adapter class to texview of another acivity
I want to pass the value of textview from the adapter class to another textview of another activity.
please help me ...

//recycleradapter class

```<code>Intent intent = new Intent(applicationContext, DetailActivity.class);

            intent.putExtra("likes",holder.quantity.toString());
            applicationContext.startActivity(intent);
</code>```

// detail acivity class

```<code>String like = getIntent().getStringExtra("Likes");
Toast.makeText(this, like+"", Toast.LENGTH_SHORT).show();
item_quantiy.setText(like);
</code>```

答: in adapter use context or activity for intent .(instead applicationContext)</p>

Body:
I want to pass the value of textview from the adapter class to another textview of another activity.
please help me ...

//recycleradapter class

Intent intent = new Intent(applicationContext, DetailActivity.class);

            intent.putExtra("likes",holder.quantity.toString());
            applicationContext.startActivity(intent);

// detail acivity class

String like = getIntent().getStringExtra("Likes");
Toast.makeText(this, like+"", Toast.LENGTH_SHORT).show();
item_quantiy.setText(like);