问:
Connecting otel agent with otel collector
I have followed all the steps mentioned in this medium article: https://medium.com/@guilospanck/telemetry-with-opentelemetry-prometheus-and-jaeger-46a2d9dec86b

My application is supposed to send trace data to collector and collector is supposed to send them to jaeger and prometheus.

However I am unable to send any traces to the collector. My tracer.properties file has following config:

```<code># debugging
#otel.javaagent.debug=true

#prod
otel.traces.exporter=otlp,logging
otel.metrics.exporter=otlp,logging
otel.logs.exporter=none
otel.service.name=service1
#otel.exporter.jaeger.endpoint=http://localhost:14278
#otel.exporter.jaeger.timeout=10000
#otel.propagators=jaeger
otel.exporter.otlp.traces.endpoint=http://localhost:14278
otel.exporter.otlp.metrics.endpoint=http://localhost:14278
otel.exporter.otlp.traces.protocol=grpc
otel.exporter.otlp.metrics.protocol=grpc
</code>```

Whenever I try to send data I get following error:

```<code>[otel.javaagent 2023-01-03 10:27:00:271 +0530] [http-nio-8081-exec-2] INFO io.opentelemetry.exporter.logging.LoggingSpanExporter - '/' : ee593fc59976ce74468789cae3dc67d9 6b6a159470d9545b SERVER [tracer: io.opentelemetry.tomcat-10.0:1.20.2-alpha] AttributesMap{data={net.sock.host.addr=127.0.0.1, http.user_agent=Java/17.0.5, http.route=/, http.method=GET, http.scheme=http, net.host.name=localhost, net.transport=ip_tcp, http.status_code=200, net.host.port=8081, http.target=/, net.sock.peer.addr=127.0.0.1, http.flavor=1.1, http.response_content_length=134, thread.name=http-nio-8081-exec-2, thread.id=26, net.sock.peer.port=61816}, capacity=128, totalAddedValues=16}
[otel.javaagent 2023-01-03 10:27:04:689 +0530] [OkHttp http://localhost:14278/...] ERROR io.opentelemetry.exporter.internal.grpc.OkHttpGrpcExporter - Failed to export spans. The request could not be executed. Full error message: FRAME_SIZE_ERROR: 4740180
</code>```

In the medium article author tries to connect a go application but here I try to connect a java application. Other than that there is no change in both of our setup.

I am able to connect directly with jaeger-all-in-one and get trace data (check commented out config in tracer.properties). Issue is connecting via collector

Body:
I have followed all the steps mentioned in this medium article: https://medium.com/@guilospanck/telemetry-with-opentelemetry-prometheus-and-jaeger-46a2d9dec86b

My application is supposed to send trace data to collector and collector is supposed to send them to jaeger and prometheus.

However I am unable to send any traces to the collector. My tracer.properties file has following config:

# debugging
#otel.javaagent.debug=true

#prod
otel.traces.exporter=otlp,logging
otel.metrics.exporter=otlp,logging
otel.logs.exporter=none
otel.service.name=service1
#otel.exporter.jaeger.endpoint=http://localhost:14278
#otel.exporter.jaeger.timeout=10000
#otel.propagators=jaeger
otel.exporter.otlp.traces.endpoint=http://localhost:14278
otel.exporter.otlp.metrics.endpoint=http://localhost:14278
otel.exporter.otlp.traces.protocol=grpc
otel.exporter.otlp.metrics.protocol=grpc

Whenever I try to send data I get following error:

[otel.javaagent 2023-01-03 10:27:00:271 +0530] [http-nio-8081-exec-2] INFO io.opentelemetry.exporter.logging.LoggingSpanExporter - '/' : ee593fc59976ce74468789cae3dc67d9 6b6a159470d9545b SERVER [tracer: io.opentelemetry.tomcat-10.0:1.20.2-alpha] AttributesMap{data={net.sock.host.addr=127.0.0.1, http.user_agent=Java/17.0.5, http.route=/, http.method=GET, http.scheme=http, net.host.name=localhost, net.transport=ip_tcp, http.status_code=200, net.host.port=8081, http.target=/, net.sock.peer.addr=127.0.0.1, http.flavor=1.1, http.response_content_length=134, thread.name=http-nio-8081-exec-2, thread.id=26, net.sock.peer.port=61816}, capacity=128, totalAddedValues=16}
[otel.javaagent 2023-01-03 10:27:04:689 +0530] [OkHttp http://localhost:14278/...] ERROR io.opentelemetry.exporter.internal.grpc.OkHttpGrpcExporter - Failed to export spans. The request could not be executed. Full error message: FRAME_SIZE_ERROR: 4740180

In the medium article author tries to connect a go application but here I try to connect a java application. Other than that there is no change in both of our setup.

I am able to connect directly with jaeger-all-in-one and get trace data (check commented out config in tracer.properties). Issue is connecting via collector


来源: stackexchange

问:
Confluent Control Center is throwing partial metrics- only getting overview page details when we connect multiple kafka clusters
Kafka Control Center is not showing topic names, Active Controller Details when we connect multiple kafka clusters in the single control center.

But cluster overview page is working fine.

Here are the configurations i have provided to send metrics of second cluster to main cluster control center:

```<code>        - name: CONFLUENT_METRICS_REPORTER_BOOTSTRAP_SERVERS
          value: SSL://kafka-ccc-cp-kafka-headless:9093
        - name: CONFLUENT_METRICS_REPORTER_SECURITY_PROTOCOL
          value: SSL
        - name: CONFLUENT_METRICS_REPORTER_SSL_TRUSTSTORE_LOCATION
          value: /etc/kafka/secrets2/kafka.server.truststore.jks
        - name: CONFLUENT_METRICS_REPORTER_SSL_TRUSTSTORE_PASSWORD
          valueFrom:
            secretKeyRef:
              key: broker.truststore.password
              name: kafka-ccc-kafka-ssl-secret
        - name: CONFLUENT_METRICS_REPORTER_SSL_KEYSTORE_LOCATION
          value: /etc/kafka/secrets2/kafka.server.keystore.jks
</code>```

Here

```<code>        - name: CONFLUENT_METRICS_REPORTER_BOOTSTRAP_SERVERS
          value: SSL://kafka-ccc-cp-kafka-headless:9093
</code>```

is the main cluster where the control center is and am sending metrics to that cluster. Its able to connect to that cluster and getting overview page and no of topics and other details which is in overview page. But when i click Topics -> its not showing topic names and topic names are blank.

is the main cluster where the control center is and am sending metrics from secondary cluster(kafka-test) to that cluster. Its able to connect to that cluster and getting overview page and no of topics and other details which is in overview page. But when i click Topics -> its not showing topic names and topic names are blank.

ContentLicense: CC BY-SA 4.0

Body:
Kafka Control Center is not showing topic names, Active Controller Details when we connect multiple kafka clusters in the single control center.

But cluster overview page is working fine.

Here are the configurations i have provided to send metrics of second cluster to main cluster control center:

        - name: CONFLUENT_METRICS_REPORTER_BOOTSTRAP_SERVERS
          value: SSL://kafka-ccc-cp-kafka-headless:9093
        - name: CONFLUENT_METRICS_REPORTER_SECURITY_PROTOCOL
          value: SSL
        - name: CONFLUENT_METRICS_REPORTER_SSL_TRUSTSTORE_LOCATION
          value: /etc/kafka/secrets2/kafka.server.truststore.jks
        - name: CONFLUENT_METRICS_REPORTER_SSL_TRUSTSTORE_PASSWORD
          valueFrom:
            secretKeyRef:
              key: broker.truststore.password
              name: kafka-ccc-kafka-ssl-secret
        - name: CONFLUENT_METRICS_REPORTER_SSL_KEYSTORE_LOCATION
          value: /etc/kafka/secrets2/kafka.server.keystore.jks

Here

        - name: CONFLUENT_METRICS_REPORTER_BOOTSTRAP_SERVERS
          value: SSL://kafka-ccc-cp-kafka-headless:9093

is the main cluster where the control center is and am sending metrics to that cluster. Its able to connect to that cluster and getting overview page and no of topics and other details which is in overview page. But when i click Topics -> its not showing topic names and topic names are blank.

is the main cluster where the control center is and am sending metrics from secondary cluster(kafka-test) to that cluster. Its able to connect to that cluster and getting overview page and no of topics and other details which is in overview page. But when i click Topics -> its not showing topic names and topic names are blank.


问:
Some parts Python's yfinance module not working. print(yf.Ticker("AMD").info['longName'])
'''
import yfinance as yf

stock_name = yf.Ticker("AMD").info

print(stock_name['website'])

print(stock_name['longName'])

print(stock_name['longBusinessSummary'])

'''

Can anyone let me know why this isn't working anymore. Just a few weeks ago it was working just fine. Was there any change in yfinance module.

You get KeyError: 'longName'


问:
How to use i18next with remix-typescript and have autocomplete?
I have remix app (Bluestack). I am using i18next for internationalisation. I want to have autocomplete feature while using keys from index.json similar to how typescript shows suggestion when type is defined.

I have tried https://www.i18next.com/overview/typescript whats given over here but the it's not working. In docs it's mentioned to create that file in src folder but in remix app there is no such directory. Where exactly do i have to keep that file? What am i missing?

Package versions:

```<code>
"@remix-run/express": "^1.6.0",
"react-i18next": "^11.18.6"
"@remix-run/node": "^1.6.0",
"@remix-run/react": "^1.6.0",
"@remix-run/server-runtime": "^1.6.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-i18next": "^11.18.6"
</code>```

This my directory structure. translation file is inside the public/locales/english/en/index.json

Body:
I have remix app (Bluestack). I am using i18next for internationalisation. I want to have autocomplete feature while using keys from index.json similar to how typescript shows suggestion when type is defined.

I have tried https://www.i18next.com/overview/typescript whats given over here but the it's not working. In docs it's mentioned to create that file in src folder but in remix app there is no such directory. Where exactly do i have to keep that file? What am i missing?

Package versions:

"@remix-run/express": "^1.6.0",
"react-i18next": "^11.18.6"
"@remix-run/node": "^1.6.0",
"@remix-run/react": "^1.6.0",
"@remix-run/server-runtime": "^1.6.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-i18next": "^11.18.6"

This my directory structure. translation file is inside the public/locales/english/en/index.json


问:
How to copy files from Webpack without needing to copy all files one by one
I am trying to copy code from webpack:// from a website to try to understand the code of a game better and to have a chance to maybe mod it.

I see you can save individual files, but the problem is that the game has too many files. I didn't try that much except for right clicking which didn't let me copy information from webpack


问:
remote debugging in Visual studio 2022
I have question how to enable remote debugging in visual 2022
in my machine this feature is enabled till 2019 but now for 2022
wanted to understand what all packages needed for 2022 as existing packages already added to ( C:\Program Files (x86)) with my current project name

When execute some operation in one machine and trying to connect it with another machine with its IP addresses then connection should get establish and the remote debugging should be possible in another machine when we debugging with out installing Visual studio 2022 in different machine

Title: remote debugging in Visual studio 2022


问:
Is there a way to detect Class constructors with typescript?
not SPECIFIC constructors -- just THAT an item is a constructor; i.e., that with foo you could call new foo(bar) and not get an error.


问:
There is no difference in the network latency of clustar batch group and spread batch group
I made two ec2 instances at clustar batch group and also made two ec2 instances at spread batch group.
I do ping test between two ec2 instances at same batch group.
I expected the result of clustar batch group is better.
But, the result show dosent show difference.
The result of clustar batch group is 0.159ms, another result of spread batch group is 0.163ms.
Why the results show no difference?</p>


问:
typeorm default function thorws duplicate value error on with batch insert
I have created default function for one column where i am generating nanoid using this package: https://www.npmjs.com/package/nanoid.

```<code>@Column('public_id', { unique: true, default: () => `'${nanoid()}'` })
</code>```

This is working fine while single insert properly. But if i try multiple insert in loop or directly provide, it throws error of duplicate value for public id. If i remove the unique constraint, it works but same value is generated for all records.  Basically it is generating same default value for all records.

Body:
I have created default function for one column where i am generating nanoid using this package: https://www.npmjs.com/package/nanoid.

@Column('public_id', { unique: true, default: () => `'${nanoid()}'` })

This is working fine while single insert properly. But if i try multiple insert in loop or directly provide, it throws error of duplicate value for public id. If i remove the unique constraint, it works but same value is generated for all records.  Basically it is generating same default value for all records.


问:
Could I use multiple package manager in Turborepo?
Currently, I have 2 apps in my Turborepo.

Their package manager is yarn 1.

Now I am going to add an app for AWS lambda. I want to use yarn berry for lambda only.

1.Is it good to manage AWS Lambda and Web Frontend code as monorepo?

2.Could I seperate package manager by app?


问:
problem with converting .tflite model to .h using xxd -i model.tflite > model.h
when ever i try to convert my TensorFlow lite model from .tflite to .h model the file size before conversion is 1.9mb and after conversion its 11.5mb and I need to deploy it on esp32 but I don't know what am gonna to do that since the file size is 11.5mb and esp32 storage size is 4mb.

is there any other way to convert without increasing the size ?


问:
Quasar Bex inject Vue components without overlaying
I am trying to write a browser extension with Quasar that overhauls the UI for a specific website. As part of this, I want to replace the website's existing header with a custom header defined by a Quasar q-layout, but keep the rest of the page accessible.

I followed the Quasar tutorial for developing browser extensions, but it places an iFrame over the entire page, meaning you cannot interact with the page when the drawer is out and the top of the page is always obscured by the layout's header.

What's more is that I was thinking of having the main page only be accessible on a specific q-route-tab, where other tabs would be fully Vue components. I'm not necessarily settled on this, so it's ok if it's not totally practical.

Let's say the content I am mostly interested in on the website is in the
:

<!DOCTYPE html>

"

```
<p>Here's my layout Vue code (basically just the tutorial):</p>
```// src/layouts/MainLayout.vue

<template>
    <q-layout view="hHh Lpr lFf">
        <q-header elevated>
            <q-toolbar>
                <q-btn
                    flat
                    dense
                    round
                    icon="menu"
                    aria-label="Menu"
                    @click="toggleLeftDrawer"
                />
                <q-toolbar-title> BEX App </q-toolbar-title>

Quasar v{{ $q.version }}

            </q-toolbar>
            <q-tabs v-model="tabs" align="left">
                <q-route-tab default name="main" to="/main" label="Main" />
                <q-route-tab
                    name="pageTwo"
                    to="/pageTwo"
                    label="Page Two"
                />
            </q-tabs>
        </q-header>

        <q-drawer show-if-above v-model="isLeftDrawerOpen" side="left" bordered>
            <q-list>
                <q-item-label header> Essential Links </q-item-label>
                Some content
            </q-list>
        </q-drawer>

        <q-page-container>
            <router-view />
        </q-page-container>
    </q-layout>
</template>

```
<p>My content script:</p>
```// src-bex/my-content-scripts.ts

// Hooks added here have a bridge allowing communication between the BEX Content Script and the Quasar Application.
// More info: https://quasar.dev/quasar-cli/developing-browser-extensions/content-hooks

import { bexContent } from 'quasar/wrappers';

const iFrame = document.createElement('iframe'),
    defaultFrameHeight = '62px';

/**
 * Set the height of our iFrame housing our BEX
 * @param height
 */
const setIFrameHeight = (height: string) => {
    iFrame.height = height;
};

/**
 * Reset the iFrame to its default height e.g The height of the top bar.
 */
const resetIFrameHeight = () => {
    setIFrameHeight(defaultFrameHeight);
};

/**
 * The code below will get everything going. Initialize the iFrame with defaults and add it to the page.
 * @type {string}
 */
iFrame.id = 'bex-app-iframe';
iFrame.width = '100%';
resetIFrameHeight();
// setIFrameHeight('100%');

// Assign some styling so it looks seamless
Object.assign(iFrame.style, {
    position: 'fixed',
    top: '0',
    right: '0',
    bottom: '0',
    left: '0',
    border: '0',
    zIndex: '9999999', // Make sure it's on top
    overflow: 'visible',
});
(function () {
    // When the page loads, insert our browser extension app.
    iFrame.src = chrome.runtime.getURL('www/index.html');
    document.body.prepend(iFrame);
})();

export default bexContent((bridge) => {
    /**
     * When the drawer is toggled set the iFrame height to take the whole page.
     * Reset when the drawer is closed.
     */
    bridge.on('wb.drawer.toggle', ({ data, respond }) => {
        if (data.isOpen) {
            setIFrameHeight('100%');
        } else {
            resetIFrameHeight();
        }
        respond();
    });
});
```

I also have some basic pages and routing, but I'm not doing anything fancy and I'm not sure how relevant they are to the issue here.

Is what I'm trying to do feasible? Is there a better tool/framework for this? It also seems like doing this might mess with the website's own JS, but I also feel like this has to be possible. Thanks!

Body:
I am trying to write a browser extension with Quasar that overhauls the UI for a specific website. As part of this, I want to replace the website's existing header with a custom header defined by a Quasar q-layout, but keep the rest of the page accessible.

I followed the Quasar tutorial for developing browser extensions, but it places an iFrame over the entire page, meaning you cannot interact with the page when the drawer is out and the top of the page is always obscured by the layout's header.

What's more is that I was thinking of having the main page only be accessible on a specific q-route-tab, where other tabs would be fully Vue components. I'm not necessarily settled on this, so it's ok if it's not totally practical.

Let's say the content I am mostly interested in on the website is in the
:

<!DOCTYPE html>

"

Here's my layout Vue code (basically just the tutorial):

// src/layouts/MainLayout.vue

<template>
    <q-layout view="hHh Lpr lFf">
        <q-header elevated>
            <q-toolbar>
                <q-btn
                    flat
                    dense
                    round
                    icon="menu"
                    aria-label="Menu"
                    @click="toggleLeftDrawer"
                />
                <q-toolbar-title> BEX App </q-toolbar-title>

Quasar v{{ $q.version }}

            </q-toolbar>
            <q-tabs v-model="tabs" align="left">
                <q-route-tab default name="main" to="/main" label="Main" />
                <q-route-tab
                    name="pageTwo"
                    to="/pageTwo"
                    label="Page Two"
                />
            </q-tabs>
        </q-header>

        <q-drawer show-if-above v-model="isLeftDrawerOpen" side="left" bordered>
            <q-list>
                <q-item-label header> Essential Links </q-item-label>
                Some content
            </q-list>
        </q-drawer>

        <q-page-container>
            <router-view />
        </q-page-container>
    </q-layout>
</template>

My content script:

// src-bex/my-content-scripts.ts

// Hooks added here have a bridge allowing communication between the BEX Content Script and the Quasar Application.
// More info: https://quasar.dev/quasar-cli/developing-browser-extensions/content-hooks

import { bexContent } from 'quasar/wrappers';

const iFrame = document.createElement('iframe'),
    defaultFrameHeight = '62px';

/**
 * Set the height of our iFrame housing our BEX
 * @param height
 */
const setIFrameHeight = (height: string) => {
    iFrame.height = height;
};

/**
 * Reset the iFrame to its default height e.g The height of the top bar.
 */
const resetIFrameHeight = () => {
    setIFrameHeight(defaultFrameHeight);
};

/**
 * The code below will get everything going. Initialize the iFrame with defaults and add it to the page.
 * @type {string}
 */
iFrame.id = 'bex-app-iframe';
iFrame.width = '100%';
resetIFrameHeight();
// setIFrameHeight('100%');

// Assign some styling so it looks seamless
Object.assign(iFrame.style, {
    position: 'fixed',
    top: '0',
    right: '0',
    bottom: '0',
    left: '0',
    border: '0',
    zIndex: '9999999', // Make sure it's on top
    overflow: 'visible',
});
(function () {
    // When the page loads, insert our browser extension app.
    iFrame.src = chrome.runtime.getURL('www/index.html');
    document.body.prepend(iFrame);
})();

export default bexContent((bridge) => {
    /**
     * When the drawer is toggled set the iFrame height to take the whole page.
     * Reset when the drawer is closed.
     */
    bridge.on('wb.drawer.toggle', ({ data, respond }) => {
        if (data.isOpen) {
            setIFrameHeight('100%');
        } else {
            resetIFrameHeight();
        }
        respond();
    });
});

I also have some basic pages and routing, but I'm not doing anything fancy and I'm not sure how relevant they are to the issue here.

Is what I'm trying to do feasible? Is there a better tool/framework for this? It also seems like doing this might mess with the website's own JS, but I also feel like this has to be possible. Thanks!


问:
How to create a stream of OGG pages with headers?
I have a stream of PCM data (16bit - stereo) & need to convert it into stream of OGG pages with respective streaming headers (version/ header type/ pattern/ checksum/ etc.,). After that it will be sent via WebSocket to my server, which will decode it back to PCM using the API DecodeAudioData

New to opus library.
So any help will be appreciated.

Environment: windows

IDE: Visual Studio 2019

Language used: c++

Bit architecture: 32-bit


问:
Is it possible to use DATE_ADD() function after ON UPDATE keyword?
I am getting a syntax error from MySQL for the following query...
Query:

```<code>ALTER TABLE tblName MODIFY COLUMN `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
    DATE_ADD(CURRENT_TIMESTAMP, INTERVAL 7 HOUR);
</code>```

Error details:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DATE_ADD(current_timestamp, INTERVAL 7 HOUR)' at line 2

My aim is to store (CURRENT_TIMESTAMP + 7HR) in updated_at field for every update.

Body:
I am getting a syntax error from MySQL for the following query...
Query:

ALTER TABLE tblName MODIFY COLUMN `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
    DATE_ADD(CURRENT_TIMESTAMP, INTERVAL 7 HOUR);

Error details:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DATE_ADD(current_timestamp, INTERVAL 7 HOUR)' at line 2

My aim is to store (CURRENT_TIMESTAMP + 7HR) in updated_at field for every update.


问:
Is there a way to derive GVIF in Jamovi?
Apparently the car package vif function and performance package check_collinearity function both calculate generalized variance inflation factor (GVIF) automatically if a categorical variable is entered into a regression. As an example, this can be done with the iris dataset with the following code:

```<code>#### Categorical Fit ####
fit.cat <- lm(
  Petal.Length ~ Species + Petal.Width + Sepal.Width,
  iris
)
check_collinearity(fit.cat)
</code>```

Which gives an an expected value of 26.10 that I have already hand calculated. However, Jamovi doesn't allow one to automatically add factors to a regression, so I dummy coded the same regression factor and entered the regression like so:

You can see in the arrow that the value doesn't match that obtained from the R function. I also double checked in R to see if it is just calculating VIF instead:

```<code>1/(1-summary(lm(as.numeric(Species) ~ 1 + Petal.Width + Sepal.Width,
                iris))$r.squared)
</code>```

But the values don't match, as this gives me a VIF of 12.78. Why is it doing this and is there a solution in Jamovi for hacking this?

Body:
Apparently the car package vif function and performance package check_collinearity function both calculate generalized variance inflation factor (GVIF) automatically if a categorical variable is entered into a regression. As an example, this can be done with the iris dataset with the following code:

#### Categorical Fit ####
fit.cat <- lm(
  Petal.Length ~ Species + Petal.Width + Sepal.Width,
  iris
)
check_collinearity(fit.cat)

Which gives an an expected value of 26.10 that I have already hand calculated. However, Jamovi doesn't allow one to automatically add factors to a regression, so I dummy coded the same regression factor and entered the regression like so:

You can see in the arrow that the value doesn't match that obtained from the R function. I also double checked in R to see if it is just calculating VIF instead:

1/(1-summary(lm(as.numeric(Species) ~ 1 + Petal.Width + Sepal.Width,
                iris))$r.squared)

But the values don't match, as this gives me a VIF of 12.78. Why is it doing this and is there a solution in Jamovi for hacking this?


问:
Button click always renders the previous state useState hook React Js
I am using below mentioned code to change the state on click of the button by executing the onSubmit function. I am using useEffect hook to re render on each state change but still whenever button is clicked the previous state is rendered. I need to know how to render the current state on button click.</p>
```<code>const Signup = () => {
    const [formData, setFormData] = useState({firstname: '', lastname: '', email: '', username: '', password: ''})
    const [resData, setResData] = useState("");
    const navigate = useNavigate();
    useEffect(()=>{
        if (resData==="registered"){
            //console.log(res.data);
            navigate("/login");
        }

    }, [resData])
    const onSubmit = (e) => {
        e.preventDefault()
        axios.post('http://localhost:8800/register', formData)
            .then((res)=>{
                setResData(res.data);
                console.log(resData);
            })
    }
</code>```

Body:
I am using below mentioned code to change the state on click of the button by executing the onSubmit function. I am using useEffect hook to re render on each state change but still whenever button is clicked the previous state is rendered. I need to know how to render the current state on button click.

const Signup = () => {
    const [formData, setFormData] = useState({firstname: '', lastname: '', email: '', username: '', password: ''})
    const [resData, setResData] = useState("");
    const navigate = useNavigate();
    useEffect(()=>{
        if (resData==="registered"){
            //console.log(res.data);
            navigate("/login");
        }

    }, [resData])
    const onSubmit = (e) => {
        e.preventDefault()
        axios.post('http://localhost:8800/register', formData)
            .then((res)=>{
                setResData(res.data);
                console.log(resData);
            })
    }


问:
unknown property 'text-fill-color css(unknown properties)
My Navbar is not working and I don't know why I think it may have to do with this line of code:

```<code>  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-fill-color: transparent;
}
</code>```

the line "text-fill-color: transparent;" gives me the message unknown property 'text-fill-color css(unknown properties)

I dont really know how to fix it

Body:
My Navbar is not working and I don't know why I think it may have to do with this line of code:

  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  text-fill-color: transparent;
}

the line "text-fill-color: transparent;" gives me the message unknown property 'text-fill-color css(unknown properties)

I dont really know how to fix it


问:
Memory leak in very simple spark streaming app (reading file stream and write to delta)?
I have a very simple spark streaming app that reads parquet data from s3 and upsert to delta table:

```<code>import boto3
import os

from pathlib import Path

from delta import *
from delta.tables import *
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *

app_name = "my_app"
spark = SparkSession.builder.appName(app_name).config("spark.databricks.io.cache.enabled", "true").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
env = os.environ["ENVIRONMENT"]

landing_bucket = f"s3a://awesommmme-data-landing-zone-{env}"  # data_real/landing
cleansing_bucket = f"s3a://awesommmme-data-cleansing-zone-{env}"
checkpoint_bucket = f"s3a://awesommmme-data-spark-checkpoints-{env}"

landing_data_label_path = os.path.join(landing_bucket, "contract_label", "data")
cleansing_data_label_path = os.path.join(cleansing_bucket, "contract_label", "data")

_label_logic_schema = [
    StructField("token_address", StringType()),
    StructField("token_type", StringType()),
]
_raw_data_schema = _label_logic_schema + [
    StructField("update_dt", TimestampType()),
    StructField("year", StringType()),
    StructField("month", StringType()),
    StructField("day", StringType()),
    StructField("hour", StringType()),
    StructField("minute", StringType()),
]
raw_data_schema = StructType(_raw_data_schema)

deltaTable = None
def upsert_to_cleaned_delta(pdf, batchId):
    global deltaTable

    if deltaTable is None:
        try:
            deltaTable = DeltaTable.forPath(spark, cleansing_data_label_path)
        except Exception as e:
            import logging

            logging.error(str(e))
            pdf.write.format("delta").partitionBy("year", "month", "day", "hour", "minute").save(
                cleansing_data_label_path
            )
            deltaTable = DeltaTable.forPath(spark, cleansing_data_label_path)
            return

    deltaTable.alias("old_data").merge(
        pdf.alias("new_data"), "old_data.token_address = new_data.token_address"
    ).whenMatchedUpdateAll(
    ).whenNotMatchedInsertAll().execute()

def main():
    _ = (
        spark.readStream.schema(raw_data_schema)
        .parquet(landing_data_label_path)
        .writeStream.format("delta")
        .option("maxFilesPerTrigger", 10)
        .option("checkpointLocation", "MY_CHECKPOINT_PATH")
        .foreachBatch(lambda pdf, batch_id: upsert_to_cleaned_delta(pdf, batch_id))
        .trigger(processingTime="1 second")
        .outputMode("append")
        .start()
    )
    spark.streams.awaitAnyTermination()

if __name__ == "__main__":
    main()

</code>```

I run this app in spark + kubernetes cluster but when I monitored resources, there is memory leak:

container

pod

As time goes, it reached to limit and pods will be dead.

Here is values.yaml used in deploying spark app using helm:

app: data-pipeline
applicationId: myapp
name: myapp-data
namespace: "{{ .Release.Namespace }}"

environment: dev

sparkConf:
  spark.executor.heartbeatInterval: "600s"
  spark.network.timeout: "3600s"

deps:
  jars:
    - delta-core_2.12-2.0.1.jar

restartPolicy:
  type: Always

driver:
  annotations: {}
  coreRequest: 100m
  coreLimit: 500m
  memory: 3g
executor:
  coreRequest: 100m
  coreLimit: 500m
  instances: 1
  memory: 2g

```

One things to note

Size of files that spark app reads is really small(Kbytes) and very seldeomly created (one file per 2~3 hours)

The delta table size is about 190MB, about 700,000 rows.

I have no idea why a memory leak occurs...

Body:
I have a very simple spark streaming app that reads parquet data from s3 and upsert to delta table:

import boto3
import os

from pathlib import Path

from delta import *
from delta.tables import *
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *

app_name = "my_app"
spark = SparkSession.builder.appName(app_name).config("spark.databricks.io.cache.enabled", "true").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
env = os.environ["ENVIRONMENT"]

landing_bucket = f"s3a://awesommmme-data-landing-zone-{env}"  # data_real/landing
cleansing_bucket = f"s3a://awesommmme-data-cleansing-zone-{env}"
checkpoint_bucket = f"s3a://awesommmme-data-spark-checkpoints-{env}"

landing_data_label_path = os.path.join(landing_bucket, "contract_label", "data")
cleansing_data_label_path = os.path.join(cleansing_bucket, "contract_label", "data")

_label_logic_schema = [
    StructField("token_address", StringType()),
    StructField("token_type", StringType()),
]
_raw_data_schema = _label_logic_schema + [
    StructField("update_dt", TimestampType()),
    StructField("year", StringType()),
    StructField("month", StringType()),
    StructField("day", StringType()),
    StructField("hour", StringType()),
    StructField("minute", StringType()),
]
raw_data_schema = StructType(_raw_data_schema)

deltaTable = None
def upsert_to_cleaned_delta(pdf, batchId):
    global deltaTable

    if deltaTable is None:
        try:
            deltaTable = DeltaTable.forPath(spark, cleansing_data_label_path)
        except Exception as e:
            import logging

            logging.error(str(e))
            pdf.write.format("delta").partitionBy("year", "month", "day", "hour", "minute").save(
                cleansing_data_label_path
            )
            deltaTable = DeltaTable.forPath(spark, cleansing_data_label_path)
            return

    deltaTable.alias("old_data").merge(
        pdf.alias("new_data"), "old_data.token_address = new_data.token_address"
    ).whenMatchedUpdateAll(
    ).whenNotMatchedInsertAll().execute()

def main():
    _ = (
        spark.readStream.schema(raw_data_schema)
        .parquet(landing_data_label_path)
        .writeStream.format("delta")
        .option("maxFilesPerTrigger", 10)
        .option("checkpointLocation", "MY_CHECKPOINT_PATH")
        .foreachBatch(lambda pdf, batch_id: upsert_to_cleaned_delta(pdf, batch_id))
        .trigger(processingTime="1 second")
        .outputMode("append")
        .start()
    )
    spark.streams.awaitAnyTermination()

if __name__ == "__main__":
    main()

I run this app in spark + kubernetes cluster but when I monitored resources, there is memory leak:

container

pod

As time goes, it reached to limit and pods will be dead.

Here is values.yaml used in deploying spark app using helm:

app: data-pipeline
applicationId: myapp
name: myapp-data
namespace: "{{ .Release.Namespace }}"

environment: dev

sparkConf:
  spark.executor.heartbeatInterval: "600s"
  spark.network.timeout: "3600s"

deps:
  jars:
    - delta-core_2.12-2.0.1.jar

restartPolicy:
  type: Always

driver:
  annotations: {}
  coreRequest: 100m
  coreLimit: 500m
  memory: 3g
executor:
  coreRequest: 100m
  coreLimit: 500m
  instances: 1
  memory: 2g

One things to note

Size of files that spark app reads is really small(Kbytes) and very seldeomly created (one file per 2~3 hours)

The delta table size is about 190MB, about 700,000 rows.

I have no idea why a memory leak occurs...


问:
what is the alternate of the above code while migrating the hazelcast from 3.x.x to 5.x.x?
```<code>     Config hz = new Config();
     hz.setProperty("hazelcast.rest.enbld", "true");
     hz.getGroupConfig().setName("abc");
     hz.getGroupConfig().setPassword("def");

</code>```

what is the alternate of the above code while converting the hazelcast from 3.x.x to 5.x.x

Body:
     Config hz = new Config();
     hz.setProperty("hazelcast.rest.enbld", "true");
     hz.getGroupConfig().setName("abc");
     hz.getGroupConfig().setPassword("def");

what is the alternate of the above code while converting the hazelcast from 3.x.x to 5.x.x


问:
How to make invisible form when screen capture is running
is there any one can help me?

i am creating a windows application in c#. and i want to make it invisible when i do screen recording. i mean, it will not record but i can use it.

i try displayaffinity

but this makes form black when record. but i want full invisible.

```<code>namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("user32.dll")]
        public static extern uint SetWindowDisplayAffinity(IntPtr hwnd, uint dwAffinity);

        private void Form1_Load(object sender, EventArgs e)
        {
            const uint WDA_NONE = 0;
            const uint WDA_MONITOR = 1;
            SetWindowDisplayAffinity(this.Handle, WDA_MONITOR);
        }
    }
}
</code>```

Body:
is there any one can help me?

i am creating a windows application in c#. and i want to make it invisible when i do screen recording. i mean, it will not record but i can use it.

i try displayaffinity

but this makes form black when record. but i want full invisible.

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [DllImport("user32.dll")]
        public static extern uint SetWindowDisplayAffinity(IntPtr hwnd, uint dwAffinity);

        private void Form1_Load(object sender, EventArgs e)
        {
            const uint WDA_NONE = 0;
            const uint WDA_MONITOR = 1;
            SetWindowDisplayAffinity(this.Handle, WDA_MONITOR);
        }
    }
}


问:
WHY ASP.NET FileUpLoad do not run in IPhone IOS
I use FileUpload control or HTML input type="file"

run on any Browser,chrome,I.E,android mobile.

It can run,only on IOS mobile do not work when Submit Button Click show "error"

```<code><input type="file" name="UploadFile" id="UploadFile" class="form-control"/>
<asp:Button ID="Button" runat="server" Text="Submit" OnClick="Button_Click"/>
</code>```

Code Behind

```<code>protected void Button_Click(object sender, EventArgs e)
{
  HttpPostedFile postedFile = Request.Files["UploadFile"];

  //Check if File is available.
  if (postedFile != null && postedFile.ContentLength > 0)
  {
      string extension = Path.GetExtension(postedFile.FileName);
      if (extension != ".png" && extension != ".jpg" && extension != ".jpeg")
      {
        Div1.Style["display"] = "flex";
        Label7.Text = "＊CHOOSE(.png 或 .jpg 或 .jpeg)!! ";
        return;
      }
      string filename = Path.GetFileName(postedFile.FileName);
      string path = "";
      path = "~/CustomerFeedbackPic/" + filename;
      string serverDir = "";
      serverDir = Server.MapPath(path);
      postedFile.SaveAs(serverDir);
      Response.Redirect("uploadsuccess.aspx");
   }
}
</code>```

Body:
I use FileUpload control or HTML input type="file"

run on any Browser,chrome,I.E,android mobile.

It can run,only on IOS mobile do not work when Submit Button Click show "error"

<input type="file" name="UploadFile" id="UploadFile" class="form-control"/>
<asp:Button ID="Button" runat="server" Text="Submit" OnClick="Button_Click"/>

Code Behind

protected void Button_Click(object sender, EventArgs e)
{
  HttpPostedFile postedFile = Request.Files["UploadFile"];

  //Check if File is available.
  if (postedFile != null && postedFile.ContentLength > 0)
  {
      string extension = Path.GetExtension(postedFile.FileName);
      if (extension != ".png" && extension != ".jpg" && extension != ".jpeg")
      {
        Div1.Style["display"] = "flex";
        Label7.Text = "＊CHOOSE(.png 或 .jpg 或 .jpeg)!! ";
        return;
      }
      string filename = Path.GetFileName(postedFile.FileName);
      string path = "";
      path = "~/CustomerFeedbackPic/" + filename;
      string serverDir = "";
      serverDir = Server.MapPath(path);
      postedFile.SaveAs(serverDir);
      Response.Redirect("uploadsuccess.aspx");
   }
}


问:
How to improve this Powershell script?
I wrote a powershell script that merges go pro video files if they have multiple files. It works when the videos are at the root drive i.e. C:, but otherwise not. The mergevideos.txt file is not created if I run the script from a different directory. Or the txt is created but it's empty. Not sure what's going on when run from a different directory.

So is there a way to fix these issues and refactor this code to make it better? Ideally I want the script to automatically look at the directory it's in or allows me to specify the directory it should work in so I can just call it from the same location but the videos can be anywhere.

```<code>$path = "C:/NewVideos/"
$oldvids = Get-ChildItem -Path $path *.mp4
foreach ($oldvid in $oldvids) {
    $curpath = $oldvid.DirectoryName

    $name = [System.IO.Path]::GetFileNameWithoutExtension($oldvid)
    $ext = [System.IO.Path]::GetExtension($oldvid)
    if ($name.StartsWith("GX01") -and !($name.EndsWith("_merged")))
    {
        $newvid = $curpath + $name + "_merged" + $ext
        if ([System.IO.File]::Exists($newvid))
        {
            Write-Output "$name | ALREADY MERGED"
            continue
        }

        $count = 1

        for ($num = 2; $num -lt 10; $num++)
        {
            $nextpart = $name.Replace("GX01", "GX0" + $num)
            if ([System.IO.File]::Exists($curpath + "/" + $nextpart + $ext))
            {
                $count = $num
            }
        }

        if ($count -eq 1)
        {
            Write-Output "$name | SINGLE VIDEO"
            continue
        }

        $mergefile = $curpath + "mergevideos.txt"
        if (!(Test-Path $mergefile))
        {
            New-Item -path $curpath -name mergevideos.txt -type "file"
        }

        Clear-Content $mergefile

        for ($num = 1; $num -le $count; $num++)
        {
            $nextpart = $name.Replace("GX01", "GX0" + $num)
            $videofilename = "file '" + $nextpart + $ext + "'"
            Add-Content $mergefile $videofilename
        }

         Write-Output "$name | MERGING  $count VIDEOS"
         ffmpeg -f concat -safe 0 -i $mergefile -c copy $newvid
    }
}
</code>```

Title: How to improve this Powershell script?

Body:
I wrote a powershell script that merges go pro video files if they have multiple files. It works when the videos are at the root drive i.e. C:, but otherwise not. The mergevideos.txt file is not created if I run the script from a different directory. Or the txt is created but it's empty. Not sure what's going on when run from a different directory.

So is there a way to fix these issues and refactor this code to make it better? Ideally I want the script to automatically look at the directory it's in or allows me to specify the directory it should work in so I can just call it from the same location but the videos can be anywhere.

$path = "C:/NewVideos/"
$oldvids = Get-ChildItem -Path $path *.mp4
foreach ($oldvid in $oldvids) {
    $curpath = $oldvid.DirectoryName

    $name = [System.IO.Path]::GetFileNameWithoutExtension($oldvid)
    $ext = [System.IO.Path]::GetExtension($oldvid)
    if ($name.StartsWith("GX01") -and !($name.EndsWith("_merged")))
    {
        $newvid = $curpath + $name + "_merged" + $ext
        if ([System.IO.File]::Exists($newvid))
        {
            Write-Output "$name | ALREADY MERGED"
            continue
        }

        $count = 1

        for ($num = 2; $num -lt 10; $num++)
        {
            $nextpart = $name.Replace("GX01", "GX0" + $num)
            if ([System.IO.File]::Exists($curpath + "/" + $nextpart + $ext))
            {
                $count = $num
            }
        }

        if ($count -eq 1)
        {
            Write-Output "$name | SINGLE VIDEO"
            continue
        }

        $mergefile = $curpath + "mergevideos.txt"
        if (!(Test-Path $mergefile))
        {
            New-Item -path $curpath -name mergevideos.txt -type "file"
        }

        Clear-Content $mergefile

        for ($num = 1; $num -le $count; $num++)
        {
            $nextpart = $name.Replace("GX01", "GX0" + $num)
            $videofilename = "file '" + $nextpart + $ext + "'"
            Add-Content $mergefile $videofilename
        }

         Write-Output "$name | MERGING  $count VIDEOS"
         ffmpeg -f concat -safe 0 -i $mergefile -c copy $newvid
    }
}


问:
Is passing context class attributes as parameters to a strategy method (when the strategy is itself a part of the context) correct?
I am implementing the Snakes and Ladders game. Where Game is one class which has Board, Dice, Players and 2 strategies - Winning Strategy and EndGameStrategy.
Different implementations of EndGameStrategy can be -

If one player wins, the game ends - OnePlayerWonGameEndStrategy

If only 1 player remains at last, the game ends - OnlyOnePlayerLeftGameEndStrategy

The Game model looks as below:

```<code>@Builder
@Getter
public class Game {
    private Board board;
    private Queue<Player> players;
    private List<Dice> dices;
    private final int MAX_BOARD_SIZE = 1000;
    private final int MAX_NUMBER_OF_PLAYERS = 10;
    private final int MAX_NUMBER_OF_DICE = 5;
    private int totalPlayers;
    private GameEndStrategy gameEndStrategy;
    private WinningStrategy winningStrategy;
    private Queue<Player>leaderBoard;
}
</code>```

The Client initializes strategies using builder.

```<code>Game game = Game.Builder()
                .setBoard(board)
                .setPlayers(playerList)
                .setDices(diceList)
                .setGameEndStrategy(new OnlyOnePlayerLeftGameEndStrategy())
                .build();
</code>```

One of the implementation of GameEndStrategy is OnlyOneplayerLeftGameEndStrategy

```<code>public class OnlyOnePlayerLeftGameEndStrategy implements GameEndStrategy{
    @Override
    public Boolean isGameEnd(int activePlayers, int totalPlayers) {
        return activePlayers == 1;
    }
}
</code>```

Other implementation is when the first player wins, the game ends

```<code>public class OnePlayerWonGameEndStrategy implements GameEndStrategy{
    @Override
    public Boolean isGameEnd(int activePlayers, int totalPlayers) {
        return totalPlayers - activePlayers == 1;
    }
}
</code>```

The client uses the strategy as follows:

```<code>while(!game.getGameEndStrategy().isGameEnd(game.getPlayers().size(), game.getTotalPlayers())) {
    \\Game logic (Player throws dice, new position is checked
}
</code>```

Here as parameters of isGameEnd method, should I pass the context class i.e the Game instance as the param? because,
OnlyOnePlayerLeftGameEndStrategy would only need the activePlayers number to check if one one player is left. But, OnePlayerWonGameEndStartegy needs both totalPlayers and activePlayers as params to check if one player has won. Also there could be another strategy in future which would need more params.
So how should we handle changing params? How should we implement the strategy pattern here in this Snakes and Ladders usecase?

Body:
I am implementing the Snakes and Ladders game. Where Game is one class which has Board, Dice, Players and 2 strategies - Winning Strategy and EndGameStrategy.
Different implementations of EndGameStrategy can be -

If one player wins, the game ends - OnePlayerWonGameEndStrategy

If only 1 player remains at last, the game ends - OnlyOnePlayerLeftGameEndStrategy

The Game model looks as below:

@Builder
@Getter
public class Game {
    private Board board;
    private Queue<Player> players;
    private List<Dice> dices;
    private final int MAX_BOARD_SIZE = 1000;
    private final int MAX_NUMBER_OF_PLAYERS = 10;
    private final int MAX_NUMBER_OF_DICE = 5;
    private int totalPlayers;
    private GameEndStrategy gameEndStrategy;
    private WinningStrategy winningStrategy;
    private Queue<Player>leaderBoard;
}

The Client initializes strategies using builder.

Game game = Game.Builder()
                .setBoard(board)
                .setPlayers(playerList)
                .setDices(diceList)
                .setGameEndStrategy(new OnlyOnePlayerLeftGameEndStrategy())
                .build();

One of the implementation of GameEndStrategy is OnlyOneplayerLeftGameEndStrategy

public class OnlyOnePlayerLeftGameEndStrategy implements GameEndStrategy{
    @Override
    public Boolean isGameEnd(int activePlayers, int totalPlayers) {
        return activePlayers == 1;
    }
}

Other implementation is when the first player wins, the game ends

public class OnePlayerWonGameEndStrategy implements GameEndStrategy{
    @Override
    public Boolean isGameEnd(int activePlayers, int totalPlayers) {
        return totalPlayers - activePlayers == 1;
    }
}

The client uses the strategy as follows:

while(!game.getGameEndStrategy().isGameEnd(game.getPlayers().size(), game.getTotalPlayers())) {
    \\Game logic (Player throws dice, new position is checked
}

Here as parameters of isGameEnd method, should I pass the context class i.e the Game instance as the param? because,
OnlyOnePlayerLeftGameEndStrategy would only need the activePlayers number to check if one one player is left. But, OnePlayerWonGameEndStartegy needs both totalPlayers and activePlayers as params to check if one player has won. Also there could be another strategy in future which would need more params.
So how should we handle changing params? How should we implement the strategy pattern here in this Snakes and Ladders usecase?


问:
I get a loss : nan when implementing mish from the scratch
I'm currently working on making a custom activation function using tf2 on python.

```<code>model architecture: VGG 16, on CIFAR-10
epochs: 100
lr: 0.001 for initial 80 epochs, 0.0001 for 20 epochs
optimizer: Adam
loss: categorical cross entropy
batch_size: 128
num_cnn_list = [2,2,4,4,4]
channel_list = [16,128,256,512,512]
</code>```

There's no problem when I use mish activation function like this:

```<code>@tf.function
def mish(x):
  return x * K.tanh(K.softplus(x))  # K.log(1 + K.exp(x))
</code>```

However, when I tried implementing mish like following:

```<code>@tf.function
def mish_inside(x):
  return K.log(1 + K.exp(x))
@tf.function
def mish(x):
  return x * K.tanh(mish_inside(x))
</code>```

Initially I get a normal loss value, but soon I get nan.(before the first epoch is done)

Which is quite crucial, because this can refer that same function(softplus and ln(1+e^x)) can have different backpropagation value according to its implementation method,
so that a new activation function should be simple or consisting of functions in the library.

This works quite well with smaller lr(0.0001), but I want it to be robust on misc. settings.

In the first place, it doesn't make a sense that same function returns different loss value.

Does implementation method really matters? or am I missing somethong else?

This is what I found on tensorflow directory:

```<code>def softplus(features, name=None):
  r"""TODO: add doc.

  Args:
    features: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`. Has the same type as `features`.
  """
  _ctx = _context._context or _context.context()
  tld = _ctx._thread_local_data
  if tld.is_eager:
    try:
      _result = pywrap_tfe.TFE_Py_FastPathExecute(
        _ctx, "Softplus", name, features)
      return _result
    except _core._NotOkStatusException as e:
      _ops.raise_from_not_ok_status(e, name)
    except _core._FallbackException:
      pass
    try:
      return softplus_eager_fallback(
          features, name=name, ctx=_ctx)
    except _core._SymbolicException:
      pass  # Add nodes to the TensorFlow graph.
  # Add nodes to the TensorFlow graph.
  _, _, _op, _outputs = _op_def_library._apply_op_helper(
        "Softplus", features=features, name=name)
  _result = _outputs[:]
  if _execute.must_record_gradient():
    _attrs = ("T", _op._get_attr_type("T"))
    _inputs_flat = _op.inputs
    _execute.record_gradient(
        "Softplus", _inputs_flat, _attrs, _result)
  _result, = _result
  return _result

Softplus = tf_export("raw_ops.Softplus")(_ops.to_raw_op(softplus))
</code>```

Still, I don't have a clue cuz I can't find pywrap_tfe.py.

Body:
I'm currently working on making a custom activation function using tf2 on python.

model architecture: VGG 16, on CIFAR-10
epochs: 100
lr: 0.001 for initial 80 epochs, 0.0001 for 20 epochs
optimizer: Adam
loss: categorical cross entropy
batch_size: 128
num_cnn_list = [2,2,4,4,4]
channel_list = [16,128,256,512,512]

There's no problem when I use mish activation function like this:

@tf.function
def mish(x):
  return x * K.tanh(K.softplus(x))  # K.log(1 + K.exp(x))

However, when I tried implementing mish like following:

@tf.function
def mish_inside(x):
  return K.log(1 + K.exp(x))
@tf.function
def mish(x):
  return x * K.tanh(mish_inside(x))

Initially I get a normal loss value, but soon I get nan.(before the first epoch is done)

Which is quite crucial, because this can refer that same function(softplus and ln(1+e^x)) can have different backpropagation value according to its implementation method,
so that a new activation function should be simple or consisting of functions in the library.

This works quite well with smaller lr(0.0001), but I want it to be robust on misc. settings.

In the first place, it doesn't make a sense that same function returns different loss value.

Does implementation method really matters? or am I missing somethong else?

This is what I found on tensorflow directory:

def softplus(features, name=None):
  r"""TODO: add doc.

  Args:
    features: A `Tensor`. Must be one of the following types: `half`, `bfloat16`, `float32`, `float64`.
    name: A name for the operation (optional).

  Returns:
    A `Tensor`. Has the same type as `features`.
  """
  _ctx = _context._context or _context.context()
  tld = _ctx._thread_local_data
  if tld.is_eager:
    try:
      _result = pywrap_tfe.TFE_Py_FastPathExecute(
        _ctx, "Softplus", name, features)
      return _result
    except _core._NotOkStatusException as e:
      _ops.raise_from_not_ok_status(e, name)
    except _core._FallbackException:
      pass
    try:
      return softplus_eager_fallback(
          features, name=name, ctx=_ctx)
    except _core._SymbolicException:
      pass  # Add nodes to the TensorFlow graph.
  # Add nodes to the TensorFlow graph.
  _, _, _op, _outputs = _op_def_library._apply_op_helper(
        "Softplus", features=features, name=name)
  _result = _outputs[:]
  if _execute.must_record_gradient():
    _attrs = ("T", _op._get_attr_type("T"))
    _inputs_flat = _op.inputs
    _execute.record_gradient(
        "Softplus", _inputs_flat, _attrs, _result)
  _result, = _result
  return _result

Softplus = tf_export("raw_ops.Softplus")(_ops.to_raw_op(softplus))

Still, I don't have a clue cuz I can't find pywrap_tfe.py.


问:
"cleanup called" warning messages on Kaggle notebook
I'm trying to build a model on Kaggle. Once I try to fit the model, my screen is flooding with cleanup called messages and the progress of training is between these warnings.

Here is the screenshot of TensorFlow version and code which I'm trying to run. Anyone, please help me to figure out the issue?

Cleanup Called Warning


问:
pygame developing a tic-tac-toe game application using minimax algorythm error
I'm trying to make a tic tac toe game for 2 players - user and computer using minimax algorythm. My problem is that the code has an error and it doesn't work properly, but I'm not sure why. More explanation about code you can see in comments for code.
I have a TypeError: cannot unpack non-iterable Non-Type object for line 258 in main row, col = comp.evaluation(board)

Here is the code and comments:
file ttt1 with variables assignment:

```<code>import random
WIDTH = 600
HEIGHT = 600

ROWS = 3 #rows of the grid
COLS = 3 #cols of the grid

SQUARE_SIZE = WIDTH // COLS #size of one square of the grid - can be height devided by rows
LINE_WIDTH = 15 #width of the lines of the grid

#circle
CIRCLE_WIDTH = 20
RADIUS = SQUARE_SIZE // 3

#cross
CROSS_WIDTH = 20

OFFSET = 50

#define colors
BACKCOLOR = ((random.randint(0,255)), (random.randint(0, 255)), (random.randint(0,255)))
LINE_COLOR = ((random.randint(0,255)), (random.randint(0, 255)), (random.randint(0,255)))
CIRCLE = ((random.randint(0,255)), (random.randint(0, 255)), (random.randint(0,255)))
CROSS = ((random.randint(0,255)), (random.randint(0, 255)), (random.randint(0,255)))
</code>```

file with classes and etc:

```<code>import sys #for quitting the application
import copy
import random
import pygame
import numpy as np

from ttt1 import * #importing things from ttt1 file

#pygamecode and set up
pygame.init() #initializig pygame module
screen = pygame.display.set_mode((WIDTH, HEIGHT)) #setting up the screen - width and height
pygame.display.set_caption("Tic Tac Toe game with minimax")
screen.fill(BACKCOLOR) #filling in the screen with a background colors

class Board:

    def __init__(self): #2 dimensional array of 0-s
        self.squares = np.zeros((ROWS, COLS)) #parameters as tuple with 0-s, making empty squares
        #self.mark_squares(1, 2, 3) #for testing
        #print(self.squares) #return 0-s in terminal
        self.empty_square = self.squares #list of squares
        self.marked_square = 0  #state of a square

    def final_condition(self, show=False):
        #returning 0 if there is no win till now(not a draw condition), if player 1 wins - then returns 1; if player 2 wins returns 2
        #vertical winning situation
        for col in range(COLS):
            if self.squares[0][col] == self.squares[1][col] == self.squares[2][col] != 0:
                if show:
                    color = CIRCLE if self.squares[0][col] == 2 else CROSS
                    start_pos = (col * SQUARE_SIZE + SQUARE_SIZE // 2, 20)
                    final_pos = (col * SQUARE_SIZE + SQUARE_SIZE // 2, HEIGHT - 20)
                    pygame.draw.line(screen, color, start_pos, final_pos, LINE_WIDTH)
                return self.squares[0][col] #return any of column from previous if stat
        #horizontal winning situation
        for row in range(ROWS):
            if self.squares[row][0] == self.squares[row][1] == self.squares[row][2] != 0:
                if show:
                    color = CIRCLE if self.squares[row][0] == 2 else CROSS
                    start_pos = (20, row * SQUARE_SIZE + SQUARE_SIZE // 2)
                    final_pos = (WIDTH - 20, row * SQUARE_SIZE + SQUARE_SIZE // 2)
                    pygame.draw.line(screen, color, start_pos, final_pos, LINE_WIDTH)
                return self.squares[row][0]

        #going down diagonal winning situation
        if self.squares[0][0] == self.squares[1][1] == self.squares[2][2] != 0:
            if show:
                color = CIRCLE if self.squares[1][1] == 2 else CROSS
                start_pos = (20, 20)
                final_pos = (WIDTH - 20, HEIGHT - 20)
                pygame.draw.line(screen, color, start_pos, final_pos, CROSS_WIDTH)
            return self.squares[1][1] #11 is a common square between 2 diagonals so it's returning this one
        #going up diagonal winning situation
        if self.squares[2][0] == self.squares[1][1] == self.squares[0][2] != 0:
            if show:
                color = CIRCLE if self.squares[1][1] == 2 else CROSS
                start_pos = (20, HEIGHT - 20)
                final_pos = (WIDTH - 20, 20)
                pygame.draw.line(screen, color, start_pos, final_pos, CROSS_WIDTH)
            return self.squares[1][1]

        return 0 #no winning yet

    def mark_squares(self, row, col, player): #for 2 players, one will be marked and zeros in tuple will be replaced in a square that was marked by a player with a player
        self.squares[row][col] = player
        #ach time square is marked it's gonna be increased by one
        self.marked_square += 1

    def empty_square(self, row, col): #checking if the square is empy or not
        return self.squares[row][col] == 0  #if return True than it's empty, if False than bot empty
    def return_empty(self):
        #square that is needed to be deleted from the empty squares
        empty = []
        for row in range(ROWS):
            for col in range(COLS): #2 dimentional array(matrix)
                if self.empty_square[row, col]:
                    empty.append((row, col))
        return empty

    def isfull(self):
        return self.marked_square == 9 #max amount of squares when the board is full
    def isempty(self):
        return self.marked_square == 0 #return if the square is marked

class MinMax:
    def __init__(self, level=1, player=2):
        self.level = level #level of game
        self.player = player #there are 2 players

    def random_choice(self, board): #random choice function
        empty = board.return_empty()
        index = random.randrange(0, len(empty))

        return empty[index] #row and col

    def minmax(self, board, max):
        #checking terminal case
        case = board.final_condition() #case
        #player 1 wins
        if case == 1:
            return 1, None #evaluation, move

        #player 2 wins
        if case == 2:
            return -1, None
        #draw
        elif board.isfull():
            return 0, None
        #coding the algorythm
        if max: #if player is maximizing
            max_eval = -100 #minimal eva;uation that player gets from a specific board
            best_move = None
            empty_square = board.return_empty()
            #loop each square inside of the list of empty squares
            for(row, col) in empty_square:
                temp_board = copy.deepcopy(board) #copying the board for testing on other boards
                temp_board.mark_squares(row, col, 1)#marking the square to a copy
                eval = self.minmax(temp_board, False)[0] #it's true because of changing the player, first position is an evaluation
                if eval > max_eval:
                    max_eval = eval #save eval into max eval
                    best_move = (row, col)
            return max_eval, best_move
        elif not max: #if player is minimizing
            min_eval = 100 #minimal eva;uation that player gets from a specific board
            best_move = None
            empty_square = board.return_empty()
            #loop each square inside of the list of empty squares
            for(row, col) in empty_square:
                temp_board = copy.deepcopy(board) #copying the board for testing on other boards - a copy of the object is copied into another object
                temp_board.mark_squares(row, col, self.player)#marking the square to a copy
                eval = self.minmax(temp_board, True)[0] #it's true because of changing the player, first position is an evaluation
                if eval < min_eval:
                    min_eval = eval
                    best_move = (row, col)
            return min_eval, best_move #returning the min eval with respect to best move

    def evaluation(self, main_board):
        if self.level == 0:
            #random choice
            eval = 'random'
            move = self.random_choice(main_board)
        else:
            #minmax alg choice
            eval, move = self.minmax(main_board, False)

        print(f'Minimax is chosen for marking the square in position {move} with an evaluation {eval}')
        return move #move is the row and the col

#drowing lines for game - lines of the grid
class TicTac:
    def __init__(self): #init method for the new game objects
        self.board = Board() #creating a new board class
        self.comp = MinMax()
        self.player = 2 #who is the next player to mark in the squares #player 1 is crosses and player 2 is circles
        self.gamemode = 'computer' #by human, or by computer (ai)
        self.run = True
        self.lines() #colling the method for showing the lines
    def make_move(self, row, col):
        self.board.mark_squares(row, col, self.player) #the last parameter changes from 1 to tictac.player
        #print(board.squares) #testing, return 0 and 1 in console whether it's empty or not
        self.draw_figure(row, col) #graphic displaying of the information
        self.another_player()
                    #print(board.squares) #checking the another player works or not, result in console

    def reset(self):
        self.__init__() #restarting all attributes to default values

    def lines(self): #defining the creating the grid function
        #background color after reseting
        screen.fill(BACKCOLOR)
        #vertical lines
        pygame.draw.line(screen, LINE_COLOR,(SQUARE_SIZE, 0), (SQUARE_SIZE, HEIGHT), LINE_WIDTH) #first line
        pygame.draw.line(screen, LINE_COLOR,(WIDTH - SQUARE_SIZE, 0), (WIDTH - SQUARE_SIZE, HEIGHT), LINE_WIDTH) #y axis is 0, x axis is first; second line
        #horizontal lines
        pygame.draw.line(screen, LINE_COLOR,(0,SQUARE_SIZE), (WIDTH, SQUARE_SIZE), LINE_WIDTH) #first line
        pygame.draw.line(screen, LINE_COLOR,(0, HEIGHT - SQUARE_SIZE), (WIDTH, HEIGHT - SQUARE_SIZE), LINE_WIDTH) #second line

    def draw_figure(self, row, col):
        if self.player == 1:
            #drawing the cross
            start_down_line = (col * SQUARE_SIZE + OFFSET, row * SQUARE_SIZE + OFFSET) #adjusting the down going line of the cross
            end_down_line = (col * SQUARE_SIZE + SQUARE_SIZE - OFFSET, row * SQUARE_SIZE + SQUARE_SIZE - OFFSET)
            pygame.draw.line(screen, CROSS, start_down_line, end_down_line, CROSS_WIDTH) #drawing the cross
            #going up line
            start_up_line = (col * SQUARE_SIZE + OFFSET, row * SQUARE_SIZE + SQUARE_SIZE - OFFSET)
            end_up_line = (col * SQUARE_SIZE + SQUARE_SIZE - OFFSET, row * SQUARE_SIZE + OFFSET)
            pygame.draw.line(screen, CROSS, start_up_line, end_up_line, CROSS_WIDTH) #drawing the line

        elif self.player == 2:
            #drawing the circle
            center = (col * SQUARE_SIZE + SQUARE_SIZE // 2, row * SQUARE_SIZE + SQUARE_SIZE // 2) #center position
            pygame.draw.circle(screen, CIRCLE, center, RADIUS, CIRCLE_WIDTH)

    def another_player(self): #chenging the player that is marking the square to the next one
        self.player = self.player % 2 + 1 #first operation will return the remainder ((model)%2) if the player is 1, than it adds 1 and there is o a remainder so the player is changing

    def change_gamemode(self):
        #self.gamemode = 'computer' if self.gamemode == 'user' else 'user'
        if self.gamemode == 'user':
            self.gamemode = 'computer'
        else:
            self.gamemode = 'user'

    def isover(self):
        return self.board.final_condition(show=True) != 0 or self.board.isfull()

def main(): #main function where the code will be executing
    #game object
    tictac = TicTac() #object and the class
    board = tictac.board
    comp = tictac.comp

    #mainloop
    while True:
            #pygame events
        for event in pygame.event.get():

            if event.type == pygame.QUIT: #event is any actin happening in the game(pressing the key etc)
                pygame.quit()
                sys.exit() #for exiting the game

            if event.type == pygame.KEYDOWN: #keydown event
                #g-gamemode
                if event.key == pygame.K_g:
                    tictac.change_gamemode()
                # r = restart
                if event.key == pygame.K_r:
                    tictac.reset()
                    board = tictac.board #board and ai will be reseted again and start from the initializing condition
                    comp = tictac.comp
                # 0 -random computer alg
                if event.key == pygame.K_0:
                    comp.level = 0
                    # 1 - random
                if event.key == pygame.K_1:
                    comp.level = 1

            if event.type == pygame.MOUSEBUTTONDOWN: #position of coursor in the pixels
                pos = event.pos #position of pixels
                row = pos[1]//SQUARE_SIZE #represents y axis of the board
                col = pos[0]//SQUARE_SIZE #position 0 of x axis
                #print(row, col) #testing
                if board.empty_square[row,col] and tictac.run:
                    tictac.make_move(row, col)

                    if tictac.isover():
                        tictac.run = False

                #board.mark_squares(row, col, 1) #in a position row col player number 1
                #print(tictac.board.squares) #testing the board, returns information to console
        if tictac.gamemode == 'computer' and tictac.player == comp.player and tictac.run:
            #update the screen
            pygame.display.update()

            #computer methods
            row, col = comp.evaluation(board)
            #board.mark_squares(row, col, comp.player)
            tictac.make_move(row, col)

            if tictac.isover():
                tictac.run = False

        pygame.display.update() #updating the screen
#minimax alg =
""" terminal case and the base case - terminal case is when the game is over
3 situations: 1) player 1 wins, 2) player 2 wins, 3) draw //terminal cases

if __name__ == "__main__":
    main()
</code>```

Body:
I'm trying to make a tic tac toe game for 2 players - user and computer using minimax algorythm. My problem is that the code has an error and it doesn't work properly, but I'm not sure why. More explanation about code you can see in comments for code.
I have a TypeError: cannot unpack non-iterable Non-Type object for line 258 in main row, col = comp.evaluation(board)

Here is the code and comments:
file ttt1 with variables assignment:

import random
WIDTH = 600
HEIGHT = 600

ROWS = 3 #rows of the grid
COLS = 3 #cols of the grid

SQUARE_SIZE = WIDTH // COLS #size of one square of the grid - can be height devided by rows
LINE_WIDTH = 15 #width of the lines of the grid

#circle
CIRCLE_WIDTH = 20
RADIUS = SQUARE_SIZE // 3

#cross
CROSS_WIDTH = 20

OFFSET = 50

#define colors
BACKCOLOR = ((random.randint(0,255)), (random.randint(0, 255)), (random.randint(0,255)))
LINE_COLOR = ((random.randint(0,255)), (random.randint(0, 255)), (random.randint(0,255)))
CIRCLE = ((random.randint(0,255)), (random.randint(0, 255)), (random.randint(0,255)))
CROSS = ((random.randint(0,255)), (random.randint(0, 255)), (random.randint(0,255)))

file with classes and etc:

import sys #for quitting the application
import copy
import random
import pygame
import numpy as np

from ttt1 import * #importing things from ttt1 file

#pygamecode and set up
pygame.init() #initializig pygame module
screen = pygame.display.set_mode((WIDTH, HEIGHT)) #setting up the screen - width and height
pygame.display.set_caption("Tic Tac Toe game with minimax")
screen.fill(BACKCOLOR) #filling in the screen with a background colors

class Board:

    def __init__(self): #2 dimensional array of 0-s
        self.squares = np.zeros((ROWS, COLS)) #parameters as tuple with 0-s, making empty squares
        #self.mark_squares(1, 2, 3) #for testing
        #print(self.squares) #return 0-s in terminal
        self.empty_square = self.squares #list of squares
        self.marked_square = 0  #state of a square

    def final_condition(self, show=False):
        #returning 0 if there is no win till now(not a draw condition), if player 1 wins - then returns 1; if player 2 wins returns 2
        #vertical winning situation
        for col in range(COLS):
            if self.squares[0][col] == self.squares[1][col] == self.squares[2][col] != 0:
                if show:
                    color = CIRCLE if self.squares[0][col] == 2 else CROSS
                    start_pos = (col * SQUARE_SIZE + SQUARE_SIZE // 2, 20)
                    final_pos = (col * SQUARE_SIZE + SQUARE_SIZE // 2, HEIGHT - 20)
                    pygame.draw.line(screen, color, start_pos, final_pos, LINE_WIDTH)
                return self.squares[0][col] #return any of column from previous if stat
        #horizontal winning situation
        for row in range(ROWS):
            if self.squares[row][0] == self.squares[row][1] == self.squares[row][2] != 0:
                if show:
                    color = CIRCLE if self.squares[row][0] == 2 else CROSS
                    start_pos = (20, row * SQUARE_SIZE + SQUARE_SIZE // 2)
                    final_pos = (WIDTH - 20, row * SQUARE_SIZE + SQUARE_SIZE // 2)
                    pygame.draw.line(screen, color, start_pos, final_pos, LINE_WIDTH)
                return self.squares[row][0]

        #going down diagonal winning situation
        if self.squares[0][0] == self.squares[1][1] == self.squares[2][2] != 0:
            if show:
                color = CIRCLE if self.squares[1][1] == 2 else CROSS
                start_pos = (20, 20)
                final_pos = (WIDTH - 20, HEIGHT - 20)
                pygame.draw.line(screen, color, start_pos, final_pos, CROSS_WIDTH)
            return self.squares[1][1] #11 is a common square between 2 diagonals so it's returning this one
        #going up diagonal winning situation
        if self.squares[2][0] == self.squares[1][1] == self.squares[0][2] != 0:
            if show:
                color = CIRCLE if self.squares[1][1] == 2 else CROSS
                start_pos = (20, HEIGHT - 20)
                final_pos = (WIDTH - 20, 20)
                pygame.draw.line(screen, color, start_pos, final_pos, CROSS_WIDTH)
            return self.squares[1][1]

        return 0 #no winning yet

    def mark_squares(self, row, col, player): #for 2 players, one will be marked and zeros in tuple will be replaced in a square that was marked by a player with a player
        self.squares[row][col] = player
        #ach time square is marked it's gonna be increased by one
        self.marked_square += 1

    def empty_square(self, row, col): #checking if the square is empy or not
        return self.squares[row][col] == 0  #if return True than it's empty, if False than bot empty
    def return_empty(self):
        #square that is needed to be deleted from the empty squares
        empty = []
        for row in range(ROWS):
            for col in range(COLS): #2 dimentional array(matrix)
                if self.empty_square[row, col]:
                    empty.append((row, col))
        return empty

    def isfull(self):
        return self.marked_square == 9 #max amount of squares when the board is full
    def isempty(self):
        return self.marked_square == 0 #return if the square is marked

class MinMax:
    def __init__(self, level=1, player=2):
        self.level = level #level of game
        self.player = player #there are 2 players

    def random_choice(self, board): #random choice function
        empty = board.return_empty()
        index = random.randrange(0, len(empty))

        return empty[index] #row and col

    def minmax(self, board, max):
        #checking terminal case
        case = board.final_condition() #case
        #player 1 wins
        if case == 1:
            return 1, None #evaluation, move

        #player 2 wins
        if case == 2:
            return -1, None
        #draw
        elif board.isfull():
            return 0, None
        #coding the algorythm
        if max: #if player is maximizing
            max_eval = -100 #minimal eva;uation that player gets from a specific board
            best_move = None
            empty_square = board.return_empty()
            #loop each square inside of the list of empty squares
            for(row, col) in empty_square:
                temp_board = copy.deepcopy(board) #copying the board for testing on other boards
                temp_board.mark_squares(row, col, 1)#marking the square to a copy
                eval = self.minmax(temp_board, False)[0] #it's true because of changing the player, first position is an evaluation
                if eval > max_eval:
                    max_eval = eval #save eval into max eval
                    best_move = (row, col)
            return max_eval, best_move
        elif not max: #if player is minimizing
            min_eval = 100 #minimal eva;uation that player gets from a specific board
            best_move = None
            empty_square = board.return_empty()
            #loop each square inside of the list of empty squares
            for(row, col) in empty_square:
                temp_board = copy.deepcopy(board) #copying the board for testing on other boards - a copy of the object is copied into another object
                temp_board.mark_squares(row, col, self.player)#marking the square to a copy
                eval = self.minmax(temp_board, True)[0] #it's true because of changing the player, first position is an evaluation
                if eval < min_eval:
                    min_eval = eval
                    best_move = (row, col)
            return min_eval, best_move #returning the min eval with respect to best move

    def evaluation(self, main_board):
        if self.level == 0:
            #random choice
            eval = 'random'
            move = self.random_choice(main_board)
        else:
            #minmax alg choice
            eval, move = self.minmax(main_board, False)

        print(f'Minimax is chosen for marking the square in position {move} with an evaluation {eval}')
        return move #move is the row and the col

#drowing lines for game - lines of the grid
class TicTac:
    def __init__(self): #init method for the new game objects
        self.board = Board() #creating a new board class
        self.comp = MinMax()
        self.player = 2 #who is the next player to mark in the squares #player 1 is crosses and player 2 is circles
        self.gamemode = 'computer' #by human, or by computer (ai)
        self.run = True
        self.lines() #colling the method for showing the lines
    def make_move(self, row, col):
        self.board.mark_squares(row, col, self.player) #the last parameter changes from 1 to tictac.player
        #print(board.squares) #testing, return 0 and 1 in console whether it's empty or not
        self.draw_figure(row, col) #graphic displaying of the information
        self.another_player()
                    #print(board.squares) #checking the another player works or not, result in console

    def reset(self):
        self.__init__() #restarting all attributes to default values

    def lines(self): #defining the creating the grid function
        #background color after reseting
        screen.fill(BACKCOLOR)
        #vertical lines
        pygame.draw.line(screen, LINE_COLOR,(SQUARE_SIZE, 0), (SQUARE_SIZE, HEIGHT), LINE_WIDTH) #first line
        pygame.draw.line(screen, LINE_COLOR,(WIDTH - SQUARE_SIZE, 0), (WIDTH - SQUARE_SIZE, HEIGHT), LINE_WIDTH) #y axis is 0, x axis is first; second line
        #horizontal lines
        pygame.draw.line(screen, LINE_COLOR,(0,SQUARE_SIZE), (WIDTH, SQUARE_SIZE), LINE_WIDTH) #first line
        pygame.draw.line(screen, LINE_COLOR,(0, HEIGHT - SQUARE_SIZE), (WIDTH, HEIGHT - SQUARE_SIZE), LINE_WIDTH) #second line

    def draw_figure(self, row, col):
        if self.player == 1:
            #drawing the cross
            start_down_line = (col * SQUARE_SIZE + OFFSET, row * SQUARE_SIZE + OFFSET) #adjusting the down going line of the cross
            end_down_line = (col * SQUARE_SIZE + SQUARE_SIZE - OFFSET, row * SQUARE_SIZE + SQUARE_SIZE - OFFSET)
            pygame.draw.line(screen, CROSS, start_down_line, end_down_line, CROSS_WIDTH) #drawing the cross
            #going up line
            start_up_line = (col * SQUARE_SIZE + OFFSET, row * SQUARE_SIZE + SQUARE_SIZE - OFFSET)
            end_up_line = (col * SQUARE_SIZE + SQUARE_SIZE - OFFSET, row * SQUARE_SIZE + OFFSET)
            pygame.draw.line(screen, CROSS, start_up_line, end_up_line, CROSS_WIDTH) #drawing the line

        elif self.player == 2:
            #drawing the circle
            center = (col * SQUARE_SIZE + SQUARE_SIZE // 2, row * SQUARE_SIZE + SQUARE_SIZE // 2) #center position
            pygame.draw.circle(screen, CIRCLE, center, RADIUS, CIRCLE_WIDTH)

    def another_player(self): #chenging the player that is marking the square to the next one
        self.player = self.player % 2 + 1 #first operation will return the remainder ((model)%2) if the player is 1, than it adds 1 and there is o a remainder so the player is changing

    def change_gamemode(self):
        #self.gamemode = 'computer' if self.gamemode == 'user' else 'user'
        if self.gamemode == 'user':
            self.gamemode = 'computer'
        else:
            self.gamemode = 'user'

    def isover(self):
        return self.board.final_condition(show=True) != 0 or self.board.isfull()

def main(): #main function where the code will be executing
    #game object
    tictac = TicTac() #object and the class
    board = tictac.board
    comp = tictac.comp

    #mainloop
    while True:
            #pygame events
        for event in pygame.event.get():

            if event.type == pygame.QUIT: #event is any actin happening in the game(pressing the key etc)
                pygame.quit()
                sys.exit() #for exiting the game

            if event.type == pygame.KEYDOWN: #keydown event
                #g-gamemode
                if event.key == pygame.K_g:
                    tictac.change_gamemode()
                # r = restart
                if event.key == pygame.K_r:
                    tictac.reset()
                    board = tictac.board #board and ai will be reseted again and start from the initializing condition
                    comp = tictac.comp
                # 0 -random computer alg
                if event.key == pygame.K_0:
                    comp.level = 0
                    # 1 - random
                if event.key == pygame.K_1:
                    comp.level = 1

            if event.type == pygame.MOUSEBUTTONDOWN: #position of coursor in the pixels
                pos = event.pos #position of pixels
                row = pos[1]//SQUARE_SIZE #represents y axis of the board
                col = pos[0]//SQUARE_SIZE #position 0 of x axis
                #print(row, col) #testing
                if board.empty_square[row,col] and tictac.run:
                    tictac.make_move(row, col)

                    if tictac.isover():
                        tictac.run = False

                #board.mark_squares(row, col, 1) #in a position row col player number 1
                #print(tictac.board.squares) #testing the board, returns information to console
        if tictac.gamemode == 'computer' and tictac.player == comp.player and tictac.run:
            #update the screen
            pygame.display.update()

            #computer methods
            row, col = comp.evaluation(board)
            #board.mark_squares(row, col, comp.player)
            tictac.make_move(row, col)

            if tictac.isover():
                tictac.run = False

        pygame.display.update() #updating the screen
#minimax alg =
""" terminal case and the base case - terminal case is when the game is over
3 situations: 1) player 1 wins, 2) player 2 wins, 3) draw //terminal cases

if __name__ == "__main__":
    main()


问:
error 403 showing while fetching the flight data from API
There are the errors

Theses are the errors.

```<code>componentDidMount() {
        const options = {
            method: 'GET',
            url: 'https://timetable-lookup.p.rapidapi.com/TimeTable/BOS/LAX/20191217/',
            headers: {
              'X-RapidAPI-Key': 'SIGN-UP-FOR-KEY',
              'X-RapidAPI-Host': 'timetable-lookup.p.rapidapi.com'
            }
          };

          axios.request(options).then(function (response) {
            console.log(response.data);
        }).catch(function (error) {
            console.error(error);
        });
    }
</code>```

i am trying to fetch data for a flight booking system and getting this error.

Body:
There are the errors

Theses are the errors.

componentDidMount() {
        const options = {
            method: 'GET',
            url: 'https://timetable-lookup.p.rapidapi.com/TimeTable/BOS/LAX/20191217/',
            headers: {
              'X-RapidAPI-Key': 'SIGN-UP-FOR-KEY',
              'X-RapidAPI-Host': 'timetable-lookup.p.rapidapi.com'
            }
          };

          axios.request(options).then(function (response) {
            console.log(response.data);
        }).catch(function (error) {
            console.error(error);
        });
    }

i am trying to fetch data for a flight booking system and getting this error.


问:
Python list to connected graph with Kivy
I am creating a program with Python Kivy framework. Basically, it is an undirected graph concept to implement. The UI is like following:

Where I want to connect among buildings/vertices. And, the nested list[] output is the connection among buildings/vertices. For example the output shown in the UI image, where 0 position nested array is the first building/vertex  and in the list shown 5 means, 0 positioned vertex is connected to 5th position vertex. Furthermore, we can connect via the input fields.

I want to produce UI based on the output list[]. Where, 12 circles/rectangles will be connected via lines based on the list[]. And, I want to show the output just below the output list.

Is it possible with Kivy and with my output list[]? Please let me know.


问:
Gitlab CI/CD through SSH causing error and unable to SSH into aws-ec2-linux server
```<code>OpenSSH_7.4p1, OpenSSL 1.0.2k-fips  26 Jan 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 58: Applying options for *
debug1: Connecting to ec2-18-216-48-255.us-east-2.compute.amazonaws.com [10.0.15.9] port 22.
debug1: Connection established.
debug1: key_load_public: No such file or directory
debug1: identity file Rifter-Test-Server.pem type -1
debug1: key_load_public: No such file or directory
debug1: identity file Rifter-Test-Server.pem-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4
debug1: match: OpenSSH_7.4 pat OpenSSH* compat 0x04000000
debug1: Authenticating to ec2-18-216-48-255.us-east-2.compute.amazonaws.com:22 as 'ec2-user'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: curve25519-sha256 need=64 dh_need=64
debug1: kex: curve25519-sha256 need=64 dh_need=64
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:KCe1X9MVFUImH5H9q8EkV2VLJ3bSehsJbSLnlWiMM+o
debug1: Host 'ec2-18-216-48-255.us-east-2.compute.amazonaws.com' is known and matches the ECDSA host key.
debug1: Found key in /home/gitlab-runner/.ssh/known_hosts:29
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic
debug1: Next authentication method: gssapi-keyex
debug1: No valid Key exchange context
debug1: Next authentication method: gssapi-with-mic
debug1: Unspecified GSS failure.  Minor code may provide more information
No Kerberos credentials available (default cache: KEYRING:persistent:994)
debug1: Unspecified GSS failure.  Minor code may provide more information
No Kerberos credentials available (default cache: KEYRING:persistent:994)
debug1: Next authentication method: publickey
debug1: Trying private key: Rifter-Test-Server.pem
debug1: read_passphrase: can't open /dev/tty: No such device or address
debug1: No more authentication methods to try.
Permission denied (publickey,gssapi-keyex,gssapi-with-mic).
</code>```

while my gitlab yaml config's are as follows

deploy:
stage: deploy
before_script:

mkdir -p ~/.ssh

chmod 700 ~/.ssh

echo -e “$SSH_PRIVATE_KEY” > ~/.ssh/id_rsa

ssh-keyscan $EC2_IPADDRESS >> ~/.ssh/known_hosts

chmod 700 ~/.ssh/*
tags:

node
script:
- ssh -Tv -i "~/.ssh/id_rsa" ec2-user@ec2-18-216-48-255.us-east-2.compute.amazonaws.com "ll; whoami"

Tried several options for login from gitlab CI/CD to aws-ec2-linux but unable till yet if anyone can see the SSH logs and help me resolving this issue.

Body:
OpenSSH_7.4p1, OpenSSL 1.0.2k-fips  26 Jan 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 58: Applying options for *
debug1: Connecting to ec2-18-216-48-255.us-east-2.compute.amazonaws.com [10.0.15.9] port 22.
debug1: Connection established.
debug1: key_load_public: No such file or directory
debug1: identity file Rifter-Test-Server.pem type -1
debug1: key_load_public: No such file or directory
debug1: identity file Rifter-Test-Server.pem-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.4
debug1: match: OpenSSH_7.4 pat OpenSSH* compat 0x04000000
debug1: Authenticating to ec2-18-216-48-255.us-east-2.compute.amazonaws.com:22 as 'ec2-user'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: curve25519-sha256
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: chacha20-poly1305@openssh.com MAC: <implicit> compression: none
debug1: kex: curve25519-sha256 need=64 dh_need=64
debug1: kex: curve25519-sha256 need=64 dh_need=64
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:KCe1X9MVFUImH5H9q8EkV2VLJ3bSehsJbSLnlWiMM+o
debug1: Host 'ec2-18-216-48-255.us-east-2.compute.amazonaws.com' is known and matches the ECDSA host key.
debug1: Found key in /home/gitlab-runner/.ssh/known_hosts:29
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic
debug1: Next authentication method: gssapi-keyex
debug1: No valid Key exchange context
debug1: Next authentication method: gssapi-with-mic
debug1: Unspecified GSS failure.  Minor code may provide more information
No Kerberos credentials available (default cache: KEYRING:persistent:994)
debug1: Unspecified GSS failure.  Minor code may provide more information
No Kerberos credentials available (default cache: KEYRING:persistent:994)
debug1: Next authentication method: publickey
debug1: Trying private key: Rifter-Test-Server.pem
debug1: read_passphrase: can't open /dev/tty: No such device or address
debug1: No more authentication methods to try.
Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

while my gitlab yaml config's are as follows

deploy:
stage: deploy
before_script:

mkdir -p ~/.ssh

chmod 700 ~/.ssh

echo -e “$SSH_PRIVATE_KEY” > ~/.ssh/id_rsa

ssh-keyscan $EC2_IPADDRESS >> ~/.ssh/known_hosts

chmod 700 ~/.ssh/*
tags:

node
script:
- ssh -Tv -i "~/.ssh/id_rsa" ec2-user@ec2-18-216-48-255.us-east-2.compute.amazonaws.com "ll; whoami"

Tried several options for login from gitlab CI/CD to aws-ec2-linux but unable till yet if anyone can see the SSH logs and help me resolving this issue.


问:
How to install Apk in Android studio and add tests using it?
I am a beginner in Android UI automation. Have a few doubts but am not able to find any relevant information. All the tutorials have a source code and have no explanation on how to install your own app in Android studio and how to create the corresponding AndroidManifest.xml

Any input would be appreciated.

I tried using Build->Analyze APK and fetching my apk but not sure how to get the corresponding Android Manifest file and point my tests to start using the apk.


问:
update a object second value as a object with JSON_SET in mysql apostrof problem
I hava a longtext type column in mysql and it is default value is like that :

```<code>{"aaaaa": [], "bbbbb": []}
</code>```

when I want to update that column with :

```<code>const IamCreator = 1;
const myValue= [1,22,66,77]; //object

const query = `UPDATE 8users SET content = JSON_SET(content, '$.aaaaa', '?') WHERE id = ?`;
            connection.query(query,[myValue,IamCreator],function (err, result, fields) {
                console.log(err)
            })
</code>```

it give syntex problemand update value like that ;

{"aaaaa": "[1,22,66,77]", "bbbbb": []}

how can I solve that appostrof prolem?

I tried :

```<code>content = JSON_SET(content, '$.aaaaa', ?)
content = JSON_SET(content,'$.aaaaa', [?])
const query = `UPDATE table SET json_column = JSON_SET(json_column, '$.mykanban', ?) WHERE id = ?`; connection.query(query, [JSON.stringify(myValue), IamCreator]);
</code>```

ı took syntex error all the time

Body:
I hava a longtext type column in mysql and it is default value is like that :

{"aaaaa": [], "bbbbb": []}

when I want to update that column with :

const IamCreator = 1;
const myValue= [1,22,66,77]; //object

const query = `UPDATE 8users SET content = JSON_SET(content, '$.aaaaa', '?') WHERE id = ?`;
            connection.query(query,[myValue,IamCreator],function (err, result, fields) {
                console.log(err)
            })

it give syntex problemand update value like that ;

{"aaaaa": "[1,22,66,77]", "bbbbb": []}

how can I solve that appostrof prolem?

I tried :

content = JSON_SET(content, '$.aaaaa', ?)
content = JSON_SET(content,'$.aaaaa', [?])
const query = `UPDATE table SET json_column = JSON_SET(json_column, '$.mykanban', ?) WHERE id = ?`; connection.query(query, [JSON.stringify(myValue), IamCreator]);

ı took syntex error all the time


问:
Visual studio not able to debug native code referenced from C#, the breakpoint will not be currently hit, no symbols have been loaded for document
I followed all the instructions mentioned on the following page to enable native debugging.
https://learn.microsoft.com/en-us/visualstudio/debugger/how-to-debug-managed-and-native-code?view=vs-2022. However Visual studio 2022 is still showing the error on placing breakpoint : "the breakpoint will not be currently hit, no symbols have been loaded for document"

Can someone please help what I could be missing?


问:
PM2 stop or restart process doesn't trigger process.exit() in node.js
I want to perform some cleanup tasks when a PM2 process stops or restarts. I've followed instructions from the link Graceful Start/Shutdown, but nothing is working.

I'm logging in a file when process exits or receive any signal. When I run with nodemon, it works fine. But with pm2, it is not working. I'm using windows 10 with node 16.13.0.

My code is:

```<code>function log(message: string) {
  fs.appendFileSync("log.txt", message + new Date().toLocaleString() + "\n");
}

process.on("message", () => {
  log("Message received...");
});

process.on("exit", () => {
  log("Exiting finally...");
  process.exit();
});
process.on("SIGINT", () => {
  log("Exiting finally...");
  process.exit();
});
process.on("SIGTERM", () => {
  log("Exiting finally...");
  process.exit();
});
</code>```

Body:
I want to perform some cleanup tasks when a PM2 process stops or restarts. I've followed instructions from the link Graceful Start/Shutdown, but nothing is working.

I'm logging in a file when process exits or receive any signal. When I run with nodemon, it works fine. But with pm2, it is not working. I'm using windows 10 with node 16.13.0.

My code is:

function log(message: string) {
  fs.appendFileSync("log.txt", message + new Date().toLocaleString() + "\n");
}

process.on("message", () => {
  log("Message received...");
});

process.on("exit", () => {
  log("Exiting finally...");
  process.exit();
});
process.on("SIGINT", () => {
  log("Exiting finally...");
  process.exit();
});
process.on("SIGTERM", () => {
  log("Exiting finally...");
  process.exit();
});


问:
ERR unknown command '--cluster' when rebalancing slots
I have created a RedisClient using go-redis

```<code>rdClient := rd.NewClusterClient(rdClusterOpts)
</code>```

I can do other database operation using the client

```<code>out,err := rdClient.Ping(context.TODO()).Result()
PONG
</code>```

I can also do get set operation using the client.
When I try to rebalance the slots, it shows an error.

```<code>out, err := rdClient.Do(context.TODO(), "--cluster", "rebalance", "10.244.0.98", "--cluster-use-empty-masters").Result()
</code>```

It shows the Error

```<code>ERR unknown command '--cluster', with args beginning with: 'rebalance' '10.244.0.96:6379' '--cluster-use-empty-masters
</code>```

Is there any way to perform the Redis Cluster Manager commands using go-redis or any other go redis client ?

Body:
I have created a RedisClient using go-redis

rdClient := rd.NewClusterClient(rdClusterOpts)

I can do other database operation using the client

out,err := rdClient.Ping(context.TODO()).Result()
PONG

I can also do get set operation using the client.
When I try to rebalance the slots, it shows an error.

out, err := rdClient.Do(context.TODO(), "--cluster", "rebalance", "10.244.0.98", "--cluster-use-empty-masters").Result()

It shows the Error

ERR unknown command '--cluster', with args beginning with: 'rebalance' '10.244.0.96:6379' '--cluster-use-empty-masters

Is there any way to perform the Redis Cluster Manager commands using go-redis or any other go redis client ?