问:
Does anyone know how to fix this TypeError: BotBase.__init__() missing 1 required positional argument: 'command_prefix'?
I'm struggling to figure out where I went wrong. I am setting up a music bot for our server in discord but I cannot get the coding right. I keep getting the below error:

```<code>"TypeError: BotBase.__init__() missing 1 required positional argument: 'command_prefix'"
</code>```

And I don't know why. my code may be messed up. I'll post my main.py if that will help.

import random
import discord
from discord.ext import commands
from discord import app_commands
import os

intents = discord.Intents().all()
bot = commands.Bot(command_prefix='./', intents=intents)

cogs = ['music']

from music_cog import music_cog
from help_cog import help_cog
class music_cog(commands('music_cog')):
    def __init__(self, music_cog):
        self.music_cog = music_cog

class help_cog(commands.Cog):
    def __init__(self, help_cog):
        self.help_cog = help_cog

intents = discord.Intents.default()
intents.message_content = True

bot = discord.Client(intents=intents)

cogs = (help_cog, music_cog)
for i in range(len(cogs)):
    cogs(i).setup('bot')

bot.command()
async def test(ctx):
    await ctx.send("test")
bot.command()
async def test(ctx):
    ctx.send("test")

bot.remove_command("Help")
bot.add_cog(help_cog(bot))
bot.add_cog(music_cog(bot))
bot.run(os.getenv("TOKEN"))

@bot.event
async def on_ready():
    print('We have logged in as {0.user}'.format(bot))
bot.run(os.getenv("TOKEN"))

@bot.event
async def on_message(message):
    username = str(message.auther).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')

    if message.author == bot.user:
        return

    if message.channel.name == 'bot-commands':
        if user_message.lower() == 'hello':
            await message.channel.send(f'See you later {username}!')
            return

        elif user_message.lower() == 'goodbye':
            await message.channel.send(f'Goodbye {username}!')
            return

        elif user_message.lower() == "!random":
            response = f'This is your random number: {random.randomrange(100)}'
            await message.channel.send(response)
            return
    if user_message.lower() == '!anywhere':
        await message.channel.send('This can be used anywhere!')
        return
@bot.command()
async def magic_eightball(ctx, *, question):
    with open("responses.txt", "r") as f:
        random_responses = f.readlines()
        response = random.choice(random_responses)
    await ctx.send(response)

@bot.command()
async def on_message(message):
    if message.auther == bot.user:
        return

    elif message.content.startswith ("-Hello"):
        await message.channel.send("Hello from the other side!!!! I must have called 1,000 times!")

bot.run('TOKEN')
```

Again, I may have messed up somewhere in there. any help is appreciated!

I have searched all over google and youtube and I can't find a solution for this issue.

Body:
I'm struggling to figure out where I went wrong. I am setting up a music bot for our server in discord but I cannot get the coding right. I keep getting the below error:

"TypeError: BotBase.__init__() missing 1 required positional argument: 'command_prefix'"

And I don't know why. my code may be messed up. I'll post my main.py if that will help.

import random
import discord
from discord.ext import commands
from discord import app_commands
import os

intents = discord.Intents().all()
bot = commands.Bot(command_prefix='./', intents=intents)

cogs = ['music']

from music_cog import music_cog
from help_cog import help_cog
class music_cog(commands('music_cog')):
    def __init__(self, music_cog):
        self.music_cog = music_cog

class help_cog(commands.Cog):
    def __init__(self, help_cog):
        self.help_cog = help_cog

intents = discord.Intents.default()
intents.message_content = True

bot = discord.Client(intents=intents)

cogs = (help_cog, music_cog)
for i in range(len(cogs)):
    cogs(i).setup('bot')

bot.command()
async def test(ctx):
    await ctx.send("test")
bot.command()
async def test(ctx):
    ctx.send("test")

bot.remove_command("Help")
bot.add_cog(help_cog(bot))
bot.add_cog(music_cog(bot))
bot.run(os.getenv("TOKEN"))

@bot.event
async def on_ready():
    print('We have logged in as {0.user}'.format(bot))
bot.run(os.getenv("TOKEN"))

@bot.event
async def on_message(message):
    username = str(message.auther).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')

    if message.author == bot.user:
        return

    if message.channel.name == 'bot-commands':
        if user_message.lower() == 'hello':
            await message.channel.send(f'See you later {username}!')
            return

        elif user_message.lower() == 'goodbye':
            await message.channel.send(f'Goodbye {username}!')
            return

        elif user_message.lower() == "!random":
            response = f'This is your random number: {random.randomrange(100)}'
            await message.channel.send(response)
            return
    if user_message.lower() == '!anywhere':
        await message.channel.send('This can be used anywhere!')
        return
@bot.command()
async def magic_eightball(ctx, *, question):
    with open("responses.txt", "r") as f:
        random_responses = f.readlines()
        response = random.choice(random_responses)
    await ctx.send(response)

@bot.command()
async def on_message(message):
    if message.auther == bot.user:
        return

    elif message.content.startswith ("-Hello"):
        await message.channel.send("Hello from the other side!!!! I must have called 1,000 times!")

bot.run('TOKEN')

Again, I may have messed up somewhere in there. any help is appreciated!

I have searched all over google and youtube and I can't find a solution for this issue.


来源: stackexchange

问:
fatal error C1083: Cannot open include file while compiling a Cython file
When I tried to compile a cython file, I got this error.

C:\Users\xxx.\AppData\Local\Programs\Python\Python39\include\pyconfig.h(59): fatal error C1083: Cannot open include file: 'io.h': No such file or directory
error: command 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.29.30133\bin\HostX86\x64\cl.exe' failed with exit code 2

I am using windows 11. and this is my visual studio build tool
enter image description here

I tried visual studio build tool 2019 as well. I got same error.

When I tried to compile a cython file.

ContentLicense: CC BY-SA 4.0


问:
Determine size of the screen in Wayland C++
I have to write several functions which do some things with the user screen like gettings screen resolution, count of monitors etc. I have working solution for Windows and Linux, but on Linux I'm stuck with Wayland. On X11 size of the screen can be easily determined, but Wayland is relatively new and not so documented as X11.

I've tried the following code:

```<code>static void global_handler(void* data, wl_registry* registry, uint32_t name,
                           const char* interface, uint32_t version) {
    wl_output* output = static_cast<wl_output*>(
        wl_registry_bind(registry, name, &wl_output_interface, 1));
    if (!output) {
        // Handle error
    }
}

    std::string GetDisplaySize(std::string args) {

        if (getenv("WAYLAND_DISPLAY") != nullptr) {

            static std::uint16_t width, height;

            wl_display* display = wl_display_connect(nullptr);
            if (!display) { return "0"; }

            wl_registry* registry = wl_display_get_registry(display);

            static const wl_registry_listener registry_listener = {
                .global = +[](void* data, wl_registry* registry, uint32_t name,
                              const char* interface, uint32_t version) -> void {
                    wl_output* output = static_cast<wl_output*>(
                        wl_registry_bind(registry, name, &wl_output_interface,
                                         1));
                    if (!output) { return; }

                    wl_output_get_geometry(output, nullptr, nullptr, &width,
                                           &height);

                    wl_output_destroy(output);
                },
                .global_remove =
                    [](void* data, wl_registry* registry, uint32_t name) {
                    },
            };
            wl_registry_add_listener(registry, &registry_listener, nullptr);

            wl_display_roundtrip(display);

            wl_display_disconnect(display);

            return "{\"width\":" + std::to_string(width) +
                   ",\"height\":" + std::to_string(height) + "}";
        } // namespace api
        else {
            GdkRectangle workarea = {0};
            gdk_monitor_get_workarea(
                gdk_display_get_primary_monitor(gdk_display_get_default()),
                &workarea);

            return "{\"width\":" + std::to_string(workarea.width) +
                   ",\"height\":" + std::to_string(workarea.height) + "}";
        }
    }
</code>```

This works for X11, but on Wayland I get compiler error

```<code>error: ‘wl_output_get_geometry’ was not declared in this scope
</code>```

I'm using GCC C++ compiler. I tried to find some info about that wl_output_get_geometry or which function I can use instead, but I didn't find anything useful.

Body:
I have to write several functions which do some things with the user screen like gettings screen resolution, count of monitors etc. I have working solution for Windows and Linux, but on Linux I'm stuck with Wayland. On X11 size of the screen can be easily determined, but Wayland is relatively new and not so documented as X11.

I've tried the following code:

static void global_handler(void* data, wl_registry* registry, uint32_t name,
                           const char* interface, uint32_t version) {
    wl_output* output = static_cast<wl_output*>(
        wl_registry_bind(registry, name, &wl_output_interface, 1));
    if (!output) {
        // Handle error
    }
}

    std::string GetDisplaySize(std::string args) {

        if (getenv("WAYLAND_DISPLAY") != nullptr) {

            static std::uint16_t width, height;

            wl_display* display = wl_display_connect(nullptr);
            if (!display) { return "0"; }

            wl_registry* registry = wl_display_get_registry(display);

            static const wl_registry_listener registry_listener = {
                .global = +[](void* data, wl_registry* registry, uint32_t name,
                              const char* interface, uint32_t version) -> void {
                    wl_output* output = static_cast<wl_output*>(
                        wl_registry_bind(registry, name, &wl_output_interface,
                                         1));
                    if (!output) { return; }

                    wl_output_get_geometry(output, nullptr, nullptr, &width,
                                           &height);

                    wl_output_destroy(output);
                },
                .global_remove =
                    [](void* data, wl_registry* registry, uint32_t name) {
                    },
            };
            wl_registry_add_listener(registry, &registry_listener, nullptr);

            wl_display_roundtrip(display);

            wl_display_disconnect(display);

            return "{\"width\":" + std::to_string(width) +
                   ",\"height\":" + std::to_string(height) + "}";
        } // namespace api
        else {
            GdkRectangle workarea = {0};
            gdk_monitor_get_workarea(
                gdk_display_get_primary_monitor(gdk_display_get_default()),
                &workarea);

            return "{\"width\":" + std::to_string(workarea.width) +
                   ",\"height\":" + std::to_string(workarea.height) + "}";
        }
    }

This works for X11, but on Wayland I get compiler error

error: ‘wl_output_get_geometry’ was not declared in this scope

I'm using GCC C++ compiler. I tried to find some info about that wl_output_get_geometry or which function I can use instead, but I didn't find anything useful.


问:
Problem with {"code":-4061,"msg":"Order's position side does not match user's setting."} while creating futures order on CCTX Binance
I'm trying to create simple future order on CCTX binance exchange using this code and get -4061 problem:

```<code>import ccxt
import asyncio
import json
import config

exchange = ccxt.binance({
    'apiKey': config.apiKey,
    'secret': config.secret,
    'enableRateLimit': True,
})

exchange.options = {'defaultType': 'future', # or 'margin' or 'spot'
                    'adjustForTimeDifference': True,
                    'newOrderRespType': 'FULL',
                    'defaultTimeInForce': 'GTC'}

markets = exchange.load_markets()

symbol = 'BTC/USDT'
type ='MARKET'
side = 'buy'
amount = 0.001
price = 26000

order = exchange.createOrder(symbol, type, side, amount, price)

open_orders = exchange.fetchOrders('BTC/USDT')
data = json.dumps(open_orders, indent=4, separators=(',', ': ') )
</code>```
```<code>ccxt.base.errors.ExchangeError: binance {"code":-4061,"msg":"Order's position side does not match user's setting."}
</code>```

I've tried to use several things like:

```<code>exchange.fapiPrivatePostPositionSideDual ({'dualSidePosition':'true'})
</code>```

or

```<code>exchange.set_position_mode(hedged=True, symbol=symbol)
</code>```

Or setting my Position setting to Hedge-mode on binance website but nothing have helped me

Body:
I'm trying to create simple future order on CCTX binance exchange using this code and get -4061 problem:

import ccxt
import asyncio
import json
import config

exchange = ccxt.binance({
    'apiKey': config.apiKey,
    'secret': config.secret,
    'enableRateLimit': True,
})

exchange.options = {'defaultType': 'future', # or 'margin' or 'spot'
                    'adjustForTimeDifference': True,
                    'newOrderRespType': 'FULL',
                    'defaultTimeInForce': 'GTC'}

markets = exchange.load_markets()

symbol = 'BTC/USDT'
type ='MARKET'
side = 'buy'
amount = 0.001
price = 26000

order = exchange.createOrder(symbol, type, side, amount, price)

open_orders = exchange.fetchOrders('BTC/USDT')
data = json.dumps(open_orders, indent=4, separators=(',', ': ') )

ccxt.base.errors.ExchangeError: binance {"code":-4061,"msg":"Order's position side does not match user's setting."}

I've tried to use several things like:

exchange.fapiPrivatePostPositionSideDual ({'dualSidePosition':'true'})

or

exchange.set_position_mode(hedged=True, symbol=symbol)

Or setting my Position setting to Hedge-mode on binance website but nothing have helped me


问:
Plotly v4 VSCode Jupyter notebook how to use Scatter.on_selection() callback
Python 3.10

```<code>import plotly.express as px
import plotly.graph_objects as go

def cb(*arg):
    print(arg)

fig = go.FigureWidget([list(px.scatter(df,'Z1','Z2', color='Metra').select_traces())[0]])

fig.data[0].on_selection(cb)
fig.data[0].on_click(cb)

assert isinstance(fig, plotly.graph_objs.FigureWidget)

fig.show()
</code>```

The call-back does not execute when running the cell and making selections or clicking on the figure. How can I get it to work? *I have Jupyter Notebook Renderers installed, which might override some plotly behavior.

package versions:
IPython          : 8.5.0
ipykernel        : 6.16.0
ipywidgets       : 8.0.2
jupyter_client   : 7.4.2
jupyter_core     : 4.11.1
jupyter_server   : not installed
jupyterlab       : not installed
nbclient         : 0.7.0
nbconvert        : 7.2.3
nbformat         : 5.7.0
notebook         : not installed
qtconsole        : not installed
traitlets        : 5.4.0

Body:
Python 3.10

import plotly.express as px
import plotly.graph_objects as go

def cb(*arg):
    print(arg)

fig = go.FigureWidget([list(px.scatter(df,'Z1','Z2', color='Metra').select_traces())[0]])

fig.data[0].on_selection(cb)
fig.data[0].on_click(cb)

assert isinstance(fig, plotly.graph_objs.FigureWidget)

fig.show()

The call-back does not execute when running the cell and making selections or clicking on the figure. How can I get it to work? *I have Jupyter Notebook Renderers installed, which might override some plotly behavior.

package versions:
IPython          : 8.5.0
ipykernel        : 6.16.0
ipywidgets       : 8.0.2
jupyter_client   : 7.4.2
jupyter_core     : 4.11.1
jupyter_server   : not installed
jupyterlab       : not installed
nbclient         : 0.7.0
nbconvert        : 7.2.3
nbformat         : 5.7.0
notebook         : not installed
qtconsole        : not installed
traitlets        : 5.4.0


问:
Cursor based pagination using typeorm, typegraphql , postgresql
So i am trying to follow a tutorial but i am getting an error that says

'Provided "take" value is not a number. Please provide a numeric value.

So while in the apollo server playground i am getting the results i want, the client side doesnt accept it and it throws the error above, only if i change the

```<code>.take(realLimitPlusOne);
</code>```

to limit it accepts it but after that it destroys my cursor based pagination logic that i want to follow.

My code is:

In my post.ts file that contains the resolver for Post entity

@Query(() => PaginatedPosts)
  async posts(
    @Arg('limit', () => Int, { nullable: true }) limit: number,
    @Arg('cursor', () => String, { nullable: true }) cursor: string | null
  ): Promise<PaginatedPosts> {
    const realLimit = Math.min(50, limit);
    const realLimitPlusOne = realLimit + 1;

      const qb = AppDataSource.getRepository(Post)
      .createQueryBuilder('p')
      .orderBy('"createdAt"', 'DESC')
      .take(realLimitPlusOne);

    if (cursor) {
      qb.where('"createdAt" < :cursor', {
        cursor: new Date(parseInt(cursor)),
      });
    }

    const posts = await qb.getMany();
    return {
      posts: posts.slice(0, realLimit),
      hasMore: posts.length === realLimitPlusOne,
    };

  }
```
<p>In my index.tsx file that represents the client side:</p>
<blockquote>
</blockquote>
<pre class="lang-js prettyprint-override"><code>import {
  Box,
  Button,
  Flex,
  Heading,
  Link,
  Stack,
  Text,
} from '@chakra-ui/react';
import { GetServerSidePropsContext } from 'next';
import Layout from '../components/Layout';
import { PostsDocument, usePostsQuery } from '../generated/graphql';
import { addApolloState, initializeApollo } from '../lib/apolloClient';

// a function that i use in order to do SSR for the query of posts
export const getServerSideProps = async ({
  req,
}: GetServerSidePropsContext) => {
  const apolloClient = initializeApollo({ ctx: { req } });
  await apolloClient.query({ query: PostsDocument });
  return addApolloState(apolloClient, {
    props: {},
  });
};

const Index = () => {
  const { data, loading, fetchMore, variables } = usePostsQuery({
    variables: {
      limit: 10,
      cursor: null,
    },
    notifyOnNetworkStatusChange: true,
  });

  if (!loading && !data) {
    return <div>you got query failed for some reason</div>;
  }

  return (
    <Layout>
      <Flex>
        <Heading>Lireddit</Heading>
        <Link href="/create-post" ml="auto">
          Create Post
        </Link>
      </Flex>
      <br></br>
      {!data && loading ? (
        <div>loading...</div>
      ) : (
        <Stack spacing={8}>
          {data!.posts.posts.map((p) => (
            <Box p={5} shadow="md" borderWidth="1px" key={p.id}>
              <Heading fontSize="xl">{p.title}</Heading>
              <Text mt={4}>{p.textSnippet}</Text>
            </Box>
          ))}
        </Stack>
      )}
      {data ? (
        <Flex>
          <Button
            onClick={() => {
              fetchMore({
                variables: {
                  limit: variables?.limit,
                  cursor:
                    data.posts.posts[data.posts.posts.length - 1].createdAt,
                },
              });
            }}
            isLoading={loading}
            m="auto"
            my={8}
          >
            Load more
          </Button>
        </Flex>
      ) : null}
    </Layout>
  );
};

export default Index;

</code>```

In my posts.graphql file:

```<code>query Posts($cursor: String, $limit: Int) {
  posts(cursor: $cursor, limit: $limit) {
    hasMore
    posts {
      id
      title
      createdAt
      updatedAt
      textSnippet
    }
  }
}

</code>```

And finally in my apolloClient.ts file :

const httpLink = new HttpLink({
  uri: 'http://localhost:4000/graphql',
  credentials: 'include',
});

function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === 'undefined',
    link: from([httpLink]),
    cache: new InMemoryCache({
      typePolicies: {
        Query: {
          fields: {
            posts: {
              // Don't cache separate results based on
              // any of this field's arguments.
              keyArgs: false,

              // Concatenate the incoming list items with
              // the existing list items.
              merge(
                existing: PaginatedPosts | undefined,
                incoming: PaginatedPosts
              ): PaginatedPosts {
                return {
                  ...incoming,
                  posts: [...(existing?.posts || []), ...incoming?.posts],
                };
              },
            },
          },
        },
      },
    }),
  });
}
```
<p>My Paginated Posts object:</p>
<pre class="lang-js prettyprint-override"><code>@ObjectType()
export class PaginatedPosts {
  @Field(() => [Post])
  posts: Post[];
  @Field()
  hasMore: boolean;
}

</code>```

Body:
So i am trying to follow a tutorial but i am getting an error that says

'Provided "take" value is not a number. Please provide a numeric value.

So while in the apollo server playground i am getting the results i want, the client side doesnt accept it and it throws the error above, only if i change the

.take(realLimitPlusOne);

to limit it accepts it but after that it destroys my cursor based pagination logic that i want to follow.

My code is:

In my post.ts file that contains the resolver for Post entity

@Query(() => PaginatedPosts)
  async posts(
    @Arg('limit', () => Int, { nullable: true }) limit: number,
    @Arg('cursor', () => String, { nullable: true }) cursor: string | null
  ): Promise<PaginatedPosts> {
    const realLimit = Math.min(50, limit);
    const realLimitPlusOne = realLimit + 1;

      const qb = AppDataSource.getRepository(Post)
      .createQueryBuilder('p')
      .orderBy('"createdAt"', 'DESC')
      .take(realLimitPlusOne);

    if (cursor) {
      qb.where('"createdAt" < :cursor', {
        cursor: new Date(parseInt(cursor)),
      });
    }

    const posts = await qb.getMany();
    return {
      posts: posts.slice(0, realLimit),
      hasMore: posts.length === realLimitPlusOne,
    };

  }

In my index.tsx file that represents the client side:

import {
  Box,
  Button,
  Flex,
  Heading,
  Link,
  Stack,
  Text,
} from '@chakra-ui/react';
import { GetServerSidePropsContext } from 'next';
import Layout from '../components/Layout';
import { PostsDocument, usePostsQuery } from '../generated/graphql';
import { addApolloState, initializeApollo } from '../lib/apolloClient';

// a function that i use in order to do SSR for the query of posts
export const getServerSideProps = async ({
  req,
}: GetServerSidePropsContext) => {
  const apolloClient = initializeApollo({ ctx: { req } });
  await apolloClient.query({ query: PostsDocument });
  return addApolloState(apolloClient, {
    props: {},
  });
};

const Index = () => {
  const { data, loading, fetchMore, variables } = usePostsQuery({
    variables: {
      limit: 10,
      cursor: null,
    },
    notifyOnNetworkStatusChange: true,
  });

  if (!loading && !data) {
    return
you got query failed for some reason
;
  }

  return (
    <Layout>
      <Flex>
        <Heading>Lireddit</Heading>
        <Link href="/create-post" ml="auto">
          Create Post
        </Link>
      </Flex>

      {!data && loading ? (

loading...

      ) : (
        <Stack spacing={8}>
          {data!.posts.posts.map((p) => (
            <Box p={5} shadow="md" borderWidth="1px" key={p.id}>
              <Heading fontSize="xl">{p.title}</Heading>
              <Text mt={4}>{p.textSnippet}</Text>
            </Box>
          ))}
        </Stack>
      )}
      {data ? (
        <Flex>
          <Button
            onClick={() => {
              fetchMore({
                variables: {
                  limit: variables?.limit,
                  cursor:
                    data.posts.posts[data.posts.posts.length - 1].createdAt,
                },
              });
            }}
            isLoading={loading}
            m="auto"
            my={8}
          >
            Load more
          </Button>
        </Flex>
      ) : null}
    </Layout>
  );
};

export default Index;

In my posts.graphql file:

query Posts($cursor: String, $limit: Int) {
  posts(cursor: $cursor, limit: $limit) {
    hasMore
    posts {
      id
      title
      createdAt
      updatedAt
      textSnippet
    }
  }
}

And finally in my apolloClient.ts file :

const httpLink = new HttpLink({
  uri: 'http://localhost:4000/graphql',
  credentials: 'include',
});

function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === 'undefined',
    link: from([httpLink]),
    cache: new InMemoryCache({
      typePolicies: {
        Query: {
          fields: {
            posts: {
              // Don't cache separate results based on
              // any of this field's arguments.
              keyArgs: false,

              // Concatenate the incoming list items with
              // the existing list items.
              merge(
                existing: PaginatedPosts | undefined,
                incoming: PaginatedPosts
              ): PaginatedPosts {
                return {
                  ...incoming,
                  posts: [...(existing?.posts || []), ...incoming?.posts],
                };
              },
            },
          },
        },
      },
    }),
  });
}

My Paginated Posts object:

@ObjectType()
export class PaginatedPosts {
  @Field(() => [Post])
  posts: Post[];
  @Field()
  hasMore: boolean;
}


问:
How to make Hamburger Menu appear in the Navbar before Transformation in React
I am making this nav Bar and cannot make the Hamburger Menu appear in the first place =>
My Idea generally is to make a Logout which I will make with React Router to send the user to the SignIn/SignUp pages.
And want to make the Hamburger Menu appear in the nav bar before minimising the Browser.
Can you help me with extra code to make the LogOut but the logout not to appear in the navbar in in the fist place but when the Hamburger menu is clicked ?
Thanks in advance!

This is the Menu

Minimizing the Browser

Clicking on the Menu

Code:

```<code>import React from 'react';
import './Profile.css';
import {FaBars, FaTimes} from "react-icons/fa";
import { useRef } from 'react';
import { useState } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Settings from '../SettingsForm/Settings';
import {useNavigate} from 'react-router-dom';
import ProfileImage from "../../assets/b112b6db-0fa4-4a2e-ae0e-a8ece6db0d06.png"

function Profile() {

    const navRef = useRef();

    const showNavbar = () => {
        navRef.current.classList.toggle("responsive_nav");
    };

    const navigate = useNavigate();

    const SendSettings = () => {
        navigate("/Settings");
    };

    const sendHome = () => {
        navigate("/Home");
    };

    return (
        <header>
             <svg xmlns="http://www.w3.org/2000/svg" width="148.301" height="182.362" viewBox="0 0 378.301 82.362">
                <path id="Exclusion_1" data-name="Exclusion 1" d="M362>
             </svg>

            <nav ref={navRef}>
                <a href="" onClick={sendHome}>LIBRARY</a>
                <a href="" onClick={SendSettings}>SETTINGS</a>

                <button
                    className="nav-btn nav-close-btn"
                    onClick={showNavbar}>
                    <FaTimes />
                </button>

            </nav>

            <button className="nav-btn" onClick={showNavbar}>
                <FaBars />
            </button>

        </header>

    );
}

export default Profile

</code>```

CSS Code:

```<code>@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@100&display=swap');

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: "Titillium Web", sans-serif;
    font-weight:inherit;
}

:root {
    --mainColor: rgb(255, 249, 249);
    --mainColorLight: white;
    --secondaryColor: black;
    --textColor: black;
}

header {
    box-shadow: 0 2px 2px -2px rgba(0,0,0,.2);
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 53px;
    padding: 0 2rem;
    background-color: var(--mainColor);
    color: var(--textColor);
}

nav a {
    margin: 0 1rem;
    color: var(--textColor);
    text-decoration: none;
}

nav a:hover {
    color: var(--secondaryColor);
    text-decoration: underline  #08C642;
    text-decoration-thickness: 4px;
    text-underline-offset: 1rem;
}

header .nav-btn {
    padding: 5px;
    cursor: pointer;
    background: transparent;
    border: none;
    outline: none;
    color: var(--textColor);
    visibility: hidden;
    opacity: 0;
    font-size: 1.8rem;
}

header div,
nav {
    display: flex;
    align-items: center;
}

.profile-btn{
    margin-right: 0px;
}

@media only screen and (max-width: 1024px) {
    header .nav-btn {
        visibility: visible;
        opacity: 1;
    }

    header nav {
        position: fixed;
        top: 0;
        left: 0;
        height: 100%;
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 1.5rem;
        background-color: var(--mainColor);
        transition: 1s;
        transform: translateY(-100vh);
    }

    header .responsive_nav {
        transform: none;
    }

    nav .nav-close-btn {
        position: absolute;
        top: 2rem;
        right: 2rem;
    }

    nav a {
        font-size: 1.5rem;
    }
}
</code>```

Body:
I am making this nav Bar and cannot make the Hamburger Menu appear in the first place =>
My Idea generally is to make a Logout which I will make with React Router to send the user to the SignIn/SignUp pages.
And want to make the Hamburger Menu appear in the nav bar before minimising the Browser.
Can you help me with extra code to make the LogOut but the logout not to appear in the navbar in in the fist place but when the Hamburger menu is clicked ?
Thanks in advance!

This is the Menu

Minimizing the Browser

Clicking on the Menu

Code:

import React from 'react';
import './Profile.css';
import {FaBars, FaTimes} from "react-icons/fa";
import { useRef } from 'react';
import { useState } from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import Settings from '../SettingsForm/Settings';
import {useNavigate} from 'react-router-dom';
import ProfileImage from "../../assets/b112b6db-0fa4-4a2e-ae0e-a8ece6db0d06.png"

function Profile() {

    const navRef = useRef();

    const showNavbar = () => {
        navRef.current.classList.toggle("responsive_nav");
    };

    const navigate = useNavigate();

    const SendSettings = () => {
        navigate("/Settings");
    };

    const sendHome = () => {
        navigate("/Home");
    };

    return (

             <svg xmlns="http://www.w3.org/2000/svg" width="148.301" height="182.362" viewBox="0 0 378.301 82.362">
                <path id="Exclusion_1" data-name="Exclusion 1" d="M362>
             </svg>

                LIBRARY
                SETTINGS

                <button
                    className="nav-btn nav-close-btn"
                    onClick={showNavbar}>
                    <FaTimes />
                </button>

            <button className="nav-btn" onClick={showNavbar}>
                <FaBars />
            </button>

    );
}

export default Profile

CSS Code:

@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@100&display=swap');

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: "Titillium Web", sans-serif;
    font-weight:inherit;
}

:root {
    --mainColor: rgb(255, 249, 249);
    --mainColorLight: white;
    --secondaryColor: black;
    --textColor: black;
}

header {
    box-shadow: 0 2px 2px -2px rgba(0,0,0,.2);
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 53px;
    padding: 0 2rem;
    background-color: var(--mainColor);
    color: var(--textColor);
}

nav a {
    margin: 0 1rem;
    color: var(--textColor);
    text-decoration: none;
}

nav a:hover {
    color: var(--secondaryColor);
    text-decoration: underline  #08C642;
    text-decoration-thickness: 4px;
    text-underline-offset: 1rem;
}

header .nav-btn {
    padding: 5px;
    cursor: pointer;
    background: transparent;
    border: none;
    outline: none;
    color: var(--textColor);
    visibility: hidden;
    opacity: 0;
    font-size: 1.8rem;
}

header div,
nav {
    display: flex;
    align-items: center;
}

.profile-btn{
    margin-right: 0px;
}

@media only screen and (max-width: 1024px) {
    header .nav-btn {
        visibility: visible;
        opacity: 1;
    }

    header nav {
        position: fixed;
        top: 0;
        left: 0;
        height: 100%;
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 1.5rem;
        background-color: var(--mainColor);
        transition: 1s;
        transform: translateY(-100vh);
    }

    header .responsive_nav {
        transform: none;
    }

    nav .nav-close-btn {
        position: absolute;
        top: 2rem;
        right: 2rem;
    }

    nav a {
        font-size: 1.5rem;
    }
}


问:
CSS ecapsulation Angular micro frontend : my file styles.scss is not included in my single bundle
I develop a micro frontend with Angular Module Federation in Webpack 5.

But I have a problem when I build my project, my main.js does not contain the SCSS which is included in my global SCSS file "styles.scss".

This file is in the root of my project and it's well included in my angular.json file.

I want to specify that this CSS works well when I launch my project locally.

It's the main.js that is generated which does not contain this CSS. So when I integrate my main.js in another application I don't have this CSS.

I want to specify that in my Angular components I did not specify a ViewEncapsulation.

Here is the configuration of my build in my angular.json file :

"build": {
  "builder": "ngx-build-plus:browser",
  "options": {
    "outputPath": "dist/my-webco",
    "index": "projects/my-webco/src/index.html",
    "main": "projects/my-webco/src/main.ts",
    "tsConfig": "projects/my-webco/tsconfig.app.json",
    "inlineStyleLanguage": "scss",
    "assets": [
    "projects/my-webco/src/favicon.ico",
    "projects/my-webco/src/assets"
    ],
    "styles": [
    "projects/my-webco/src/styles.scss"
    ],
    "scripts": [],
    "extraWebpackConfig": "projects/my-webco/webpack.config.js",
    "commonChunk": false
  },
  "configurations": {
    "preproduction": {
      "aot": true,
      "buildOptimizer": true,
      "optimization": true,
      "sourceMap": false,
      "namedChunks": false,
      "extractLicenses": true,
      "vendorChunk": false,
      "keepPolyfills": false,
      "keepStyles": false,
      "singleBundle": true,
      "outputHashing": "none",
      "extraWebpackConfig": "projects/my-webco/webpack.prod.config.js"
    },
    },
  "defaultConfiguration": "preproduction"
},
```


问:
How do I distinguish icons between positive and negative values in reactablefmtr's icon_sets instead of distinguishing based on lower and upper 50%?
I am trying to use reactablefmtr's icon_sets feature to show red up arrows when the value is positive and green down arrows when the value is negative. However, I am getting a green down arrow for slightly positive values. I believe it is because the default setting - when 2 icons are declared - is to use the upper and lower 50% instead of less than zero and greater than 0.

Can anyone help me adjust these settings?

Attached is the screenshot to show the erroneous arrow.
enter image description here

Here is my code:

```<code>cell = icon_sets(data,
 icons=c("down-long","up-long"),
 colors=c("#f77f34", "#f03535"),
 number_fmt = scales::label_percent(accuracy = 0.1))
</code>```

I tried looking through the reference documents for reactablefmtr but didn't find a clear answer.

Body:
I am trying to use reactablefmtr's icon_sets feature to show red up arrows when the value is positive and green down arrows when the value is negative. However, I am getting a green down arrow for slightly positive values. I believe it is because the default setting - when 2 icons are declared - is to use the upper and lower 50% instead of less than zero and greater than 0.

Can anyone help me adjust these settings?

Attached is the screenshot to show the erroneous arrow.
enter image description here

Here is my code:

cell = icon_sets(data,
 icons=c("down-long","up-long"),
 colors=c("#f77f34", "#f03535"),
 number_fmt = scales::label_percent(accuracy = 0.1))

I tried looking through the reference documents for reactablefmtr but didn't find a clear answer.


问:
Automatically filter SQLAlchemy Query on certain fields
We are working on implementing SQLAlchemy ORM in our existing app. We used to use SQLAlchemy Core but introduced some much additional complexity on top that we ended up rewriting most of the Core components, which was hard to maintain and not scalable.

We are now implementing SQLAlchemy ORM and do not want to make the same mistakes. Currently we are stuck on what the best design pattern is to automatically filter each Query on certain Base attributes. I will elaborate with a minimum working example below.

Assume that we have the following Base class and Entity model, where client_id is assumed to be a valid client ID that is set on each record that is committed to the database. This is the part that works as expected, when we retrieve all records, client_ids are reflected properly.

```<code>from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import declarative_base

class Base:
    __abstract__ = True

    client_id = Column('client_id', Integer)  # assume the client_id has a valid ID for the logged in user at the time a model was initiated and the record stored in the database

base = declarative_base(cls=Base, constructor=None)

class Entity(Base):
    __tablename__ = 'entity'

    name = Column(String, nullable=False)

</code>```

To filter records for a valid client, we would do something like

```<code>session.query(Entity).filter(client_id=1)
</code>```

In essence, this works. However, we do not want to bother our programmers with having to filter each resultset on the client_id, since that should happen on each and every query. If our programmers have to do this manually on each query this would also introduce a security issue if this is forgotten and the reviewer didn't pick it up.

What is the best pattern to achieve automatic filtering of the results on a client_id, so that we can do:

```<code>session.query(Entity)
</code>```

and it would behave exactly as if we specified the filter ourselves?

We have considered overwriting the query method on the session, e.g. as such (pseudo)

```<code>def query(...):
   return session.query(Entity).filter(client_id=id)
</code>```

We also considered adding a query method to each data model, as such:

class Base:
   ... # identical to above

   def query(...):
       return session.query(self).filter(self.client_id=id)
```

However both of these solutions don't feel right, as in (1) we have to overwrite Session and in (2) we have to call query on a model instead of a session, which feels like it is not in line with SQLAlchemy best practice.

Are there any patterns we can consider that will enable us to do this without overriding SQLAlchemy components so as to improve maintainability?

Body:
We are working on implementing SQLAlchemy ORM in our existing app. We used to use SQLAlchemy Core but introduced some much additional complexity on top that we ended up rewriting most of the Core components, which was hard to maintain and not scalable.

We are now implementing SQLAlchemy ORM and do not want to make the same mistakes. Currently we are stuck on what the best design pattern is to automatically filter each Query on certain Base attributes. I will elaborate with a minimum working example below.

Assume that we have the following Base class and Entity model, where client_id is assumed to be a valid client ID that is set on each record that is committed to the database. This is the part that works as expected, when we retrieve all records, client_ids are reflected properly.

from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import declarative_base

class Base:
    __abstract__ = True

    client_id = Column('client_id', Integer)  # assume the client_id has a valid ID for the logged in user at the time a model was initiated and the record stored in the database

base = declarative_base(cls=Base, constructor=None)

class Entity(Base):
    __tablename__ = 'entity'

    name = Column(String, nullable=False)

To filter records for a valid client, we would do something like

session.query(Entity).filter(client_id=1)

In essence, this works. However, we do not want to bother our programmers with having to filter each resultset on the client_id, since that should happen on each and every query. If our programmers have to do this manually on each query this would also introduce a security issue if this is forgotten and the reviewer didn't pick it up.

What is the best pattern to achieve automatic filtering of the results on a client_id, so that we can do:

session.query(Entity)

and it would behave exactly as if we specified the filter ourselves?

We have considered overwriting the query method on the session, e.g. as such (pseudo)

def query(...):
   return session.query(Entity).filter(client_id=id)

We also considered adding a query method to each data model, as such:

class Base:
   ... # identical to above

   def query(...):
       return session.query(self).filter(self.client_id=id)

However both of these solutions don't feel right, as in (1) we have to overwrite Session and in (2) we have to call query on a model instead of a session, which feels like it is not in line with SQLAlchemy best practice.

Are there any patterns we can consider that will enable us to do this without overriding SQLAlchemy components so as to improve maintainability?


问:
React Native Auto Linking NEVER HAPPENS
Well I am currently making a react native app and something is getting me really angry, as the title says everytime I install a package in react native that needs linking NEVER works and I really do not know why,and because I am using the latest version of the framework,manual linking with the react-native link command is not an option because it does not exist anymore,react native is so confident about their quality that they destroyed my unique option of help.

I dont know if it will help but this is the package.json of my CRUD app :

```<code>{
  "name": "MyApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.12.1",
    "@react-native-community/masked-view": "^0.1.11",
    "@react-navigation/bottom-tabs": "^6.5.1",
    "@react-navigation/drawer": "^6.5.5",
    "@react-navigation/material-bottom-tabs": "^6.2.9",
    "@react-navigation/native": "^6.1.1",
    "@react-navigation/stack": "^6.3.9",
    "@types/react-native-vector-icons": "^6.4.12",
    "axios": "0.27.2",
    "native-base": "^3.4.25",
    "react": "18.1.0",
    "react-native": "0.70.6",
    "react-native-elements": "^3.4.2",
    "react-native-fontawesome": "^7.0.0",
    "react-native-gesture-handler": "^2.8.0",
    "react-native-paper": "^5.0.1",
    "react-native-reanimated": "^2.13.0",
    "react-native-safe-area-context": "3.3.2",
    "react-native-screens": "^3.18.2",
    "react-native-simple-toast": "^2.0.0",
    "react-native-svg": "12.1.1",
    "react-native-sweet-alert": "^3.5.0",
    "react-native-vector-icons": "^9.2.0",
    "react-native-webview": "^11.26.0",
    "react-query": "^3.39.2"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "@tsconfig/react-native": "^2.0.3",
    "@types/jest": "^29.2.4",
    "@types/react": "^18.0.26",
    "@types/react-native": "^0.70.8",
    "@types/react-test-renderer": "^18.0.0",
    "babel-jest": "^26.6.3",
    "eslint": "^7.32.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "0.72.3",
    "react-test-renderer": "18.1.0",
    "typescript": "^4.9.4"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

PS:many of the dependencies listed here like fontawesome or webview I still cannot use because it says that they are undefined and need manual linking (but how am I supposed to do it react native I ask you????)

By the way thanks for reading until here !

Title: React Native Auto Linking NEVER HAPPENS

Body:
Well I am currently making a react native app and something is getting me really angry, as the title says everytime I install a package in react native that needs linking NEVER works and I really do not know why,and because I am using the latest version of the framework,manual linking with the react-native link command is not an option because it does not exist anymore,react native is so confident about their quality that they destroyed my unique option of help.

I dont know if it will help but this is the package.json of my CRUD app :

{
  "name": "MyApp",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@react-native-community/async-storage": "^1.12.1",
    "@react-native-community/masked-view": "^0.1.11",
    "@react-navigation/bottom-tabs": "^6.5.1",
    "@react-navigation/drawer": "^6.5.5",
    "@react-navigation/material-bottom-tabs": "^6.2.9",
    "@react-navigation/native": "^6.1.1",
    "@react-navigation/stack": "^6.3.9",
    "@types/react-native-vector-icons": "^6.4.12",
    "axios": "0.27.2",
    "native-base": "^3.4.25",
    "react": "18.1.0",
    "react-native": "0.70.6",
    "react-native-elements": "^3.4.2",
    "react-native-fontawesome": "^7.0.0",
    "react-native-gesture-handler": "^2.8.0",
    "react-native-paper": "^5.0.1",
    "react-native-reanimated": "^2.13.0",
    "react-native-safe-area-context": "3.3.2",
    "react-native-screens": "^3.18.2",
    "react-native-simple-toast": "^2.0.0",
    "react-native-svg": "12.1.1",
    "react-native-sweet-alert": "^3.5.0",
    "react-native-vector-icons": "^9.2.0",
    "react-native-webview": "^11.26.0",
    "react-query": "^3.39.2"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "@tsconfig/react-native": "^2.0.3",
    "@types/jest": "^29.2.4",
    "@types/react": "^18.0.26",
    "@types/react-native": "^0.70.8",
    "@types/react-test-renderer": "^18.0.0",
    "babel-jest": "^26.6.3",
    "eslint": "^7.32.0",
    "jest": "^26.6.3",
    "metro-react-native-babel-preset": "0.72.3",
    "react-test-renderer": "18.1.0",
    "typescript": "^4.9.4"
  },
  "jest": {
    "preset": "react-native"
  }
}

PS:many of the dependencies listed here like fontawesome or webview I still cannot use because it says that they are undefined and need manual linking (but how am I supposed to do it react native I ask you????)

By the way thanks for reading until here !


问:
What is causing the following stackoverflow error in a spring boot application with a scheduler?
The issue happened in production and need an immediate fix. Please help me

I have a spring boot application which is dockerized and running on an ec2 instance. Today the application started giving java.lang.StackOverflowError: null error suddenly without even making any changes.

The stack trace is attached below

So in the stack trace you can see coffeejms-4, That is nothing but a thread's name. So issue happened within a thread that is running a scheduled job in my spring boot application.

The scheduler configuration is attached below

I don't know what caused this all of a sudden. I just restarted my docker container. I didn't change the image at all. I have tried following things

Restarted docker service

Restarted my ec2 instance

Assigned more memory for the spring boot app

But nothing is helping it. If someone could help me with this as soon as possible that would be greatly appreciated.

Thanks


问:
Mobile side-nav menu not scrolling
Hello I have this code

```<code><div id="slide-out" class="side-nav mobile-menu-items-main-div  w-100">
    <div class="custom-scrollbar color-primary mobile-menu-items" style="height:100%;overflow-y:auto;">
     ....
    </div>
</div>

.mobile-menu-items-main-div {
            min-height: 100vh !important;
            height: 100% !important;

            overflow-y: auto !important;
            background-color: white;
            position: absolute !important;
        }
        .mobile-menu-items {
            min-height: 100vh !important;
            height: 100% !important;

            display: flex;
            flex-direction: column;
            overflow-y: auto !important;
            /*justify-content:space-between;*/
        }

.side-nav {
    position: fixed;
    width: 15rem;
    left: 0;
    top: 0;
    margin: 0;
    transform: translateX(-100%);
    height: 100%;
    background-color: #2c2f34;
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    z-index: 1040;
    backface-visibility: hidden;
    overflow: hidden;
    will-change: transform;
    backface-visibility: hidden;
    list-style-type: none;
    padding: 0;
    box-shadow: 0 2px 5px 0 rgb(0 0 0 / 16%), 0 2px 10px 0 rgb(0 0 0 / 12%);
}
</code>```

Can somebody explain to me why I can scroll on the computer browser using responsive mode, but I can't scroll on my iPhone or any other mobile device?

Thank you

Title: Mobile side-nav menu not scrolling

Body:
Hello I have this code

     ....

.mobile-menu-items-main-div {
            min-height: 100vh !important;
            height: 100% !important;

            overflow-y: auto !important;
            background-color: white;
            position: absolute !important;
        }
        .mobile-menu-items {
            min-height: 100vh !important;
            height: 100% !important;

            display: flex;
            flex-direction: column;
            overflow-y: auto !important;
            /*justify-content:space-between;*/
        }

.side-nav {
    position: fixed;
    width: 15rem;
    left: 0;
    top: 0;
    margin: 0;
    transform: translateX(-100%);
    height: 100%;
    background-color: #2c2f34;
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    z-index: 1040;
    backface-visibility: hidden;
    overflow: hidden;
    will-change: transform;
    backface-visibility: hidden;
    list-style-type: none;
    padding: 0;
    box-shadow: 0 2px 5px 0 rgb(0 0 0 / 16%), 0 2px 10px 0 rgb(0 0 0 / 12%);
}

Can somebody explain to me why I can scroll on the computer browser using responsive mode, but I can't scroll on my iPhone or any other mobile device?

Thank you


问:
MS Access file size limitation error despite linking tables from SQL Server
I have SQL Server tables (backend) linked to my MS Access frontend.

I am trying to import 9GB CSV file to my linked SQL Server table but in the middle of the importing I get file size limitation error, that my access file has exceeded 2 GB?!!!

What am I doing wrong here?

I tried to link my CSV file directly to MS Access and it worked but then I will have to use an append query to do the importing process by appending to my sql server table.

I would like to understand why I am getting this error


问:
Why do Tradingview VWAP standard deviation values not match excel STDEV?
I've searched all over stack overflow - but couldnt figure it out:

**The Tradingview (TV) built-in indicator VWAP (anchored at session start) standard deviation (e.g. included in Upper Band) does not match the standard deviation I get from Excel (STDEV()) using the same VWAP data:  **

VWAP
STDEV Excel
STDEV TV
Upper Band value TV
Upper Band Excel
Delta (expect 0)

3905.50
0.00
0.00
3905.50
3905.50
0

3905.29
0.15
0.34
3905.63
3905.44
0.19

3905.26
0.13
0.33
3905.60
3905.39
0.20

3905.35
0.11
0.42
3905.76
3905.45
0.31

3905.37
0.09
0.44.
3905.81
3905.47
0.35

3905.35
0.08
0.45
3905.80
3905.43
0.37

what I've tried:

I've checked Pinescript (https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}vwap)
but I cannot figure out what's happening within TA.vwap:

```<code>ta.vwap(source, anchor, stdev_mult) → [series float, series float, series float]
</code>```

I've used the different Excel formulas for standard deviation: STDEV(), STDEV.S(), and STDEV.P(), all with non-satisfactory results

Thank you for your help!

Body:
I've searched all over stack overflow - but couldnt figure it out:

**The Tradingview (TV) built-in indicator VWAP (anchored at session start) standard deviation (e.g. included in Upper Band) does not match the standard deviation I get from Excel (STDEV()) using the same VWAP data:  **

VWAP
STDEV Excel
STDEV TV
Upper Band value TV
Upper Band Excel
Delta (expect 0)

3905.50
0.00
0.00
3905.50
3905.50
0

3905.29
0.15
0.34
3905.63
3905.44
0.19

3905.26
0.13
0.33
3905.60
3905.39
0.20

3905.35
0.11
0.42
3905.76
3905.45
0.31

3905.37
0.09
0.44.
3905.81
3905.47
0.35

3905.35
0.08
0.45
3905.80
3905.43
0.37

what I've tried:

I've checked Pinescript (https://www.tradingview.com/pine-script-reference/v5/#fun_ta{dot}vwap)
but I cannot figure out what's happening within TA.vwap:

ta.vwap(source, anchor, stdev_mult) → [series float, series float, series float]

I've used the different Excel formulas for standard deviation: STDEV(), STDEV.S(), and STDEV.P(), all with non-satisfactory results

Thank you for your help!


问:
Mock axios with Typescript
In order to mock my rest call I'm using "axios-mock-adapter".

My service where I'm triggering the call looks like this:

```<code>export class ApiService {
    private static instance: ApiService
    private axiosInstance: AxiosInstance

    private constructor() {
        this.axiosInstance = axios.create({
            baseURL: '...'
            headers: {...}
        })
    }

    async getAll(apiRequests: ApiRequest<unknown>[]): Promise<void> {
        try {
            await Promise.all(apiRequests.map(apiRequest => {
                    return this.axiosInstance.get<typeof apiRequest.response>(apiRequest.path)
...
</code>```

Then, in my test:

```<code>import MockAdapter from 'axios-mock-adapter'

const mockAdapter = new MockAdapter(axios)

 it('should mock', async () => {
        // Given
        mockAdapter.onGet(/.*/).reply(404)

        // WHEN
        await expect(ApiService.getInstance().getAll([
            new ApiRequest('/test-1'),
            new ApiRequest('/test-2')
        ], false)).rejects.toThrow(Error('Request failed with status code 404'))

    })
</code>```

Here I receive this error:

```<code>mockAdapter.onGet is not a function
</code>```

Any idea how to solve this?

Title: Mock axios with Typescript

Body:
In order to mock my rest call I'm using "axios-mock-adapter".

My service where I'm triggering the call looks like this:

export class ApiService {
    private static instance: ApiService
    private axiosInstance: AxiosInstance

    private constructor() {
        this.axiosInstance = axios.create({
            baseURL: '...'
            headers: {...}
        })
    }

    async getAll(apiRequests: ApiRequest<unknown>[]): Promise<void> {
        try {
            await Promise.all(apiRequests.map(apiRequest => {
                    return this.axiosInstance.get<typeof apiRequest.response>(apiRequest.path)
...

Then, in my test:

import MockAdapter from 'axios-mock-adapter'

const mockAdapter = new MockAdapter(axios)

 it('should mock', async () => {
        // Given
        mockAdapter.onGet(/.*/).reply(404)

        // WHEN
        await expect(ApiService.getInstance().getAll([
            new ApiRequest('/test-1'),
            new ApiRequest('/test-2')
        ], false)).rejects.toThrow(Error('Request failed with status code 404'))

    })

Here I receive this error:

mockAdapter.onGet is not a function

Any idea how to solve this?


问:
How to cache on specific retrofit requests
So I'm trying to enable caching (online) but only for some specific requests.

I have this as my Interceptor:

```<code>    val request = chain.request()
    val token = tokenManager.getToken()
    return if (request.header("ApplyCache") == "True") {
            val originalResponse = chain.proceed(chain.request())
            println("retrieved from cache")
            originalResponse.newBuilder()
                .removeHeader("ApplyCache")
                .header("Cache-Control", "public, max-age=" + 60000)
                .header("Authorization", "Bearer $token")
                .build()

    }else {
       println("reetrieve without cache");
       return chain.proceed(chain.request().newBuilder()
           .addHeader("Authorization", "Bearer $token")
           .removeHeader("ApplyCache").build())
    }
</code>```

I'm adding ApplyCache: True on my GET requests as a header, and then cache the data based.

There's no error, and the data is retrieved without any problem, but it appears that the cache is not being used at all:

if I send a GET request /cities/ for example, add another city, and then GET /cities/ again... the city I added between the two requests is showing up, for some reason.

This is my OkHttpClient:

```<code>@Singleton
@Provides
fun provideOkHttpClient(interceptor: AuthInterceptor): OkHttpClient {
    return OkHttpClient.Builder().addInterceptor(interceptor).cache(Cache( File(
        getCacheDir(),
    "apiResponses"), 5 * 1024 * 1024))
    .build()
}
</code>```

Body:
So I'm trying to enable caching (online) but only for some specific requests.

I have this as my Interceptor:

    val request = chain.request()
    val token = tokenManager.getToken()
    return if (request.header("ApplyCache") == "True") {
            val originalResponse = chain.proceed(chain.request())
            println("retrieved from cache")
            originalResponse.newBuilder()
                .removeHeader("ApplyCache")
                .header("Cache-Control", "public, max-age=" + 60000)
                .header("Authorization", "Bearer $token")
                .build()

    }else {
       println("reetrieve without cache");
       return chain.proceed(chain.request().newBuilder()
           .addHeader("Authorization", "Bearer $token")
           .removeHeader("ApplyCache").build())
    }

I'm adding ApplyCache: True on my GET requests as a header, and then cache the data based.

There's no error, and the data is retrieved without any problem, but it appears that the cache is not being used at all:

if I send a GET request /cities/ for example, add another city, and then GET /cities/ again... the city I added between the two requests is showing up, for some reason.

This is my OkHttpClient:

@Singleton
@Provides
fun provideOkHttpClient(interceptor: AuthInterceptor): OkHttpClient {
    return OkHttpClient.Builder().addInterceptor(interceptor).cache(Cache( File(
        getCacheDir(),
    "apiResponses"), 5 * 1024 * 1024))
    .build()
}


问:
Gradle task overriding environment spring profile
I have a task in my build.gradle:

```<code>task integrationTest(type: Test) {
  systemProperty "spring.profiles.active", "postgres"
  testLogging {
      events = ["passed", "failed", "skipped"]
  }
  filter {
      includeTestsMatching "foo.bar.integration.*"
  }
  useJUnitPlatform()
}
</code>```

and want my spring application to run with the postgres profile when I run ./gradlew integrationTest however it runs with a test profile instead.

What is causing gradle to override my spring profile setting?

Body:
I have a task in my build.gradle:

task integrationTest(type: Test) {
  systemProperty "spring.profiles.active", "postgres"
  testLogging {
      events = ["passed", "failed", "skipped"]
  }
  filter {
      includeTestsMatching "foo.bar.integration.*"
  }
  useJUnitPlatform()
}

and want my spring application to run with the postgres profile when I run ./gradlew integrationTest however it runs with a test profile instead.

What is causing gradle to override my spring profile setting?


问:
MUI Autocomplete conflicts with Redux toolkit
I have an element that can return different components based on the type of my ElsRecord like this:

since it returns so many elements, I just showed one example

```<code>const DynamicFormCreator = ({
  filtered,
  NumberFormatCustom,
  setRadio,
  radio,
  myTheme,
}) => {
  return (
    <React.Fragment>
      {filtered !== undefined && (
        <>
          {filtered.ElsRecord.Type === "DataGridView" && (
            <ElsFormGrid
              filtered={filtered}
              NumberFormatCustom={NumberFormatCustom}
              setRadio={setRadio}
              radio={radio}
              myTheme={myTheme}
            />
          )}
        </>
      )}
    </React.Fragment>
  );
};

export default DynamicFormCreator;
</code>```

as you can see it returns a custom component called ElsFormGrid and the compnent itself have one of DynamicFormCreator inside of it:

```<code>{filtered.ListColumnInfo.map(
          (detail) =>
            detail.VisibleColumn && (
              <div key={uuidV4()}>
                <DynamicFormCreator
                  filtered={detail}
                  NumberFormatCustom={NumberFormatCustom}
                  setRadio={setRadio}
                  radio={radio}
                  myTheme={myTheme}
                />
              </div>
            )
        )}
</code>```

I do this because my form is dynamic. everything inside of it should come from API. and based on what data I receive, it generates components.

my problem is ElsFormGrid whenever I use useSelector to access my state from redux toolkit, it prevents autocomplete component of MUI to work.

```<code>const CustomAutoComplete = ({ filtered, uuidV4 }) => {
  const options = React.useMemo(() => {
    const memoOptions = filtered.ElsRecord.ListDefaultAnswer.map(
      ({ Name, ...rest }) => ({
        label: Name,
        ...rest,
      })
    );
    return memoOptions;
  }, [filtered]);
  const { FormDataHandler } = useElsFormDataHandler(filtered);
  return (
    <>
      <Autocomplete
        options={options}
        renderOption={(props, option) => {
          return (
            <li {...props} key={uuidV4()}>
              {option.label}
            </li>
          );
        }}
        renderInput={(params) => (
          <TextField {...params} label={filtered.ElsRecord.Name} fullWidth />
        )}
        fullWidth
        sx={{ mb: "10px" }}
        onChange={FormDataHandler}
        getOptionLabel={(option) => option.label}
      />
    </>
</code>```

the Autocomplete itself is also part of DynamicFormCreator which also generates when inside of ElsFormGrid

when I define useSelector inside of ElsFormGrid I can't select anything inside of AutoComplete component. even if I don't use it.

like this:

```<code>  const { ElsFormDetails } = useSelector((state) => state.ElsFormsDetails);
</code>```

whenever I define this line, I can't select anything with AutoComplete. when I select an option, it remains empty.

Body:
I have an element that can return different components based on the type of my ElsRecord like this:

since it returns so many elements, I just showed one example

const DynamicFormCreator = ({
  filtered,
  NumberFormatCustom,
  setRadio,
  radio,
  myTheme,
}) => {
  return (
    <React.Fragment>
      {filtered !== undefined && (
        <>
          {filtered.ElsRecord.Type === "DataGridView" && (
            <ElsFormGrid
              filtered={filtered}
              NumberFormatCustom={NumberFormatCustom}
              setRadio={setRadio}
              radio={radio}
              myTheme={myTheme}
            />
          )}
        </>
      )}
    </React.Fragment>
  );
};

export default DynamicFormCreator;

as you can see it returns a custom component called ElsFormGrid and the compnent itself have one of DynamicFormCreator inside of it:

{filtered.ListColumnInfo.map(
          (detail) =>
            detail.VisibleColumn && (

                <DynamicFormCreator
                  filtered={detail}
                  NumberFormatCustom={NumberFormatCustom}
                  setRadio={setRadio}
                  radio={radio}
                  myTheme={myTheme}
                />

            )
        )}

I do this because my form is dynamic. everything inside of it should come from API. and based on what data I receive, it generates components.

my problem is ElsFormGrid whenever I use useSelector to access my state from redux toolkit, it prevents autocomplete component of MUI to work.

const CustomAutoComplete = ({ filtered, uuidV4 }) => {
  const options = React.useMemo(() => {
    const memoOptions = filtered.ElsRecord.ListDefaultAnswer.map(
      ({ Name, ...rest }) => ({
        label: Name,
        ...rest,
      })
    );
    return memoOptions;
  }, [filtered]);
  const { FormDataHandler } = useElsFormDataHandler(filtered);
  return (
    <>
      <Autocomplete
        options={options}
        renderOption={(props, option) => {
          return (

              {option.label}

          );
        }}
        renderInput={(params) => (
          <TextField {...params} label={filtered.ElsRecord.Name} fullWidth />
        )}
        fullWidth
        sx={{ mb: "10px" }}
        onChange={FormDataHandler}
        getOptionLabel={(option) => option.label}
      />
    </>

the Autocomplete itself is also part of DynamicFormCreator which also generates when inside of ElsFormGrid

when I define useSelector inside of ElsFormGrid I can't select anything inside of AutoComplete component. even if I don't use it.

like this:

  const { ElsFormDetails } = useSelector((state) => state.ElsFormsDetails);

whenever I define this line, I can't select anything with AutoComplete. when I select an option, it remains empty.


问:
How to install a specific version of rpm on MacOS?
I currently have nom version 8.19.2 installed on my MacBook. I want to downgrade it to 8.11.0. I have looked up all the existing posts but nothing helped me.

I have tried:

```<code>npm install --global npm@8.11.0
</code>```

This says it has update some packages, but if I do npm --version I`ll get again 8.19.2. Same with update instead of install.

I have tried this also locally (above command without --global). But then I get npm error code 1

maybe there is something wrong with my $PATH variable, it looks like this when I do echo $PATH :

```<code>/Users/itsme/.yarn/bin:/Users/itsme/.config/yarn/global/node_modules/.bin:/Library/Frameworks/Python.framework/Versions/3.11/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/MacGPG2/bin
</code>```

I really need help and I am thankful for all answers :)

Body:
I currently have nom version 8.19.2 installed on my MacBook. I want to downgrade it to 8.11.0. I have looked up all the existing posts but nothing helped me.

I have tried:

npm install --global npm@8.11.0

This says it has update some packages, but if I do npm --version I`ll get again 8.19.2. Same with update instead of install.

I have tried this also locally (above command without --global). But then I get npm error code 1

maybe there is something wrong with my $PATH variable, it looks like this when I do echo $PATH :

/Users/itsme/.yarn/bin:/Users/itsme/.config/yarn/global/node_modules/.bin:/Library/Frameworks/Python.framework/Versions/3.11/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/MacGPG2/bin

I really need help and I am thankful for all answers :)


问:
Is it possible to open sheets with a hyperlink in the addon sidebar?
I want to use my addon sidebar to open a sheet when a text is clicked. I'm using this code:

```<code>`<a href="${ss().getUrl()}#gid=${ss().getSheetByName(sheets[i].getName()).getSheetId()}">Go</a>`
</code>```

(It's a dynamic url) I have not problems getting the URL of the sheet. But when I click the text it does not open the sheet.

I've also tried using a button that calls a function. This is working properly, but calling google.script.run to invoke activate() makes a 1-2 seconds lag, and it's annoying. That's why i was looking for a non-backend way to do this. (Or a backend alternative if you know how to avoid this lag).

```<code><button type="button" id="goToSheetButton" class="btn btn-primary"><i class="fa-solid fa-right-long"></i>

function goToSheet(sheetname) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  let sh = ss.getSheetByName(sheetname);
  sh.activate();
}
</code>```

Thanks!

Body:
I want to use my addon sidebar to open a sheet when a text is clicked. I'm using this code:

`<a href="${ss().getUrl()}#gid=${ss().getSheetByName(sheets[i].getName()).getSheetId()}">Go</a>`

(It's a dynamic url) I have not problems getting the URL of the sheet. But when I click the text it does not open the sheet.

I've also tried using a button that calls a function. This is working properly, but calling google.script.run to invoke activate() makes a 1-2 seconds lag, and it's annoying. That's why i was looking for a non-backend way to do this. (Or a backend alternative if you know how to avoid this lag).

<button type="button" id="goToSheetButton" class="btn btn-primary">

function goToSheet(sheetname) {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  let sh = ss.getSheetByName(sheetname);
  sh.activate();
}

Thanks!


问:
Injecting dynamic value in tailwind CSS styles
I have a variable, NAV_HEIGHT which holds a value I need to inject into multiple tailwind styles.

```<code>import { NAV_HEIGHT } from '../../constants'

const Nav = () => {
  return (
    <nav className={`h-${NAV_HEIGHT} fixed bg-blue-500 w-full`}>
...
</code>```

in another component I need the value of NAV_HEIGHT to be applied to a pt-${NAV_HEIGHT}

Which is the best practice for doing this?

Body:
I have a variable, NAV_HEIGHT which holds a value I need to inject into multiple tailwind styles.

import { NAV_HEIGHT } from '../../constants'

const Nav = () => {
  return (
    <nav className={`h-${NAV_HEIGHT} fixed bg-blue-500 w-full`}>
...

in another component I need the value of NAV_HEIGHT to be applied to a pt-${NAV_HEIGHT}

Which is the best practice for doing this?


问:
Does Spark support lifecycle hook functions?
In Spark, is it possible to register certain code to run within certain parts of the job lifecycle - say when a new executor starts, when an executor shuts down, when a new partition is about to be processed...etc?

Currently there are methods like forEachPartition or forEachRdd but you have to infer their execution context implicitly, and any hook code has to be written inline rather than registered separately.


问:
"tf.cond" in "tf.compat.v1.train.Optimizer" produces "ValueError: None values not supported" for TF2 but not for TF1.15
Requirement:
I want to override the variable update behavior of TF optimizers such as
tf.compat.v1.train.GradientDescentOptimizer and
tf.compat.v1.train.AdamOptimizer.
A simple example is to do the gradient update for even values of global_step and simply not do the the gradient update for odd values of global_step. See the following code that implements this logic.

Problem:
The code runs fine (without errors) with TF1.15, but produces the error shown below with TF2 (Python version: 3.9.13, TF2 version: 2.11.0). Any ideas why this is the case?

Code to run:

```<code>import tensorflow as tf
from tensorflow.python.framework import ops
tf.compat.v1.disable_eager_execution()

# No errors if used tf.compat.v1.train.GradientDescentOptimizer
class MyOptimizer(tf.compat.v1.train.AdamOptimizer):

    def _resource_apply_dense(self, grad, var):
        return self.update(super()._resource_apply_dense, grad, var)

    def _apply_dense(self, grad, var):
        return self.update(super()._apply_dense, grad, var)

    def update(self, apply_func, grad, var):

        ctrl_dep = ops.control_dependencies

        def odd_fn():
            return tf.no_op()

        def even_fn():
            with ctrl_dep([apply_func(grad, var)]):
                return tf.no_op()

        # update gradient only in even steps
        return tf.cond(pred=tf.equal(global_step%2, 0), true_fn=even_fn, false_fn=odd_fn)

global_step = tf.Variable(0, name='global_step', trainable=False)
learning_rate = tf.compat.v1.placeholder(tf.float32, shape=[])
loss = (tf.Variable(0.)-10.)**2 # loss for some model with only one variable
train_op = MyOptimizer(learning_rate).minimize(loss, global_step)
</code>```

Traceback of the error with TF2:

```<code>Traceback (most recent call last):
  File "/home/src/zz.py", line 34, in <module>
    train_op = MyOptimizer(learning_rate).minimize(loss, global_step)
  File "/home/user/anaconda3/lib/python3.9/site-packages/tensorflow/python/training/optimizer.py", line 486, in minimize
    return self.apply_gradients(grads_and_vars, global_step=global_step,
  File "/home/user/anaconda3/lib/python3.9/site-packages/tensorflow/python/training/optimizer.py", line 716, in apply_gradients
    update_ops.append(processor.update_op(self, grad))
  File "/home/user/anaconda3/lib/python3.9/site-packages/tensorflow/python/training/optimizer.py", line 172, in update_op
    update_op = optimizer._resource_apply_dense(g, self._v)
  File "/home/src/zz.py", line 10, in _resource_apply_dense
    return self.update(super()._resource_apply_dense, grad, var)
  File "/home/src/zz.py", line 28, in update
    return tf.cond(pred=tf.equal(global_step%2, 0), true_fn=even_fn, false_fn=odd_fn)
  File "/home/user/anaconda3/lib/python3.9/site-packages/tensorflow/python/util/traceback_utils.py", line 153, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "/home/src/zz.py", line 24, in even_fn
    with ctrl_dep([apply_func(grad, var)]):
ValueError: None values not supported.
</code>```

Other observations:
Code runs fine on both TF versions if tf.compat.v1.train.GradientDescentOptimizer is used (instead of tf.compat.v1.train.AdamOptimizer) as the parent class of MyOptimizer.

Related questions:
The closest related question I found is the one here, but it doesn't explain why I see different behaviors for different TF versions and two optimizer types.

Body:
Requirement:
I want to override the variable update behavior of TF optimizers such as
tf.compat.v1.train.GradientDescentOptimizer and
tf.compat.v1.train.AdamOptimizer.
A simple example is to do the gradient update for even values of global_step and simply not do the the gradient update for odd values of global_step. See the following code that implements this logic.

Problem:
The code runs fine (without errors) with TF1.15, but produces the error shown below with TF2 (Python version: 3.9.13, TF2 version: 2.11.0). Any ideas why this is the case?

Code to run:

import tensorflow as tf
from tensorflow.python.framework import ops
tf.compat.v1.disable_eager_execution()

# No errors if used tf.compat.v1.train.GradientDescentOptimizer
class MyOptimizer(tf.compat.v1.train.AdamOptimizer):

    def _resource_apply_dense(self, grad, var):
        return self.update(super()._resource_apply_dense, grad, var)

    def _apply_dense(self, grad, var):
        return self.update(super()._apply_dense, grad, var)

    def update(self, apply_func, grad, var):

        ctrl_dep = ops.control_dependencies

        def odd_fn():
            return tf.no_op()

        def even_fn():
            with ctrl_dep([apply_func(grad, var)]):
                return tf.no_op()

        # update gradient only in even steps
        return tf.cond(pred=tf.equal(global_step%2, 0), true_fn=even_fn, false_fn=odd_fn)

global_step = tf.Variable(0, name='global_step', trainable=False)
learning_rate = tf.compat.v1.placeholder(tf.float32, shape=[])
loss = (tf.Variable(0.)-10.)**2 # loss for some model with only one variable
train_op = MyOptimizer(learning_rate).minimize(loss, global_step)

Traceback of the error with TF2:

Traceback (most recent call last):
  File "/home/src/zz.py", line 34, in <module>
    train_op = MyOptimizer(learning_rate).minimize(loss, global_step)
  File "/home/user/anaconda3/lib/python3.9/site-packages/tensorflow/python/training/optimizer.py", line 486, in minimize
    return self.apply_gradients(grads_and_vars, global_step=global_step,
  File "/home/user/anaconda3/lib/python3.9/site-packages/tensorflow/python/training/optimizer.py", line 716, in apply_gradients
    update_ops.append(processor.update_op(self, grad))
  File "/home/user/anaconda3/lib/python3.9/site-packages/tensorflow/python/training/optimizer.py", line 172, in update_op
    update_op = optimizer._resource_apply_dense(g, self._v)
  File "/home/src/zz.py", line 10, in _resource_apply_dense
    return self.update(super()._resource_apply_dense, grad, var)
  File "/home/src/zz.py", line 28, in update
    return tf.cond(pred=tf.equal(global_step%2, 0), true_fn=even_fn, false_fn=odd_fn)
  File "/home/user/anaconda3/lib/python3.9/site-packages/tensorflow/python/util/traceback_utils.py", line 153, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "/home/src/zz.py", line 24, in even_fn
    with ctrl_dep([apply_func(grad, var)]):
ValueError: None values not supported.

Other observations:
Code runs fine on both TF versions if tf.compat.v1.train.GradientDescentOptimizer is used (instead of tf.compat.v1.train.AdamOptimizer) as the parent class of MyOptimizer.

Related questions:
The closest related question I found is the one here, but it doesn't explain why I see different behaviors for different TF versions and two optimizer types.


问:
nginx controller in k8 TLS version issue
I have installed a nginx controller using the following link:

https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nginx-ingress-with-cert-manager-on-digitalocean-kubernetes

And I have added a NLB with TLS termination. Everything works as expected and I can ping the NLB domain but when I ping my domain with https although all the cert-manager settings are correct I receive the following error:

```<code>lij43@NCATS-2170711-M ~ % curl -v -I https://nginx-ing-poc.ncats.io/
*   Trying 52.72.56.47:443...
* Connected to nginx-ing-poc.ncats.io (52.72.56.47) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*  CAfile: /etc/ssl/cert.pem
*  CApath: none
* (304) (OUT), TLS handshake, Client hello (1):
* error:1404B42E:SSL routines:ST_CONNECT:tlsv1 alert protocol version
* Closing connection 0
curl: (35) error:1404B42E:SSL routines:ST_CONNECT:tlsv1 alert protocol version
</code>```

I expect to see the output as echo1 which is mentioned id DO's instructions.

Body:
I have installed a nginx controller using the following link:

https://www.digitalocean.com/community/tutorials/how-to-set-up-an-nginx-ingress-with-cert-manager-on-digitalocean-kubernetes

And I have added a NLB with TLS termination. Everything works as expected and I can ping the NLB domain but when I ping my domain with https although all the cert-manager settings are correct I receive the following error:

lij43@NCATS-2170711-M ~ % curl -v -I https://nginx-ing-poc.ncats.io/
*   Trying 52.72.56.47:443...
* Connected to nginx-ing-poc.ncats.io (52.72.56.47) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*  CAfile: /etc/ssl/cert.pem
*  CApath: none
* (304) (OUT), TLS handshake, Client hello (1):
* error:1404B42E:SSL routines:ST_CONNECT:tlsv1 alert protocol version
* Closing connection 0
curl: (35) error:1404B42E:SSL routines:ST_CONNECT:tlsv1 alert protocol version

I expect to see the output as echo1 which is mentioned id DO's instructions.


问:
Angular not working as expected in production
So, my project is working just fine in development, but i production, angular connects to socket.io just fine, but not doing anything. No socket.emit or socket.on none of then works.

Can you tell me why?

Heres the website: https://new.chatenium.hu

The lang is set to HU by default, but change it to english in the homapage (it forgets the selected lang after refresh, bc its not finished, its just up for testing).

I dont run the api all day for now, so let me know if its not running!

Thanks!


问:
Userid already exists when trying to create posts with a single user (TYPEORM)
I have two entities in my application, a user and a post. In my Post entity I have the "user" column that receives the user id as a parameter through OneToOne

```<code>import { Column, CreateDateColumn, Entity, JoinColumn, OneToOne, PrimaryGeneratedColumn } from "typeorm";
import { User } from "./User";

@Entity('posts')
export class Post {
    @PrimaryGeneratedColumn('uuid')
    id: string;

    @OneToOne(() => User)
    @JoinColumn()
    user: User

    @Column()
    title: string;

    @Column()
    desc: string;

    @CreateDateColumn({
        type: 'timestamp',
        precision: 3
      })
      createdAt: Date;
}
</code>```

I created the post creation controller, and it worked perfectly, but the problem is that I can only make one post for each user, if I try to create another post with the same user id that has already created a post before, it returns me the error:

```<code>    "detail": "Key (\"userId\")=(ffbe9e3d-13e5-4bec-b69d-990992327649) already exists.",

</code>```

ffbe9e3d-13e5-4bec-b69d-990992327649 is the user id

controller

```<code>import { Request, Response } from "express";
import { Post } from "../../entities/Post";
import { AppDataSource } from "../../database/config";

class CreatePostController {
    async store(req: Request, res: Response) {
        const { user, title, desc } = req.body;
        const post = new Post();

        try {
            post.user = user;
            post.title = title;
            post.desc = desc;

            await AppDataSource.manager.save(post);

            return res.status(200).json(post);
        } catch (err) {
            return res.status(500).json(err);
        }

    }
}

export default new CreatePostController();
</code>```

How can I make my application accept multiple posts from the same user id?

Body:
I have two entities in my application, a user and a post. In my Post entity I have the "user" column that receives the user id as a parameter through OneToOne

import { Column, CreateDateColumn, Entity, JoinColumn, OneToOne, PrimaryGeneratedColumn } from "typeorm";
import { User } from "./User";

@Entity('posts')
export class Post {
    @PrimaryGeneratedColumn('uuid')
    id: string;

    @OneToOne(() => User)
    @JoinColumn()
    user: User

    @Column()
    title: string;

    @Column()
    desc: string;

    @CreateDateColumn({
        type: 'timestamp',
        precision: 3
      })
      createdAt: Date;
}

I created the post creation controller, and it worked perfectly, but the problem is that I can only make one post for each user, if I try to create another post with the same user id that has already created a post before, it returns me the error:

    "detail": "Key (\"userId\")=(ffbe9e3d-13e5-4bec-b69d-990992327649) already exists.",

ffbe9e3d-13e5-4bec-b69d-990992327649 is the user id

controller

import { Request, Response } from "express";
import { Post } from "../../entities/Post";
import { AppDataSource } from "../../database/config";

class CreatePostController {
    async store(req: Request, res: Response) {
        const { user, title, desc } = req.body;
        const post = new Post();

        try {
            post.user = user;
            post.title = title;
            post.desc = desc;

            await AppDataSource.manager.save(post);

            return res.status(200).json(post);
        } catch (err) {
            return res.status(500).json(err);
        }

    }
}

export default new CreatePostController();

How can I make my application accept multiple posts from the same user id?


问:
TypeScript globally vs locally
I really don't understand about installing typescript globally or locally.

What is the different to install typescript globally and locally?

Any cons and/or pros?

What context is relevant to use globally or locally?

Thank you!

```<code>* To install TypeScript globally, run:
$ npm i typescript -g

*And to install locally, run:
$ npm i typescript --save-dev
</code>```

Title: TypeScript globally vs locally

Body:
I really don't understand about installing typescript globally or locally.

What is the different to install typescript globally and locally?

Any cons and/or pros?

What context is relevant to use globally or locally?

Thank you!

* To install TypeScript globally, run:
$ npm i typescript -g

*And to install locally, run:
$ npm i typescript --save-dev


问:
Python: reconstruct image from difference
Using the following code I calculated the difference matrix between two images:

```<code>import time
import cv2
from imutils.video import VideoStream
from skimage.metrics import structural_similarity
from skimage.color import rgb2gray

cap = VideoStream(src=0, framerate=30).start()
cap.stream.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

time.sleep(2)

image1 = cap.read()
time.sleep(0.1)
image2 = cap.read()

image1_gray = rgb2gray(image1)
image2_gray = rgb2gray(image2)

score, difference = structural_similarity(image1_gray, image2_gray, full=True)
</code>```

Now I need to apply this difference to the second image in order to extract a (480,640,3) RGB image, where the only colored pixels are the different ones extracted, and the others are "empty" (black or transparent maybe?).

Is there any way to do this since the difference calculated is a 1 channel image (480,640)?
I should also replace those pixels to the first image, any ideas?

EDIT:

I also tryed this approach:

```<code>encode_params = [int(cv2.IMWRITE_JPEG_QUALITY), 80,
                 int(cv2.IMWRITE_JPEG_PROGRESSIVE), 1]

# to calculate diff:
diff = cv2.absdiff(frame1, frame2)
_, buffer = cv2.imencode('.jpg', diff, encode_params)

# to recontruct the image
diff = cv2.imdecode(buffer, cv2.IMREAD_COLOR)
prev_frame[diff != 0] = diff[diff != 0]
</code>```

but the result is not as expected

Body:
Using the following code I calculated the difference matrix between two images:

import time
import cv2
from imutils.video import VideoStream
from skimage.metrics import structural_similarity
from skimage.color import rgb2gray

cap = VideoStream(src=0, framerate=30).start()
cap.stream.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.stream.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

time.sleep(2)

image1 = cap.read()
time.sleep(0.1)
image2 = cap.read()

image1_gray = rgb2gray(image1)
image2_gray = rgb2gray(image2)

score, difference = structural_similarity(image1_gray, image2_gray, full=True)

Now I need to apply this difference to the second image in order to extract a (480,640,3) RGB image, where the only colored pixels are the different ones extracted, and the others are "empty" (black or transparent maybe?).

Is there any way to do this since the difference calculated is a 1 channel image (480,640)?
I should also replace those pixels to the first image, any ideas?

EDIT:

I also tryed this approach:

encode_params = [int(cv2.IMWRITE_JPEG_QUALITY), 80,
                 int(cv2.IMWRITE_JPEG_PROGRESSIVE), 1]

# to calculate diff:
diff = cv2.absdiff(frame1, frame2)
_, buffer = cv2.imencode('.jpg', diff, encode_params)

# to recontruct the image
diff = cv2.imdecode(buffer, cv2.IMREAD_COLOR)
prev_frame[diff != 0] = diff[diff != 0]

but the result is not as expected


问:
How do I allow the user to select a file save location?
I have the following code, but I need to allow the user to choose where they want the .csv file saved.

```<code>    public void ExportData()
    {
        Init();

        TableQuery<Record> Records = conn.Table<Record>();

        List<Record> records = Records.ToList();

        string csvFilePath = System.IO.Path.Combine(FileSystem.AppDataDirectory, "export.csv");

        using (StreamWriter writer = new StreamWriter(csvFilePath))
        {
            // Write the column headers to the CSV file
            // writer.WriteLine("Id,Amount,Paid,PurchaseDate");

            // Loop through the list of records and write each record to the CSV file
            foreach (Record record in Records)
            {
                writer.WriteLine("{0},{1},{2}", record.Amount, record.Paid, record.PurchaseDate);
            }
        }

        conn.Close();
    }
</code>```

Anyone know how to do that?

EDIT:

The solutions provided in the comments below seem to be Windows and MacOS based.  I am looking for an Android based solution.

Body:
I have the following code, but I need to allow the user to choose where they want the .csv file saved.

    public void ExportData()
    {
        Init();

        TableQuery<Record> Records = conn.Table<Record>();

        List<Record> records = Records.ToList();

        string csvFilePath = System.IO.Path.Combine(FileSystem.AppDataDirectory, "export.csv");

        using (StreamWriter writer = new StreamWriter(csvFilePath))
        {
            // Write the column headers to the CSV file
            // writer.WriteLine("Id,Amount,Paid,PurchaseDate");

            // Loop through the list of records and write each record to the CSV file
            foreach (Record record in Records)
            {
                writer.WriteLine("{0},{1},{2}", record.Amount, record.Paid, record.PurchaseDate);
            }
        }

        conn.Close();
    }

Anyone know how to do that?

EDIT:

The solutions provided in the comments below seem to be Windows and MacOS based.  I am looking for an Android based solution.


问:
Can not import ibd to mysql in xampp
I got a wordpress website, today it give me an error on xampp, I managed to re-install xampp, before this, I create a backup from mysql/data db folders, it contains ibd and frm files, I installed fresh xampp and I paste those db folders to mysql/data but when I open phpmyadmin it won't let open any tables and give me an error:

#1932 - Table ... doesn't exist in engine

I googled about 3hrs and figured out I can restore lost data from ibd file, so I follow instruction from this article but after run ALTER TABLE table_name IMPORT TABLESPACE; it give me another error:

internal error: Drop all secondary indexes before importing table

I am not mysql expert, I don't know how to restore my data, at least from wp_posts and wp_postmeta with these ibd files, I got very important data on this table, my bad is never run a sql backup before this happen! now I wondering if there is a way to restore data from those files or I failed? is there any hope?

I would be thankful for any help!

Title: Can not import ibd to mysql in xampp


问:
excel VBA - Copy row above, with formula | From Sheet 1 Insert into Sheets 4, 6 | Delete row on Sheet 1 also deleting row Sheet 4, 6
Sheet 1 copy down code works on Sheet 1. The same code does not work on other sheets. The delete row code deletes the Sheet 1 row however the Sheet 4 and 6 row deletion create errors across other rows on Sheet 4 and 6.

I need the VBA code to copy the row above when the command button is clicked as if I inserted a row and copied the row above into that new row. However, I need the new row to ignore the value in the copied row cells that have formulas, leaving only the copied formula in the new cell.

I need the VBA Code for Delete Row to delete a row on sheet 1 and delete that same row on Sheets 4 and 6 without creating errors across other row.

Current Code:

```<code>Sub CopyDown()

    SelRow = ActiveCell.Row
        HideButtons
        MoveButtons

    With ActiveSheet
        ActiveSheet.Range(SelRow & ":" & SelRow).Copy
        ActiveSheet.Range(SelRow & ":" & SelRow).Insert xlDown
        Application.CutCopyMode = False
        DisplayButtons

    End With

    Calculations.Range(SelRow - 4 & ":" & SelRow - 4).Copy
    Calculations.Range(SelRow - 4 & ":" & SelRow - 4).Insert xlDown
</code>```
```<code>Sub DeleteRow()

    SelRow = ActiveCell.Row
    MoveButtons
    ActiveSheet.Range(SelRow & ":" & SelRow).EntireRow.Delete
    ActiveSheet.Range("A" & SelRow).Select
    DisplayButtons

    Calculations.Range(SelRow - 4 & ":" & SelRow - 4).EntireRow.Delete
    CostSummary.Range(SelRow - 4 & ":" & SelRow - 4).EntireRow.Delete

End Sub
</code>```

Copy Down:

I have adjusted the formula on the sheet 1 (Base Year), Cell J11 to read:

=INDIRECT("Calculations!I" & ROW()-4)

Sheet 4 is titled Calculations and the input data for the Sheet 1 cell is found in column I.

On Sheets 2 (Option Yr) I adjusted the formula of Cell J11 to read:

=INDIRECT("Calculations!I" & ROW()+36)

On Sheet 4 (Calculations) the input data for Cell J11 was adjusted from -4 to +36. This adkustment corresponds with the J11 cell of the Option yr.

Delete Row:

I do not know of a solution to try since the VBA code deletes the row correctly on Sheet 1 (IGCE) and on the correct Calculations sheet table associated with the IGCE.

Body:
Sheet 1 copy down code works on Sheet 1. The same code does not work on other sheets. The delete row code deletes the Sheet 1 row however the Sheet 4 and 6 row deletion create errors across other rows on Sheet 4 and 6.

I need the VBA code to copy the row above when the command button is clicked as if I inserted a row and copied the row above into that new row. However, I need the new row to ignore the value in the copied row cells that have formulas, leaving only the copied formula in the new cell.

I need the VBA Code for Delete Row to delete a row on sheet 1 and delete that same row on Sheets 4 and 6 without creating errors across other row.

Current Code:

Sub CopyDown()

    SelRow = ActiveCell.Row
        HideButtons
        MoveButtons

    With ActiveSheet
        ActiveSheet.Range(SelRow & ":" & SelRow).Copy
        ActiveSheet.Range(SelRow & ":" & SelRow).Insert xlDown
        Application.CutCopyMode = False
        DisplayButtons

    End With

    Calculations.Range(SelRow - 4 & ":" & SelRow - 4).Copy
    Calculations.Range(SelRow - 4 & ":" & SelRow - 4).Insert xlDown

Sub DeleteRow()

    SelRow = ActiveCell.Row
    MoveButtons
    ActiveSheet.Range(SelRow & ":" & SelRow).EntireRow.Delete
    ActiveSheet.Range("A" & SelRow).Select
    DisplayButtons

    Calculations.Range(SelRow - 4 & ":" & SelRow - 4).EntireRow.Delete
    CostSummary.Range(SelRow - 4 & ":" & SelRow - 4).EntireRow.Delete

End Sub

Copy Down:

I have adjusted the formula on the sheet 1 (Base Year), Cell J11 to read:

=INDIRECT("Calculations!I" & ROW()-4)

Sheet 4 is titled Calculations and the input data for the Sheet 1 cell is found in column I.

On Sheets 2 (Option Yr) I adjusted the formula of Cell J11 to read:

=INDIRECT("Calculations!I" & ROW()+36)

On Sheet 4 (Calculations) the input data for Cell J11 was adjusted from -4 to +36. This adkustment corresponds with the J11 cell of the Option yr.

Delete Row:

I do not know of a solution to try since the VBA code deletes the row correctly on Sheet 1 (IGCE) and on the correct Calculations sheet table associated with the IGCE.


问:
Flutter PDF Viewer with Slider?
So, i loaded a pdf file in my flutter app and i want to move the pages with a slider

here is my approach:

`

```<code>              Slider(
                  value: _currentSliderValue,
                  min: 0,
                  max: _pdfViewController.pageCount.toDouble(),
                  onChanged: ((value) {
                    setState(() {
                      _currentSliderValue = value;
                      value = _pdfViewController.pageNumber.toDouble();
                    });
                  }))
</code>```

`

i have tried to set the page number value with slider value but when i do that the slider stops moving completely.

Title: Flutter PDF Viewer with Slider?

Body:
So, i loaded a pdf file in my flutter app and i want to move the pages with a slider

here is my approach:

`

              Slider(
                  value: _currentSliderValue,
                  min: 0,
                  max: _pdfViewController.pageCount.toDouble(),
                  onChanged: ((value) {
                    setState(() {
                      _currentSliderValue = value;
                      value = _pdfViewController.pageNumber.toDouble();
                    });
                  }))

`

i have tried to set the page number value with slider value but when i do that the slider stops moving completely.


问:
How to create a subtraction formula in R that is conditional?
I want to create a variable which has as value the distance between two other variables that are already there. I know I have to calculate the difference between the two variables to get the distance. Now the problem is that I need to make sure, that the first value is bigger than the second one:

```<code>Distance = ( X (if X bigger than Y, otherwise Y) – Y ( if Y smaller than X, otherwise X)
</code>```

Does anyone know how to translate the conditions into an R-formula?

I have tried a normal R formula for a subtraction:

```<code>coilp5 <- mutate(coilp5, dist. = X - Y)
</code>```

but then I get values I cannot work with, if the X is smaller than the Y

Body:
I want to create a variable which has as value the distance between two other variables that are already there. I know I have to calculate the difference between the two variables to get the distance. Now the problem is that I need to make sure, that the first value is bigger than the second one:

Distance = ( X (if X bigger than Y, otherwise Y) – Y ( if Y smaller than X, otherwise X)

Does anyone know how to translate the conditions into an R-formula?

I have tried a normal R formula for a subtraction:

coilp5 <- mutate(coilp5, dist. = X - Y)

but then I get values I cannot work with, if the X is smaller than the Y


问:
Please explain why RSS can not be used to compare models for test data
Quick question here. I can see many times that RSS can be used to compare the models with training data, but RSS is not for test data. Can anyone explain me?

I read multiple text books, but I can not intuitively understand them. It'll be great if you provide any examples or codes. Also, if you know any links that explain well will be great.