问:
socket_read fails after 2 attempts
I am trying to connect to a TCP socket server using php. First 2 connections and send it is successfull but after that it can not read, hangs at socket_read.

```<code><?php

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_connect($sock, '127.0.0.1', 10000) === false) {
    echo "socket_connect() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

do {

    $stdin = fopen('php://stdin', 'r');
    $msg = trim(fgets($stdin));
    socket_write($sock, $msg, strlen($msg));

    if (false === ($buf = socket_read($sock, 2048, PHP_NORMAL_READ))) {
        echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
    }

    echo "response: $buf \n";

} while (true);
</code>```

Server is functioning properly there are no problems on that end. Any suggestions anyone ?

Title: socket_read fails after 2 attempts

Body:
I am trying to connect to a TCP socket server using php. First 2 connections and send it is successfull but after that it can not read, hangs at socket_read.

<?php

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_connect($sock, '127.0.0.1', 10000) === false) {
    echo "socket_connect() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}

do {

    $stdin = fopen('php://stdin', 'r');
    $msg = trim(fgets($stdin));
    socket_write($sock, $msg, strlen($msg));

    if (false === ($buf = socket_read($sock, 2048, PHP_NORMAL_READ))) {
        echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
    }

    echo "response: $buf \n";

} while (true);

Server is functioning properly there are no problems on that end. Any suggestions anyone ?


来源: stackexchange

问:
Change value of array element at specific index
I want to change the value of array element at a specific position but whenever i am trying to so it throws me an error. Can anyone suggest me a way to change the value

```<code>{% set explode_field_id = data.field_id|split('-') %}
{% set explode_field_id_length = explode_field_id|length %}
{% set reqValue = explode_field_id_length - 1 %}
{% set explode_field_id[reqValue] = data.field_details[dependent_field] %}
{% set dependent_field_id = explode_field_id|join('-') %}
</code>```

Here explode_field_id = categoryList-category_list-0-category_list

ERROR - Unexpected token "punctuation" of value "[" ("end of statement block" expected).

ContentLicense: CC BY-SA 4.0

Body:
I want to change the value of array element at a specific position but whenever i am trying to so it throws me an error. Can anyone suggest me a way to change the value

{% set explode_field_id = data.field_id|split('-') %}
{% set explode_field_id_length = explode_field_id|length %}
{% set reqValue = explode_field_id_length - 1 %}
{% set explode_field_id[reqValue] = data.field_details[dependent_field] %}
{% set dependent_field_id = explode_field_id|join('-') %}

Here explode_field_id = categoryList-category_list-0-category_list

ERROR - Unexpected token "punctuation" of value "[" ("end of statement block" expected).


问:
MSAL logoutRedirect leads to being stuck on iPhone/Safari (network request not finishing)
We have a WebApp developed with Angular 14. It is deployed on Azure Blob Storage (static website).
Authentification is done with the msal library for javascript. Azure AD B2C is used as identity provider.

To logout we use the method msalService.logoutRedirect() which will then redirect to our login page again. This works for all devices without a problem except on iPhones using the Safari browser. When we logout on iPhone/Safari it sometimes gets stuck and Safari displays a "neverending" network request (where google.fonts are loaded but I doubt this is really the case). The page itself then displays a whitescreen and the network tab displays a never ending network request:

If you then try to manually refresh the page the following errors are shown in the console (the screen is still white, but after about a minute Safari is usually able to recover from this state and you see the login page again):

Whenever we deploy, the built WebApp is deployed to the Blob Storage (older versions are not deleted first, so there are unreferenced/unused files on the Blob Storage). This error is not reproducable (until now) on a temporary stage on a different blob storage account (that only holds the current version and no unreferenced files).

Has anyone an idea if there could be a difference in the Azure Blob Storage itself, that could cause this?
Otherwise, could the MsalInterceptor and the MsalGuard somehow interfere and cause this problem?

Additional information and code snippets:
We handle the redirect observable by bootstrapping the MsalRedirectComponent and add it to the index.html file. We use the MsalGuard and the MsalInterceptor and have them configured like this:

```<code>@NgModule({
 // declarations, imports, exports...,
 providers: [
   {
      provide: HTTP_INTERCEPTORS,
      useClass: MsalInterceptor,
      multi: true,
    },
    {
      provide: MSAL_INTERCEPTOR_CONFIG,
      useFactory: () => ({
        interactionType: InteractionType.Redirect,
        protectedResourceMap: authConfig.protectedResources,
        authRequest: {
          scopes: environment.auth.scopes,
        },
      }),
    },
    MsalGuard,
    {
      provide: MSAL_GUARD_CONFIG,
      useFactory: () => ({
        interactionType: InteractionType.Redirect,
        authRequest: {
          scopes: environment.auth.scopes,
        },
      }),
    },
    // some other providers
  ]
})
</code>```

We are listening for the InteractionStatus.None from the inProgress$ observable before we load the current logged in user like this:

```<code>this.msalBroadcastService.inProgress$.pipe(
      filter(status => status === InteractionStatus.None)
  ).subscribe(...)
</code>```

Body:
We have a WebApp developed with Angular 14. It is deployed on Azure Blob Storage (static website).
Authentification is done with the msal library for javascript. Azure AD B2C is used as identity provider.

To logout we use the method msalService.logoutRedirect() which will then redirect to our login page again. This works for all devices without a problem except on iPhones using the Safari browser. When we logout on iPhone/Safari it sometimes gets stuck and Safari displays a "neverending" network request (where google.fonts are loaded but I doubt this is really the case). The page itself then displays a whitescreen and the network tab displays a never ending network request:

If you then try to manually refresh the page the following errors are shown in the console (the screen is still white, but after about a minute Safari is usually able to recover from this state and you see the login page again):

Whenever we deploy, the built WebApp is deployed to the Blob Storage (older versions are not deleted first, so there are unreferenced/unused files on the Blob Storage). This error is not reproducable (until now) on a temporary stage on a different blob storage account (that only holds the current version and no unreferenced files).

Has anyone an idea if there could be a difference in the Azure Blob Storage itself, that could cause this?
Otherwise, could the MsalInterceptor and the MsalGuard somehow interfere and cause this problem?

Additional information and code snippets:
We handle the redirect observable by bootstrapping the MsalRedirectComponent and add it to the index.html file. We use the MsalGuard and the MsalInterceptor and have them configured like this:

@NgModule({
 // declarations, imports, exports...,
 providers: [
   {
      provide: HTTP_INTERCEPTORS,
      useClass: MsalInterceptor,
      multi: true,
    },
    {
      provide: MSAL_INTERCEPTOR_CONFIG,
      useFactory: () => ({
        interactionType: InteractionType.Redirect,
        protectedResourceMap: authConfig.protectedResources,
        authRequest: {
          scopes: environment.auth.scopes,
        },
      }),
    },
    MsalGuard,
    {
      provide: MSAL_GUARD_CONFIG,
      useFactory: () => ({
        interactionType: InteractionType.Redirect,
        authRequest: {
          scopes: environment.auth.scopes,
        },
      }),
    },
    // some other providers
  ]
})

We are listening for the InteractionStatus.None from the inProgress$ observable before we load the current logged in user like this:

this.msalBroadcastService.inProgress$.pipe(
      filter(status => status === InteractionStatus.None)
  ).subscribe(...)


问:
How to pass all arguments of a function to a program?
Following-up on the last suggestion of a previous answer, I am trying to find a way to disable interpretation of the parameters I want to feed to an executable

Since

```<code>D:\program.exe this is a #full sentence
</code>```

will discard #full sentence as a comment (and I specifically do not want to use quotes), I was hoping that an intermediate function would fix the problem:

```<code>function global:note {
  D:\program.exe  --% @Args
}
</code>```

The rationale was that I do not want to interpret anything after --% in the course of the execution of program.exe, but still want to replace @Args when running the function note (as part of the execution of the function). Unfortunately, the result is a verbatim

```<code>D:\program.exe @Args
</code>```

(the argument of program.exe is the string @Args)

My question: why isn't @Args expanded in the presence of --%, and the expansion happens without? Isn't --% supposed to stop the interpretation of the command line (i.e. do not interpret the command line for D:\program.exe this is a #full sentence when the arguments of the function are this is a #full sentence)

Following Matthias' comment on splatting, here is what I get in different scenarios:

Case 1

```<code>function global:note {
  D:\program.exe @Args
}
</code>```

Output when typing note this is a #complete sentence at the PS prompt:

```<code>this is a
</code>```

Case 2

```<code>function global:note {
  D:\program.exe --% @Args
}
</code>```

Output when typing note this is a #complete sentence at the PS prompt:

```<code>@Args
</code>```

Body:
Following-up on the last suggestion of a previous answer, I am trying to find a way to disable interpretation of the parameters I want to feed to an executable

Since

D:\program.exe this is a #full sentence

will discard #full sentence as a comment (and I specifically do not want to use quotes), I was hoping that an intermediate function would fix the problem:

function global:note {
  D:\program.exe  --% @Args
}

The rationale was that I do not want to interpret anything after --% in the course of the execution of program.exe, but still want to replace @Args when running the function note (as part of the execution of the function). Unfortunately, the result is a verbatim

D:\program.exe @Args

(the argument of program.exe is the string @Args)

My question: why isn't @Args expanded in the presence of --%, and the expansion happens without? Isn't --% supposed to stop the interpretation of the command line (i.e. do not interpret the command line for D:\program.exe this is a #full sentence when the arguments of the function are this is a #full sentence)

Following Matthias' comment on splatting, here is what I get in different scenarios:

Case 1

function global:note {
  D:\program.exe @Args
}

Output when typing note this is a #complete sentence at the PS prompt:

this is a

Case 2

function global:note {
  D:\program.exe --% @Args
}

Output when typing note this is a #complete sentence at the PS prompt:

@Args


问:
Is there a way to make working a Kanban in the new version of SuiteCRM?
I've followed all these steps:

Installation of the package module, you need to download the latest version of the plugin from the link https://github.com/SidorkinAlex/Opportunities_kanban/releases/download/2.0.1/Build_2_0_1.zip

Then in SuiteCRM open the Module Loader (Administration -> Module Loader)

Download package archive

Click the install button.

After installation, you need to make a Quick Repair and Rebuild (Admin -> Repair ->Quick Repair and Rebuild).

Then, I try to prepare the settings of the Kanban: After installing the package, go to Administration -> Configuring modules for which the kanban board is available. Even I try to access the module and then it stops working:

Error in the view
Error ocurred while fetching metadata

Error in the console :
node_modules_angular_core_fesm2015_core_js-es2015.e67882692b6d3d658f6b.js:1 ERROR Error: Uncaught (in promise): Error: Http failure response for https://crm.name.com/api/graphql: 403 Forbidden Error: Http failure response for https://crm.name.com/api/graphql: 403 Forbidden at new t (node_modules_apollo-angular_fesm2015_ngApollo_js-_0ddc0-es2015.31fc3a06fac668918939.js:1:35812) at node_modules_apollo-angular_fesm2015_ngApollo_js-_0ddc0-es2015.31fc3a06fac668918939.js:1:66628 at r (node_modules_apollo-angular_fesm2015_ngApollo_js-_0ddc0-es2015.31fc3a06fac668918939.js:1:33160) at node_modules_apollo-angular_fesm2015_ngApollo_js-_0ddc0-es2015.31fc3a06fac668918939.js:1:33086 at new P (polyfills-es2015.6eb6bd3b6068c2595c2b.js:1:18300) at Object.then (node_modules_apollo-angular_fesm2015_ngApollo_js-_0ddc0-es2015.31fc3a06fac668918939.js:1:33053) at Object.error (node_modules_apollo-angular_fesm2015_ngApollo_js-_0ddc0-es2015.31fc3a06fac668918939.js:1:33170) at v (core_app_shell_src_bootstrap_ts-es2015.376068f61f1fb7ece8f1.js:1:165870) at \ _(core_app_shell_src_bootstrap_ts-es2015.376068f61f1fb7ece8f1.js:1:166366) at t.error (core_app_shell_src_bootstrap_ts-es2015.376068f61f1fb7ece8f1.js:1:166919) at w (polyfills-es2015.6eb6bd3b6068c2595c2b.js:1:16429) at w (polyfills-es2015.6eb6bd3b6068c2595c2b.js:1:15965) at polyfills-es2015.6eb6bd3b6068c2595c2b.js:1:17272 at u.invokeTask (polyfills-es2015.6eb6bd3b6068c2595c2b.js:1:7770) at Object.onInvokeTask (node_modules_angular_core_fesm2015_core_js-es2015.e67882692b6d3d658f6b.js:1:198001) at u.invokeTask (polyfills-es2015.6eb6bd3b6068c2595c2b.js:1:7691) at t.runTask (polyfills-es2015.6eb6bd3b6068c2595c2b.js:1:3166) at b (polyfills-es2015.6eb6bd3b6068c2595c2b.js:1:9764) at l.invokeTask [as invoke] (polyfills-es2015.6eb6bd3b6068c2595c2b.js:1:8849) at m (polyfills-es2015.6eb6bd3b6068c2595c2b.js:1:20635) ni @ node_modules_angular_core_fesm2015_core_js-es2015.e67882692b6d3d658f6b.js:1

It should appear the kanban, without any pop-up error:
What I'm expecting

There is no code introduced, only the steps I've already shown. The process is from GitHub -->https://github.com/SidorkinAlex/Opportunities_kanban


问:
Minified React Error #130 Encountered, doesn't seem import-related?
The minified react error instructs me that an "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined."

Looking around, it seems that most people have issues with import/exports and the use of braces when necessary, eg. while using the default keyword.

However, this doesn't seem to be the issue here, which leaves me befuddled.

I have a few components in my program I've included below. None of these seem to strike me as improper importing or importing an undefined element.

How would I go about debugging this? If this is not import related, would it be dependency-related?

Code for reference below:

ExerciseDay:

```<code>import React from 'react';
import ExerciseItem from './ExerciseRoutine';
import ProgressionChart from "./ProgressionChart";
import surveyHelp from '../img/chart-help.png';
import surveyHelpText from '../questionnaire/chart-help.json';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';

export default class ExerciseDay extends React.Component {
    constructor() {
        super();
        this.state = {help: false, visibility: true};
        const experience = localStorage["experience"];
        const pageChosen = sessionStorage.getItem("page");
        this.numeric = pageChosen ? sessionStorage["page"] : experience === "No" ? "29" : experience === "Yes, once" ? "30" : "31";
        this.sheikoData = require("../programs/Sheiko" + this.numeric + ".json");
    }

    render() {
        let exerciseRoutines;
        if (this.sheikoData) {
            exerciseRoutines = this.sheikoData.map(exerciseDay => {
                return (<ExerciseItem key={exerciseDay.day} exerciseDay={exerciseDay}/>);
            });
        }
        return (
            <div className="ExerciseDay">
                <div style={{textAlign: "center", fontFamily: "Spectral SC", fontSize: 60}}>
                    Sheiko {!this.numeric.includes('-') ? '#' : null}{this.numeric}</div>
                <ProgressionChart data={this.sheikoData}/>
                <div className="Survey-help" style={{marginLeft: "5%"}}>
                    <img id="help-button" src={surveyHelp} alt=""
                         style={{width: "2%", float: "left", borderRadius: "5px", background: "lightgreen"}}
                         onClick={() => {
                             this.setState({help: !this.state.help})
                         }}/>
                    <ReactCSSTransitionGroup transitionName="fade" transitionEnterTimeout={300}
                                             transitionLeaveTimeout={500}>
                        <p style={{
                            marginLeft: "5%",
                            fontFamily: "Itim, cursive",
                            fontSize: 22
                        }}>{this.state.help ? surveyHelpText.text : null}</p>
                    </ReactCSSTransitionGroup>
                </div>
                {exerciseRoutines}
            </div>
        );
    }
}
</code>```

ExerciseRoutine:

```<code>import React from "react";
import ExerciseType from "./ExerciseType";
import show from '../img/show.png';
import hide from '../img/hide.png';

export default class ExerciseRoutine extends React.Component {
    constructor() {
        super();
        this.state = {showExerciseType: true};
    }

    render() {
        let exerciseRoutine;
        if (this.props.exerciseDay.routine) {
            let routineKey = 0;
            exerciseRoutine = this.props.exerciseDay.routine.map(routine => {
                return <ExerciseType key={routine.exercise + routineKey++} routine={routine}/>
            });
        }

        return (
            <div className="ExerciseRoutine" style={{marginLeft: "15%"}}>
                <div>
                    <h2 style={{
                        fontFamily: "Arima Madurai, cursive",
                        fontSize: 30,
                        display: "inline"
                    }}>{this.props.exerciseDay.day}
                        - {this.props.exerciseDay.routine.length} exercises</h2>

                    <img src={this.state.showExerciseType ? hide : show}
                         style={{width: this.state.showExerciseType? "2%": "2%", transform: "translateY(22%)"}} alt=""
                         onClick={() => this.setState({showExerciseType: !this.state.showExerciseType})}/>
                </div>
                <hr/>
                {this.state.showExerciseType ? exerciseRoutine : null}
                <br/>
            </div>
        )
    }

}
</code>```

ExerciseSelector:

```<code>import React from "react";
import Select from 'react-select';
import selection from "../programs/SheikoSelector.json";

export default class ExerciseSelector extends React.Component {
    render() {
        function logChange(val) {
            if(!val)  return;
            sessionStorage["page"] = val.value;
            window.location.reload();
        }

        return (
            <Select name="exercise-selector" value="Current" clearValueText="yes"
                    options={selection} onChange={logChange} autofocus={true}
                    placeholder="Click here to search Sheiko program..."/>
        );
    }
}
</code>```

ExerciseTask:

```<code>import React from "react";
import ReactToolTip from 'react-tooltip'

export default class ExerciseTask extends React.Component {
    render() {
        const effort = this.props.task.effort !== 0 ? Math.round(this.props.task.effort * 100) + "%" : "a comfortable";
        return (<li className="ExerciseTask">
            {this.props.task.sets} Sets of {this.props.task.reps} reps at {effort} effort
            <ReactToolTip/>
        </li>);
    }
}
</code>```

and ExerciseType:

```<code>import React from 'react';
import ExerciseTask from "./ExerciseTask";
import benchpress from '../img/benchpress.png';
import squat from '../img/squat.png';
import flies from '../img/flies.png';
import abs from '../img/abs.png';
import pushup from '../img/pushup.png';
import other from '../img/other.png';

export default class ExerciseType extends React.Component {
    render() {
        let exerciseType;
        if (this.props.routine.tasks) {
            let taskKey = 0;
            exerciseType = this.props.routine.tasks.map(task => {
                return <ExerciseTask key={taskKey++} task={task}/>
            });
        }

        function determineImage(exercise) {
            return exercise.includes("Bench") ? benchpress : exercise.includes("Squat") ? squat : exercise.includes("Fly") ? flies : exercise.includes("Abs") ? abs : exercise.includes("Push up") ? pushup : other;
        }

        return (<div className="ExerciseType" style={{backgroundColor: "#f9fbff"}}>
            <h3 style={{
                fontFamily: "Arima Madurai, cursive",
                fontSize: 23
            }}>{this.props.routine.exercise.charAt(0).toUpperCase() + this.props.routine.exercise.slice(1)}</h3>
            <div style={{float: "left", whiteSpace: "nowrap"}}>
                {exerciseType}
            </div>
            <img id="exercise-picture" src={determineImage(this.props.routine.exercise)}
                 data-tip={this.props.routine.exercise} alt=""/>
        </div>);
    }
}
</code>```

Body:
The minified react error instructs me that an "Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined."

Looking around, it seems that most people have issues with import/exports and the use of braces when necessary, eg. while using the default keyword.

However, this doesn't seem to be the issue here, which leaves me befuddled.

I have a few components in my program I've included below. None of these seem to strike me as improper importing or importing an undefined element.

How would I go about debugging this? If this is not import related, would it be dependency-related?

Code for reference below:

ExerciseDay:

import React from 'react';
import ExerciseItem from './ExerciseRoutine';
import ProgressionChart from "./ProgressionChart";
import surveyHelp from '../img/chart-help.png';
import surveyHelpText from '../questionnaire/chart-help.json';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';

export default class ExerciseDay extends React.Component {
    constructor() {
        super();
        this.state = {help: false, visibility: true};
        const experience = localStorage["experience"];
        const pageChosen = sessionStorage.getItem("page");
        this.numeric = pageChosen ? sessionStorage["page"] : experience === "No" ? "29" : experience === "Yes, once" ? "30" : "31";
        this.sheikoData = require("../programs/Sheiko" + this.numeric + ".json");
    }

    render() {
        let exerciseRoutines;
        if (this.sheikoData) {
            exerciseRoutines = this.sheikoData.map(exerciseDay => {
                return (<ExerciseItem key={exerciseDay.day} exerciseDay={exerciseDay}/>);
            });
        }
        return (

                    Sheiko {!this.numeric.includes('-') ? '#' : null}{this.numeric}

                <ProgressionChart data={this.sheikoData}/>

                     {
                             this.setState({help: !this.state.help})
                         }}/>
                    <ReactCSSTransitionGroup transitionName="fade" transitionEnterTimeout={300}
                                             transitionLeaveTimeout={500}>

{this.state.help ? surveyHelpText.text : null}

                    </ReactCSSTransitionGroup>

                {exerciseRoutines}

        );
    }
}

ExerciseRoutine:

import React from "react";
import ExerciseType from "./ExerciseType";
import show from '../img/show.png';
import hide from '../img/hide.png';

export default class ExerciseRoutine extends React.Component {
    constructor() {
        super();
        this.state = {showExerciseType: true};
    }

    render() {
        let exerciseRoutine;
        if (this.props.exerciseDay.routine) {
            let routineKey = 0;
            exerciseRoutine = this.props.exerciseDay.routine.map(routine => {
                return <ExerciseType key={routine.exercise + routineKey++} routine={routine}/>
            });
        }

        return (

{this.props.exerciseDay.day}
                        - {this.props.exerciseDay.routine.length} exercises

                     this.setState({showExerciseType: !this.state.showExerciseType})}/>

                {this.state.showExerciseType ? exerciseRoutine : null}

        )
    }

}

ExerciseSelector:

import React from "react";
import Select from 'react-select';
import selection from "../programs/SheikoSelector.json";

export default class ExerciseSelector extends React.Component {
    render() {
        function logChange(val) {
            if(!val)  return;
            sessionStorage["page"] = val.value;
            window.location.reload();
        }

        return (
            <Select name="exercise-selector" value="Current" clearValueText="yes"
                    options={selection} onChange={logChange} autofocus={true}
                    placeholder="Click here to search Sheiko program..."/>
        );
    }
}

ExerciseTask:

import React from "react";
import ReactToolTip from 'react-tooltip'

export default class ExerciseTask extends React.Component {
    render() {
        const effort = this.props.task.effort !== 0 ? Math.round(this.props.task.effort * 100) + "%" : "a comfortable";
        return (

            {this.props.task.sets} Sets of {this.props.task.reps} reps at {effort} effort
            <ReactToolTip/>

);
    }
}

and ExerciseType:

import React from 'react';
import ExerciseTask from "./ExerciseTask";
import benchpress from '../img/benchpress.png';
import squat from '../img/squat.png';
import flies from '../img/flies.png';
import abs from '../img/abs.png';
import pushup from '../img/pushup.png';
import other from '../img/other.png';

export default class ExerciseType extends React.Component {
    render() {
        let exerciseType;
        if (this.props.routine.tasks) {
            let taskKey = 0;
            exerciseType = this.props.routine.tasks.map(task => {
                return <ExerciseTask key={taskKey++} task={task}/>
            });
        }

        function determineImage(exercise) {
            return exercise.includes("Bench") ? benchpress : exercise.includes("Squat") ? squat : exercise.includes("Fly") ? flies : exercise.includes("Abs") ? abs : exercise.includes("Push up") ? pushup : other;
        }

        return (

{this.props.routine.exercise.charAt(0).toUpperCase() + this.props.routine.exercise.slice(1)}

                {exerciseType}

);
    }
}


问:
Weird return value changing of netgen::Mesh.GetNSE() before and after passing it to WriteUserFormat(...)?
as you can see:

For the same netgen::Mesh object,after mesh generating,print the returned value of mesh.GetNSE(),I got:
256

Then passing the this object to WriteUserFormat(),and print the returned value of mesh.GetNSE(),I got a totally different value:
868

Why does this happen?


问:
Is there a way to use two format codes in an fstring in Python?
I'm building a basic program to calculate taxes in the UK. The code looks like this:

```<code>income = int(input("Income: "))

taxable = income - 12570

if income < 12_571:
    print(f"You pay no tax.
    Your income is £{income:.2f}")

elif income < 50_271:
    afterTax = taxable * 0.8
    realIncome = afterTax + 12570
    print(f"You pay 20% tax.
    Your income is £{realIncome:.2f}")

elif income < 150_000:
    afterTax = taxable * 0.6
    realIncome = afterTax + 12570
    print(f"You pay 40% tax.
    Your income is £{realIncome:.2f}")

else:
    afterTax = taxable * 0.55
    realIncome = afterTax + 12570
    print(f"You pay 45% tax.
    Your income is £{realIncome:.2f}")
</code>```

`

When I run it, I get this:
Income: 3555555555555555532 You pay 45% tax. Your income is £1955555555555561472.00

The problem is I either format it to have 2 decimal places with :.2f, or to have comas with :,. Is there a way to do both?

Body:
I'm building a basic program to calculate taxes in the UK. The code looks like this:

income = int(input("Income: "))

taxable = income - 12570

if income < 12_571:
    print(f"You pay no tax.
    Your income is £{income:.2f}")

elif income < 50_271:
    afterTax = taxable * 0.8
    realIncome = afterTax + 12570
    print(f"You pay 20% tax.
    Your income is £{realIncome:.2f}")

elif income < 150_000:
    afterTax = taxable * 0.6
    realIncome = afterTax + 12570
    print(f"You pay 40% tax.
    Your income is £{realIncome:.2f}")

else:
    afterTax = taxable * 0.55
    realIncome = afterTax + 12570
    print(f"You pay 45% tax.
    Your income is £{realIncome:.2f}")

`

When I run it, I get this:
Income: 3555555555555555532 You pay 45% tax. Your income is £1955555555555561472.00

The problem is I either format it to have 2 decimal places with :.2f, or to have comas with :,. Is there a way to do both?


问:
How to register callback for stable HAL AIDL
We need implement a stable AIDL interface in /vendor on Android 11,to comunicate from java apk to service in /vendor, based on this document https://www.codeinsideout.com/blog/android/hal/aidl/, we already implement the interface and call it by ServiceManager.getService(), but when we try to add callback for the interface, it report errors while run in java application

01-10 05:01:53.791  2651  2651 E AndroidRuntime: java.lang.NoSuchMethodError: No virtual method markVintfStability()V in class Landroid/hardware/test/ITestCallback$Stub; or its super classes (declaration of 'android.hardware.test.ITestCallback$Stub' appears in /data/app/~~YnBU-5dLkTN-
fKvRl_DNGg==/com.example.myapplication-qOs99EEE-GIQ3pDHJEaSGg==/base.apk!classes4.dex)

anyone can help it?Many thanks!

```<code>ITestCallback.aidl
@VintfStability
interface  ITestCallback{
    void notify(int eventType,int param0,int param1);
}
</code>```
```<code>ITestManager.aidl
@VintfStability
interface ITestManager {
void registerCallback(in ITestCallback callback);
void unRegisterCallback(in ITestCallback callback);
}
</code>```

in java apk

```<code>IBinder binder = ServiceManager.getService(ITest_AIDL_INTERFACE);
        if (binder == null) {
            Log.e(TAG, "Getting " + " service daemon binder failed!");
        } else {
            invcaseAJ = ITestManager.Stub.asInterface(binder);--------worked

            ITestCallback callback = new ITestCallback.Stub() { ---------repo error above
                @Override
                public void notify(int i, int i1, int i2) throws RemoteException {
                    Log.i(TAG,"");
                }
            };

                Log.d(TAG, "AIDL daemon interface is binded!");

</code>```

Body:
We need implement a stable AIDL interface in /vendor on Android 11,to comunicate from java apk to service in /vendor, based on this document https://www.codeinsideout.com/blog/android/hal/aidl/, we already implement the interface and call it by ServiceManager.getService(), but when we try to add callback for the interface, it report errors while run in java application

01-10 05:01:53.791  2651  2651 E AndroidRuntime: java.lang.NoSuchMethodError: No virtual method markVintfStability()V in class Landroid/hardware/test/ITestCallback$Stub; or its super classes (declaration of 'android.hardware.test.ITestCallback$Stub' appears in /data/app/~~YnBU-5dLkTN-
fKvRl_DNGg==/com.example.myapplication-qOs99EEE-GIQ3pDHJEaSGg==/base.apk!classes4.dex)

anyone can help it?Many thanks!

ITestCallback.aidl
@VintfStability
interface  ITestCallback{
    void notify(int eventType,int param0,int param1);
}

ITestManager.aidl
@VintfStability
interface ITestManager {
void registerCallback(in ITestCallback callback);
void unRegisterCallback(in ITestCallback callback);
}

in java apk

IBinder binder = ServiceManager.getService(ITest_AIDL_INTERFACE);
        if (binder == null) {
            Log.e(TAG, "Getting " + " service daemon binder failed!");
        } else {
            invcaseAJ = ITestManager.Stub.asInterface(binder);--------worked

            ITestCallback callback = new ITestCallback.Stub() { ---------repo error above
                @Override
                public void notify(int i, int i1, int i2) throws RemoteException {
                    Log.i(TAG,"");
                }
            };

                Log.d(TAG, "AIDL daemon interface is binded!");


问:
Can't change user profile image in django
I am really new to django and I am building a website for internal use in my company. I have extended the user model with another model called "profile" in order to store extra information about each user, including a profile picture.

I have set up a form.py class with the data i'd like to be able to modify:

```<code>class UserForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['office','role', 'userImage']
</code>```

The form in the html is as follows:

```<code><form class="form" action="" method="POST" enctype="multipart/form-data">
                    {% csrf_token %}
                    {% for field in form %}
                    <div class="form__group">
                        <label for="Profile.userImage">{{ field.label }}</label>
                        {{ field }}
                    </div>
                    {% endfor %}

                    <div class="form__action">
                        <a class="btn btn--dark" href="{% url 'user-profile' request.user.id%}">Cancel</a>
                        <button class="btn btn--main" type="submit">Update</button>
                    </div>
</form>
</code>```

And in the views.py, here is the function that takes care of this:

```<code>
def update_user(request):
    user = request.user
    profile = request.user.profile
    if request.method == 'POST':
        form = UserForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            form.save()
            return redirect('user-profile', pk=user.id)
    else:
        form = UserForm(instance = profile)
    return render(request, 'base/update-user.html', {'form': form})
</code>```

And the profile model is:

```<code>class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    job= models.TextField(max_length=50, blank=True, verbose_name="Centro")
    role= models.TextField(null=True, max_length=50, blank=True, verbose_name="Cargo")
    userImage = models.ImageField(upload_to='profileImages/', default='profileImages/happy.jpg', verbose_name="Profile Image")

    @receiver(post_save, sender=User)
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user_profile(sender, instance, **kwargs):
        instance.profile.save()
</code>```

in addition, the MEDIA_ROOT and MEDIA_URL are as follows:

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') MEDIA_URL = '/images/'

The form works fine for all fields, they both dispplay and update all the information regarding the "office" and "job" fields, but not the profile image.. It neither uploads a file to the folder I have assigned it to upload to. Even when I manually insert another image in the folder, it doesn't change it. Everything works through django admin though. Images are uploaded and changed correctly. It just wont do it via the form, no errors come up and the terminal doesn't display any issues, neither does the console in the browser.

I don't know what to do, please let me know if you need any extra information in order to diagnose the problem.
I appreciate any help provided!

Body:
I am really new to django and I am building a website for internal use in my company. I have extended the user model with another model called "profile" in order to store extra information about each user, including a profile picture.

I have set up a form.py class with the data i'd like to be able to modify:

class UserForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ['office','role', 'userImage']

The form in the html is as follows:

<form class="form" action="" method="POST" enctype="multipart/form-data">
                    {% csrf_token %}
                    {% for field in form %}

                        {{ field.label }}
                        {{ field }}

                    {% endfor %}

                        Cancel
                        <button class="btn btn--main" type="submit">Update</button>

</form>

And in the views.py, here is the function that takes care of this:

def update_user(request):
    user = request.user
    profile = request.user.profile
    if request.method == 'POST':
        form = UserForm(request.POST, request.FILES, instance=profile)
        if form.is_valid():
            form.save()
            return redirect('user-profile', pk=user.id)
    else:
        form = UserForm(instance = profile)
    return render(request, 'base/update-user.html', {'form': form})

And the profile model is:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    job= models.TextField(max_length=50, blank=True, verbose_name="Centro")
    role= models.TextField(null=True, max_length=50, blank=True, verbose_name="Cargo")
    userImage = models.ImageField(upload_to='profileImages/', default='profileImages/happy.jpg', verbose_name="Profile Image")

    @receiver(post_save, sender=User)
    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            Profile.objects.create(user=instance)

    @receiver(post_save, sender=User)
    def save_user_profile(sender, instance, **kwargs):
        instance.profile.save()

in addition, the MEDIA_ROOT and MEDIA_URL are as follows:

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') MEDIA_URL = '/images/'

The form works fine for all fields, they both dispplay and update all the information regarding the "office" and "job" fields, but not the profile image.. It neither uploads a file to the folder I have assigned it to upload to. Even when I manually insert another image in the folder, it doesn't change it. Everything works through django admin though. Images are uploaded and changed correctly. It just wont do it via the form, no errors come up and the terminal doesn't display any issues, neither does the console in the browser.

I don't know what to do, please let me know if you need any extra information in order to diagnose the problem.
I appreciate any help provided!


问:
How to connect multistep form react to node
Everyone
I tried many tutorials on youtube but no one is telling me how to connect multistep form react to nodejs.
I need some help please

Hello,Everyone
I tried many tutorials on youtube but no one is telling me how to connect multistep form react to nodejs.
I need some help please


问:
Call Python (classes and functions) from Matlab Simulink
I am going to make a simulation in Simulink in which my controller is designed in Python, and I need to call this from the Simulink Matlab Function. I succeeded in getting results when I only defined "def" in python code; however when I defined "class" in Python, I could not refer to the class and desired function in Python (from the Matlab function) I have seen most examples of this, but the majority of them call Matlab from Python or Call Python functions(def). I put my simple Simulink here; I would appreciate it if anybody could help me.

Thank you.

Simulink Model

[Interpreted Matlab function]

```<code>function out = RunPythonn(uu)

    in1=uu(1);
    in2=uu(2);
    coder.extrinsic('Example.py');
    controller=py.Example.Controller(in1,10);
    out=controller.test(in1,in2);

 end
</code>```

[Python code]

```<code>class Controller:

    def __init__(self,x1,time):
        self.time=time
        self.x1=x1

    def test(self,in1,in2):
        out=in1+in2+self.x1
        return out

</code>```

I expect to call each Python classes and functions which I need from Interpreted Matlab function. at each time step, I need to call python code.

Body:
I am going to make a simulation in Simulink in which my controller is designed in Python, and I need to call this from the Simulink Matlab Function. I succeeded in getting results when I only defined "def" in python code; however when I defined "class" in Python, I could not refer to the class and desired function in Python (from the Matlab function) I have seen most examples of this, but the majority of them call Matlab from Python or Call Python functions(def). I put my simple Simulink here; I would appreciate it if anybody could help me.

Thank you.

Simulink Model

[Interpreted Matlab function]

function out = RunPythonn(uu)

    in1=uu(1);
    in2=uu(2);
    coder.extrinsic('Example.py');
    controller=py.Example.Controller(in1,10);
    out=controller.test(in1,in2);

 end

[Python code]

class Controller:

    def __init__(self,x1,time):
        self.time=time
        self.x1=x1

    def test(self,in1,in2):
        out=in1+in2+self.x1
        return out

I expect to call each Python classes and functions which I need from Interpreted Matlab function. at each time step, I need to call python code.


问:
Discontinuous y-axis in inset plot with `ggplot2`
I am trying to insert a Kaplan-Meier inset "zoom" plot into the same KM plot (when Survival curves are very similar to allow more accurate inspection). This is currently used by many journals. Unfortunately, I find creating an inset plot with a discontinuous y-axis non-trivial.  I have tried various approaches but unfortunately never got to the desired goal.

First I create the two plots (one with risk table, the inset plot without x/y labels and without risk table).

```<code>library(survival)
library(survminer)
library(ggh4x)
library(ggbreak)

# fit model
sfit <- survfit(Surv(time, status) ~ sex, data = colon)

# create main plot with risk table
main_plot <- ggsurvplot(sfit, risk.table=TRUE)

# create inset plot
inset_plot <- ggsurvplot(sfit, risk.table=FALSE, ylim = c(0.4,1), legend = "none", xlab ="", ylab = "")

# transparent background for inset_plot
inset_plot$plot <-  inset_plot$plot +
  theme(
    panel.background = element_rect(fill = "transparent",
                                    colour = NA_character_), # necessary to avoid drawing panel outline
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    plot.background = element_rect(fill = "transparent",
                                   colour = NA_character_), # necessary to avoid drawing plot outline
    legend.background = element_rect(fill = "transparent"),
    legend.box.background = element_rect(fill = "transparent"),
    legend.key = element_rect(fill = "transparent")
  )

main_plot$plot <- main_plot$plot +
  annotation_custom(grob = ggplotGrob(inset_plot$plot ),
                    xmin = 1.5,xmax=Inf,ymin = -0.05 ,ymax = 0.7)
main_plot
</code>```

main_plot

For the inset_plot I want a discontinuous y-axis

There are good answers to the stackoverflow question about discontinuous axes in ggplot2.

Approach 1)

The problem is that the segment label does not appear exactly on the y-axis.

```<code>inset_plot$plot +
  annotate("segment",
           x = c(-200, -100), xend = c(100, 200),
           y = c(0.425, 0.425), yend = c(0.45, 0.45)
           ) +
  coord_cartesian(clip = "off") +
  guides(y = guide_axis_truncated(
    trunc_lower = c(-Inf, 0.45),
    trunc_upper = c(0.425, Inf)
  ))
#> Coordinate system already present. Adding new coordinate system, which will
#> replace the existing one.
</code>```

Inset plot error 1

Approach 2)

The easiest solution I found for a discontinous axis with ggplot2 was using the ggbreak library. Unfortunately, this only worked for the single plot. As soon as I inserted it as an inset plot, the discontinuous y axis disappeared.

```<code>ggbreak_inset <- inset_plot$plot +
  scale_y_cut(c(0.4), which=c(1, 2), scales=c(10, 1), space = 0.1) +
  scale_y_continuous(breaks = c(0.6, 0.8, 1))
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.
ggbreak_inset
</code>```

Although no nice // labeling on y-axis, this works for the single plot. But as soon as this plot is inserted as inset plot, the discontinuous y-axis disappears and the axis scaling becomes erroneous.

```<code>new_main_plot <- main_plot  # copy
new_main_plot$plot <- new_main_plot$plot +
  annotation_custom(grob = ggplotGrob(ggbreak_inset ),
                    xmin = 1.5,xmax=Inf, ymin = -0.05 ,ymax = 0.7)
new_main_plot  # discontinuous y-axis missing, axis scaling incorrect
</code>```

Inset plot error 2

The ideal figure would look something like below. How can I make this discontinuous axis in an inset plot using ggplot2?

expected plot

Body:
I am trying to insert a Kaplan-Meier inset "zoom" plot into the same KM plot (when Survival curves are very similar to allow more accurate inspection). This is currently used by many journals. Unfortunately, I find creating an inset plot with a discontinuous y-axis non-trivial.  I have tried various approaches but unfortunately never got to the desired goal.

First I create the two plots (one with risk table, the inset plot without x/y labels and without risk table).

library(survival)
library(survminer)
library(ggh4x)
library(ggbreak)

# fit model
sfit <- survfit(Surv(time, status) ~ sex, data = colon)

# create main plot with risk table
main_plot <- ggsurvplot(sfit, risk.table=TRUE)

# create inset plot
inset_plot <- ggsurvplot(sfit, risk.table=FALSE, ylim = c(0.4,1), legend = "none", xlab ="", ylab = "")

# transparent background for inset_plot
inset_plot$plot <-  inset_plot$plot +
  theme(
    panel.background = element_rect(fill = "transparent",
                                    colour = NA_character_), # necessary to avoid drawing panel outline
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    plot.background = element_rect(fill = "transparent",
                                   colour = NA_character_), # necessary to avoid drawing plot outline
    legend.background = element_rect(fill = "transparent"),
    legend.box.background = element_rect(fill = "transparent"),
    legend.key = element_rect(fill = "transparent")
  )

main_plot$plot <- main_plot$plot +
  annotation_custom(grob = ggplotGrob(inset_plot$plot ),
                    xmin = 1.5,xmax=Inf,ymin = -0.05 ,ymax = 0.7)
main_plot

main_plot

For the inset_plot I want a discontinuous y-axis

There are good answers to the stackoverflow question about discontinuous axes in ggplot2.

Approach 1)

The problem is that the segment label does not appear exactly on the y-axis.

inset_plot$plot +
  annotate("segment",
           x = c(-200, -100), xend = c(100, 200),
           y = c(0.425, 0.425), yend = c(0.45, 0.45)
           ) +
  coord_cartesian(clip = "off") +
  guides(y = guide_axis_truncated(
    trunc_lower = c(-Inf, 0.45),
    trunc_upper = c(0.425, Inf)
  ))
#> Coordinate system already present. Adding new coordinate system, which will
#> replace the existing one.

Inset plot error 1

Approach 2)

The easiest solution I found for a discontinous axis with ggplot2 was using the ggbreak library. Unfortunately, this only worked for the single plot. As soon as I inserted it as an inset plot, the discontinuous y axis disappeared.

ggbreak_inset <- inset_plot$plot +
  scale_y_cut(c(0.4), which=c(1, 2), scales=c(10, 1), space = 0.1) +
  scale_y_continuous(breaks = c(0.6, 0.8, 1))
#> Scale for y is already present.
#> Adding another scale for y, which will replace the existing scale.
ggbreak_inset

Although no nice // labeling on y-axis, this works for the single plot. But as soon as this plot is inserted as inset plot, the discontinuous y-axis disappears and the axis scaling becomes erroneous.

new_main_plot <- main_plot  # copy
new_main_plot$plot <- new_main_plot$plot +
  annotation_custom(grob = ggplotGrob(ggbreak_inset ),
                    xmin = 1.5,xmax=Inf, ymin = -0.05 ,ymax = 0.7)
new_main_plot  # discontinuous y-axis missing, axis scaling incorrect

Inset plot error 2

The ideal figure would look something like below. How can I make this discontinuous axis in an inset plot using ggplot2?

expected plot


问:
JENKINS with Tivoli Workload Scheduler Integration
Is it possible to interface Jenkins with Tivoli Workload Scheduler, such as to trigger Jenkins to run a job requested by a TWS job stream ?

A trigger should wait for the Jenkins job to complete and return to TWS with a proper returncode.

But I havn't been able to find any info as yet!

PS. I'm just the interface guy and I have no Jenkins knowledge that so ever, so please any points of direction is welcome.


问:
angular in prod kill auto when i run npm run start
i have an application in o2switch server, and i use a proxy middleware for api externe, when i run npm run start without pm2 just for test, it doesn't show error but kill automatically:

trees@0.0.0 start /home/user14212/front.test.com
ng serve --proxy-config proxy.conf.js

⠋ Generating browser application bundles...[HPM] Proxy created: [ '/api/*' ]  ->  https://back.test.com
⠏ Generating browser application bundles (phase: building)...Killed

i have tried many tricks but nothing


问:
extract/separate duration value from postgresql log in elk
I have elk(elasticsearch, logstash , kibana) for monitor logs.
 postgresql logs with filebeat send to logstash and show logs in kibana.

I enabled log_duration in postgresql.conf and logged correctly.

for example, the postgresql log is below :

```<code>2023-01-11 06:17:09.754 EST [19751] user@books LOG:  duration: 0.014 ms  execute <unnamed>: SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY
2023-01-11 06:17:09.755 EST [19751] user@books LOG:  duration: 0.016 ms  bind S_1: BEGIN
2023-01-11 06:17:09.755 EST [19751] user@books LOG:  duration: 0.006 ms  execute S_1: BEGIN
2023-01-11 06:17:09.756 EST [19751] user@books LOG:  duration: 0.488 ms  parse <unnamed>: select * from books
</code>```

but in kibana, The duration value of the field is not separate and it is displayed as one with the message field, and there is no possibility of aggregation and other opetaions.

how to extract and split duration value from message ???

Body:
I have elk(elasticsearch, logstash , kibana) for monitor logs.
 postgresql logs with filebeat send to logstash and show logs in kibana.

I enabled log_duration in postgresql.conf and logged correctly.

for example, the postgresql log is below :

2023-01-11 06:17:09.754 EST [19751] user@books LOG:  duration: 0.014 ms  execute <unnamed>: SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY
2023-01-11 06:17:09.755 EST [19751] user@books LOG:  duration: 0.016 ms  bind S_1: BEGIN
2023-01-11 06:17:09.755 EST [19751] user@books LOG:  duration: 0.006 ms  execute S_1: BEGIN
2023-01-11 06:17:09.756 EST [19751] user@books LOG:  duration: 0.488 ms  parse <unnamed>: select * from books

but in kibana, The duration value of the field is not separate and it is displayed as one with the message field, and there is no possibility of aggregation and other opetaions.

how to extract and split duration value from message ???


问:
Where in the O365 mail flow is the Tenant Allow/Block List rules and Journal rules applied
Based on this diagram, does anyone know at what point the following O365 features are applied?

When are Tenant Allow/Block list exceptions applied to a message?

I think it happens after Anti-Malware but before Mail-Flow Rules based on my testing

When would a message be journaled if using a legacy journal rule?

Is it within the EOP steps, or afterwards?

I've read endless MS articles but cannot find a clear answer.


问:
java socketChannel::finishConnect throws NoConnectionPendingException even though connect has been successful
I have the following Java code:

```<code>class TestClient {

...
      SocketChannel channel = SocketChannel.open()
      channel.configureBlocking(false)
      SelectionKey key = channel.register(clientSelector, SelectionKey.OP_CONNECT)
      channel.connect(serverSocketAddress)
...
</code>```

In the Selector thread I have the standard while loop and inside that:

```<code>if(key.isConnectable()) {
    SocketChannel channel = (SocketChannel) key.channel();
    channel.finishConnect(); <-- This is throwing NoConnectionPendingException rarely
}
</code>```

Error message is: NoConnectionPendingException null

And this is spinning - see approx 100 messages like this.

Now, why would this be happening? If the connect fails, why would key.isConnectable() be true? Is this a race condition whereby the connect has failed. I cannot see any failure in the connect - no exception is thrown. Could it be a race condition where the connect is successful, then key.isConnectable is true, and somewhere between that and finishConnect() the connection has failed?

What can I do about it?

Body:
I have the following Java code:

class TestClient {

...
      SocketChannel channel = SocketChannel.open()
      channel.configureBlocking(false)
      SelectionKey key = channel.register(clientSelector, SelectionKey.OP_CONNECT)
      channel.connect(serverSocketAddress)
...

In the Selector thread I have the standard while loop and inside that:

if(key.isConnectable()) {
    SocketChannel channel = (SocketChannel) key.channel();
    channel.finishConnect(); <-- This is throwing NoConnectionPendingException rarely
}

Error message is: NoConnectionPendingException null

And this is spinning - see approx 100 messages like this.

Now, why would this be happening? If the connect fails, why would key.isConnectable() be true? Is this a race condition whereby the connect has failed. I cannot see any failure in the connect - no exception is thrown. Could it be a race condition where the connect is successful, then key.isConnectable is true, and somewhere between that and finishConnect() the connection has failed?

What can I do about it?


问:
Main class doesnt detect the change of an attribute
I have a GameEngine class that waits for the UserInterface class to change its aField attributes.
While it is null, it stays in the while loop, but whenever aField changes processCommand() is supposed to exit the loop.
An action performed in UserInterface changes this attribute (aField appears changed through a System.out.println), but the while loop is not exited.
Here is the code :

Game Engine class :

```<code>public String processCommand(){
        while(aGui.getField()==null) {

        }
        String a = aGui.getField();
        aGui.setCommand(null);
        System.out.println("a :"+a +".");
        return a;
}
</code>```

User Interface class:

```<code>public void actionPerformed(final ActionEvent pE){
        this.processCommandUI();
    }

public void processCommandUI(){
        try{
            String vInput = this.aEntryField.getText();
            this.aEntryField.setText("");
            aField=vInput;
            System.out.println(aField);
        }
        catch (Exception e) {
            System.out.println("Erreur");
        }
}
</code>```

I tried to change the attribute to an int but it did not change anything.

Body:
I have a GameEngine class that waits for the UserInterface class to change its aField attributes.
While it is null, it stays in the while loop, but whenever aField changes processCommand() is supposed to exit the loop.
An action performed in UserInterface changes this attribute (aField appears changed through a System.out.println), but the while loop is not exited.
Here is the code :

Game Engine class :

public String processCommand(){
        while(aGui.getField()==null) {

        }
        String a = aGui.getField();
        aGui.setCommand(null);
        System.out.println("a :"+a +".");
        return a;
}

User Interface class:

public void actionPerformed(final ActionEvent pE){
        this.processCommandUI();
    }

public void processCommandUI(){
        try{
            String vInput = this.aEntryField.getText();
            this.aEntryField.setText("");
            aField=vInput;
            System.out.println(aField);
        }
        catch (Exception e) {
            System.out.println("Erreur");
        }
}

I tried to change the attribute to an int but it did not change anything.


问:
No token found in response, service=oauth2:email openid profile
When the Google button is clicked in the application, if the process is successful, I take the user's e-mail address and send it to the backend. This situation works in debug mode, but does not work after publishing the application in the market. iOS works fine. The only error I can find in logcat is as follows. How can I solve this problem?

```<code>2023-01-12 13:20:37.361 2577-12107/? W/Auth: [GetTokenResponse] No token found in response, service=oauth2:email openid profile [CONTEXT service_id=153 ]
</code>```

import React from "react"
import { Button } from "react-native"
import { GoogleSignin } from '@react-native-google-signin/google-signin';
import auth from '@react-native-firebase/auth';

export default function AuthScreen() {

    async function onGoogleButtonPress() {

        // Get the users ID token
        const { idToken } = await GoogleSignin.signIn();

        // Create a Google credential with the token
        const googleCredential = auth.GoogleAuthProvider.credential(idToken);

        // Sign-in the user with the credential
        return auth().signInWithCredential(googleCredential).then((response: any) => {
            console.log(response.user.email)
            // send email to the backend..ƒ
        })
    }

    return (
        <Button
            title={"google signin"}
            onPress={() => onGoogleButtonPress().then(() => console.log('Signed in with Google!'))}
        />

    )
}```

Body:
When the Google button is clicked in the application, if the process is successful, I take the user's e-mail address and send it to the backend. This situation works in debug mode, but does not work after publishing the application in the market. iOS works fine. The only error I can find in logcat is as follows. How can I solve this problem?

2023-01-12 13:20:37.361 2577-12107/? W/Auth: [GetTokenResponse] No token found in response, service=oauth2:email openid profile [CONTEXT service_id=153 ]

import React from "react"
import { Button } from "react-native"
import { GoogleSignin } from '@react-native-google-signin/google-signin';
import auth from '@react-native-firebase/auth';

export default function AuthScreen() {

    async function onGoogleButtonPress() {

        // Get the users ID token
        const { idToken } = await GoogleSignin.signIn();

        // Create a Google credential with the token
        const googleCredential = auth.GoogleAuthProvider.credential(idToken);

        // Sign-in the user with the credential
        return auth().signInWithCredential(googleCredential).then((response: any) => {
            console.log(response.user.email)
            // send email to the backend..ƒ
        })
    }

    return (
        <Button
            title={"google signin"}
            onPress={() => onGoogleButtonPress().then(() => console.log('Signed in with Google!'))}
        />

    )
}


问:
How to get Runtime permission for Image Read and write in target Android Api level 33
```<code>binding.ivCamera.setOnClickListener(v -> Dexter.withContext(EditProfileActivity.this)
                .withPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_MEDIA_IMAGES)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {
                        if (report.areAllPermissionsGranted()) {
                            ImagePickerActivity.showImagePickerOptions(EditProfileActivity.this, pickerOptionListener);
                        }

                        if (report.isAnyPermissionPermanentlyDenied()) {

                            showSettingsDialog();
                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {

                        token.continuePermissionRequest();
                    }
                }).check());
    }
</code>```

This is my code i wrote to ask permission  to access file  i am trying to select photo from gallery and take picture from camera show that i can upload photo to server or i can download photo in our sdcard  but when i  am trying to give permission then it always goes to isAnyPermissionPermanentlyDenied  i am targeting android 33 can any one help me how to ask permission for read write file in android .

Body:
binding.ivCamera.setOnClickListener(v -> Dexter.withContext(EditProfileActivity.this)
                .withPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_MEDIA_IMAGES)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {
                        if (report.areAllPermissionsGranted()) {
                            ImagePickerActivity.showImagePickerOptions(EditProfileActivity.this, pickerOptionListener);
                        }

                        if (report.isAnyPermissionPermanentlyDenied()) {

                            showSettingsDialog();
                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {

                        token.continuePermissionRequest();
                    }
                }).check());
    }

This is my code i wrote to ask permission  to access file  i am trying to select photo from gallery and take picture from camera show that i can upload photo to server or i can download photo in our sdcard  but when i  am trying to give permission then it always goes to isAnyPermissionPermanentlyDenied  i am targeting android 33 can any one help me how to ask permission for read write file in android .


问:
Filebeat errors while connecting to ESAAS
Below is my filebeat-dev.yaml & its not able to connect to ESAAS :-

filebeat-dev.yaml

```<code>filebeat.inputs:
  - type: log
    paths:
      - /var/log/fb/*/*/*.log
    fields:
      app: "29880"
      es_id: "xxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxx"
      es_ver: 0.02
    tags: ["fb-test", "dev"]

output.logstash:
  hosts: ["xxxxxx-filestream-nonprod-xxxx-1-esaasstreams.xxxxx.xxxxx:xxxx"]
  ttl: 120
  loadbalance: true
  ssl.enabled: false
  ssl.certificate_authorities: ["/etc/secrets/ca.crt"]
</code>```

ERRORS:-

```<code>    2023-01-12T09:59:31.709Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.7.116:55048->28.39.30.85:56019: write: connection reset by peer
2023-01-12T09:59:31.709Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:31.709Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:32.890Z    ERROR   [publisher_pipeline_output] pipeline/output.go:180  failed to publish events: write tcp 10.128.7.116:55048->28.39.30.85:56019: write: connection reset by peer
2023-01-12T09:59:32.891Z    INFO    [publisher_pipeline_output] pipeline/output.go:143  Connecting to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019))
2023-01-12T09:59:32.894Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:32.895Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:32.925Z    INFO    [publisher_pipeline_output] pipeline/output.go:151  Connection to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019)) established
2023-01-12T09:59:32.995Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.9.116:41382->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:32.995Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:32.996Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:34.210Z    ERROR   [publisher_pipeline_output] pipeline/output.go:180  failed to publish events: write tcp 10.128.9.116:41382->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:34.210Z    INFO    [publisher_pipeline_output] pipeline/output.go:143  Connecting to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019))
2023-01-12T09:59:34.210Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:34.210Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:34.250Z    INFO    [publisher_pipeline_output] pipeline/output.go:151  Connection to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019)) established
2023-01-12T09:59:34.305Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.7.116:34410->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:34.305Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:34.305Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:35.401Z    ERROR   [publisher_pipeline_output] pipeline/output.go:180  failed to publish events: write tcp 10.128.7.116:34410->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:35.401Z    INFO    [publisher_pipeline_output] pipeline/output.go:143  Connecting to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019))
2023-01-12T09:59:35.402Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:35.402Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:35.428Z    INFO    [publisher_pipeline_output] pipeline/output.go:151  Connection to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019)) established
2023-01-12T09:59:35.477Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.7.116:34418->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:35.477Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:35.477Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:37.442Z    ERROR   [publisher_pipeline_output] pipeline/output.go:180  failed to publish events: write tcp 10.128.7.116:34418->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:37.442Z    INFO    [publisher_pipeline_output] pipeline/output.go:143  Connecting to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019))
2023-01-12T09:59:37.442Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:37.442Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:37.468Z    INFO    [publisher_pipeline_output] pipeline/output.go:151  Connection to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019)) established
2023-01-12T09:59:37.543Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.7.116:34424->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:37.543Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:37.543Z    INFO    [publisher] pipeline/retry.go:223     done
</code>```

Body:
Below is my filebeat-dev.yaml & its not able to connect to ESAAS :-

filebeat-dev.yaml

filebeat.inputs:
  - type: log
    paths:
      - /var/log/fb/*/*/*.log
    fields:
      app: "29880"
      es_id: "xxxxxxx-xxxx-xxxxx-xxxx-xxxxxxxxxxx"
      es_ver: 0.02
    tags: ["fb-test", "dev"]

output.logstash:
  hosts: ["xxxxxx-filestream-nonprod-xxxx-1-esaasstreams.xxxxx.xxxxx:xxxx"]
  ttl: 120
  loadbalance: true
  ssl.enabled: false
  ssl.certificate_authorities: ["/etc/secrets/ca.crt"]

ERRORS:-

    2023-01-12T09:59:31.709Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.7.116:55048->28.39.30.85:56019: write: connection reset by peer
2023-01-12T09:59:31.709Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:31.709Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:32.890Z    ERROR   [publisher_pipeline_output] pipeline/output.go:180  failed to publish events: write tcp 10.128.7.116:55048->28.39.30.85:56019: write: connection reset by peer
2023-01-12T09:59:32.891Z    INFO    [publisher_pipeline_output] pipeline/output.go:143  Connecting to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019))
2023-01-12T09:59:32.894Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:32.895Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:32.925Z    INFO    [publisher_pipeline_output] pipeline/output.go:151  Connection to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019)) established
2023-01-12T09:59:32.995Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.9.116:41382->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:32.995Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:32.996Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:34.210Z    ERROR   [publisher_pipeline_output] pipeline/output.go:180  failed to publish events: write tcp 10.128.9.116:41382->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:34.210Z    INFO    [publisher_pipeline_output] pipeline/output.go:143  Connecting to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019))
2023-01-12T09:59:34.210Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:34.210Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:34.250Z    INFO    [publisher_pipeline_output] pipeline/output.go:151  Connection to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019)) established
2023-01-12T09:59:34.305Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.7.116:34410->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:34.305Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:34.305Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:35.401Z    ERROR   [publisher_pipeline_output] pipeline/output.go:180  failed to publish events: write tcp 10.128.7.116:34410->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:35.401Z    INFO    [publisher_pipeline_output] pipeline/output.go:143  Connecting to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019))
2023-01-12T09:59:35.402Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:35.402Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:35.428Z    INFO    [publisher_pipeline_output] pipeline/output.go:151  Connection to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019)) established
2023-01-12T09:59:35.477Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.7.116:34418->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:35.477Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:35.477Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:37.442Z    ERROR   [publisher_pipeline_output] pipeline/output.go:180  failed to publish events: write tcp 10.128.7.116:34418->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:37.442Z    INFO    [publisher_pipeline_output] pipeline/output.go:143  Connecting to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019))
2023-01-12T09:59:37.442Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:37.442Z    INFO    [publisher] pipeline/retry.go:223     done
2023-01-12T09:59:37.468Z    INFO    [publisher_pipeline_output] pipeline/output.go:151  Connection to backoff(async(tcp://xxxxx-filestream-nonprod-euwest1-1-esaasstreams.xxxxx.intranet:56019)) established
2023-01-12T09:59:37.543Z    ERROR   [logstash]  logstash/async.go:280   Failed to publish events caused by: write tcp 10.128.7.116:34424->28.39.32.10:56019: write: connection reset by peer
2023-01-12T09:59:37.543Z    INFO    [publisher] pipeline/retry.go:219   retryer: send unwait signal to consumer
2023-01-12T09:59:37.543Z    INFO    [publisher] pipeline/retry.go:223     done


问:
Outdoor measurement of electricity production and consumption; must be sent to an API
At a public school, three different energy production methods must be established for teaching use:

A solar cell (approx. 1 m2)

A windmill (also very small)

An exercise bike

The electricity produced is stored on a battery, from which the students can use it to drive water pumps etc.

We would like to measure the electricity production and consumption in a way where data is sent every second (or at least every 5 seconds) to an API (which we would like to make ourselves if necessary) so that data can be stored in a database.

We prefer that we measure everywhere with the same kind of hardware, so that we don't have to integrate for different ways of getting this data.

We therefore imagine that we will find an electricity meter that we can connect to each device - the solar cell, the bicycle, the wind turbine, the water pump (so that the electricity produced or consumed flows through the meter). And then this meter is online (WiFi is available) and calls the API with its data.

My question is 'simply': What hardware products exist for this?

Hope it makes sense. Or else; ask!


问:
Decrypt in python pycryptodome AES CBC mode 256
Followed the example here:
https://pycryptodome.readthedocs.io/en/latest/src/cipher/classic.html#cbc-mode

Also can decrypt in online encryption/decryption services.

My example is not working:

```<code>import hashlib
from base64 import b64encode, b64decode
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

def decipher():
    secret_key = 'secret key'
    secret_iv = 'secret iv'
    key = hashlib.sha256(secret_key.encode('utf-8')).hexdigest()[:32].encode("utf-8")
    iv = hashlib.sha256(secret_iv.encode('utf-8')).hexdigest()[:16].encode("utf-8")
    s = 'HNAQf+1/fZXxzGTdVUs1qg=='
    s = str.encode(s)
    cipher = AES.new(key, AES.MODE_CBC, iv=iv)

    plain_text = unpad(cipher.decrypt(s), AES.block_size) #<-- this line

    return plain_text
</code>```

ValueError: Data must be padded to 16 byte boundary in CBC mode

Body:
Followed the example here:
https://pycryptodome.readthedocs.io/en/latest/src/cipher/classic.html#cbc-mode

Also can decrypt in online encryption/decryption services.

My example is not working:

import hashlib
from base64 import b64encode, b64decode
from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad

def decipher():
    secret_key = 'secret key'
    secret_iv = 'secret iv'
    key = hashlib.sha256(secret_key.encode('utf-8')).hexdigest()[:32].encode("utf-8")
    iv = hashlib.sha256(secret_iv.encode('utf-8')).hexdigest()[:16].encode("utf-8")
    s = 'HNAQf+1/fZXxzGTdVUs1qg=='
    s = str.encode(s)
    cipher = AES.new(key, AES.MODE_CBC, iv=iv)

    plain_text = unpad(cipher.decrypt(s), AES.block_size) #<-- this line

    return plain_text

ValueError: Data must be padded to 16 byte boundary in CBC mode


问:
cannot delete file after Isolate.kill: "The process cannot access the file because it is being used by another process"
I'm working on a simple windows app, where I encrypt a file in a dart isolate. During the process, the user can cancel the operation, and when that happened, I'll kill the isolate and do some cleanup, e.g, delete the partially processed file.

I got a "The process cannot access the file because it is being used by another process" when trying to delete the partially written file.

I tried the following

Delete the file right after Isolate.kill

Delete the file in on exit handler

Both results in the same "File being used by process" error.

My question is, is there any way to wait for the isolate to completely killed (all file handles are released), so I can safely delete them? Or if it's possible to get notifed in the code running in isolate, so that I can stop and release the file handle...


问:
Line chart is not shoing properly data
I am using the Charts library for displaying a line chart in my app

However, the chart is not displaying correctly when there are only three points available

See the attached screenshots below. Thanks in advance.

I want this type of chart

but results get this type

See Below my code for reference

I am using this library:-
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'

```<code>        chartView?.invalidate()
        chartView?.setViewPortOffsets(0f, 0f, 0f, 0f)
        chartView?.description?.isEnabled = false
        chartView?.setTouchEnabled(true)
        chartView?.isDragEnabled = true
        chartView?.setScaleEnabled(false)
        chartView?.setPinchZoom(false)
        chartView?.setDrawGridBackground(false)
        chartView?.maxHighlightDistance = 300f
        val x: XAxis? = chartView?.xAxis
        x?.isEnabled = Valse

        val y = chartView?.axisLeft
        y?.setLabelCount(0, false)
        y?.isEnabled = false
        y?.textColor = Color.GRAY
        y?.setDrawGridLines(false)
        y?.axisLineColor = Color.BLACK
        chartView?.axisLeft?.axisMinimum = 0f
        chartView?.axisRight?.axisMinimum = 0f

        chartView?.axisRight?.isEnabled = false

        chartView?.legend?.isEnabled = false

        val values = ArrayList<Entry>()
        values.add(Entry(0f, 4836.62f))
        values.add(Entry(1f, 4856.41f))
        values.add(Entry(2f, 4940.18f))

        val set1: LineDataSet

        if (chartView?.data != null &&
            chartView.data!!.dataSetCount > 0
        ) {
            set1 = chartView.data.getDataSetByIndex(0) as LineDataSet
            set1.values = values
            chartView.data.notifyDataChanged()
            chartView.notifyDataSetChanged()
            chartView.invalidate()
        } else {
            // create a dataset and give it a type
            set1 = LineDataSet(values, "")
            set1.mode = LineDataSet.Mode.CUBIC_BEZIER
            set1.cubicIntensity = 0.2f
            set1.setDrawFilled(false)
            set1.setDrawCircles(false)
            set1.lineWidth = 1.5f
            set1.color = ContextCompat.getColor(activity, R.color.colorPrimary)
            indexValue?.text = arrIndexList?.last()?.indexValue.toString()
            change?.text = arrIndexList?.last()?.change.toString()
            changePercent?.text = arrIndexList?.last()?.changePercent.toString()

            val data = LineData(set1)
            data.setValueTextSize(9f)
            data.setDrawValues(false)
            chartView?.data = data
            chartView?.animateX(1500)
        }
</code>```

Title: Line chart is not shoing properly data

Body:
I am using the Charts library for displaying a line chart in my app

However, the chart is not displaying correctly when there are only three points available

See the attached screenshots below. Thanks in advance.

I want this type of chart

but results get this type

See Below my code for reference

I am using this library:-
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'

        chartView?.invalidate()
        chartView?.setViewPortOffsets(0f, 0f, 0f, 0f)
        chartView?.description?.isEnabled = false
        chartView?.setTouchEnabled(true)
        chartView?.isDragEnabled = true
        chartView?.setScaleEnabled(false)
        chartView?.setPinchZoom(false)
        chartView?.setDrawGridBackground(false)
        chartView?.maxHighlightDistance = 300f
        val x: XAxis? = chartView?.xAxis
        x?.isEnabled = Valse

        val y = chartView?.axisLeft
        y?.setLabelCount(0, false)
        y?.isEnabled = false
        y?.textColor = Color.GRAY
        y?.setDrawGridLines(false)
        y?.axisLineColor = Color.BLACK
        chartView?.axisLeft?.axisMinimum = 0f
        chartView?.axisRight?.axisMinimum = 0f

        chartView?.axisRight?.isEnabled = false

        chartView?.legend?.isEnabled = false

        val values = ArrayList<Entry>()
        values.add(Entry(0f, 4836.62f))
        values.add(Entry(1f, 4856.41f))
        values.add(Entry(2f, 4940.18f))

        val set1: LineDataSet

        if (chartView?.data != null &&
            chartView.data!!.dataSetCount > 0
        ) {
            set1 = chartView.data.getDataSetByIndex(0) as LineDataSet
            set1.values = values
            chartView.data.notifyDataChanged()
            chartView.notifyDataSetChanged()
            chartView.invalidate()
        } else {
            // create a dataset and give it a type
            set1 = LineDataSet(values, "")
            set1.mode = LineDataSet.Mode.CUBIC_BEZIER
            set1.cubicIntensity = 0.2f
            set1.setDrawFilled(false)
            set1.setDrawCircles(false)
            set1.lineWidth = 1.5f
            set1.color = ContextCompat.getColor(activity, R.color.colorPrimary)
            indexValue?.text = arrIndexList?.last()?.indexValue.toString()
            change?.text = arrIndexList?.last()?.change.toString()
            changePercent?.text = arrIndexList?.last()?.changePercent.toString()

            val data = LineData(set1)
            data.setValueTextSize(9f)
            data.setDrawValues(false)
            chartView?.data = data
            chartView?.animateX(1500)
        }


问:
How to remotely change AdMob app unit ID?
Is there a way to remotely change the AdMob app unit ID, which is located in the manifest file? I already use Firebase Remote Config, but I could not find a way to update Manifest remotely...

In Manifest file:

```<code><meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="ca-app-pub-3940256099942544~3347511713"/>
</code>```

Body:
Is there a way to remotely change the AdMob app unit ID, which is located in the manifest file? I already use Firebase Remote Config, but I could not find a way to update Manifest remotely...

In Manifest file:

<meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="ca-app-pub-3940256099942544~3347511713"/>


问:
Confusion matrix almost perfectly balanced
I'm trying to predict the winning team of a Destiny2 PvP match based on the player stats.
The dataset has multiple columns:

player_X_stat

X from 1 to 12 for each player, players from 1 to 6 are in team A and players from 7 to 12 are in team B

stat is a specific player stat like average number of kills per game or average number of deaths per game etc.

So there are X * (number of different stat) columns (around 100 at the end)

winning_team being always 0 (see note below). The winning team is always composed of players from 1 to 6 (team A) and the losing team is composed of players from 7 to 12 (team B).

note: To set up a balanced dataset, I shuffle the teams so that the winning_team column has as many 0s as 1s. For example, player_1_kills becomes player_7_kills, player_7_kills becomes player_1_kills and winning_team becomes 1.

However when training a catboost classifier or a simple SVC, the confusion matrix is almost perfectly balanced:

[[87486 31592]

[31883 87196]]

It seems to me that this is an anomaly but I have no idea where it could come from.

Edit: link to google colab notebook


问:
How to use the cursorPaginate/CursorPaginator on a custom built array
```<code>$filtered_restros= new \Illuminate\Pagination\CursorPaginator($restaurants, 1);
$data['message'] = "Restaurants fetched successfully";
$data['status'] = "success";
$data['data'] = $filtered_restros;
</code>```

I did this code and i'm getting fallowing results

```<code>{
    "message": "Restaurants fetched successfully",
    "status": "success",
    "data": {
        "data": [
            {
                "id": 5,
                "name": "HB Town Restro",
                "email": "2321efsd@gmail.com",
                "phone_number": "12",
                "mobile_number": "454554354",
                "address": "hjgjghioiu",
                "pincode": "4400255241653",
                "latitude": "21.150964",
                "longitude": "79.150516",
                "restro_type": 1,
                "cuisine_type": "American",
                "book_now_btn": 1,
                "queue_btn": 0,
                "is_saved": 0,
                "restro_cuisines": [
                    {
                        "cuisine_id": 5,
                        "cuisine_name": "North indian"
                    }
                ],
                "seating_options": [
                    "Cafeteria",
                    "fghfghf",
                    "Cafeterias",
                    "indoor"
                ],
                "description": "gj",
                "menu_category": "5",
                "parking": "Onsite",
                "image": "http://localhost/projectx/public/restaurants/hb.jpg",
                "status": 1
            }
        ],
        "path": "/",
        "per_page": 1,
        "next_page_url": "/?cursor=eyJfcG9pbnRzVG9OZXh0SXRlbXMiOnRydWV9",
        "prev_page_url": null
    }
}
</code>```

after hitting the "next_page_url"

http://localhost/projectx/api/user/explore_all_restaurants?cursor=eyJfcG9pbnRzVG9OZXh0SXRlbXMiOnRydWV9

this printing same results as above means cursor pagination is not working.

When i did same thing using eloquent

```<code>$users = DB::table('restros')->orderBy('id')->cursorPaginate(15);
</code>```

its working properly and pagination is also working and full next page url are automatically generating. but its using eloquent and i want to do the cursor pagination on my processed array and its not working properly.

In short i'm asking how to do cursor pagination on custom array.

Body:
$filtered_restros= new \Illuminate\Pagination\CursorPaginator($restaurants, 1);
$data['message'] = "Restaurants fetched successfully";
$data['status'] = "success";
$data['data'] = $filtered_restros;

I did this code and i'm getting fallowing results

{
    "message": "Restaurants fetched successfully",
    "status": "success",
    "data": {
        "data": [
            {
                "id": 5,
                "name": "HB Town Restro",
                "email": "2321efsd@gmail.com",
                "phone_number": "12",
                "mobile_number": "454554354",
                "address": "hjgjghioiu",
                "pincode": "4400255241653",
                "latitude": "21.150964",
                "longitude": "79.150516",
                "restro_type": 1,
                "cuisine_type": "American",
                "book_now_btn": 1,
                "queue_btn": 0,
                "is_saved": 0,
                "restro_cuisines": [
                    {
                        "cuisine_id": 5,
                        "cuisine_name": "North indian"
                    }
                ],
                "seating_options": [
                    "Cafeteria",
                    "fghfghf",
                    "Cafeterias",
                    "indoor"
                ],
                "description": "gj",
                "menu_category": "5",
                "parking": "Onsite",
                "image": "http://localhost/projectx/public/restaurants/hb.jpg",
                "status": 1
            }
        ],
        "path": "/",
        "per_page": 1,
        "next_page_url": "/?cursor=eyJfcG9pbnRzVG9OZXh0SXRlbXMiOnRydWV9",
        "prev_page_url": null
    }
}

after hitting the "next_page_url"

http://localhost/projectx/api/user/explore_all_restaurants?cursor=eyJfcG9pbnRzVG9OZXh0SXRlbXMiOnRydWV9

this printing same results as above means cursor pagination is not working.

When i did same thing using eloquent

$users = DB::table('restros')->orderBy('id')->cursorPaginate(15);

its working properly and pagination is also working and full next page url are automatically generating. but its using eloquent and i want to do the cursor pagination on my processed array and its not working properly.

In short i'm asking how to do cursor pagination on custom array.


问:
How to create multiple tabs in Superset Dashboard?
Having trouble finding the option to create multiple tabs in superset dashboard.

I tried to find the option to create the tabs. I couldn't able to see the option.


问:
Is it necessary to dispose a task when ran to completion or faulted?
I am accepting TCP clients using the below code:

```<code>TcpClient client = tcpListener.AcceptTcpClient();
Task.Factory.StartNew(() => Read_it(client, tcpPort)).ContinueWith(x =>
    {
       if (x.Exception != null)
       {
           x.Dispose();
       }
           }, TaskContinuationOptions.OnlyOnFaulted |
       TaskContinuationOptions.OnlyOnRanToCompletion).ContinueWith(x =>
       {
           x.Dispose();
       });
    }
</code>```

I have two questions.

Is it necessary to dispose tasks like this? Especially when the task itself has disposed code for the TcpClient and NetworkStream?

Is my code an acceptable way of disposing tasks that ran to completion or faulted? Or for example, does the Garbage Collector eventually clean up any task that has been completed one way or another? Maybe do I manually call Garbage Collector, say every 10 minutes or so?

Body:
I am accepting TCP clients using the below code:

TcpClient client = tcpListener.AcceptTcpClient();
Task.Factory.StartNew(() => Read_it(client, tcpPort)).ContinueWith(x =>
    {
       if (x.Exception != null)
       {
           x.Dispose();
       }
           }, TaskContinuationOptions.OnlyOnFaulted |
       TaskContinuationOptions.OnlyOnRanToCompletion).ContinueWith(x =>
       {
           x.Dispose();
       });
    }

I have two questions.

Is it necessary to dispose tasks like this? Especially when the task itself has disposed code for the TcpClient and NetworkStream?

Is my code an acceptable way of disposing tasks that ran to completion or faulted? Or for example, does the Garbage Collector eventually clean up any task that has been completed one way or another? Maybe do I manually call Garbage Collector, say every 10 minutes or so?


问:
New bundled expo-cli start is returning a manifest that cannot be parsed by expo-dev-launcher
We are currently going through the upgrade to expo SDK 47, following these instructions:
https://blog.expo.dev/expo-sdk-47-a0f6f5c038af

Part of the upgrade involves the recommended switch to using the bundled expo-cli, rather than the global instance.

When we make this change, and run npx expo start --dev-client, our android app throws an error when selecting the dev server, with the message:

Value ----------------------------224819657222108214122421 of type java.lang.String cannot be converted to JSONObject

When I hit the dev server url (eg. http://192.168.0.146:8081/?platform=android) manually to obtain the manifest, I can see it is indeed starting with the above value, as it contains some meta-data, eg.

```<code>----------------------------224819657222108214122421
Content-Disposition: form-data; name="manifest"
Content-Type: application/json

{"id":"f5c3b7be-999c-436e-b9c4-b453cf873af0","createdAt":"2023-01-12T10:13:41.499Z","runtimeVersion":"1.e","launchAsset":{"key":"bundle","contentType":"application/javascript","url":"http://10.20.0.174:8081/index.bundle?platform=android&dev=true&hot=false"},"asset
...
</code>```

When I switch back to using the globally installed CLI as per the instructions in the upgrade blog, so changing the start command from npx expo start to expo-cli start, the same test results in the manifest being returned without the supplementary data, and the app can be loaded successfully.

Body:
We are currently going through the upgrade to expo SDK 47, following these instructions:
https://blog.expo.dev/expo-sdk-47-a0f6f5c038af

Part of the upgrade involves the recommended switch to using the bundled expo-cli, rather than the global instance.

When we make this change, and run npx expo start --dev-client, our android app throws an error when selecting the dev server, with the message:

Value ----------------------------224819657222108214122421 of type java.lang.String cannot be converted to JSONObject

When I hit the dev server url (eg. http://192.168.0.146:8081/?platform=android) manually to obtain the manifest, I can see it is indeed starting with the above value, as it contains some meta-data, eg.

----------------------------224819657222108214122421
Content-Disposition: form-data; name="manifest"
Content-Type: application/json

{"id":"f5c3b7be-999c-436e-b9c4-b453cf873af0","createdAt":"2023-01-12T10:13:41.499Z","runtimeVersion":"1.e","launchAsset":{"key":"bundle","contentType":"application/javascript","url":"http://10.20.0.174:8081/index.bundle?platform=android&dev=true&hot=false"},"asset
...

When I switch back to using the globally installed CLI as per the instructions in the upgrade blog, so changing the start command from npx expo start to expo-cli start, the same test results in the manifest being returned without the supplementary data, and the app can be loaded successfully.


问:
Is there a way to add 'fl' parameter to a Solr query to return all attributes without "_" symbols?
I want to retrieve all attributes in a query from Apache Solr(9.0.0) which does not have any underscores. what should the fl parameter be to achieve this?</p>


问:
Minimum remainder in range of multiple of integer for an integer
Is it possible to resolve below given problem with excel formula?

One machine can produce in lot ( range of integer between two numbers)
For example, it can produce in multiple of 5 to 7 batches per lot ( can produce in multiple of 5,6 & 7 ). I have one order of 8 batches , now I want to compute that how many MINIMUM extra batches needs to be produce to fulfill the lot size requirement.
Answer for this question is = 2 ( I can produce 5+5=10 ( 8 order + 2 extra ).

Variable value
Variable value
Variable value
Want formula to calculate this
For ref

Min capability
Max capability
Order
Extra batch to fulfill order
Lot combi

5
7
1
4
5

5
7
2
3
5

5
7
3
2
5

5
7
4
1
5

5
7
5
0
5

5
7
6
0
6

5
7
7
0
7

5
7
8
2
5+5

5
7
9
1
5+5

5
7
10
0
5+5

5
7
11
0
5+6

5
7
12
0
5+7

5
7
13
0
6+7

5
7
14
0
7+7

5
7
15
0
5+5+5

5
7
16
0
5+5+6

...
...
...
...
...


问:
What is the best alternative of ParkMyCloud to rightsize and schedule when your resources run and stop for GCP?
Context: We are working on GCP and using ParkMyCloud(PMC) to schedule the resources run and stop. The developers from different teams in the company have access to the run/stop operations on the PMC application. This is to reduce the costs on GCP.

Problem: ParkMyCloud is no more available for GCP (because it is bought by IBM and the substituted application is very expensive)

The application which are proposed to be an alternative to PMC are doing only monitoring&security in general.

My question is that if there is an application which performs the following:

Resources (instances, sql operations etc.) can by shut down manually,

Scheduling the the resources run and stop is possible and can be customised.

After googling I have found some candidates such as Doit-Flexsave and Rapid7-InsightCloudSec, but these are doing only Monitoring, Reporting or Security. I am not looking for such tools.

Another solution is to use Cloud Functions and Scheduler, but for now I would like to know that if I can find a tool like ParkMyCloud.


问:
how to work with local tmp files in an Nodejs API?
I am currently making a little API which returns jsons according to an input. This API needs to run some local programs on the server and also needs to place some temporary files. It all works if I ask the API once a time and just with one "user".

The problem is, that I only have one temp folder to store the temporary files.so whenever there are multiple API queries, the tmp folder screws up - the data in there mixes up.

What would be a good way to have an API using temp files - and still keep it working if every run needs its own temp data?

The current process is:

```<code>server/api/getGeometry?lat=52.5167776&lon=13.4092091&bboxSize=2000&output=glb
</code>```

server queries zips according to lat/lon

unpacks

converts

does voodoo

generates json

sends back the json

cleans up the tmp folder

next run same story...
so every time the same tmp folder, I guess it's not the way to go.

Thanks a lot for ideas!

Body:
I am currently making a little API which returns jsons according to an input. This API needs to run some local programs on the server and also needs to place some temporary files. It all works if I ask the API once a time and just with one "user".

The problem is, that I only have one temp folder to store the temporary files.so whenever there are multiple API queries, the tmp folder screws up - the data in there mixes up.

What would be a good way to have an API using temp files - and still keep it working if every run needs its own temp data?

The current process is:

server/api/getGeometry?lat=52.5167776&lon=13.4092091&bboxSize=2000&output=glb

server queries zips according to lat/lon

unpacks

converts

does voodoo

generates json

sends back the json

cleans up the tmp folder

next run same story...
so every time the same tmp folder, I guess it's not the way to go.

Thanks a lot for ideas!