问:
ASP.NET Razor Pages: helperTag seems to not be updating after logout
I'm going through a tutorial on Razor Pages and trying to add functionality on the side.

I have just implemented a login/logout logic using c# within a partial view (_AccountInfoPartial.cshtml) to display only one of the corresponding two buttons in a dropdown menu, depending on whether the user is logged in or not (User.Identity.IsAuthenticated is true or false). The logout button is part of a form in this partial view, and the form submits a post request to Logout.cshtml.cs, where the logout is handled in OnPostAsync()

In OnPostAsync, after the signout is completed, I redirect to the same Logout.cshtml view, which checks whether the user is logged in or not, and displays text accordingly. I realize this is probably not very elegant. The reason I do this at the moment is to have the page display different content depending on the status of the user, so that I can handle the case when the user manually types in the URL of the logout page. In the case that this happens, I display a logout button on the logout page if the user is not logged out already, instead of logging him out directly. If he is already logged out, I give him that information by displaying "You have logged out."

Here is the relevant part of the partial view (_AccountInfoPartial.cshtml)

```<code><ul class="navbar-nav">
    <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            @if (User.Identity.IsAuthenticated)
            {
                    @User.Identity.Name
            }

                <img src="~/Images/Account/login.png" class="menu-image" />
        </a>
        <ul class="dropdown-menu" aria-labelledby="navbarDropdown">

            @if (User.Identity.IsAuthenticated)
            {
                <li>
                    <form method="post" class="form-inline" asp-page="Account/Logout">
                        <button type="submit" class="dropdown-item">Logout</button>
                    </form>
                </li>
            }
            else
            {
                <li><a class="dropdown-item" asp-area="" asp-page="Account/Login">Login</a></li>
            }
        </ul>

    </li>
</ul>
</code>```

Here is the OnPostAsync Method from Logout.cshtml.cs

```<code> public async Task<IActionResult> OnPostAsync()
 {
     await HttpContext.SignOutAsync("MyCookieAuthentication");
     return RedirectToPage("/Account/Logout");
 }
</code>```

Here is the Logout view (Logout.cshtml):

```<code>@page
@model ShagMeThatsAGreatRecipeRazor.Pages.Account.LogoutModel

<h1>Logout</h1>
@if(User.Identity.IsAuthenticated)
{
    <form method="post">
        <button type="submit" class="btn btn-primary" asp-page="Account/Logout">Logout</button>
    </form>

}
else
{
    <h3 class="text-center">You have logged out.</h3>
}
</code>```

I'm getting the following behaviour, as illustrated by the screenshot further down in this post:

After I login, I click the logout button.

The OnPostAsync method is called, the cookie is deleted, and the user gets redirected to the (same)
/Account/Logout.cshtml view.

The page picks up on the fact that the
user is not authenticated anymore, and displays the correct content
("You have logged out.").

The partial view also seems to update
correctly in the sense that it seems to pick up that the user is
no longer authenticated, displaying the Login text.

However, the helper tag (asp-page) is still pointing to Account/Logout (not, as I would hope, to Account/Login), as can be seen
in the bottom left of the browser when mousing over the login-text.

If I click the login link (which is somehow pointing to the logout
page), the OnPostAysnc method of Logout.cshtml.cs does not get called (my breakpoint is not hit), but the OnGet method of the same viewmodel does get called, and the page gets reloaded.

However, the page remains the same, with the Login text still (again) being presented in the partial view, but still pointing to the logout page.

If I click again, the whole thing repeats over and over.

However, when I then browse to another page within the app, the
partial view does update, and the login button works again.

Since I am new to Razor Pages and MVVM, I have done some research into finding the cause of this. I have come across suggestions such as refreshing the partial view via Ajax (which I don't know how to do yet and would hope for this to be more simple) or updating the page via JavaScript (again something I was hoping would not be necessary)

My questions are:

Why is this happening? I would like to understand this, as I am sure
it points to some gap in my understanding of Razor and/or web apps.

Is there some pattern/logic I can use with my existing page structure
and architecture to get this to work correctly, without having to resort to Ajax or JS? Or would I need to revise my page

structure/architecture or resort to either of the mentioned solutions, or something else entirely?

Body:
I'm going through a tutorial on Razor Pages and trying to add functionality on the side.

I have just implemented a login/logout logic using c# within a partial view (_AccountInfoPartial.cshtml) to display only one of the corresponding two buttons in a dropdown menu, depending on whether the user is logged in or not (User.Identity.IsAuthenticated is true or false). The logout button is part of a form in this partial view, and the form submits a post request to Logout.cshtml.cs, where the logout is handled in OnPostAsync()

In OnPostAsync, after the signout is completed, I redirect to the same Logout.cshtml view, which checks whether the user is logged in or not, and displays text accordingly. I realize this is probably not very elegant. The reason I do this at the moment is to have the page display different content depending on the status of the user, so that I can handle the case when the user manually types in the URL of the logout page. In the case that this happens, I display a logout button on the logout page if the user is not logged out already, instead of logging him out directly. If he is already logged out, I give him that information by displaying "You have logged out."

Here is the relevant part of the partial view (_AccountInfoPartial.cshtml)

            @if (User.Identity.IsAuthenticated)
            {
                    @User.Identity.Name
            }

            @if (User.Identity.IsAuthenticated)
            {

                    <form method="post" class="form-inline" asp-page="Account/Logout">
                        <button type="submit" class="dropdown-item">Logout</button>
                    </form>

            }
            else
            {

Login

            }

Here is the OnPostAsync Method from Logout.cshtml.cs

 public async Task<IActionResult> OnPostAsync()
 {
     await HttpContext.SignOutAsync("MyCookieAuthentication");
     return RedirectToPage("/Account/Logout");
 }

Here is the Logout view (Logout.cshtml):

@page
@model ShagMeThatsAGreatRecipeRazor.Pages.Account.LogoutModel

Logout

@if(User.Identity.IsAuthenticated)
{
    <form method="post">
        <button type="submit" class="btn btn-primary" asp-page="Account/Logout">Logout</button>
    </form>

}
else
{

You have logged out.

}

I'm getting the following behaviour, as illustrated by the screenshot further down in this post:

After I login, I click the logout button.

The OnPostAsync method is called, the cookie is deleted, and the user gets redirected to the (same)
/Account/Logout.cshtml view.

The page picks up on the fact that the
user is not authenticated anymore, and displays the correct content
("You have logged out.").

The partial view also seems to update
correctly in the sense that it seems to pick up that the user is
no longer authenticated, displaying the Login text.

However, the helper tag (asp-page) is still pointing to Account/Logout (not, as I would hope, to Account/Login), as can be seen
in the bottom left of the browser when mousing over the login-text.

If I click the login link (which is somehow pointing to the logout
page), the OnPostAysnc method of Logout.cshtml.cs does not get called (my breakpoint is not hit), but the OnGet method of the same viewmodel does get called, and the page gets reloaded.

However, the page remains the same, with the Login text still (again) being presented in the partial view, but still pointing to the logout page.

If I click again, the whole thing repeats over and over.

However, when I then browse to another page within the app, the
partial view does update, and the login button works again.

Since I am new to Razor Pages and MVVM, I have done some research into finding the cause of this. I have come across suggestions such as refreshing the partial view via Ajax (which I don't know how to do yet and would hope for this to be more simple) or updating the page via JavaScript (again something I was hoping would not be necessary)

My questions are:

Why is this happening? I would like to understand this, as I am sure
it points to some gap in my understanding of Razor and/or web apps.

Is there some pattern/logic I can use with my existing page structure
and architecture to get this to work correctly, without having to resort to Ajax or JS? Or would I need to revise my page

structure/architecture or resort to either of the mentioned solutions, or something else entirely?


来源: stackexchange

问:
Reading 2D/Multidimensional Array From a .txt File In C++
```<code>#include <iostream>
#include <fstream>

using namespace std;

int main() {
    const int m = 5, n = 2;

    int arr[m][n]{};

    ifstream iFile;
    iFile.open("TextFile1.txt");

    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            iFile >> arr[i][j];
        }
    }

    iFile.close();

    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}
</code>```

The code above was written to read a .txt file containing numbers [1-10] in a 5 by 2 array.

My issue is when the code is complied I get my desired  5 x 2 grid though it seems the file isn't being read resulting to this:

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

When I should really be getting this as an output:

```<code>1 2
3 4
5 6
7 8
9 10
</code>```

I also would like to know how I can build off of this to read 3 x 3 arrays for example.

Thank you! :)

ContentLicense: CC BY-SA 4.0

Body:
#include <iostream>
#include <fstream>

using namespace std;

int main() {
    const int m = 5, n = 2;

    int arr[m][n]{};

    ifstream iFile;
    iFile.open("TextFile1.txt");

    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            iFile >> arr[i][j];
        }
    }

    iFile.close();

    for (int i = 0; i < m; i++)
    {
        for (int j = 0; j < n; j++)
        {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

The code above was written to read a .txt file containing numbers [1-10] in a 5 by 2 array.

My issue is when the code is complied I get my desired  5 x 2 grid though it seems the file isn't being read resulting to this:

0 0
0 0
0 0
0 0
0 0

When I should really be getting this as an output:

1 2
3 4
5 6
7 8
9 10

I also would like to know how I can build off of this to read 3 x 3 arrays for example.

Thank you! :)


问:
Flink Fails on kafka NoClassDefFoundError
I have flink 1.14.4 job that have 2 kafka sources and 2 kafka sinks.
After a time my job failed on the error

java.lang.NoClassDefFoundError: org/apache/kafka/common/security/scram/internals/ScramSaslClient$1
```

The error cause a crash loop that flink restart won't fix.

The only thing that seems to help is redeploy the flink environment and rerun the job.
The environment run on a kubernetes cluster and deployed by helm and argoccd

Body:
I have flink 1.14.4 job that have 2 kafka sources and 2 kafka sinks.
After a time my job failed on the error

java.lang.NoClassDefFoundError: org/apache/kafka/common/security/scram/internals/ScramSaslClient$1

The error cause a crash loop that flink restart won't fix.

The only thing that seems to help is redeploy the flink environment and rerun the job.
The environment run on a kubernetes cluster and deployed by helm and argoccd


问:
How to find unknown value if idf is given
We know the formula for idf is as fol:-

```<code>idf = log10 (N/df)
</code>```

where N is the total number of documents. what if we have idf and df values given and we have to find N. I tried following method but it  returns wrong result:-

```<code> if y = logb (x) then
    x = b^y
</code>```

please help.

Body:
We know the formula for idf is as fol:-

idf = log10 (N/df)

where N is the total number of documents. what if we have idf and df values given and we have to find N. I tried following method but it  returns wrong result:-

 if y = logb (x) then
    x = b^y

please help.


问:
CommonJS packed library has no named exports
I created an icon package library for my ecosystem using Vite and Typescript. It's a simple library that only needs to export icon objects. When I try to use the compiled cjs file, I always get this error message, even though I try only named exports

(I try to use it with 'npm link' in a test application inside the library)

Uncaught SyntaxError: The requested module '/@fs/C:/Users/tidus/Projects/libraries/packages/glyphs/dist/glyphs.cjs.js' does not provide an export named 'ArrowLightLeft' (at App.tsx:3:9)

I've built it with ViteJS, tsc into commonjs with no luck.

if I use it import Test from '@xengine/glyphs' instead of named import it give me this output :

Here is the library's index.ts

import {IconType} from "./iconType";

 const ArrowLightLeft: IconType = {
    name: 'arrow-light-left',
    key: 'ArrowLightLeft',
    type: 'misc',
    width: 24,
    height: 24,
    attributes: {"fill":"currentColor"},
    svgPathData: ["M11.39 2.42c.28.27.43.63.43 1.01s-.16.75-.43 1.01L3.57 12l7.82 7.56c.56.56.55 1.45-.02 2s-1.48.56-2.07.02L.43 13.01C.16 12.74 0 12.38 0 12s.16-.74.43-1.01L9.3 2.42c.28-.27.65-.42 1.04-.42s.77.15 1.05.42zM1.48 12c0-.79.66-1.43 1.48-1.43h19.21c.82 0 1.48.64 1.48 1.43s-.66 1.43-1.48 1.43H2.96c-.82 0-1.48-.64-1.48-1.43z"],
}

export {ArrowLightLeft};
```
<p>package.json</p>
<pre class="lang-json prettyprint-override"><code>{
  "name": "@xengine/glyphs",
  "version": "1.0.0",
  "description": "A library of glyphs",
  "main": "./dist/glyphs.cjs.js",
  //"module": "./dist/glyphs.es.js" --> opted out in order to test cjs.js
  "types": "./dist/types/index.d.ts",
  "private": false,
  "type": "module",
  "files": [
    "dist"
  ],
  "scripts": {
    "build": "vite build"
  },
  "devDependencies": {
  }
}
</code>```

vite.config.js

export default defineConfig({
    plugins: [
        dtsPlugin(
            {
                outputDir: "dist/types",
            }
        )
    ],
    build: {
        lib: {
            entry: "./src/index.ts",
            name: "Glyphs",
            fileName: (format) => `glyphs.${format}.js`,
            formats: ["cjs", "es"],
        },

        minify: false,
    }
})
```
<p>this is how I try to use the library :</p>
<pre class="lang-js prettyprint-override"><code>import {ArrowLightLeft} from "@xengine/glyphs";

function App() {
console.log(ArrowLightLeft)
  return (
    <div className="App">
    </div>
  )
}

export default App
</code>```

Body:
I created an icon package library for my ecosystem using Vite and Typescript. It's a simple library that only needs to export icon objects. When I try to use the compiled cjs file, I always get this error message, even though I try only named exports

(I try to use it with 'npm link' in a test application inside the library)

Uncaught SyntaxError: The requested module '/@fs/C:/Users/tidus/Projects/libraries/packages/glyphs/dist/glyphs.cjs.js' does not provide an export named 'ArrowLightLeft' (at App.tsx:3:9)

I've built it with ViteJS, tsc into commonjs with no luck.

if I use it import Test from '@xengine/glyphs' instead of named import it give me this output :

Here is the library's index.ts

import {IconType} from "./iconType";

 const ArrowLightLeft: IconType = {
    name: 'arrow-light-left',
    key: 'ArrowLightLeft',
    type: 'misc',
    width: 24,
    height: 24,
    attributes: {"fill":"currentColor"},
    svgPathData: ["M11.39 2.42c.28.27.43.63.43 1.01s-.16.75-.43 1.01L3.57 12l7.82 7.56c.56.56.55 1.45-.02 2s-1.48.56-2.07.02L.43 13.01C.16 12.74 0 12.38 0 12s.16-.74.43-1.01L9.3 2.42c.28-.27.65-.42 1.04-.42s.77.15 1.05.42zM1.48 12c0-.79.66-1.43 1.48-1.43h19.21c.82 0 1.48.64 1.48 1.43s-.66 1.43-1.48 1.43H2.96c-.82 0-1.48-.64-1.48-1.43z"],
}

export {ArrowLightLeft};

package.json

{
  "name": "@xengine/glyphs",
  "version": "1.0.0",
  "description": "A library of glyphs",
  "main": "./dist/glyphs.cjs.js",
  //"module": "./dist/glyphs.es.js" --> opted out in order to test cjs.js
  "types": "./dist/types/index.d.ts",
  "private": false,
  "type": "module",
  "files": [
    "dist"
  ],
  "scripts": {
    "build": "vite build"
  },
  "devDependencies": {
  }
}

vite.config.js

export default defineConfig({
    plugins: [
        dtsPlugin(
            {
                outputDir: "dist/types",
            }
        )
    ],
    build: {
        lib: {
            entry: "./src/index.ts",
            name: "Glyphs",
            fileName: (format) => `glyphs.${format}.js`,
            formats: ["cjs", "es"],
        },

        minify: false,
    }
})

this is how I try to use the library :

import {ArrowLightLeft} from "@xengine/glyphs";

function App() {
console.log(ArrowLightLeft)
  return (

  )
}

export default App


问:
Einsum matrix multiplication with missing dimensions
I want to modify this einsum to be more flexible. Right now it's doing a matrix multiplication of the last two dimensions of A against the last 3 of B:

```<code>tf.einsum("...xp,...pyz->...xyz", A, B)
</code>```

However I want it to be able to handle any number of dimensions after p in B. If it helps, I do know the pivot_axis of p (i.e. the position in tf.shape(B)).

I suppose one way to do it would be to get the number of dimensions after p and do some string trick like:

```<code>suffix='abcdefghijklmno'[:len(tf.shape(B))-pivot_axis]
tf.einsum(f"...xp,...p{suffix}->...x{suffix}", A, B)

</code>```

and append it to the einsum strings? Is there a cleaner way?

Body:
I want to modify this einsum to be more flexible. Right now it's doing a matrix multiplication of the last two dimensions of A against the last 3 of B:

tf.einsum("...xp,...pyz->...xyz", A, B)

However I want it to be able to handle any number of dimensions after p in B. If it helps, I do know the pivot_axis of p (i.e. the position in tf.shape(B)).

I suppose one way to do it would be to get the number of dimensions after p and do some string trick like:

suffix='abcdefghijklmno'[:len(tf.shape(B))-pivot_axis]
tf.einsum(f"...xp,...p{suffix}->...x{suffix}", A, B)

and append it to the einsum strings? Is there a cleaner way?


问:
How to add a property to reduce function
I have this code:

```<code>    source.map(data =>
      /*tslint:disable:no-string-literal*/
      Object['values'](
        data.reduce(
          (acc, { name, type, count }) =>
            (((acc[name] = acc[name] || { name })[type] = count), acc),
          {},
        ),
      ),
    ),
</code>```

This code outputs this:

```<code>  {
    "name": "name1",
    "type": "type1",
    "size": 2,
    "total": 4
  },
</code>```

I want to add one more property to the output so it looks like that:

```<code>  {
    "name": "name1",
    "type": "type1",
    "size": 2,
    "total": 4,
    "newProp": 'value'
  },
</code>```

The new prop is a hardcoded prop so it wont come from the source..

What is the best way to do that?

After playing with a code turned out that I had to take the newProp value from the source.

```<code>source.map(data =>
      /*tslint:disable:no-string-literal*/
      Object['values'](
        data.reduce(
          (acc, { name, type, count, newProp }) =>
            (((acc[name] = acc[name] || { name })[type] = count), acc), //how would you assign a newProp value here?
          {},
        ),
      ),
    ),
</code>```

How would you assign a newProp value within a reduce funcion?

Body:
I have this code:

    source.map(data =>
      /*tslint:disable:no-string-literal*/
      Object['values'](
        data.reduce(
          (acc, { name, type, count }) =>
            (((acc[name] = acc[name] || { name })[type] = count), acc),
          {},
        ),
      ),
    ),

This code outputs this:

  {
    "name": "name1",
    "type": "type1",
    "size": 2,
    "total": 4
  },

I want to add one more property to the output so it looks like that:

  {
    "name": "name1",
    "type": "type1",
    "size": 2,
    "total": 4,
    "newProp": 'value'
  },

The new prop is a hardcoded prop so it wont come from the source..

What is the best way to do that?

After playing with a code turned out that I had to take the newProp value from the source.

source.map(data =>
      /*tslint:disable:no-string-literal*/
      Object['values'](
        data.reduce(
          (acc, { name, type, count, newProp }) =>
            (((acc[name] = acc[name] || { name })[type] = count), acc), //how would you assign a newProp value here?
          {},
        ),
      ),
    ),

How would you assign a newProp value within a reduce funcion?


问:
Is there a library support saml in react js?
am looking for a library to use with react js to  implement saml authentication

I tried to use node-saml but it deprecated now


问:
Is it possible to keep music playing normally when in a voice call on Android?
I'm using Unity's Vivox voice chat library in a game. The library's documentation says that it uses MODE_IN_COMMUNICATION on Android. When on speaker, during a voice session the volume of the game music becomes lower, and 3D sound effects seem to be weakened too. I'm not familar with Android programming. Is this an expected behaviour of Android or is there a way to prevent voice call from affecting music play?</p>


问:
Error: RPC failed; HTTP 302 curl 22 The requested URL returned error: 302
When I executed the git clone command, I got the the following error.

```<code>Error: RPC failed; HTTP 302 curl 22 The requested URL returned error: 302
</code>```

The error always happened in case of Ubuntu 18.04 or 20.04, but The error didn't happen in case of Ubuntu 16.04.

I don't know the difference Ubuntu 16.04 and 18.04/20.04.

Could you please give me some advice me?

Body:
When I executed the git clone command, I got the the following error.

Error: RPC failed; HTTP 302 curl 22 The requested URL returned error: 302

The error always happened in case of Ubuntu 18.04 or 20.04, but The error didn't happen in case of Ubuntu 16.04.

I don't know the difference Ubuntu 16.04 and 18.04/20.04.

Could you please give me some advice me?


问:
Flutter Persistant Bottom Navigation Package - Appbar height error
after using a safe area to scaffold-

I am using persistent_bottom_nav_bar this package for keeping Bottonavigation for all screens but the height of the appbar has changed

enter image description here

Here is my code. I have wrapped Scaffold using SafeAreait works fine after adding the safearea but it showing some white spaces at the top of the appbar.

```<code>import 'package:flutter/cupertino.dart';
import 'package:newmart/Order/order.dart';
import 'package:newmart/Screens/dashboard.dart';
import 'package:newmart/Recharge/recharge.dart';
import 'package:newmart/Company/support.dart';
import 'package:newmart/Screens/wallet.dart';
import 'package:flutter/material.dart';
import 'package:persistent_bottom_nav_bar/persistent_tab_view.dart';
// ignore: unused_import
import 'package:shared_preferences/shared_preferences.dart';

import '../widgets/floating_cart_total.dart';

class HomePage extends StatefulWidget {
const HomePage({super.key, required this.mobileNumber});
final String mobileNumber;
@override
State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
String mb = "";

final PersistentTabController _controller =
    PersistentTabController(initialIndex: 0);

@override
void initState() {
  super.initState();
}

final int _selectedIndex = 0;
// ignore: non_constant_identifier_names
int Index = 0;

List<Widget> _buildScreens() {
  return [
    const Dashboard(),
    const Order(),
    const Wallet(),
    const Recharge(),
    const Support(),
  ];
}

List<PersistentBottomNavBarItem> _navBarsItems() {
  return [
    PersistentBottomNavBarItem(
      icon: const Icon(CupertinoIcons.home),
      title: ("Home"),
      activeColorPrimary: CupertinoColors.activeGreen,
      inactiveColorPrimary: CupertinoColors.systemGrey,
    ),
    PersistentBottomNavBarItem(
      icon: const Icon(Icons.shopping_bag_outlined),
      title: ("Order"),
      activeColorPrimary: CupertinoColors.activeGreen,
      inactiveColorPrimary: CupertinoColors.systemGrey,
    ),
    PersistentBottomNavBarItem(
      icon: const Icon(Icons.wallet),
      title: ("Wallet"),
      activeColorPrimary: CupertinoColors.activeGreen,
      inactiveColorPrimary: CupertinoColors.systemGrey,
    ),
    PersistentBottomNavBarItem(
      icon: const Icon(Icons.charging_station),
      title: ("Recharge"),
      activeColorPrimary: CupertinoColors.activeGreen,
      inactiveColorPrimary: CupertinoColors.systemGrey,
    ),
    PersistentBottomNavBarItem(
      icon: const Icon(Icons.support_agent),
      title: ("Support"),
      activeColorPrimary: CupertinoColors.activeGreen,
      inactiveColorPrimary: CupertinoColors.systemGrey,
    ),
  ];
}

@override
Widget build(BuildContext context) {
  return SafeArea(
    child: Scaffold(
        floatingActionButton: const TotalCartCount(),
        bottomNavigationBar: PersistentTabView(
          context,
          // bottomScreenMargin: 0,
          // margin: top,
          controller: _controller,
          screens: _buildScreens(),
          items: _navBarsItems(),
          confineInSafeArea: true,
          backgroundColor: Colors.white, // Default is Colors.white.
          handleAndroidBackButtonPress: true, // Default is true.
          resizeToAvoidBottomInset:
              true, // This needs to be true if you want to move up the screen when keyboard appears. Default is true.
          stateManagement: true, // Default is true.
          hideNavigationBarWhenKeyboardShows:
              true, // Recommended to set 'resizeToAvoidBottomInset' as true while using this argument. Default is true.
          decoration: NavBarDecoration(
            borderRadius: BorderRadius.circular(10.0),
            colorBehindNavBar: Colors.white,
          ),
          popAllScreensOnTapOfSelectedTab: true,
          popActionScreens: PopActionScreensType.all,
          itemAnimationProperties: const ItemAnimationProperties(
            // Navigation Bar's items animation properties.
            duration: Duration(milliseconds: 200),
            curve: Curves.ease,
          ),
          screenTransitionAnimation: const ScreenTransitionAnimation(
            // Screen transition animation on change of selected tab.
            animateTabTransition: true,
            curve: Curves.ease,
            duration: Duration(milliseconds: 200),
          ),
          navBarStyle: NavBarStyle
              .style1, // Choose the nav bar style with this property.
        )),
  );
}
}
</code>```

Body:
after using a safe area to scaffold-

I am using persistent_bottom_nav_bar this package for keeping Bottonavigation for all screens but the height of the appbar has changed

enter image description here

Here is my code. I have wrapped Scaffold using SafeAreait works fine after adding the safearea but it showing some white spaces at the top of the appbar.

import 'package:flutter/cupertino.dart';
import 'package:newmart/Order/order.dart';
import 'package:newmart/Screens/dashboard.dart';
import 'package:newmart/Recharge/recharge.dart';
import 'package:newmart/Company/support.dart';
import 'package:newmart/Screens/wallet.dart';
import 'package:flutter/material.dart';
import 'package:persistent_bottom_nav_bar/persistent_tab_view.dart';
// ignore: unused_import
import 'package:shared_preferences/shared_preferences.dart';

import '../widgets/floating_cart_total.dart';

class HomePage extends StatefulWidget {
const HomePage({super.key, required this.mobileNumber});
final String mobileNumber;
@override
State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
String mb = "";

final PersistentTabController _controller =
    PersistentTabController(initialIndex: 0);

@override
void initState() {
  super.initState();
}

final int _selectedIndex = 0;
// ignore: non_constant_identifier_names
int Index = 0;

List<Widget> _buildScreens() {
  return [
    const Dashboard(),
    const Order(),
    const Wallet(),
    const Recharge(),
    const Support(),
  ];
}

List<PersistentBottomNavBarItem> _navBarsItems() {
  return [
    PersistentBottomNavBarItem(
      icon: const Icon(CupertinoIcons.home),
      title: ("Home"),
      activeColorPrimary: CupertinoColors.activeGreen,
      inactiveColorPrimary: CupertinoColors.systemGrey,
    ),
    PersistentBottomNavBarItem(
      icon: const Icon(Icons.shopping_bag_outlined),
      title: ("Order"),
      activeColorPrimary: CupertinoColors.activeGreen,
      inactiveColorPrimary: CupertinoColors.systemGrey,
    ),
    PersistentBottomNavBarItem(
      icon: const Icon(Icons.wallet),
      title: ("Wallet"),
      activeColorPrimary: CupertinoColors.activeGreen,
      inactiveColorPrimary: CupertinoColors.systemGrey,
    ),
    PersistentBottomNavBarItem(
      icon: const Icon(Icons.charging_station),
      title: ("Recharge"),
      activeColorPrimary: CupertinoColors.activeGreen,
      inactiveColorPrimary: CupertinoColors.systemGrey,
    ),
    PersistentBottomNavBarItem(
      icon: const Icon(Icons.support_agent),
      title: ("Support"),
      activeColorPrimary: CupertinoColors.activeGreen,
      inactiveColorPrimary: CupertinoColors.systemGrey,
    ),
  ];
}

@override
Widget build(BuildContext context) {
  return SafeArea(
    child: Scaffold(
        floatingActionButton: const TotalCartCount(),
        bottomNavigationBar: PersistentTabView(
          context,
          // bottomScreenMargin: 0,
          // margin: top,
          controller: _controller,
          screens: _buildScreens(),
          items: _navBarsItems(),
          confineInSafeArea: true,
          backgroundColor: Colors.white, // Default is Colors.white.
          handleAndroidBackButtonPress: true, // Default is true.
          resizeToAvoidBottomInset:
              true, // This needs to be true if you want to move up the screen when keyboard appears. Default is true.
          stateManagement: true, // Default is true.
          hideNavigationBarWhenKeyboardShows:
              true, // Recommended to set 'resizeToAvoidBottomInset' as true while using this argument. Default is true.
          decoration: NavBarDecoration(
            borderRadius: BorderRadius.circular(10.0),
            colorBehindNavBar: Colors.white,
          ),
          popAllScreensOnTapOfSelectedTab: true,
          popActionScreens: PopActionScreensType.all,
          itemAnimationProperties: const ItemAnimationProperties(
            // Navigation Bar's items animation properties.
            duration: Duration(milliseconds: 200),
            curve: Curves.ease,
          ),
          screenTransitionAnimation: const ScreenTransitionAnimation(
            // Screen transition animation on change of selected tab.
            animateTabTransition: true,
            curve: Curves.ease,
            duration: Duration(milliseconds: 200),
          ),
          navBarStyle: NavBarStyle
              .style1, // Choose the nav bar style with this property.
        )),
  );
}
}


问:
How Can i use includ in php without excute the first page code
i try to get a variable from header page to a game page.. but when i do it with include 'header.php" he excute the header code in game.php ( header("refresh"))
i wanna to excute the refresh one time in first page only

header.php code :

```<code><?php
$memory = "ahmed";
echo "Remember This Word : " . $memory;
header("Refresh: 5; url= game.php");
// exit;
?>
</code>```

game.php code :

```<code><?php
// ob_start();
// include "header.php";
// ob_end_clean();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
       if($_POST['solution'] == "ahmed") {
          $_SESSION['username'] = $_POST['solution'];
        } else {
            echo "Try again";
        }
    }
        if(isset($_SESSION['username'])) {
            echo "Well Done <br>";
            echo '<a href="game.php"> Play again</a>';
        } else {

?>
<form action="" method="POST">
    <input type="text" name="solution" id="">
    <input type="submit" value="check">
</form>
<?php } ?>
</code>```

Body:
i try to get a variable from header page to a game page.. but when i do it with include 'header.php" he excute the header code in game.php ( header("refresh"))
i wanna to excute the refresh one time in first page only

header.php code :

<?php
$memory = "ahmed";
echo "Remember This Word : " . $memory;
header("Refresh: 5; url= game.php");
// exit;
?>

game.php code :

<?php
// ob_start();
// include "header.php";
// ob_end_clean();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
       if($_POST['solution'] == "ahmed") {
          $_SESSION['username'] = $_POST['solution'];
        } else {
            echo "Try again";
        }
    }
        if(isset($_SESSION['username'])) {
            echo "Well Done
";
            echo ' Play again';
        } else {

?>
<form action="" method="POST">
    <input type="text" name="solution" id="">
    <input type="submit" value="check">
</form>
<?php } ?>


问:
Unable to read file from S3 url
I have excel file stored in S3 bucket fro where I am storing the file url inside mongodb.I
want to read data from this excel file and transform into JSON.So for that I am XLSX package but it is not reading the file as I am passing the file url inside the method,

Below is my code:

```<code>try {

    const data = await productSchema.findOne({ report_id: reportId });

    if (data) {

        console.log(data.me_url); //I am getting the file url

        const file = xlsx.readFile(data.me_url);
        const sheetNames = file.SheetNames;
        const totalSheets = sheetNames.length;

        console.log(sheetNames);
        console.log(totalSheets);
    }
}
catch (err) {
    return err;
}
</code>```

Any idea why it is not reading the file or anyhthing I have missed.

Title: Unable to read file from S3 url

Body:
I have excel file stored in S3 bucket fro where I am storing the file url inside mongodb.I
want to read data from this excel file and transform into JSON.So for that I am XLSX package but it is not reading the file as I am passing the file url inside the method,

Below is my code:

try {

    const data = await productSchema.findOne({ report_id: reportId });

    if (data) {

        console.log(data.me_url); //I am getting the file url

        const file = xlsx.readFile(data.me_url);
        const sheetNames = file.SheetNames;
        const totalSheets = sheetNames.length;

        console.log(sheetNames);
        console.log(totalSheets);
    }
}
catch (err) {
    return err;
}

Any idea why it is not reading the file or anyhthing I have missed.


问:
Jenkins groovy if condition within steps does not work
I have the following stage in groovy script of a jenkins job":

```<code>stage('Remove servers') {
            when {
                expression { params.DO_REMOVE == true }
            }
            steps {
                script {
                    parallel RemoveSource: {
                        sh """set -x
                            export KUBECONFIG=${source_config}
                            kubectl get ns ${source_namespace} || exists="False"
                        """
                        echo "${exists}"
                        if ("${exists}" != "False") {
                            build job: 'RemoveFCC',
                                parameters: [string(name: 'Branch', value: Branch),
                                             booleanParam(name: 'build_ansible', value: false),
                                             string(name: 'pipeline', value: 'yes')]
                        } else {
                            echo "Server does not exist. skipped fcc run"
                        }
                },
                RemoveTarget: {
                    sh """set -x
                        export KUBECONFIG=${target_config}
                        kubectl get ns ${target_namespace} || exists="False"
                    """
                    echo "${exists}"
                    if ("${exists}" != "False") {
                        build job: 'RemoveFCC',
                            parameters: [string(name: 'Branch', value: Branch),
                                         booleanParam(name: 'build_ansible', value: false),
                                         string(name: 'pipeline', value: 'yes')]
                        } else {
                               echo "Server does not exist. skipped fcc run"
                        }
                    }
                }
            }
        }
</code>```

Even though echo "${exists}" prints False the if condition is still getting executed. I am not sure what am I missing here. Tried things like adding when instead of if.

Body:
I have the following stage in groovy script of a jenkins job":

stage('Remove servers') {
            when {
                expression { params.DO_REMOVE == true }
            }
            steps {
                script {
                    parallel RemoveSource: {
                        sh """set -x
                            export KUBECONFIG=${source_config}
                            kubectl get ns ${source_namespace} || exists="False"
                        """
                        echo "${exists}"
                        if ("${exists}" != "False") {
                            build job: 'RemoveFCC',
                                parameters: [string(name: 'Branch', value: Branch),
                                             booleanParam(name: 'build_ansible', value: false),
                                             string(name: 'pipeline', value: 'yes')]
                        } else {
                            echo "Server does not exist. skipped fcc run"
                        }
                },
                RemoveTarget: {
                    sh """set -x
                        export KUBECONFIG=${target_config}
                        kubectl get ns ${target_namespace} || exists="False"
                    """
                    echo "${exists}"
                    if ("${exists}" != "False") {
                        build job: 'RemoveFCC',
                            parameters: [string(name: 'Branch', value: Branch),
                                         booleanParam(name: 'build_ansible', value: false),
                                         string(name: 'pipeline', value: 'yes')]
                        } else {
                               echo "Server does not exist. skipped fcc run"
                        }
                    }
                }
            }
        }

Even though echo "${exists}" prints False the if condition is still getting executed. I am not sure what am I missing here. Tried things like adding when instead of if.


问:
Get feature names after OneHotEncoder through ColumnTransformer
I want to get feature names after I fit the pipeline.

```<code>cat_attribs = ['isveteran','isgreenliving','dwelling_type_desc',
               'cat_owner','dog_owner','sports_grouping','outdoors_grouping',
               'reading_grouping','cooking_food_grouping','exercise_health_grouping',
               'movie_music_grouping','electronics_computers_grouping','home_improvement_grouping','investing_finance_grouping',
               'collectibles_and_antiques_grouping','paymentmethodsource',
               'marital_status_desc','household_income_class','household_composition','household_education','home_exterior_desc',
               'home_heat_source_desc','home_heating_cooling_desc','children_number_in_household_desc','household_age_range',
               'gender','grandchildren','career','education_online']

# 'sqft_desc','lot_sqft_desc',

#set the numerical attributes
num_attribs = list( Exelon.drop(cat_attribs, axis=1) )

num_attribs

num_pipeline = Pipeline( [
  ('imputer', SimpleImputer(strategy="median")),
  ('std_scaler', StandardScaler()),
])

#define the pipeline process for the data set
full_pipeline = ColumnTransformer( [
    ('num', num_pipeline, num_attribs),
    ('cat', OneHotEncoder(sparse=False), cat_attribs)
])
</code>```

Finally

```<code>X = Exelon.sample(n=20000)
X_set = pd.DataFrame(full_pipeline.fit_transform(X))

df_sample = full_pipeline.get_feature_names(X_set)
</code>```

After fitting with dataframe, I was trying to gather feature names but I end up getting an error:

```<code>TypeError: get_feature_names() takes 1 positional argument but 2 were given
</code>```

Please advise on how I can column names after going through the pipeline.

Body:
I want to get feature names after I fit the pipeline.

cat_attribs = ['isveteran','isgreenliving','dwelling_type_desc',
               'cat_owner','dog_owner','sports_grouping','outdoors_grouping',
               'reading_grouping','cooking_food_grouping','exercise_health_grouping',
               'movie_music_grouping','electronics_computers_grouping','home_improvement_grouping','investing_finance_grouping',
               'collectibles_and_antiques_grouping','paymentmethodsource',
               'marital_status_desc','household_income_class','household_composition','household_education','home_exterior_desc',
               'home_heat_source_desc','home_heating_cooling_desc','children_number_in_household_desc','household_age_range',
               'gender','grandchildren','career','education_online']

# 'sqft_desc','lot_sqft_desc',

#set the numerical attributes
num_attribs = list( Exelon.drop(cat_attribs, axis=1) )

num_attribs

num_pipeline = Pipeline( [
  ('imputer', SimpleImputer(strategy="median")),
  ('std_scaler', StandardScaler()),
])

#define the pipeline process for the data set
full_pipeline = ColumnTransformer( [
    ('num', num_pipeline, num_attribs),
    ('cat', OneHotEncoder(sparse=False), cat_attribs)
])

Finally

X = Exelon.sample(n=20000)
X_set = pd.DataFrame(full_pipeline.fit_transform(X))

df_sample = full_pipeline.get_feature_names(X_set)

After fitting with dataframe, I was trying to gather feature names but I end up getting an error:

TypeError: get_feature_names() takes 1 positional argument but 2 were given

Please advise on how I can column names after going through the pipeline.


问:
Why do we need to return reference to the object when we're using operator overloads so that we can chain operator?
```<code>ostream &operator<<(ostream &output, coords coord)
</code>```

So i have this code right here, and can someone explain why by returning reference to the object, the operator can be chained and we can write codes such as cout << coord1 << coord2; (the coord1 and coord2 belongs to the coords class in case you don't know) ? And also what does returning reference to the object mean in this case, does it return a reference to the cout object or what so that we cannot create a copy of it? How does this work exactly behind the compiler?

I've tried removing the reference sign.

```<code>ostream operator<<(ostream &output, coords coord)
</code>```

And it doesn't allow me to chain operators, so how does this work exactly?

Body:
ostream &operator<<(ostream &output, coords coord)

So i have this code right here, and can someone explain why by returning reference to the object, the operator can be chained and we can write codes such as cout << coord1 << coord2; (the coord1 and coord2 belongs to the coords class in case you don't know) ? And also what does returning reference to the object mean in this case, does it return a reference to the cout object or what so that we cannot create a copy of it? How does this work exactly behind the compiler?

I've tried removing the reference sign.

ostream operator<<(ostream &output, coords coord)

And it doesn't allow me to chain operators, so how does this work exactly?


问:
AttributeError: 'ModbusIOException' object has no attribute 'bits'
```<code>from pymodbus.client import ModbusTcpClient

PLC_IP = '192.168.0.200'
PLC_PORT = 502
client = ModbusTcpClient(PLC_IP, PLC_PORT)
status = client.connect()
print(status)
result = client.read_coils(1,5)
if result.bits[0] == True:
    print("Hello world")
client.close()
</code>```

It shows the error I put in the title.
I recently changed my pc and I think it might be my pymodbus version.
Thanks and I wish to have luck finding a solution to my problem.

Body:
from pymodbus.client import ModbusTcpClient

PLC_IP = '192.168.0.200'
PLC_PORT = 502
client = ModbusTcpClient(PLC_IP, PLC_PORT)
status = client.connect()
print(status)
result = client.read_coils(1,5)
if result.bits[0] == True:
    print("Hello world")
client.close()

It shows the error I put in the title.
I recently changed my pc and I think it might be my pymodbus version.
Thanks and I wish to have luck finding a solution to my problem.


问:
tailwind, color prop only working with orange color
enter image description hereI am passing two components and only working one is "orange" when i change second to orange it works as well

```<code><BalanceCard color="orange" />
<BalanceCard color="yellow" />

<div
        className={`flex flex-col w-52 items-center bg-${color}-200 rounded-lg`}
      >

</code>```

i tried with other colors too like blue,red and such, only working one is orange.
charjs component i was using it is getting color just right but bg-${color}-200 only works with orange

Body:
enter image description hereI am passing two components and only working one is "orange" when i change second to orange it works as well

<BalanceCard color="orange" />
<BalanceCard color="yellow" />

<div
        className={`flex flex-col w-52 items-center bg-${color}-200 rounded-lg`}
      >

i tried with other colors too like blue,red and such, only working one is orange.
charjs component i was using it is getting color just right but bg-${color}-200 only works with orange


问:
If I remove a user from bitbucket do I have to delete the ssh key too?
I want to remove a user completely from bitbucket, so that he don't have access to the bitbucket website and via terminal to the repo.

In the repo at Repository Settings/User and group access I have removed the user.
Is that enough?

Or do I have to delete the SSH key in Pipelines/SSH keys, too, and have to create a new one for myself?
Is that key just for the pipeline?


问:
AWS - CDK: Get resources from CfnEnvironment
I am creating a beanstalk using the CDK and after than I would like to create the cloudwatch dashboard on the same the stalk to view the beanstalk metrics. How can I get the beanstalk loadbalancer details using CfnEnvironment?

const dashboardBody = {
    widgets:[
        {
            "type": "metric",
            "width": 24,
            "height": 3,
            "properties": {
                "title": "Request Count",
                "metrics": [
                    [
                        "AWS/ApplicationELB",
                        "RequestCount",
                        "LoadBalancer",
                        ***"<<Loadbalancer Name>>"***
                    ]
                ],
                "region": "<<AWS Region>>",
                "stat": "Sum",
                "yAxis": {
                    "left": {
                        "min": 0
                    }
                }
            }
        }
    ]
}
const dashobard = new cdk.aws_cloudwatch.CfnDashboard(this, 'dashboard', {
    dashboardName: 'dashboard',
    dashboardBody: JSON.stringify(dashboardBody)
})

```


问:
Copy Datasets - Between different Organizations in GCP
we are having a couple of GCP Organizations, Company X in the EU and the other company in the US. I know we can move datasets across different regions.

But is it also possible to move resources across other Organizations?


问:
AttributeError: 'GenericRelatedObjectManager' object has no attribute
I tried to use generic relation in django project. but it gives attribute error.
Generic relation is between UniqueSourcePresenter and UniqueDbSource

i have an instance of TextTable which has a foreignkey attribute for UniqueSourcePresenter i tried to use reverse relation as self.presenter.texttable in UniqueDbSource's instance method. but it gives error es below

File "/usr/src/app/apps/tableau/models/source.py", line 191, in create_datum
backend     |     if self.presenter.texttable is not None:
backend     | AttributeError: 'GenericRelatedObjectManager' object has no attribute 'texttable'
```
<p>My models are like follows</p>
<pre class="lang-py prettyprint-override"><code>class UniqueSourcePresenter(models.Model):
    """
    Generic Relation Manager of all types of source
    """
    # Below the mandatory fields for generic relation
    limit = models.Q(app_label = 'tableau', model = 'UniqueDbSource'.lower()) | models.Q(app_label = 'tableau', model = 'UniqueAPISource'.lower())
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to = limit)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()
    pass
</code>```

class DataSource(models.Model):
    pass
```
<pre class="lang-py prettyprint-override"><code>class UniqueSource(DataSource):
    presenter = GenericRelation(UniqueSourcePresenter)

    class Meta:
        abstract = True
</code>```

class UniqueDbSource(UniqueSource):
    """
    THIS CLASS ADDED TO CONTENTTYPE
    """
    def create_datum(self):
        """ THIS METHOD CALLED WITH SIGNAL """
        d = DatumDb()
        d.title = f"{self.title}_datum"
        if self.presenter.texttable is not None: ## THIS LINE GIVES ERROR
            d.connector = self.presenter.texttable.init_source.data.connector
            query = self.presenter.texttable.init_source.data.query
        elif self.presenter.charttable is not None:
            d.connector = self.charttable.presenter.init_source.data.connector
            query = self.charttable.presenter.init_source.data.query
        query.pk = None
        query.save()
        d.query = query
        d.save()
        self.data = d
    pass

    def create_presenter(self):
        p = UniqueSourcePresenter()
        p.content_type = ContentType.objects.get(app_label='tableau', model='UniqueDbSource'.lower())
        p.object_id = self.id
        p.save()
```
<pre class="lang-py prettyprint-override"><code>class Table(models.Model):
    unique_source = models.OneToOneField(UniqueSourcePresenter, on_delete=models.CASCADE, null=True, blank=True, related_name="%(class)s")

    class Meta:
        abstract = True
</code>```

class TextTable(Table):
    pass

    def create_unique_source(self):
        """
        create a unique source object if created
        and add selfs
        """
        if self.init_source.content_type.model == 'InitialDbSource'.lower():
            us = UniqueDbSource()
            us.title = f"{self.title}_unique_source"
            us.save()
            self.unique_source = us.presenter
        elif self.init_source.content_type.model == 'InitialAPISource'.lower():
            us = UniqueAPISource()
            us.title = f"{self.title}_unique_source"
            us.save()
            self.unique_source = us.presenter
        pass
```
<p>I added <code>pass</code> words where is not about my problem.</p>
<p>EDIT:
signal.py</p>
<pre class="lang-py prettyprint-override"><code>@receiver(post_save, sender=UniqueDbSource)
@receiver(post_save, sender=UniqueAPISource)
def after_unique_source_save(sender, instance, created, **kwargs):
    if created:
        instance.create_datum()
        instance.create_presenter()
        instance.__class__.objects.filter(id=instance.id).update(
            data=DatumDb.objects.all().last())
    else:
        pass

@receiver(post_save, sender=TextTable)
def after_table_save(sender, instance, created, **kwargs):
    if created:
        pass
        instance.create_unique_source()
    pass
    if created:
        TextTable.objects.filter(id=instance.id).update(
            unique_source=UniqueSourcePresenter.objects.all().last()
        ) # may you can also give a good advice for this line
</code>```

Body:
I tried to use generic relation in django project. but it gives attribute error.
Generic relation is between UniqueSourcePresenter and UniqueDbSource

i have an instance of TextTable which has a foreignkey attribute for UniqueSourcePresenter i tried to use reverse relation as self.presenter.texttable in UniqueDbSource's instance method. but it gives error es below

File "/usr/src/app/apps/tableau/models/source.py", line 191, in create_datum
backend     |     if self.presenter.texttable is not None:
backend     | AttributeError: 'GenericRelatedObjectManager' object has no attribute 'texttable'

My models are like follows

class UniqueSourcePresenter(models.Model):
    """
    Generic Relation Manager of all types of source
    """
    # Below the mandatory fields for generic relation
    limit = models.Q(app_label = 'tableau', model = 'UniqueDbSource'.lower()) | models.Q(app_label = 'tableau', model = 'UniqueAPISource'.lower())
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to = limit)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey()
    pass

class DataSource(models.Model):
    pass

class UniqueSource(DataSource):
    presenter = GenericRelation(UniqueSourcePresenter)

    class Meta:
        abstract = True

class UniqueDbSource(UniqueSource):
    """
    THIS CLASS ADDED TO CONTENTTYPE
    """
    def create_datum(self):
        """ THIS METHOD CALLED WITH SIGNAL """
        d = DatumDb()
        d.title = f"{self.title}_datum"
        if self.presenter.texttable is not None: ## THIS LINE GIVES ERROR
            d.connector = self.presenter.texttable.init_source.data.connector
            query = self.presenter.texttable.init_source.data.query
        elif self.presenter.charttable is not None:
            d.connector = self.charttable.presenter.init_source.data.connector
            query = self.charttable.presenter.init_source.data.query
        query.pk = None
        query.save()
        d.query = query
        d.save()
        self.data = d
    pass

    def create_presenter(self):
        p = UniqueSourcePresenter()
        p.content_type = ContentType.objects.get(app_label='tableau', model='UniqueDbSource'.lower())
        p.object_id = self.id
        p.save()

class Table(models.Model):
    unique_source = models.OneToOneField(UniqueSourcePresenter, on_delete=models.CASCADE, null=True, blank=True, related_name="%(class)s")

    class Meta:
        abstract = True

class TextTable(Table):
    pass

    def create_unique_source(self):
        """
        create a unique source object if created
        and add selfs
        """
        if self.init_source.content_type.model == 'InitialDbSource'.lower():
            us = UniqueDbSource()
            us.title = f"{self.title}_unique_source"
            us.save()
            self.unique_source = us.presenter
        elif self.init_source.content_type.model == 'InitialAPISource'.lower():
            us = UniqueAPISource()
            us.title = f"{self.title}_unique_source"
            us.save()
            self.unique_source = us.presenter
        pass

I added pass words where is not about my problem.

EDIT:
signal.py

@receiver(post_save, sender=UniqueDbSource)
@receiver(post_save, sender=UniqueAPISource)
def after_unique_source_save(sender, instance, created, **kwargs):
    if created:
        instance.create_datum()
        instance.create_presenter()
        instance.__class__.objects.filter(id=instance.id).update(
            data=DatumDb.objects.all().last())
    else:
        pass

@receiver(post_save, sender=TextTable)
def after_table_save(sender, instance, created, **kwargs):
    if created:
        pass
        instance.create_unique_source()
    pass
    if created:
        TextTable.objects.filter(id=instance.id).update(
            unique_source=UniqueSourcePresenter.objects.all().last()
        ) # may you can also give a good advice for this line


问:
How can I check if an external link contains playable media before opening in new tab
I would like to check if an external link contains playable media before opening the link in a new tab. I am attempting to do this in an if else format so that I can modify the link if it does not contain playable media.

I am struggling to figure out how to check for this if both links end in .mp4 in the URL. Essentially one link gets an XML error and the other does not, and I am trying to account for these differences and dynamically adjust the link before opening it.  I've also just tried to check for strings on the new page to see if there is an XML error, but the script stops as soon as a new tab is opened with window.open, and chrome.tabs.create doesn't seem to work.

I'm new to Javascript. Any advice would be helpful.

//var win = window.open(modifiedLink, '_blank').focus();
chrome.tabs.create({
    url: modifiedLink,
    selected: true,
  })

var checkForErrors = document.querySelector("body > div.header > span").innerHTML;

if (checkForErrors.includes("This XML file does not appear to have any style")) {
    modifiedLink = modifiedLink.replace('/ask_video/', '/encoded/')
    window.open(modifiedLink, '_blank').focus();
}
```


问:
Winter cms 1.2 app,public, resorces folders are missing
I have recentely install winterCms 1.2 which is based on laravel 9. But in winter CMS app,public,resorces,routes folders are missing. we can't run make:controller command,similar laravel 9. How can I work with winterCms if I want do simple crud.

I just want to use features of Winter cms with basic laravel functionality.


问:
How to move an app to a new project in Huawei AppGallery Connect
I've misunderstood how projects work in AppGallery Connect - and uploaded 4 different apps to the same project (they have all been published for a while). Is it possible to move apps to a new project? There is an option to transfer apps, but that is to move the app to a whole new account.</p>


问:
Magento 2 Different Swatch Types in the Category and Product Page
Would it be possible to use 2 different Swatch Types in the Category and Product Page?

My view.xml as follows. I'd like to use the swatch_image in the Category Page and swatch_image_base in the Product page for the swatches.

        <images module="Magento_Catalog">
            <image id="swatch_image" type="swatch_image">
                <width>30</width>
                <height>30</height>
            </image>
            <image id="swatch_thumb" type="swatch_thumb">
                <width>110</width>
                <height>90</height>
            </image>
            <image id="swatch_image_base" type="swatch_image">
                <width>60</width>
                <height>60</height>
            </image>```

Is this possible to do?

Body:
Would it be possible to use 2 different Swatch Types in the Category and Product Page?

My view.xml as follows. I'd like to use the swatch_image in the Category Page and swatch_image_base in the Product page for the swatches.

        <images module="Magento_Catalog">
            <image id="swatch_image" type="swatch_image">
                <width>30</width>
                <height>30</height>
            </image>
            <image id="swatch_thumb" type="swatch_thumb">
                <width>110</width>
                <height>90</height>
            </image>
            <image id="swatch_image_base" type="swatch_image">
                <width>60</width>
                <height>60</height>
            </image>

Is this possible to do?


问:
How to CalendarView on click date show same schedule for every Mon,Tue,Wed.ect... throughout the year
I can not display a specific schedule on click Monday (example Mondays: "Rice with Chicken") or any other day if it is not that day....
i would like to set a calendar view which shows a month and on any click it shows the specific Schedule for that day in a separate Textfield. I manage to show dates i+i1+i2 at any day on click, but does not work with days like Mon,Tue,Wed ect.</p>


问:
select one month data from particular source type
We got hdfs data in - source_type/yyyymmdd/hr/xxx.parquet

How do we search in hue/impala if we need one month of data (say Aug 2022) from a particular source_type?

Thanks!


问:
To display the data from postgraphile api into the react app
`

```<code>import React, { useEffect, useState } from 'react';
import { useQuery, gql } from '@apollo/client';
import { LOAD_USERS } from "../GraphQL/Queries"

function GetUsers() {

  const { error, loading, data } = useQuery(LOAD_USERS);
  const [users, setUsers] = useState([]);

  useEffect(() => {
    if (data) {
      console.log(data.allUsers)
      setUsers(data.allUsers)
    }
  }, [data]);
  return (
    <div>
      {users.map((val) => {
        return <h1> {val.firstname} </h1>
      })}
    </div>
  )

}

export default GetUsers;
</code>```

`

the error is occuring in console log as

Uncaught TypeError: users.map is not a function. So please help me with this how do i display it on app. it is being print in the console log

Body:
`

import React, { useEffect, useState } from 'react';
import { useQuery, gql } from '@apollo/client';
import { LOAD_USERS } from "../GraphQL/Queries"

function GetUsers() {

  const { error, loading, data } = useQuery(LOAD_USERS);
  const [users, setUsers] = useState([]);

  useEffect(() => {
    if (data) {
      console.log(data.allUsers)
      setUsers(data.allUsers)
    }
  }, [data]);
  return (

      {users.map((val) => {
        return
 {val.firstname}

      })}

  )

}

export default GetUsers;

`

the error is occuring in console log as

Uncaught TypeError: users.map is not a function. So please help me with this how do i display it on app. it is being print in the console log


问:
Train mobileBERT from scratch for other languages
I am thinking of training a mobileBERT model from scratch for the German language.
Can I use the English mobileBERT model from HuggingFace to apply it to a dataset in another language?
It makes sense that I would have to adapt the teacher model of mobileBERT to a BERT model of the corresponding language. Unfortunately, I could not find a parameter to adapt the teacher model.

Are there any other ideas on how best to train a mobileBERT model for another language?

Many greetings and many thanks!
ALPacker


问:
Avoid Type casting on Factory Pattern
I am writing a payment service class in Dart that wraps more than 1 payment provider. The expectation is the caller can simply switch one to another without any hassle.
Let's imagine I have classes like this:

```<code>enum PaymentProvider { providerA, providerB }

abstract class PaymentService {
   void processPayment(Order oder);
}

class PaymentServiceA implements PaymentService {
    final String appKey;
    final String merchantId;

    PaymentServiceA(this.appKey, this.merchantId);

    @override
    void processPayment(Order oder) {
      // concrete implementation to process payment
    }

    String getVoucher() {
       // return voucher code
    }
}

class PaymentServiceB implements PaymentService {
    final PaymentBOptions options;

    PaymentServiceB(this.options);

    @override
    void processPayment(Order oder) {
      // concrete implementation to process payment
    }

    List<PaymentBHistory> getPaymentHistory() {
      // return payment history
    }

}

class PaymentBOptions {
   final bool sendEmailReceipt;
   final Function()? successCallback;

   PaymentBOptions(this.sendEmailReceipt, this.successCallback);
}
</code>```

So here PaymentServiceA and PaymentServiceB have same method (processPayment) so we can create base class PaymentService and let them implements this base class.
However as you can see each of them also has different constructor parameter and specific methods.

How is the best approach to create PaymentService that wrap more than 1 provider like this?

I was trying to use factory pattern like this:

```<code>abstract class PaymentService {
   factory PaymentService(PaymentProvider provider) {
      switch(provider) {
        case PaymentProvider.providerA:
          String appKey = "xxxx";
          String merchantId = "123"
          return PaymentServiceA(appKey, merchantId);
        case PaymentProvider.providerB:
          PaymentBOptions options = PaymentBOptions(() {

          });
          return PaymentServiceB(options);
      }
   }

   void processPayment(Order order);
}
</code>```

But I don't think this is the good practice because:

If we create PaymentServiceA or PaymentServiceB instance using PaymentService factory method it will return as PaymentService and we need to cast to appropriate class in order to access specific PaymentService method.

We can't supply specific constructor parameter of PaymentServiceA or PaymentServiceB outside PaymentService abstract class via factory constructor.

Any idea on how is the best practice and what's the suitable design pattern when facing this kind of scenario?

Thanks.

Title: Avoid Type casting on Factory Pattern

Body:
I am writing a payment service class in Dart that wraps more than 1 payment provider. The expectation is the caller can simply switch one to another without any hassle.
Let's imagine I have classes like this:

enum PaymentProvider { providerA, providerB }

abstract class PaymentService {
   void processPayment(Order oder);
}

class PaymentServiceA implements PaymentService {
    final String appKey;
    final String merchantId;

    PaymentServiceA(this.appKey, this.merchantId);

    @override
    void processPayment(Order oder) {
      // concrete implementation to process payment
    }

    String getVoucher() {
       // return voucher code
    }
}

class PaymentServiceB implements PaymentService {
    final PaymentBOptions options;

    PaymentServiceB(this.options);

    @override
    void processPayment(Order oder) {
      // concrete implementation to process payment
    }

    List<PaymentBHistory> getPaymentHistory() {
      // return payment history
    }

}

class PaymentBOptions {
   final bool sendEmailReceipt;
   final Function()? successCallback;

   PaymentBOptions(this.sendEmailReceipt, this.successCallback);
}

So here PaymentServiceA and PaymentServiceB have same method (processPayment) so we can create base class PaymentService and let them implements this base class.
However as you can see each of them also has different constructor parameter and specific methods.

How is the best approach to create PaymentService that wrap more than 1 provider like this?

I was trying to use factory pattern like this:

abstract class PaymentService {
   factory PaymentService(PaymentProvider provider) {
      switch(provider) {
        case PaymentProvider.providerA:
          String appKey = "xxxx";
          String merchantId = "123"
          return PaymentServiceA(appKey, merchantId);
        case PaymentProvider.providerB:
          PaymentBOptions options = PaymentBOptions(() {

          });
          return PaymentServiceB(options);
      }
   }

   void processPayment(Order order);
}

But I don't think this is the good practice because:

If we create PaymentServiceA or PaymentServiceB instance using PaymentService factory method it will return as PaymentService and we need to cast to appropriate class in order to access specific PaymentService method.

We can't supply specific constructor parameter of PaymentServiceA or PaymentServiceB outside PaymentService abstract class via factory constructor.

Any idea on how is the best practice and what's the suitable design pattern when facing this kind of scenario?

Thanks.


问:
Inserting component on click between grid rows positioning
I have the exact same issue depicted in this post(link attached below), the only difference is that I can't seem to get the positioning correct for the new element. Currently, my element just inserts at the end of the grid instead of below the card clicked.

Inserting component on click between grid rows

I have been trying to use the ID and row index of each card to hopefully get the new element to drop below the card that was clicked.

in the code below I am trying to append the
 on button click to a specific card based on its ID

```<code><div fxFlex class="grid-container">

    <div
      class="grid-item card"
      *ngFor="let x of fleetVehicles; let i =  index;"
      [id]="x.id"
      (click)="toggleCard(i + 1, x.id)"

    >
      <div class="inside-card">
        <header>
          <header>Audi {{ x.id }}</header>
        </header>
        <article>
          <div>
            <img src="assets/images/audi.png" style="width: 80%; height: 70%" />
          </div>

          <div>
            <footer>HVC 529 EC</footer>
          </div>
          <!-- <div
            kind="highlight"
            [class]="collapse ? 'dropdown' : 'gsMDEi'"
          ></div> -->
        </article>
      </div>
    </div>

    <li *ngIf="collapse" id="confirmBooking" class="accordion">
      <div class="card-dropdown" style="flex-direction: row; display: flex">
        <div fxFlex="60" style="width: 100%; height: 100%">
          <header class="dropdown-header">Audi</header>
          <article>
            <div style="padding: 26px;">
              <div class="icon-pos">
                <div class="p-info">
                  <i class="fas fa-door-open icon-style"></i>Doors
                </div>
                <div class="p-info">
                  <i class="fas fa-users icon-style"></i>Seats
                </div>
                <div class="p-info">
                  <i class="fas fa-gear icon-style"></i>Manual
                </div>
                <div class="p-info">
                  <i class="far fa-snowflake icon-style"></i>A/C
                </div>
              </div>
              <div style="height: 100%; width: 100%;">
                <img src="assets/images/audi.png" style="width: 75%;"/>
              </div>
            </div>
            <footer style="height: 50px;">
              <div class="dropdown-footer">HVC 529 EC</div>
            </footer>
          </article>
        </div>

        <div fxFlex="40" style="width: 70%; height: 100%; text-align: -webkit-center">
          <div style="height: 100%; display: flex; justify-content: center">
            <form style="width: 50%; margin: 6px;">
              <label for="Vehicle">Vehicle</label>
              <input
                type="text"
                id="Vehicle"
                name="Vehicle"
                placeholder="Vehicle"
              />
              <label for="Name">Name</label>
              <input
                type="text"
                id="Name"
                name="Name"
                placeholder="Enter your name"
              />
              <label for="Start Date">Start Date</label>
              <input matInput type="datetime-local" />
              <br />
              <label for="End date">End date</label>
              <input matInput type="datetime-local" />
              <br />
              <label for="Customers">Customers</label>
              <select id="Customers" name="country">
                <option value="australia">VW</option>
                <option value="canada">Audi</option>
                <option value="usa">Mercedes</option>
              </select>

              <label for="Passengers">Passengers</label>
              <select id="Passengers" name="country">
                <option value="australia">1</option>
                <option value="canada">2</option>
                <option value="usa">3</option>
              </select>

              <label for="Personal Tracker">Personal Tracker</label>
              <input
                type="text"
                id="Personal Tracker"
                name="Personal Tracker"
                placeholder="If you have a personal tracker, enter the tracking number"
              />

              <label for="Floater">Floater Tracker</label>
              <select id="Floater" name="country">
                <option value="" disabled selected style="text-color: grey">
                  If you don not have a personal tracker, select a floater
                </option>
                <option value="australia">Anel</option>
                <option value="canada">Andrew</option>
                <option value="usa">Nico</option>
              </select>

              <button type="submit" class="sub-button" (click)="makeBooking()">Submit</button>
              <button type="submit" class="can-button" (click)="cancelBooking()">Cancel</button>
            </form>
          </div>
        </div>
      </div>
    </li>
</div>
</code>```

here is my typescript for each card that will be displayed based on the fleetVehicles array. in the toggle card function is where I am needing to have the
 display on click.

```<code> fleetVehicles = [
    { id: 1, name: 'Marc' },
    { id: 2, name: 'Marc' },
    { id: 3, name: 'Marc' },
    { id: 4, name: 'Marc' },
    { id: 5, name: 'Marc' },
    { id: 6, name: 'Marc' },
    { id: 7, name: 'Marc' },
    { id: 8, name: 'Marc' },
    { id: 9, name: 'Marc' },
    { id: 10, name: 'Marc' },
    { id: 11, name: 'Marc' },
    { id: 12, name: 'Marc' },
  ];

collapse = false;
  selectedRowIndex!: number;

  toggleCard(row: number, id: number) {
    this.selectedRowIndex = row;
    console.log(row);

    // this.model = {
    //   columnId: Array.from(
    //     this.renderer.parentNode(this.column).children
    //   ).indexOf(this.column),
    //   width: this.width,
    // };
    // console.log(this.model);

    if ((row = id)) {
      // this.collapse = !this.collapse;
      document.getElementById('confirmBooking');
      // b?.style.display="block";
    }
    console.log(this.fleetVehicles.find((x) => x.id == id));
  }
</code>```

Body:
I have the exact same issue depicted in this post(link attached below), the only difference is that I can't seem to get the positioning correct for the new element. Currently, my element just inserts at the end of the grid instead of below the card clicked.

Inserting component on click between grid rows

I have been trying to use the ID and row index of each card to hopefully get the new element to drop below the card that was clicked.

in the code below I am trying to append the
 on button click to a specific card based on its ID

          Audi {{ x.id }}

            HVC 529 EC

          Audi

                  Doors

                  Seats

                  Manual

                  A/C

HVC 529 EC

            <form style="width: 50%; margin: 6px;">
              Vehicle
              <input
                type="text"
                id="Vehicle"
                name="Vehicle"
                placeholder="Vehicle"
              />
              Name
              <input
                type="text"
                id="Name"
                name="Name"
                placeholder="Enter your name"
              />
              Start Date
              <input matInput type="datetime-local" />

              End date
              <input matInput type="datetime-local" />

              Customers
              <select id="Customers" name="country">
                <option value="australia">VW</option>
                <option value="canada">Audi</option>
                <option value="usa">Mercedes</option>
              </select>

              Passengers
              <select id="Passengers" name="country">
                <option value="australia">1</option>
                <option value="canada">2</option>
                <option value="usa">3</option>
              </select>

              Personal Tracker
              <input
                type="text"
                id="Personal Tracker"
                name="Personal Tracker"
                placeholder="If you have a personal tracker, enter the tracking number"
              />

              Floater Tracker
              <select id="Floater" name="country">
                <option value="" disabled selected style="text-color: grey">
                  If you don not have a personal tracker, select a floater
                </option>
                <option value="australia">Anel</option>
                <option value="canada">Andrew</option>
                <option value="usa">Nico</option>
              </select>

              <button type="submit" class="sub-button" (click)="makeBooking()">Submit</button>
              <button type="submit" class="can-button" (click)="cancelBooking()">Cancel</button>
            </form>

here is my typescript for each card that will be displayed based on the fleetVehicles array. in the toggle card function is where I am needing to have the
 display on click.

 fleetVehicles = [
    { id: 1, name: 'Marc' },
    { id: 2, name: 'Marc' },
    { id: 3, name: 'Marc' },
    { id: 4, name: 'Marc' },
    { id: 5, name: 'Marc' },
    { id: 6, name: 'Marc' },
    { id: 7, name: 'Marc' },
    { id: 8, name: 'Marc' },
    { id: 9, name: 'Marc' },
    { id: 10, name: 'Marc' },
    { id: 11, name: 'Marc' },
    { id: 12, name: 'Marc' },
  ];

collapse = false;
  selectedRowIndex!: number;

  toggleCard(row: number, id: number) {
    this.selectedRowIndex = row;
    console.log(row);

    // this.model = {
    //   columnId: Array.from(
    //     this.renderer.parentNode(this.column).children
    //   ).indexOf(this.column),
    //   width: this.width,
    // };
    // console.log(this.model);

    if ((row = id)) {
      // this.collapse = !this.collapse;
      document.getElementById('confirmBooking');
      // b?.style.display="block";
    }
    console.log(this.fleetVehicles.find((x) => x.id == id));
  }


问:
Issue with configuring alert via API on Influx DB
I'm using InfluxDB to configure alert against data collected via node_exporter & prometheus. I use the attached query to validate the usage of CPU (refer image 1)

```<code>from(bucket: "prometheus")
    |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
    |> filter(fn: (r) => r["_field"] == "node_cpu_seconds_total" and r["mode"] == "idle")
    |> aggregateWindow(every: 1m, fn: mean, createEmpty: false)
    |> derivative(timeColumn: "_time", columns: ["_value"])
    |> map(
        fn: (r) =>
            ({
                _time: r._time,
                node_cpu_seconds_total: r["_value"],
                _field: r.cpu,
                _value: 100.0 - r._value * 100.0,
            }),
    )
    |> yield()
</code>```

The output is working as expected. But when i try to configure an alert against the same query via API. It's not working as expected.
API Endpoint: https://ap-southeast-2-1.aws.cloud2.influxdata.com/api/v2/checks
Method: POST
Payload:

```<code>{
    "id": null,
    "type": "threshold",
    "status": "active",
    "activeStatus": "active",
    "name": "API Test",
    "query": {
        "name": "",
        "text": "from(bucket: \"prometheus\") |> range(start: -30m) |> filter(fn: (r) => r[\"_field\"] == \"node_cpu_seconds_total\" and r[\"mode\"] == \"idle\") |> aggregateWindow(every: 1m, fn: mean, createEmpty: false) |> derivative(timeColumn: \"_time\", columns: [\"_value\"]) |> map( fn: (r) => ({_time: r._time, _field: r.cpu,node_cpu_seconds_total: r[\"_value\"], job: r[\"job\"], _value: 100.0 - r._value * 100.0}), ) |> yield()",
        "editMode": "builder",
        "builderConfig": {
            "buckets": [
                "prometheus"
            ],
            "tags": [
                {
                    "key": "_measurement",
                    "values": [
                        "_all"
                    ],
                    "aggregateFunctionType": "filter"
                },
                {
                    "key": "_field",
                    "values": [
                        "_value"
                    ],
                    "aggregateFunctionType": "filter"
                }
            ],
            "functions": [
                {
                    "name": "mean"
                }
            ],
            "aggregateWindow": {
                "period": "30m",
                "fillValues": false
            }
        },
        "hidden": false
    },
    "orgID": "2f4c02f2aa443cb5",
    "labels": [],
    "description": "",
    "every": "1m",
    "offset": "0s",
    "statusMessageTemplate": "Check: ${ r._check_name } is: ${ r._level }",
    "tags": [],
    "thresholds": [
        {
            "type": "greater",
            "value": 3.0,
            "level": "INFO"
        }
    ]
}
</code>```

Observations:

Alert is created on the console

The task created against the alert is not reflecting the query i mentioned. Attached the task code below.

```<code>import "influxdata/influxdb/monitor"
import "influxdata/influxdb/schema"

data =
    from(bucket: "prometheus")
        |> range(start: -1m)
        |> filter(fn: (r) => r["_field"] == "node_cpu_seconds_total" and r["mode"] == "idle")
        |> aggregateWindow(every: 1m, fn: mean, createEmpty: false)
        |> derivative(timeColumn: "_time", columns: ["_value"])
        |> map(
            fn: (r) =>
                ({
                    _time: r._time,
                    _field: r.cpu,
                    node_cpu_seconds_total: r["_value"],
                    job: r["job"],
                    _value: 100.0 - r._value * 100.0,
                }),
        )

option task = {name: "API Test", every: 1m, offset: 0s}

check = {_check_id: "0a65e164fceff000", _check_name: "API Test", _type: "threshold", tags: {}}
info = (r) => r["node_cpu_seconds_total"] > 3.0
messageFn = (r) => "Check: ${ r._check_name } is: ${ r._level }"

data |> schema["fieldsAsCols"]() |> monitor["check"](data: check, messageFn: messageFn, info: info)
</code>```

Output

Body:
I'm using InfluxDB to configure alert against data collected via node_exporter & prometheus. I use the attached query to validate the usage of CPU (refer image 1)

from(bucket: "prometheus")
    |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
    |> filter(fn: (r) => r["_field"] == "node_cpu_seconds_total" and r["mode"] == "idle")
    |> aggregateWindow(every: 1m, fn: mean, createEmpty: false)
    |> derivative(timeColumn: "_time", columns: ["_value"])
    |> map(
        fn: (r) =>
            ({
                _time: r._time,
                node_cpu_seconds_total: r["_value"],
                _field: r.cpu,
                _value: 100.0 - r._value * 100.0,
            }),
    )
    |> yield()

The output is working as expected. But when i try to configure an alert against the same query via API. It's not working as expected.
API Endpoint: https://ap-southeast-2-1.aws.cloud2.influxdata.com/api/v2/checks
Method: POST
Payload:

{
    "id": null,
    "type": "threshold",
    "status": "active",
    "activeStatus": "active",
    "name": "API Test",
    "query": {
        "name": "",
        "text": "from(bucket: \"prometheus\") |> range(start: -30m) |> filter(fn: (r) => r[\"_field\"] == \"node_cpu_seconds_total\" and r[\"mode\"] == \"idle\") |> aggregateWindow(every: 1m, fn: mean, createEmpty: false) |> derivative(timeColumn: \"_time\", columns: [\"_value\"]) |> map( fn: (r) => ({_time: r._time, _field: r.cpu,node_cpu_seconds_total: r[\"_value\"], job: r[\"job\"], _value: 100.0 - r._value * 100.0}), ) |> yield()",
        "editMode": "builder",
        "builderConfig": {
            "buckets": [
                "prometheus"
            ],
            "tags": [
                {
                    "key": "_measurement",
                    "values": [
                        "_all"
                    ],
                    "aggregateFunctionType": "filter"
                },
                {
                    "key": "_field",
                    "values": [
                        "_value"
                    ],
                    "aggregateFunctionType": "filter"
                }
            ],
            "functions": [
                {
                    "name": "mean"
                }
            ],
            "aggregateWindow": {
                "period": "30m",
                "fillValues": false
            }
        },
        "hidden": false
    },
    "orgID": "2f4c02f2aa443cb5",
    "labels": [],
    "description": "",
    "every": "1m",
    "offset": "0s",
    "statusMessageTemplate": "Check: ${ r._check_name } is: ${ r._level }",
    "tags": [],
    "thresholds": [
        {
            "type": "greater",
            "value": 3.0,
            "level": "INFO"
        }
    ]
}

Observations:

Alert is created on the console

The task created against the alert is not reflecting the query i mentioned. Attached the task code below.

import "influxdata/influxdb/monitor"
import "influxdata/influxdb/schema"

data =
    from(bucket: "prometheus")
        |> range(start: -1m)
        |> filter(fn: (r) => r["_field"] == "node_cpu_seconds_total" and r["mode"] == "idle")
        |> aggregateWindow(every: 1m, fn: mean, createEmpty: false)
        |> derivative(timeColumn: "_time", columns: ["_value"])
        |> map(
            fn: (r) =>
                ({
                    _time: r._time,
                    _field: r.cpu,
                    node_cpu_seconds_total: r["_value"],
                    job: r["job"],
                    _value: 100.0 - r._value * 100.0,
                }),
        )

option task = {name: "API Test", every: 1m, offset: 0s}

check = {_check_id: "0a65e164fceff000", _check_name: "API Test", _type: "threshold", tags: {}}
info = (r) => r["node_cpu_seconds_total"] > 3.0
messageFn = (r) => "Check: ${ r._check_name } is: ${ r._level }"

data |> schema["fieldsAsCols"]() |> monitor["check"](data: check, messageFn: messageFn, info: info)

Output


问:
npm install on React project produces ERESOLVE
I had been attempting to update dependencies on an old project recently. Within my package.json file - I outline my npm and node version, as well as the dependencies I'm using:

```<code>"engines": {
    "npm": "9.x",
    "node": "14.x"
  },
  "dependencies": {
    "isomorphic-fetch": "^3.0.0",
    "jquery": "^3.3.1",
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "react-google-charts": "^1.6.6",
    "react-scripts": "^2.1.3",
    "react-select": "^1.3.0",
    "react-toggle-display": "^2.2.0",
    "react-tooltip": "^3.8.4",
    "react-transition-group": "^4.4.5",
    "survey-react": "^0.12.36"
  }
</code>```

When I run npm install; however, I'm met with a litany of errors regarding the packages I'm using.

```<code>npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: react-transition-group@4.4.5
npm ERR! Found: react@16.5.2
npm ERR! node_modules/react
npm ERR!   react@"^16.5.2" from the root project
npm ERR!   peer react@"^16.0.0" from react-dom@16.5.2
npm ERR!   node_modules/react-dom
npm ERR!     react-dom@"^16.5.2" from the root project
npm ERR!     peer react-dom@">=15.0.0" from react-google-charts@1.6.6
npm ERR!     node_modules/react-google-charts
npm ERR!       react-google-charts@"^1.6.6" from the root project
npm ERR!     2 more (react-select, react-tooltip)
npm ERR!   4 more (react-google-charts, react-input-autosize, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@">=16.6.0" from react-transition-group@4.4.5
npm ERR! node_modules/react-transition-group
npm ERR!   react-transition-group@"^4.4.5" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: react@18.2.0
npm ERR! node_modules/react
npm ERR!   peer react@">=16.6.0" from react-transition-group@4.4.5
npm ERR!   node_modules/react-transition-group
npm ERR!     react-transition-group@"^4.4.5" from the root project
</code>```

I'm unsure what steps I should take to resolve this. Is this an issue with the version of react I'm currently using?

Body:
I had been attempting to update dependencies on an old project recently. Within my package.json file - I outline my npm and node version, as well as the dependencies I'm using:

"engines": {
    "npm": "9.x",
    "node": "14.x"
  },
  "dependencies": {
    "isomorphic-fetch": "^3.0.0",
    "jquery": "^3.3.1",
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "react-google-charts": "^1.6.6",
    "react-scripts": "^2.1.3",
    "react-select": "^1.3.0",
    "react-toggle-display": "^2.2.0",
    "react-tooltip": "^3.8.4",
    "react-transition-group": "^4.4.5",
    "survey-react": "^0.12.36"
  }

When I run npm install; however, I'm met with a litany of errors regarding the packages I'm using.

npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: react-transition-group@4.4.5
npm ERR! Found: react@16.5.2
npm ERR! node_modules/react
npm ERR!   react@"^16.5.2" from the root project
npm ERR!   peer react@"^16.0.0" from react-dom@16.5.2
npm ERR!   node_modules/react-dom
npm ERR!     react-dom@"^16.5.2" from the root project
npm ERR!     peer react-dom@">=15.0.0" from react-google-charts@1.6.6
npm ERR!     node_modules/react-google-charts
npm ERR!       react-google-charts@"^1.6.6" from the root project
npm ERR!     2 more (react-select, react-tooltip)
npm ERR!   4 more (react-google-charts, react-input-autosize, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@">=16.6.0" from react-transition-group@4.4.5
npm ERR! node_modules/react-transition-group
npm ERR!   react-transition-group@"^4.4.5" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: react@18.2.0
npm ERR! node_modules/react
npm ERR!   peer react@">=16.6.0" from react-transition-group@4.4.5
npm ERR!   node_modules/react-transition-group
npm ERR!     react-transition-group@"^4.4.5" from the root project

I'm unsure what steps I should take to resolve this. Is this an issue with the version of react I'm currently using?


问:
can we use encryption at creation of table
```<code>CREATE TABLE Person (
    PersonId INT IDENTITY (1, 1) PRIMARY KEY
   ,Name VARCHAR(100)
   ,Password VARCHAR(6)
);
</code>```

how to encrypt password

Body:
CREATE TABLE Person (
    PersonId INT IDENTITY (1, 1) PRIMARY KEY
   ,Name VARCHAR(100)
   ,Password VARCHAR(6)
);

how to encrypt password