问:
I am creating an jobsearch website in django. where jobseekers can find jobs and recruiters can post the jobs,
I have three diffrent apps in my django project, Home, jobseeker and recruiter. and each app have different subdomain. Home => localhost:8000, jobseeker => jobseeker.localhost.8000, and for recruiter => recruiter.localhost:8000. i have an registration form in my Home app(localhost:8000) when i submitting the form i am getting..

```<code>Forbidden (403)
CSRF verification failed. Request aborted.

Help
Reason given for failure:

    Origin checking failed - null does not match any trusted origins.
</code>```

how can i solve this?

here is my hosts.py file

```<code>from django_hosts import patterns, host

host_patterns = patterns('',
                         host(r'^(?:www\.)?$', 'Home.urls', name='perfectpesha'),
                         host(r'jobseeker', 'jobseeker.urls', name='jobseeker'),
                         host(r'recruiter', 'recruiter.urls', name='recruiter'),
                         )
</code>```

here is my registration form

```<code>{% extends "layout.html" %}
{% load i18n %}
{% load hosts %}
{% load static %}
{% load tz %}

{% block content %}

<form class="form-horizontal" method="POST" action="{% host_url "jobseekerRegister" host "jobseeker" %}">

    {% csrf_token %}

    <div class="formrow">

        <input type="text" name="name" class="form-control" required="required"
               placeholder="Full Name" {% if form.name.errors %}style="border: 1px solid #FE0004"{% endif %}>

        {% if form.name.errors %}
            {% for error in form.name.errors %}
                <span class="help-block-error"> <strong>{{ error }}</strong></span>
            {% endfor %}
        {% endif %}

    </div>

    <div class="formrow">

        <input type="email" name="email" class="form-control" required="required"
               placeholder="Email" {% if form.email.errors %}style="border: 1px solid #FE0004"{% endif %}>

        {% if form.email.errors %}

                {% for error in form.email.errors %}
                    <span class="help-block-error"> <strong>{{ error }}</strong></span>
                {% endfor %}

        {% endif %}

    </div>

    <div class="formrow">

        <input type="number" name="mobile" class="form-control" required="required"
               placeholder="Mobile" {% if form.mobile.errors %}style="border: 1px solid #FE0004"{% endif %}>

        {% if form.mobile.errors %}

                {% for error in form.mobile.errors %}
                    <span class="help-block-error"> <strong>{{ error }}</strong></span>
                {% endfor %}

        {% endif %}

    </div>

    <div class="formrow">

        <input type="password" name="password" class="form-control" required="required"
               placeholder="Password" {% if form.password.errors %}style="border: 1px solid #FE0004"{% endif %}>

        {% if form.password.errors %}
                {% for error in form.password.errors %}
                   <span class="help-block-error"> <strong>{{ error }}</strong></span>
                {% endfor %}

        {% endif %}
    </div>

    <div class="formrow">

        <input type="password" name="password_confirmation" class="form-control"
               required="required" placeholder="Password Confirmation" {% if form.password_confirmation.errors %}style="border: 1px solid #FE0004"{% endif %}>

        {% if form.password_confirmation.errors %}

            {% for error in form.password_confirmation.errors %}
                <span class="help-block-error"> <strong>{{ error }}</strong></span>
            {% endfor %}

        {% endif %}
    </div>

    <div class="formrow">

        <textarea class="form-control" name="address" placeholder="address"></textarea>

    </div>

    <div class="formrow">

        <input type="checkbox" value="1" name="is_subscribed"
               checked="checked"/>
        Subscribe to Newsletter

    </div>

    <div class="formrow">

        <input type="checkbox" value="1" name="terms_of_use"/>

        <a href="#">I accept Terms of Use</a>

    </div>

    <input type="submit" class="btn" value="Register">

</form>
{% endblock %}
</code>```

and here is jobseeker url

```<code>path("register/", views.register, name="jobseekerRegister"),
</code>```

my form is submitting from localhost:8000/login to jobseeker.localhost:8000/login but i am getting csrf error.

this is my settings.py file

```<code>ALLOWED_HOSTS = [env('HOST'), 'jobseeker.' + env('HOST'), 'recruiter.' + env('HOST')]

CSRF_TRUSTED_ORIGINS = ['http://' + env('HOST'), 'http://jobseeker.' + env('HOST'), 'http://recruiter.' + env('HOST')]
</code>```

in .env file

```<code>HOST='localhost'
</code>```

please help me.....

Body:
I have three diffrent apps in my django project, Home, jobseeker and recruiter. and each app have different subdomain. Home => localhost:8000, jobseeker => jobseeker.localhost.8000, and for recruiter => recruiter.localhost:8000. i have an registration form in my Home app(localhost:8000) when i submitting the form i am getting..

Forbidden (403)
CSRF verification failed. Request aborted.

Help
Reason given for failure:

    Origin checking failed - null does not match any trusted origins.

how can i solve this?

here is my hosts.py file

from django_hosts import patterns, host

host_patterns = patterns('',
                         host(r'^(?:www\.)?$', 'Home.urls', name='perfectpesha'),
                         host(r'jobseeker', 'jobseeker.urls', name='jobseeker'),
                         host(r'recruiter', 'recruiter.urls', name='recruiter'),
                         )

here is my registration form

{% extends "layout.html" %}
{% load i18n %}
{% load hosts %}
{% load static %}
{% load tz %}

{% block content %}

<form class="form-horizontal" method="POST" action="{% host_url "jobseekerRegister" host "jobseeker" %}">

    {% csrf_token %}

        <input type="text" name="name" class="form-control" required="required"
               placeholder="Full Name" {% if form.name.errors %}style="border: 1px solid #FE0004"{% endif %}>

        {% if form.name.errors %}
            {% for error in form.name.errors %}
                 {{ error }}
            {% endfor %}
        {% endif %}

        <input type="email" name="email" class="form-control" required="required"
               placeholder="Email" {% if form.email.errors %}style="border: 1px solid #FE0004"{% endif %}>

        {% if form.email.errors %}

                {% for error in form.email.errors %}
                     {{ error }}
                {% endfor %}

        {% endif %}

        <input type="number" name="mobile" class="form-control" required="required"
               placeholder="Mobile" {% if form.mobile.errors %}style="border: 1px solid #FE0004"{% endif %}>

        {% if form.mobile.errors %}

                {% for error in form.mobile.errors %}
                     {{ error }}
                {% endfor %}

        {% endif %}

        <input type="password" name="password" class="form-control" required="required"
               placeholder="Password" {% if form.password.errors %}style="border: 1px solid #FE0004"{% endif %}>

        {% if form.password.errors %}
                {% for error in form.password.errors %}
                    {{ error }}
                {% endfor %}

        {% endif %}

        <input type="password" name="password_confirmation" class="form-control"
               required="required" placeholder="Password Confirmation" {% if form.password_confirmation.errors %}style="border: 1px solid #FE0004"{% endif %}>

        {% if form.password_confirmation.errors %}

            {% for error in form.password_confirmation.errors %}
                 {{ error }}
            {% endfor %}

        {% endif %}

        <textarea class="form-control" name="address" placeholder="address"></textarea>

        <input type="checkbox" value="1" name="is_subscribed"
               checked="checked"/>
        Subscribe to Newsletter

        <input type="checkbox" value="1" name="terms_of_use"/>

        I accept Terms of Use

    <input type="submit" class="btn" value="Register">

</form>
{% endblock %}

and here is jobseeker url

path("register/", views.register, name="jobseekerRegister"),

my form is submitting from localhost:8000/login to jobseeker.localhost:8000/login but i am getting csrf error.

this is my settings.py file

ALLOWED_HOSTS = [env('HOST'), 'jobseeker.' + env('HOST'), 'recruiter.' + env('HOST')]

CSRF_TRUSTED_ORIGINS = ['http://' + env('HOST'), 'http://jobseeker.' + env('HOST'), 'http://recruiter.' + env('HOST')]

in .env file

HOST='localhost'

please help me.....


来源: stackexchange

问:
i'm using nest js and mongodb with prisma and i want to send the district data in form of array but have facing some problem
error is : Type 'districttype' is not assignable to type 'UserCreateroleInput | Enumerable'

here is my authdto file. in authdto i'm taking district type. for the type of districtype i'm create a district.dto and here is my auth dto and distric dto

```<code>export class AuthDto {
  @IsNotEmpty()
  firstName: string;
  @IsEmail()
  @IsNotEmpty()
  email: string;
  @IsNotEmpty()
  @IsString()
  password: string;

  @IsOptional()
  @IsArray()
  distric?: districtypes[]

  @IsBoolean()
  @Type(() => Boolean)
  isActive?: boolean;
}
</code>```

in before code you see my distric.dto file in my distric dto i'm taking sum types for distric
here is distric.dto file

```<code>import { IsBoolean } from "class-validator"

export interface districtypes{

    is_udaipur:boolean;
    is_jaipur:boolean
    is_bikaner:boolean
    is_chittor:boolean
}
</code>```

and i want to send the distric data in array form in database but face some error. here is my auth .service file

```<code>export class AuthService {
  constructor(
    private prisma: PrismaService,
    private jwt: JwtService,
    private config: ConfigService,
  ) {}
  async signUp(dto: AuthDto) {
      const hash = await argon.hash(dto.password);
      console.log('dto',dto);
      const user = await this.prisma.user.create({
        data: {
          firstName: dto.firstName,
          lastName: dto.lastName,
          mobile: dto.mobile,
          email: dto.email,
          district: dto.district,   //i'm facing this problem on this place the error is
                              "Types'districttypes[]' is not assignable to type 'UserCreateroleInput |
                                                                    Enumerable<string>'."
          hash,
          isActive: dto.isActive,
        },
      });
            return this.signInToken(
        user.id,
        user.email,
      );
    }
  }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
error is : Type 'districttype' is not assignable to type 'UserCreateroleInput | Enumerable'

here is my authdto file. in authdto i'm taking district type. for the type of districtype i'm create a district.dto and here is my auth dto and distric dto

export class AuthDto {
  @IsNotEmpty()
  firstName: string;
  @IsEmail()
  @IsNotEmpty()
  email: string;
  @IsNotEmpty()
  @IsString()
  password: string;

  @IsOptional()
  @IsArray()
  distric?: districtypes[]

  @IsBoolean()
  @Type(() => Boolean)
  isActive?: boolean;
}

in before code you see my distric.dto file in my distric dto i'm taking sum types for distric
here is distric.dto file

import { IsBoolean } from "class-validator"

export interface districtypes{

    is_udaipur:boolean;
    is_jaipur:boolean
    is_bikaner:boolean
    is_chittor:boolean
}

and i want to send the distric data in array form in database but face some error. here is my auth .service file

export class AuthService {
  constructor(
    private prisma: PrismaService,
    private jwt: JwtService,
    private config: ConfigService,
  ) {}
  async signUp(dto: AuthDto) {
      const hash = await argon.hash(dto.password);
      console.log('dto',dto);
      const user = await this.prisma.user.create({
        data: {
          firstName: dto.firstName,
          lastName: dto.lastName,
          mobile: dto.mobile,
          email: dto.email,
          district: dto.district,   //i'm facing this problem on this place the error is
                              "Types'districttypes[]' is not assignable to type 'UserCreateroleInput |
                                                                    Enumerable<string>'."
          hash,
          isActive: dto.isActive,
        },
      });
            return this.signInToken(
        user.id,
        user.email,
      );
    }
  }


问:
The Jenkins build for executing a sh file is successful, but when checked in backend (terminal) , the sh file hasn't started yet
In my Jenkins job when I try to run the following line, I'm getting response as the build is successful however, the .sh file is not getting executed in the back end (terminal) :

ssh -T username@ip ‘sh /path/file.sh’

#the command is supposed to start a service

The same .sh file runs in backend (terminal) when executed manually from backend.

The same command is working for other servers.


问:
How to override attribute of a BERT class
I am using BertJapaneseTokenizer for an NLP project.
I am running into the error "The unidic_lite dictionary is not installed". On checking under the hood it looks from one of the elif conditions that this error will be thrown only if the variable mecab_dic is set = "unidic_lite" (please see this link https://huggingface.co/transformers/v4.11.3/_modules/transformers/models/bert_japanese/tokenization_bert_japanese.html)

Furthermore, due to some unavoidable constraints I cannot install unidic_lite module (let's just assume this is a constraint I have). However, I can install unidic. So my question is -- is there a way to do a manual override like mecab_dic = "unidic" such that elif statement for unidic_lite is bypassed altogether?
(relatedly, we can see from the constructor of MecabTokenizer that mecab_dic should have default value as "ipadic", then why is it set as mecab_dic set = 'unidic_lite' anyway!?)

Any suggestion would be super helpful. Thanks!

(P.S: I am not super tech-savvy so this was attempt at a crude workaround)

What I tried: downloaded the tokenization_bert_japanese.py code to my local machine and created a static variable mecab_dic = "unidic" in it and tried to import BertJapanesTokenizer from this customized python script instead of the standard "from transformers import BertJapaneseTokenzier"


问:
next.js build failed before firebase deploy

I am trying to deploy my next.js file to firebase.

The command firebase deploy --only hosting works, but the deployed file is not built in the file of next.js.

I tried this:

I edited package.json, script.build setting next build into next build && next export
thus the /out folder was automatically created.

I set the /out folder as the public directory and then executed firebase deploy.

Here is the guide I used:

https://medium.com/nerd-for-tech/lets-deploy-a-next-js-app-with-firebase-hosting-e070b3aecd04

Obviously this failed. That is why I am asking for help.

When I edit index.html in the /out file and then deploy, it is successfully deployed.
Here is the picture:

I am expecting that the problem is on building the next.js file.

Is there anyone that knows what to do in order to build it successfully?


问:
Length of header or names does not match length of data when using pd.read_csv
I tried to read a .dat file in python and convert to pandas dataframe using the below code

```<code>DATA_ = pd.read_csv(r'C:\Users\my_exp\data_new.dat', encoding = "latin1", engine = 'python', sep=',;:\r\t\s+|\s+')
</code>```

(Note: I was not able to read the dt file through notepad++ or even vs code and hence tried to use all delimiters in sep. Also I tried with other encodings starting with utf-8, but they didn't work and so switched to latin1)

As there was error I read through other stackoverflow posts and finally used the below piece of code

```<code>DATA_ = pd.read_csv(r'C:\Users\my_exp\data_new.dat',encoding = "latin1", engine = 'python', sep=',;:\r\t\s+|\s+', index_col = False, header =0)
</code>```

and the problem I had was

MemoryError: Unable to allocate 75.6 GiB for an array with shape
(1189027, 8538) and data type object

So, I used nrows as below

```<code>DATA_ = pd.read_csv(r'C:\Users\my_exp\data_new.dat',encoding = "latin1", engine = 'python', sep=',;:\r\t\s+|\s+', nrows=50, index_col = False, header =0)
</code>```

Now the error I'm seeing is

ParserWarning: Length of header or names does not match length of
data. This leads to a loss of data with index_col=False.

Please let me know how to deal with this. Is there any better way to inspect dat files? I tried pr.read_fwf as well but doesnt seem to work.

Just to mention. Using encoding = 'utf-8' throws this error

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position
0: invalid start byte

What is the mistake I'm making or is there an issue with the data itself....please clarify.

Body:
I tried to read a .dat file in python and convert to pandas dataframe using the below code

DATA_ = pd.read_csv(r'C:\Users\my_exp\data_new.dat', encoding = "latin1", engine = 'python', sep=',;:\r\t\s+|\s+')

(Note: I was not able to read the dt file through notepad++ or even vs code and hence tried to use all delimiters in sep. Also I tried with other encodings starting with utf-8, but they didn't work and so switched to latin1)

As there was error I read through other stackoverflow posts and finally used the below piece of code

DATA_ = pd.read_csv(r'C:\Users\my_exp\data_new.dat',encoding = "latin1", engine = 'python', sep=',;:\r\t\s+|\s+', index_col = False, header =0)

and the problem I had was

MemoryError: Unable to allocate 75.6 GiB for an array with shape
(1189027, 8538) and data type object

So, I used nrows as below

DATA_ = pd.read_csv(r'C:\Users\my_exp\data_new.dat',encoding = "latin1", engine = 'python', sep=',;:\r\t\s+|\s+', nrows=50, index_col = False, header =0)

Now the error I'm seeing is

ParserWarning: Length of header or names does not match length of
data. This leads to a loss of data with index_col=False.

Please let me know how to deal with this. Is there any better way to inspect dat files? I tried pr.read_fwf as well but doesnt seem to work.

Just to mention. Using encoding = 'utf-8' throws this error

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position
0: invalid start byte

What is the mistake I'm making or is there an issue with the data itself....please clarify.


问:
Resource management with Concurrency
```<code>ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Connection> task = () -> getConnection(); // a complicated method but safe from resource leaks
try (Connection connection = timeOut == null
        ? executor.submit(task).get()
        : executor.submit(task).get(timeOut.toMillis(), TimeUnit.MILLISECONDS)) {
    // business logic
} catch (SQLException e) {
    // log
} catch (InterruptedException e) {
    // log
    Thread.currentThread().interrupt();
} catch (ExecutionException e) {
    // log
} catch (Exception e) {
    // log
} finally {
    executor.shutdownNow();
}
</code>```

I have a piece of code which is supposed to fail if getConnection() takes too long,
I am new to combining resource management with concurrency, is there any risk of resource leak if I implement it like this?
Is there a better way to do it?

Title: Resource management with Concurrency

Body:
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Connection> task = () -> getConnection(); // a complicated method but safe from resource leaks
try (Connection connection = timeOut == null
        ? executor.submit(task).get()
        : executor.submit(task).get(timeOut.toMillis(), TimeUnit.MILLISECONDS)) {
    // business logic
} catch (SQLException e) {
    // log
} catch (InterruptedException e) {
    // log
    Thread.currentThread().interrupt();
} catch (ExecutionException e) {
    // log
} catch (Exception e) {
    // log
} finally {
    executor.shutdownNow();
}

I have a piece of code which is supposed to fail if getConnection() takes too long,
I am new to combining resource management with concurrency, is there any risk of resource leak if I implement it like this?
Is there a better way to do it?


问:
How to simplify python schedule.every().day.at("12:45").do(job) function call as 1 simple function? that accepts only function call
The schedule.every().day.at("12:45").do(job) accepts only function call in the .do(job) parameter. Because of this I need to create multiple functions. Is there any better way to reduce the it to 1 to 2 Functions?. If it could have accepts parameter like .at("12:45") function, I could have used a for loop and scheduled that jobs at once. But unable to figure it out other way.

Scheduler Documentation

I have some list of 'times' with 'audio file path' in SQLite Database. These data needs to be fetched and played at the mentioned times. I'm worried about large code as this needs to be run on Raspberry Pi all the time and more than 20 different time needed to be scheduled. Here is the code that I'm trying to simplify

The Function:

```<code>def curr_job(test):
    print('From rec_time called curr_job:')
    print(audiofile)
    print(test)
    mixer.music.load(audiofile)
    mixer.music.play(1)
</code>```

Calling the curr_job function inside schedule:

```<code>rec_time = "12:45"
#schedule.every().day.at(rec_time).do(curr_job)
schedule.every().day.at(rec_time).do(curr_job, test='test') #takes additional parameter like this
</code>```

Body:
The schedule.every().day.at("12:45").do(job) accepts only function call in the .do(job) parameter. Because of this I need to create multiple functions. Is there any better way to reduce the it to 1 to 2 Functions?. If it could have accepts parameter like .at("12:45") function, I could have used a for loop and scheduled that jobs at once. But unable to figure it out other way.

Scheduler Documentation

I have some list of 'times' with 'audio file path' in SQLite Database. These data needs to be fetched and played at the mentioned times. I'm worried about large code as this needs to be run on Raspberry Pi all the time and more than 20 different time needed to be scheduled. Here is the code that I'm trying to simplify

The Function:

def curr_job(test):
    print('From rec_time called curr_job:')
    print(audiofile)
    print(test)
    mixer.music.load(audiofile)
    mixer.music.play(1)

Calling the curr_job function inside schedule:

rec_time = "12:45"
#schedule.every().day.at(rec_time).do(curr_job)
schedule.every().day.at(rec_time).do(curr_job, test='test') #takes additional parameter like this


问:
Sending form-data in a POST request in golang
I'm trying to send form-data by making a post request. The api works fine (I've tested on postman), but I'm not sure why I'm having trouble to do it in golang. The form-data contains a task field and a file field. But if I do the following I get Bad Request. Any ideas why I might be getting this? Thanks in advance.</p>
```<code>// Create new buffer and writer
buf := new(bytes.Buffer)
w := multipart.NewWriter(buf)

// read data from file
var fdata []byte
if fd, e := os.Open(pdf); e != nil {
    log.Fatal(e)
} else {
    fd.Read(fdata)
}

// create file field and write
part, err := w.CreateFormFile("file", pdf)
if err != nil {
    log.Fatal(err)
}
part.Write(fdata)

// create the task field and write
part, err = w.CreateFormField("task")
if err != nil {
    log.Fatal(err)
}

part.Write([]byte(os.Getenv("task")))

w.Close()

// Create a new request
req, err := http.NewRequest("POST", fmt.Sprintf("https://%v/v1/upload",os.Getenv("server")), buf)

// Set content type header
req.Header.Add("Content-Type", "multipart/form-data")

// Send the request
client := &http.Client{}

resp, err := client.Do(req)
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

// other stuff

</code>```

Body:
I'm trying to send form-data by making a post request. The api works fine (I've tested on postman), but I'm not sure why I'm having trouble to do it in golang. The form-data contains a task field and a file field. But if I do the following I get Bad Request. Any ideas why I might be getting this? Thanks in advance.

// Create new buffer and writer
buf := new(bytes.Buffer)
w := multipart.NewWriter(buf)

// read data from file
var fdata []byte
if fd, e := os.Open(pdf); e != nil {
    log.Fatal(e)
} else {
    fd.Read(fdata)
}

// create file field and write
part, err := w.CreateFormFile("file", pdf)
if err != nil {
    log.Fatal(err)
}
part.Write(fdata)

// create the task field and write
part, err = w.CreateFormField("task")
if err != nil {
    log.Fatal(err)
}

part.Write([]byte(os.Getenv("task")))

w.Close()

// Create a new request
req, err := http.NewRequest("POST", fmt.Sprintf("https://%v/v1/upload",os.Getenv("server")), buf)

// Set content type header
req.Header.Add("Content-Type", "multipart/form-data")

// Send the request
client := &http.Client{}

resp, err := client.Do(req)
if err != nil {
    log.Fatal(err)
}
defer resp.Body.Close()

// other stuff


问:
Optimizer Hessian in tensorflow using Python
How can I implement optimizer for the following code in neural network using tensorflow for large data?

```<code>tf.hessians(
    ys,
    xs,
    gate_gradients=False,
    aggregation_method=None,
    name='hessians'
)
</code>```

I have following code:

```<code># Model A (2n, 2n+2n_1/3+n_2/2+n_3/2)
modelA1 = Sequential()
modelA1.add(Dense(132, input_dim=66, kernel_initializer="normal", activation='linear')) # input shape is (features,)
modelA1.add(Dropout(0.2))
modelA1.add(Dense(1, activation='relu'))

# loss function

#Compile the model (method 2)
ADGRAD=tf.keras.optimizers.experimental.Adagrad(
    learning_rate=0.075)

#Compile the model (method 1)

modelA1.compile(
    loss=tf.keras.losses.MeanSquaredLogarithmicError(),
    optimizer=ADGRAD,
    metrics=["Poisson"]
)
# train the model
tf.random.set_seed(1)
history1 = modelA1.fit(
    x,
    y,
    epochs=1000,
    batch_size=64,
    validation_split=0.2
)
</code>```

Is it possible and how to use optimizer Hessian instead of Adagrad? What is ys and xs refers to in above code tf.Hessian()?

Body:
How can I implement optimizer for the following code in neural network using tensorflow for large data?

tf.hessians(
    ys,
    xs,
    gate_gradients=False,
    aggregation_method=None,
    name='hessians'
)

I have following code:

# Model A (2n, 2n+2n_1/3+n_2/2+n_3/2)
modelA1 = Sequential()
modelA1.add(Dense(132, input_dim=66, kernel_initializer="normal", activation='linear')) # input shape is (features,)
modelA1.add(Dropout(0.2))
modelA1.add(Dense(1, activation='relu'))

# loss function

#Compile the model (method 2)
ADGRAD=tf.keras.optimizers.experimental.Adagrad(
    learning_rate=0.075)

#Compile the model (method 1)

modelA1.compile(
    loss=tf.keras.losses.MeanSquaredLogarithmicError(),
    optimizer=ADGRAD,
    metrics=["Poisson"]
)
# train the model
tf.random.set_seed(1)
history1 = modelA1.fit(
    x,
    y,
    epochs=1000,
    batch_size=64,
    validation_split=0.2
)

Is it possible and how to use optimizer Hessian instead of Adagrad? What is ys and xs refers to in above code tf.Hessian()?


问:
Implementing Lime with Sequential three-D Keras model
I want to implement LIME explainer to describe a three-dimensional Keras Sequential model (n_samples, n_timesteps, n_features).

I cannot understand whether I have to use Lime "RecurrentTabularExplainer" or "LimeTabularExplainer".

Also I cannot understand what the "classifier_fn" in "explain_instance" has to return and in what size.

For the moment I'm proceeding like this:

```<code>explainer = lime_tabular.RecurrentTabularExplainer(
      X_train
    , training_labels      = y_train
    , feature_names        = features
    , categorical_features = [3,5]
    , class_names          = ['Ko', 'Ok']
    , mode                 = 'regression'
)
</code>```
```<code>i = 40
exp = explainer.explain_instance(
      X_test[ i ]
    , classifier_f
    , labels = y_test[ i ]
)
</code>```

with

```<code>X_train.shape (4124,60,19)
y_train.shape (4124,60)

X_test.shape (938,60,19)
y_test.shape (938,60)
</code>```

Model

```<code> Layer (type)                Output Shape              Param #
=================================================================
 masking (Masking)           (None, 60, 19)            0

 gru (GRU)                   (None, 60, 100)           25800

 batch_normalization (BatchN  (None, 60, 100)          200
 ormalization)

 time_distributed (TimeDistr  (None, 60, 1)            101
 ibuted)
=================================================================
</code>```

Thank you a lot in advance.

Body:
I want to implement LIME explainer to describe a three-dimensional Keras Sequential model (n_samples, n_timesteps, n_features).

I cannot understand whether I have to use Lime "RecurrentTabularExplainer" or "LimeTabularExplainer".

Also I cannot understand what the "classifier_fn" in "explain_instance" has to return and in what size.

For the moment I'm proceeding like this:

explainer = lime_tabular.RecurrentTabularExplainer(
      X_train
    , training_labels      = y_train
    , feature_names        = features
    , categorical_features = [3,5]
    , class_names          = ['Ko', 'Ok']
    , mode                 = 'regression'
)

i = 40
exp = explainer.explain_instance(
      X_test[ i ]
    , classifier_f
    , labels = y_test[ i ]
)

with

X_train.shape (4124,60,19)
y_train.shape (4124,60)

X_test.shape (938,60,19)
y_test.shape (938,60)

Model

 Layer (type)                Output Shape              Param #
=================================================================
 masking (Masking)           (None, 60, 19)            0

 gru (GRU)                   (None, 60, 100)           25800

 batch_normalization (BatchN  (None, 60, 100)          200
 ormalization)

 time_distributed (TimeDistr  (None, 60, 1)            101
 ibuted)
=================================================================

Thank you a lot in advance.


问:
Getting HttpClientErrorException$Unauthorized: 401 : [no body] while using RestTemplate (service to service call)
I am using resttemplate to consume another service which returns List.Example:

Service A

```<code>        @Autowired
        RestTemplate restTemplate;

        private ResponseEntity<List<User>> getUsers() {
            try {
             return restTemplate.exchange("http://localhost:8082/api/users", HttpMethod.GET, new HttpEntity<>(List.class),
                        new ParameterizedTypeReference<>(){});
            }catch(Exception e) {
                e.printStackTrace();
            }
             return new ResponseEntity(HttpStatus.BAD_REQUEST);
        }
</code>```

Service B

Controller:

```<code> @GetMapping("/api/users")
@PreAuthorize("hasRole('user_read')")
public List<User> findUsers() {
    List<User> users = new ArrayList<>();
    users.add(User.builder().userId("1").name("user1").build());
    users.add(User.builder().userId("2").name("user2").build());
    return users;
}
</code>```

VO:

```<code>@Data
@Builder
public class User {
    String userId;
    String name;
}
</code>```

But I am getting this error while calling Service B's findUsers() from Service A

```<code>org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 : [no body]
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:105)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:168)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:122)
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:819)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:777)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:631)
</code>```

Note: Using keycloak so I have provided required client-id and it's client-secret.

Body:
I am using resttemplate to consume another service which returns List.Example:

Service A

        @Autowired
        RestTemplate restTemplate;

        private ResponseEntity<List<User>> getUsers() {
            try {
             return restTemplate.exchange("http://localhost:8082/api/users", HttpMethod.GET, new HttpEntity<>(List.class),
                        new ParameterizedTypeReference<>(){});
            }catch(Exception e) {
                e.printStackTrace();
            }
             return new ResponseEntity(HttpStatus.BAD_REQUEST);
        }

Service B

Controller:

 @GetMapping("/api/users")
@PreAuthorize("hasRole('user_read')")
public List<User> findUsers() {
    List<User> users = new ArrayList<>();
    users.add(User.builder().userId("1").name("user1").build());
    users.add(User.builder().userId("2").name("user2").build());
    return users;
}

VO:

@Data
@Builder
public class User {
    String userId;
    String name;
}

But I am getting this error while calling Service B's findUsers() from Service A

org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 : [no body]
    at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:105)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:168)
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:122)
    at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:819)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:777)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:631)

Note: Using keycloak so I have provided required client-id and it's client-secret.


问:
vite + svelte application deployment on digital ocean
I'm trying to deploy an application on digital ocean, i created the env variable in app platform then i tried to use them in vite project
i used import.meta.env and prefixed the variable with VITE_ but got undefined !
I used node REPL to view the .env file and it's there,
any Idea ?


问:
How to know why sidekiq job is in dead queue
in my system there are dead jobs but our monitoring did not catch any unrescued sidekiq errors. these jobs were scheduled to perform immediately. Is there a way to know why it go to the dead queue? I have run

```<code>job.error?
job.error_backtrace
</code>```

but the first one returns false and the second one returns nil.

is it possible to know why it moved to dead queue? is it possible there were too many jobs and it waited for a period of time before it give up? thanks

Body:
in my system there are dead jobs but our monitoring did not catch any unrescued sidekiq errors. these jobs were scheduled to perform immediately. Is there a way to know why it go to the dead queue? I have run

job.error?
job.error_backtrace

but the first one returns false and the second one returns nil.

is it possible to know why it moved to dead queue? is it possible there were too many jobs and it waited for a period of time before it give up? thanks


问:
Jacobi and Gauss iterative methods
I'm writing iterative solvers of linear systems and I run into the problem of OverflowError: Python int too large to convert to C long
I'm unsure what the problem is as I've gotten them to work without OverflowError before (albeit wrong solutions).

Code:

`

```<code>def Jacobi(A_in,x0_in,b_in,tol,step_max):
    N=len(A_in)
    x0=x0_in
    b=b_in
    it=0
    A=A_in.copy()
    x1=np.copy(x0)
    while 1:
        for i in range(0,N):
            S=0.0
            for j in range(0,N):
                if i!=j:
                    S+=(A[i][j]*x0[j])   <-- Either I'm wrong about formulation here
            x1[i]=(b[i]-S)/A[i][i]       <-- Or it's to do with how Python treats my copies...?
        dist_x0_x1=0
        for i in range(N):                  #Distance between x0 and x1
            dist_x0_x1+=(x0[i]-x1[i])**2
        dist_x0_x1=np.sqrt(dist_x0_x1)
        print(f"kth iteration:{x1}")
        if (dist_x0_x1)<tol:
            return x1
        else:
            x0=np.copy(x1)
            it+=1
        if it>step_max:
            print("Diverging")
            break

A1=np.array([[2,4,-2,-2],[1,2,4,-3],[-3,-3,8,-2],[-1,1,6,-3]])
b1=np.array([4,-3,5,1])
</code>```

`

Code below produces a slightly different error:
`

```<code>RuntimeWarning: overflow encountered in long_scalars
  dist+=(x0[d]-x_g[d])**2
</code>```

`

and:

```<code>RuntimeWarning: invalid value encountered in power
  dist=(dist)**0.5
</code>```

`

`

```<code>
def GaussSeidel(A_in,x0,b_in,tol=1E-5,max_step=100):
    b=b_in.copy()
    AC=A_in.copy()
    N=len(A_in)
    it=0
    x_g=np.copy(x0)
    while(1):
        for i in range(0,N):
            S=0.0
            for j in range(0,N):
                if i==j:
                    continue
                else:
                    S+=AC[i][j]*x0[j]
            x0[i]=(b[i]-S)/AC[i][i]

        dist=0
        for d in range(N):
            dist+=(x0[d]-x_g[d])**2

        dist=(dist)**0.5

        if dist<tol:
            return x0
        else:
            x_g=np.copy(x0)
            it+=1
        if it>max_step:
            print("Divergent")
            break

 A=np.array([[2.0,4.0,-2.0,-2.0],[1.0,2.0,4.0,-3.0],[-3.0,-3.0,8.0,-2.0],     [-1.0,1.0,6.0,-3.0]],dtype="f")
b1=np.array([4.0,-3.0,5.0,1.0])
</code>```

`

I've tried changing the location of initialization of S thinking it would impact the run by avoiding recursive explosion. I've changed the formulation of dist several times and made sure it produces the results I need. I've tried to change the way the program copies the input matrix, solution vector and x0 initial guesses to prevent inaccuracies or incompatability with the syntax in the loops but I'm at a loss!

Title: Jacobi and Gauss iterative methods

Body:
I'm writing iterative solvers of linear systems and I run into the problem of OverflowError: Python int too large to convert to C long
I'm unsure what the problem is as I've gotten them to work without OverflowError before (albeit wrong solutions).

Code:

`

def Jacobi(A_in,x0_in,b_in,tol,step_max):
    N=len(A_in)
    x0=x0_in
    b=b_in
    it=0
    A=A_in.copy()
    x1=np.copy(x0)
    while 1:
        for i in range(0,N):
            S=0.0
            for j in range(0,N):
                if i!=j:
                    S+=(A[i][j]*x0[j])   <-- Either I'm wrong about formulation here
            x1[i]=(b[i]-S)/A[i][i]       <-- Or it's to do with how Python treats my copies...?
        dist_x0_x1=0
        for i in range(N):                  #Distance between x0 and x1
            dist_x0_x1+=(x0[i]-x1[i])**2
        dist_x0_x1=np.sqrt(dist_x0_x1)
        print(f"kth iteration:{x1}")
        if (dist_x0_x1)<tol:
            return x1
        else:
            x0=np.copy(x1)
            it+=1
        if it>step_max:
            print("Diverging")
            break

A1=np.array([[2,4,-2,-2],[1,2,4,-3],[-3,-3,8,-2],[-1,1,6,-3]])
b1=np.array([4,-3,5,1])

`

Code below produces a slightly different error:
`

RuntimeWarning: overflow encountered in long_scalars
  dist+=(x0[d]-x_g[d])**2

`

and:

RuntimeWarning: invalid value encountered in power
  dist=(dist)**0.5

`

`

def GaussSeidel(A_in,x0,b_in,tol=1E-5,max_step=100):
    b=b_in.copy()
    AC=A_in.copy()
    N=len(A_in)
    it=0
    x_g=np.copy(x0)
    while(1):
        for i in range(0,N):
            S=0.0
            for j in range(0,N):
                if i==j:
                    continue
                else:
                    S+=AC[i][j]*x0[j]
            x0[i]=(b[i]-S)/AC[i][i]

        dist=0
        for d in range(N):
            dist+=(x0[d]-x_g[d])**2

        dist=(dist)**0.5

        if dist<tol:
            return x0
        else:
            x_g=np.copy(x0)
            it+=1
        if it>max_step:
            print("Divergent")
            break

 A=np.array([[2.0,4.0,-2.0,-2.0],[1.0,2.0,4.0,-3.0],[-3.0,-3.0,8.0,-2.0],     [-1.0,1.0,6.0,-3.0]],dtype="f")
b1=np.array([4.0,-3.0,5.0,1.0])

`

I've tried changing the location of initialization of S thinking it would impact the run by avoiding recursive explosion. I've changed the formulation of dist several times and made sure it produces the results I need. I've tried to change the way the program copies the input matrix, solution vector and x0 initial guesses to prevent inaccuracies or incompatability with the syntax in the loops but I'm at a loss!


问:
Browser back button to go back to specific route
I am on a certain link when I click on the browser back button I want to send it back to the homepage which is the "/" route. How can I implement this feature in Next js?</p>


问:
How To Use One Data Class For Two View Pager Android Kotlin
In my app, there is a viewpager fragment that contains 2 tab. First tab is all data, second tab is top 10 data.

When the fragment is loaded, it calls two API Endpoints

```<code>@GET("api/get-all")
suspend fun getAllLinks(@Query("userid") userID: String, @Query("token") token: String, @Query("page") page: Int) : Respond

@GET("api/topten")
suspend fun getTopTen(@Query("userid") userid: String, @Query("token")token: String): Respond
</code>```

Both of them will return the data to Respond data class

```<code>data class Respond(
val error: List<ErrorMsg>?,
val data: List<DataContent>?,
val token: String?,
)
</code>```

The problem is, when I want to show the data to the recylerview, only the data of All Data that is shown

I'm guessing it's because there is only one instance of Respond data class that only holds data of All Data.

Because when I create another data class named RespondTop

```<code>data class RespondTop(
val error: List<ErrorMsgTop>?,
val data: List<DataContentTop>?,
val token: String?,
)
</code>```

and change

```<code>@GET("api/topten")
suspend fun getTopTen(@Query("userid") userid: String, @Query("token")token: String): Respond
</code>```

to this

```<code>@GET("api/topten")
suspend fun getTopTen(@Query("userid") userid: String, @Query("token")token: String): RespondTop
</code>```

Both All Data and Top Data are shown

So, my question is, how do I return both all data and top data into one data class without needing to create another data class?

Update

Here is the AllDataViewModel

```<code>fun getData(userid: String, token: String, page: Int){
    val job = viewModelScope.launch {
        _loading.value = true
        try {
            val getData = Network.networkService.getAll(userid, token, page)
            _respond.value = getData
            _loading.value = false
            _error.value = false
            _isCancelled.value = false
        }catch (e: Exception){
            Log.e("AllLinksException", e.message.toString())
            _loading.value = false
            if(e.message.toString() == "StandaloneCoroutine was cancelled"){
                _error.value = false
                _isCancelled.value = true
            } else {
                _error.value = true
                _isCancelled.value = false
            }
        }
    }
    resetValue()

    runningJob = job
}
</code>```

This is I observe the data in AllLink Fragment

```<code>viewModel.respond.observe(viewLifecycleOwner) {
        it?.let {
            binding.shimmer.visibility = View.GONE
            binding.rvLinks.visibility = View.VISIBLE
            Utils.sharedPreferenceString(sharedPreferences, "token", it.token.toString())
            token = it.token.toString()
            if (it.error?.get(0)?.invalidToken != null) {
                Utils.showToast(requireContext(), it.error.get(0).invalidToken.toString())
            } else {
                    for (i in 0..it?.data!!.size - 1) {
                        links.add(
                            CurrentLink(
                                it.data.get(i).ID.toString(),
                                it.data.get(i).title.toString(),
                                it.data.get(i).createdDate.toString()
                            )
                        )
                    }
                    totalLink = it.data.get(0).totalLink!!.toInt()
                    binding.tvTotalLinks.text = totalLink.toString()
                    linkAdapter.notifyDataSetChanged()
                }
                page++
            }
        }
</code>```

TopData ViewModel

```<code>fun getData(userid: String, token: String){
    viewModelScope.launch {
        try {
            val data = Network.networkService.getTopTen(userid, token)
            _respond.value = data
        }catch (e: Exception){
            Log.e("Top Ten Exception", e.message.toString())
        }
    }
}
</code>```

This is TopTenFragment

```<code>binding = FragmentTopBinding.inflate(inflater)
    viewModel = ViewModelProvider(this).get(TopDataViewModel::class.java)
    sharedPreferences = requireActivity().getSharedPreferences(SHARED_PREF_KEY, Context.MODE_PRIVATE)
    val userid = sharedPreferences.getString("userid", null)
    val token = sharedPreferences.getString("token", null)
    viewModel.getData(userid.toString(), token.toString())
    val adapter = TopTenAdapter()
    binding.rvLinks.adapter = adapter

    viewModel.respond.observe(viewLifecycleOwner){
        Log.i("Data Link", "jkfdjksf")
        Log.i("Data Link Top", it.toString())
        binding.shimmer.visibility = View.GONE
        binding.rvLinks.visibility = View.VISIBLE

        if(it?.error!!.get(0).invalidToken != null){
            Utils.showToast(requireContext(), it.error.get(0).invalidToken.toString())
        } else {
            Log.i("Data Link Top", it.toString())
        }
    }
    return binding.root
</code>```

Body:
In my app, there is a viewpager fragment that contains 2 tab. First tab is all data, second tab is top 10 data.

When the fragment is loaded, it calls two API Endpoints

@GET("api/get-all")
suspend fun getAllLinks(@Query("userid") userID: String, @Query("token") token: String, @Query("page") page: Int) : Respond

@GET("api/topten")
suspend fun getTopTen(@Query("userid") userid: String, @Query("token")token: String): Respond

Both of them will return the data to Respond data class

data class Respond(
val error: List<ErrorMsg>?,
val data: List<DataContent>?,
val token: String?,
)

The problem is, when I want to show the data to the recylerview, only the data of All Data that is shown

I'm guessing it's because there is only one instance of Respond data class that only holds data of All Data.

Because when I create another data class named RespondTop

data class RespondTop(
val error: List<ErrorMsgTop>?,
val data: List<DataContentTop>?,
val token: String?,
)

and change

@GET("api/topten")
suspend fun getTopTen(@Query("userid") userid: String, @Query("token")token: String): Respond

to this

@GET("api/topten")
suspend fun getTopTen(@Query("userid") userid: String, @Query("token")token: String): RespondTop

Both All Data and Top Data are shown

So, my question is, how do I return both all data and top data into one data class without needing to create another data class?

Update

Here is the AllDataViewModel

fun getData(userid: String, token: String, page: Int){
    val job = viewModelScope.launch {
        _loading.value = true
        try {
            val getData = Network.networkService.getAll(userid, token, page)
            _respond.value = getData
            _loading.value = false
            _error.value = false
            _isCancelled.value = false
        }catch (e: Exception){
            Log.e("AllLinksException", e.message.toString())
            _loading.value = false
            if(e.message.toString() == "StandaloneCoroutine was cancelled"){
                _error.value = false
                _isCancelled.value = true
            } else {
                _error.value = true
                _isCancelled.value = false
            }
        }
    }
    resetValue()

    runningJob = job
}

This is I observe the data in AllLink Fragment

viewModel.respond.observe(viewLifecycleOwner) {
        it?.let {
            binding.shimmer.visibility = View.GONE
            binding.rvLinks.visibility = View.VISIBLE
            Utils.sharedPreferenceString(sharedPreferences, "token", it.token.toString())
            token = it.token.toString()
            if (it.error?.get(0)?.invalidToken != null) {
                Utils.showToast(requireContext(), it.error.get(0).invalidToken.toString())
            } else {
                    for (i in 0..it?.data!!.size - 1) {
                        links.add(
                            CurrentLink(
                                it.data.get(i).ID.toString(),
                                it.data.get(i).title.toString(),
                                it.data.get(i).createdDate.toString()
                            )
                        )
                    }
                    totalLink = it.data.get(0).totalLink!!.toInt()
                    binding.tvTotalLinks.text = totalLink.toString()
                    linkAdapter.notifyDataSetChanged()
                }
                page++
            }
        }

TopData ViewModel

fun getData(userid: String, token: String){
    viewModelScope.launch {
        try {
            val data = Network.networkService.getTopTen(userid, token)
            _respond.value = data
        }catch (e: Exception){
            Log.e("Top Ten Exception", e.message.toString())
        }
    }
}

This is TopTenFragment

binding = FragmentTopBinding.inflate(inflater)
    viewModel = ViewModelProvider(this).get(TopDataViewModel::class.java)
    sharedPreferences = requireActivity().getSharedPreferences(SHARED_PREF_KEY, Context.MODE_PRIVATE)
    val userid = sharedPreferences.getString("userid", null)
    val token = sharedPreferences.getString("token", null)
    viewModel.getData(userid.toString(), token.toString())
    val adapter = TopTenAdapter()
    binding.rvLinks.adapter = adapter

    viewModel.respond.observe(viewLifecycleOwner){
        Log.i("Data Link", "jkfdjksf")
        Log.i("Data Link Top", it.toString())
        binding.shimmer.visibility = View.GONE
        binding.rvLinks.visibility = View.VISIBLE

        if(it?.error!!.get(0).invalidToken != null){
            Utils.showToast(requireContext(), it.error.get(0).invalidToken.toString())
        } else {
            Log.i("Data Link Top", it.toString())
        }
    }
    return binding.root


问:
Do I need to generate a new key after changing my Flutter app package name?
I created a flutter application and generated a key for it to upload to play-store, but because it was named com.example.testapp play-store didn't allow me to upload it and I tried changing the name. But after the application was uploaded it kept crashing, it wasn't running on any device and I figured that it might be because I changed the package name incorrectly.

After following this link, I successfully changed the app package name.

Now when I am uploading again do I delete the previous app from the playstore? And do I need to generate a new key or just create a new bundle and upload it?


问:
LearnDash Setting fields are not getting selected
I have created a custom multi-select setting field on the lesson edit page in backend.

The code is as below

```<code>public function ld_custom_meta( $args ) {

    $cur_post_id =  $_GET['post'];
    $get_ld_lesson_val = get_post_meta( $cur_post_id, '_sfwd-lessons', true );

    $selected_val = $get_ld_lesson_val['sfwd-lessons__ld_media_products'];

    $_ld_media_products = get_media_products();

    $args['sfwd-lessons']['fields']['_ld_media_products'] = array(
        'name'              => __( 'Related Media Products', 'new-lms' ),
        'type'              => 'multiselect',
        'help_text'         => __( 'The selected products will be provided for free when a user gets access to this lesson via a subscription.', 'new-lms' ),
        'lazy_load'         => 1,
        'class'             => "ld_media_products select2",
        'value'             => $selected_val,
        'initial_options'   => $_ld_media_products,
    );
    return $args;
}
</code>```

However, the value is not getting selected on the admin side.

Body:
I have created a custom multi-select setting field on the lesson edit page in backend.

The code is as below

public function ld_custom_meta( $args ) {

    $cur_post_id =  $_GET['post'];
    $get_ld_lesson_val = get_post_meta( $cur_post_id, '_sfwd-lessons', true );

    $selected_val = $get_ld_lesson_val['sfwd-lessons__ld_media_products'];

    $_ld_media_products = get_media_products();

    $args['sfwd-lessons']['fields']['_ld_media_products'] = array(
        'name'              => __( 'Related Media Products', 'new-lms' ),
        'type'              => 'multiselect',
        'help_text'         => __( 'The selected products will be provided for free when a user gets access to this lesson via a subscription.', 'new-lms' ),
        'lazy_load'         => 1,
        'class'             => "ld_media_products select2",
        'value'             => $selected_val,
        'initial_options'   => $_ld_media_products,
    );
    return $args;
}

However, the value is not getting selected on the admin side.


问:
How to make celery pick up task after prior processing(saving a file before reading it) is done
I have an api that saves a file to a folder which should then be read by a celery task that processes it asyncly. The issue is , the task is starting up before the file is saved. How do I make it so that the task is queued after the file is saved ?

My code.

API:

```<code>@app.post("/upload")
async def upload_image(in_file: UploadFile = File(...)):
    file_name, file_ext = in_file.filename.split(".")
    if file_ext not in ACCEPTED_FILE_EXT:
        return f".{file_ext} not accepted . Please upload a file with extension in {ACCEPTED_FILE_EXT}"

    request_identifier = uuid4()
    orig_path = os.path.join(ORIGINAL_IMG_PATH, str(request_identifier), "")
    processed_path = os.path.join(PROCESSED_IMG_PATH, str(request_identifier), "")
    Path(orig_path).mkdir(parents=True, exist_ok=True)
    Path(processed_path).mkdir(parents=True, exist_ok=True)

    try:
        contents = in_file.file.read()
        with open(orig_path + in_file.filename, 'wb') as f:
            f.write(contents)
    except Exception:
        return {"message": "There was an error uploading the file"}
    finally:
        logger.info("File saved succesfully!")
        in_file.file.close()
        os.chmod(orig_path + in_file.filename, 0o777)

    process_image.delay(in_file.filename, orig_path, processed_path)

    return {"request_identifier": str(request_identifier),
            "original_file_path": orig_path + in_file.filename,
            "processed_file_path": processed_path}
</code>```

Celery task:

```<code>@celery_app.task(name='process_image')
def process_image(file_name: str, orig_path: str, processed_path: str):
    logger.info("Processing image...")
    orig_file = orig_path + file_name
    file_name, file_ext = file_name.split(".")

    if file_ext in ["jpg", "jpeg"]:
        # convert jpeg , jpg to png
        with Image(filename=orig_file) as img:
            rgb_img = img.convert('RGB')
            Image(rgb_img).save(filename=processed_path + file_name + ".png")

    elif file_ext == "pdf":
        with(Image(filename=orig_file)) as source:
            for i, image in enumerate(source.sequence):
                new_file_name = file_name + str(i + 1) + '.png'
                Image(image).save(filename=processed_path + new_file_name)

    return "Done processing !"
</code>```

Logs :

```<code>[2022-12-30 07:33:19,675: INFO/MainProcess] Task process_image[f1fb3812-0e86-460e-9f4b-466ba627dce7] received
[2022-12-30 07:33:19,678: INFO/ForkPoolWorker-7] Processing image...
[2022-12-30 07:33:19,711: ERROR/ForkPoolWorker-7] Task process_image[f1fb3812-0e86-460e-9f4b-466ba627dce7] raised unexpected: BlobError("unable to open image `/scratch/orig/e5755ada-9676-4633-b3f7-2783a1f0e7c0/12.jpg': No such file or directory @ error/blob.c/OpenBlob/2924")
</code>```

"Processing image..." is getting logged before "File saved succesfully!".

Please help.

Body:
I have an api that saves a file to a folder which should then be read by a celery task that processes it asyncly. The issue is , the task is starting up before the file is saved. How do I make it so that the task is queued after the file is saved ?

My code.

API:

@app.post("/upload")
async def upload_image(in_file: UploadFile = File(...)):
    file_name, file_ext = in_file.filename.split(".")
    if file_ext not in ACCEPTED_FILE_EXT:
        return f".{file_ext} not accepted . Please upload a file with extension in {ACCEPTED_FILE_EXT}"

    request_identifier = uuid4()
    orig_path = os.path.join(ORIGINAL_IMG_PATH, str(request_identifier), "")
    processed_path = os.path.join(PROCESSED_IMG_PATH, str(request_identifier), "")
    Path(orig_path).mkdir(parents=True, exist_ok=True)
    Path(processed_path).mkdir(parents=True, exist_ok=True)

    try:
        contents = in_file.file.read()
        with open(orig_path + in_file.filename, 'wb') as f:
            f.write(contents)
    except Exception:
        return {"message": "There was an error uploading the file"}
    finally:
        logger.info("File saved succesfully!")
        in_file.file.close()
        os.chmod(orig_path + in_file.filename, 0o777)

    process_image.delay(in_file.filename, orig_path, processed_path)

    return {"request_identifier": str(request_identifier),
            "original_file_path": orig_path + in_file.filename,
            "processed_file_path": processed_path}

Celery task:

@celery_app.task(name='process_image')
def process_image(file_name: str, orig_path: str, processed_path: str):
    logger.info("Processing image...")
    orig_file = orig_path + file_name
    file_name, file_ext = file_name.split(".")

    if file_ext in ["jpg", "jpeg"]:
        # convert jpeg , jpg to png
        with Image(filename=orig_file) as img:
            rgb_img = img.convert('RGB')
            Image(rgb_img).save(filename=processed_path + file_name + ".png")

    elif file_ext == "pdf":
        with(Image(filename=orig_file)) as source:
            for i, image in enumerate(source.sequence):
                new_file_name = file_name + str(i + 1) + '.png'
                Image(image).save(filename=processed_path + new_file_name)

    return "Done processing !"

Logs :

[2022-12-30 07:33:19,675: INFO/MainProcess] Task process_image[f1fb3812-0e86-460e-9f4b-466ba627dce7] received
[2022-12-30 07:33:19,678: INFO/ForkPoolWorker-7] Processing image...
[2022-12-30 07:33:19,711: ERROR/ForkPoolWorker-7] Task process_image[f1fb3812-0e86-460e-9f4b-466ba627dce7] raised unexpected: BlobError("unable to open image `/scratch/orig/e5755ada-9676-4633-b3f7-2783a1f0e7c0/12.jpg': No such file or directory @ error/blob.c/OpenBlob/2924")

"Processing image..." is getting logged before "File saved succesfully!".

Please help.


问:
python3 minimalmodbus query PZEM-014 -> PZEM-016 AC and DC multimeters
[SOLVED] Could someone help on this? I use minimalmodbus on python 3.11.1 to query a USB<->RS485 transceiver (see picture below) that is connected to a PZEM-016 (for measuring AC power consumption: voltage, current, power, energy, frequency...).
<img src="https://i.stack.imgur.com/q2gsg.png" alt="USB<->RS485 transceiver" />

When used with the Simply Modbus Master 8.1.2, I can read the data without any problem.

With Python and minimalmodbus, I can only get up to 7 registers and of course the data is wrong (I can't pass the 7th register).

Here is the code

```<code>import minimalmodbus

#######################################
# CONSTANTS declaration
#######################################
# Communication constants
PORT_NAME       ='COM3'
BAUD_RATE       = 9600
BYTE_SIZE       = 8
STOP_BITS       = 1
TIMEOUT_VAL     = 0.7

SLAVE_ADDR      = 1
READ_MODE_NB    = 4 # minimalmodus default to 3 PZEM requires 4 or it issues an error
WRITE_FCT_NB    = 16 #HEX: 0x10
DEBUG_VAL       = True
ECHO_VAL        = False # Changed back from True to False after solution found

# Register constants
BASE_REG        = 0
VOLT_REG        = 0 #0x0000
CURR_LOW_REG    = 1 #0x0001
CURR_HIGH_REG   = 2 #0x0002
POWER_LOW_REG   = 3 #0x0003
POWER_HIGH_REG  = 4 #0x0004
ENGY_LOW_REG    = 5 #0x0005
ENGY_HIGH_REG   = 6 #0x0006
FREQCY_REG      = 7 #0x0007
POWER_FACTOR_REG = 8 #0x0008
ALARM_REG       = 9 #0x0009

#######################################
# Variables initialization
#######################################
instrument      = ''
response        = ''
voltage         = ''
current_high    = ''
current_low     = ''
power_high      = ''
power_low       = ''
energy_high     = ''
energy_low      = ''
frequency       = ''
power_factor    = ''
alarm_status    = ''

#######################################
# Set up the instrument
#######################################
instrument = minimalmodbus.Instrument(PORT_NAME, SLAVE_ADDR)

#######################################
# Explicit instrument settings
#######################################
instrument.serial.baudrate = BAUD_RATE # baud rate
instrument.serial.bytesize = BYTE_SIZE # data bits
instrument.serial.parity   = minimalmodbus.serial.PARITY_NONE # parity
instrument.serial.stopbits = STOP_BITS # stop bit
instrument.serial.timeout  = TIMEOUT_VAL # seconds
instrument.mode            = minimalmodbus.MODE_RTU # communication protocol
# instrument.address         = SLAVE_ADDR # slave address when only one slave in the bus
instrument.debug           = DEBUG_VAL
instrument.handle_local_echo = ECHO_VAL
instrument.close_port_after_each_call = True
instrument.clear_buffers_before_each_transaction = True

#######################################
# Typical request format of the master
# Slave address: x001
# Command type: 0x04
# First register address high = left bytes: 0x00
# First register address low = right bytes: 0x00 (=> 0x0000 = 0)
# Number of registers high = left bytes: 0x00
# Number of registers low = right bytes: 0x0A (=> 0x000A = 10)
# CRC check high = left bytes: 0x70
# CRC check low = right bytes: 0x0D (=> 0x700D)
# 01 04 00 00 00 0A 70 0D

# Typical reply format of the slave
# Slave address: 0x01
# Command type: 0x04
# Number of bytes: 0x14 (= 20 bytes = 2 bytes per requested register)
# Register 1: Voltage 8 bits
# Register 1 data high byte = left byte: 0x09
# Register 1 data low byte = right byte: 0x2E (=> 0x092E = 2350 = 235.0V)
# Register 2 + 3: Current 16 bits
# Register 2 data low byte = right bits: 0x01
# Register 2 data high byte = left bits: 0x78
# Register 3 data low byte = right bits: 0x00
# Register 3 data high byte = left bits: 0x00 (=> 0x00000178 = 376 = 0.376A)
# Register 4 + 5: Power 16 bits
# Register 4 data low byte = right bits: 0x01
# Register 4 data high byte = left bits: 0xE7
# Register 5 data low byte = right bits: 0x00
# Register 5 data high byte = left bits: 0x00 (=> 0x000001E7 = 487 = 48.7W)
# Register 6 + 7: Energy 16 bits
# Register 6 data low byte = right bits: 0x02
# Register 6 data high byte = left bits: 0xEA
# Register 7 data low byte = right bits: 0x00
# Register 7 data high byte = left bits: 0x00 (=> 0x000002EA = 746 = 746Wh)
# Register 8: Frequency 8 bits
# Register 8 data high byte = left byte: 0x01
# Register 8 data low byte = right byte: 0xF4 (=> 0x01F4 = 500 = 50.0Hz)
# Register 9: Power factor 8 bits
# Register 9 data high byte = left byte: 0x00
# Register 9 data low byte = right byte: 0x37 (=> 0x0037 = 55 = 0.55)
# Register 10: Alarm status 8 bits
# Register 10 data high byte = left byte: 0x00
# Register 10 data low byte = right byte: 0x00 (=> 0x0000 = 0 = No alarm)
# CRC check high = left bytes: 0xE5 (= 229)
# CRC check low = right bytes: 0xFD (= 253) (=> 0xE5FD)
# LED lights turned on
# 01 04 14 09 2E 01 78 00 00 01 E7 00 00 02 EA 00 00 01 F4 00 37 00 00 39 51
# LED lights turned off
# 01 04 14 09 34 00 00 00 00 00 05 00 00 02 E4 00 00 01 F3 00 64 00 00 E5 FD
#######################################

print('instrument: ', instrument)

#######################################
# Read and print registers' data
#######################################
response = instrument.read_registers(VOLT_REG, 10, READ_MODE_NB)
print('Response raw: ', response)

</code>```

With the wrong read mode value, I get an error message with the read_registers() command

```<code>>>> ReadSerial.py
< MinimalModbus debug mode. Will write to instrument (expecting 25 bytes back): 01 03 00 00 00 0A C5 CD (8 bytes)
MinimalModbus debug mode. Clearing serial buffers for port COM3
MinimalModbus debug mode. No sleep required before write. Time since previous read: 167521078.00 ms, minimum silent period: 4.01 ms.
MinimalModbus debug mode. Closing port COM3
MinimalModbus debug mode. Response from instrument: 01 83 02 C0 F1 (5 bytes), roundtrip time: 0.8 ms. Timeout for reading: 700.0 ms.

< Traceback (most recent call last):
  File "...\ReadSerial.py", line 127, in <module>
    response = instrument.read_registers(VOLT_REG, 10, READ_MODE_NB)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "...\minimalmodbus.py", line 904, in read_registers
    returnvalue = self._generic_command(
                  ^^^^^^^^^^^^^^^^^^^^^^
  File "...\minimalmodbus.py", line 1245, in _generic_command
    payload_from_slave = self._perform_command(functioncode, payload_to_slave)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "...\minimalmodbus.py", line 1329, in _perform_command
    payload_from_slave = _extract_payload(
                         ^^^^^^^^^^^^^^^^^
  File "...\minimalmodbus.py", line 1880, in _extract_payload
    _check_response_slaveerrorcode(response)
  File "...\minimalmodbus.py", line 3538, in _check_response_slaveerrorcode
    raise error
minimalmodbus.IllegalRequestError: Slave reported illegal data address
</code>```

I matched everything I could with the Simply Modbus Master example, except for the query mode, which value should be 4 (minimalmodbus default read mode is 3).

Update from above

I finally found the error in my code, which was very stupid, but errors are often stupid like a missing ";".

I still have to figure out why the read_register() command doesn't work (without the "s" for reading one register at a time). I can't pass the 7th register without errors and the returned data is wrong.

I leave the question and the answer for the community, in case someone uses the same PZEM-014 -> PZEM0-17 and looks for a python solution to retrieve the data

Body:
[SOLVED] Could someone help on this? I use minimalmodbus on python 3.11.1 to query a USB<->RS485 transceiver (see picture below) that is connected to a PZEM-016 (for measuring AC power consumption: voltage, current, power, energy, frequency...).
<img src="https://i.stack.imgur.com/q2gsg.png" alt="USB<->RS485 transceiver" />

When used with the Simply Modbus Master 8.1.2, I can read the data without any problem.

With Python and minimalmodbus, I can only get up to 7 registers and of course the data is wrong (I can't pass the 7th register).

Here is the code

import minimalmodbus

#######################################
# CONSTANTS declaration
#######################################
# Communication constants
PORT_NAME       ='COM3'
BAUD_RATE       = 9600
BYTE_SIZE       = 8
STOP_BITS       = 1
TIMEOUT_VAL     = 0.7

SLAVE_ADDR      = 1
READ_MODE_NB    = 4 # minimalmodus default to 3 PZEM requires 4 or it issues an error
WRITE_FCT_NB    = 16 #HEX: 0x10
DEBUG_VAL       = True
ECHO_VAL        = False # Changed back from True to False after solution found

# Register constants
BASE_REG        = 0
VOLT_REG        = 0 #0x0000
CURR_LOW_REG    = 1 #0x0001
CURR_HIGH_REG   = 2 #0x0002
POWER_LOW_REG   = 3 #0x0003
POWER_HIGH_REG  = 4 #0x0004
ENGY_LOW_REG    = 5 #0x0005
ENGY_HIGH_REG   = 6 #0x0006
FREQCY_REG      = 7 #0x0007
POWER_FACTOR_REG = 8 #0x0008
ALARM_REG       = 9 #0x0009

#######################################
# Variables initialization
#######################################
instrument      = ''
response        = ''
voltage         = ''
current_high    = ''
current_low     = ''
power_high      = ''
power_low       = ''
energy_high     = ''
energy_low      = ''
frequency       = ''
power_factor    = ''
alarm_status    = ''

#######################################
# Set up the instrument
#######################################
instrument = minimalmodbus.Instrument(PORT_NAME, SLAVE_ADDR)

#######################################
# Explicit instrument settings
#######################################
instrument.serial.baudrate = BAUD_RATE # baud rate
instrument.serial.bytesize = BYTE_SIZE # data bits
instrument.serial.parity   = minimalmodbus.serial.PARITY_NONE # parity
instrument.serial.stopbits = STOP_BITS # stop bit
instrument.serial.timeout  = TIMEOUT_VAL # seconds
instrument.mode            = minimalmodbus.MODE_RTU # communication protocol
# instrument.address         = SLAVE_ADDR # slave address when only one slave in the bus
instrument.debug           = DEBUG_VAL
instrument.handle_local_echo = ECHO_VAL
instrument.close_port_after_each_call = True
instrument.clear_buffers_before_each_transaction = True

#######################################
# Typical request format of the master
# Slave address: x001
# Command type: 0x04
# First register address high = left bytes: 0x00
# First register address low = right bytes: 0x00 (=> 0x0000 = 0)
# Number of registers high = left bytes: 0x00
# Number of registers low = right bytes: 0x0A (=> 0x000A = 10)
# CRC check high = left bytes: 0x70
# CRC check low = right bytes: 0x0D (=> 0x700D)
# 01 04 00 00 00 0A 70 0D

# Typical reply format of the slave
# Slave address: 0x01
# Command type: 0x04
# Number of bytes: 0x14 (= 20 bytes = 2 bytes per requested register)
# Register 1: Voltage 8 bits
# Register 1 data high byte = left byte: 0x09
# Register 1 data low byte = right byte: 0x2E (=> 0x092E = 2350 = 235.0V)
# Register 2 + 3: Current 16 bits
# Register 2 data low byte = right bits: 0x01
# Register 2 data high byte = left bits: 0x78
# Register 3 data low byte = right bits: 0x00
# Register 3 data high byte = left bits: 0x00 (=> 0x00000178 = 376 = 0.376A)
# Register 4 + 5: Power 16 bits
# Register 4 data low byte = right bits: 0x01
# Register 4 data high byte = left bits: 0xE7
# Register 5 data low byte = right bits: 0x00
# Register 5 data high byte = left bits: 0x00 (=> 0x000001E7 = 487 = 48.7W)
# Register 6 + 7: Energy 16 bits
# Register 6 data low byte = right bits: 0x02
# Register 6 data high byte = left bits: 0xEA
# Register 7 data low byte = right bits: 0x00
# Register 7 data high byte = left bits: 0x00 (=> 0x000002EA = 746 = 746Wh)
# Register 8: Frequency 8 bits
# Register 8 data high byte = left byte: 0x01
# Register 8 data low byte = right byte: 0xF4 (=> 0x01F4 = 500 = 50.0Hz)
# Register 9: Power factor 8 bits
# Register 9 data high byte = left byte: 0x00
# Register 9 data low byte = right byte: 0x37 (=> 0x0037 = 55 = 0.55)
# Register 10: Alarm status 8 bits
# Register 10 data high byte = left byte: 0x00
# Register 10 data low byte = right byte: 0x00 (=> 0x0000 = 0 = No alarm)
# CRC check high = left bytes: 0xE5 (= 229)
# CRC check low = right bytes: 0xFD (= 253) (=> 0xE5FD)
# LED lights turned on
# 01 04 14 09 2E 01 78 00 00 01 E7 00 00 02 EA 00 00 01 F4 00 37 00 00 39 51
# LED lights turned off
# 01 04 14 09 34 00 00 00 00 00 05 00 00 02 E4 00 00 01 F3 00 64 00 00 E5 FD
#######################################

print('instrument: ', instrument)

#######################################
# Read and print registers' data
#######################################
response = instrument.read_registers(VOLT_REG, 10, READ_MODE_NB)
print('Response raw: ', response)

With the wrong read mode value, I get an error message with the read_registers() command

>>> ReadSerial.py
< MinimalModbus debug mode. Will write to instrument (expecting 25 bytes back): 01 03 00 00 00 0A C5 CD (8 bytes)
MinimalModbus debug mode. Clearing serial buffers for port COM3
MinimalModbus debug mode. No sleep required before write. Time since previous read: 167521078.00 ms, minimum silent period: 4.01 ms.
MinimalModbus debug mode. Closing port COM3
MinimalModbus debug mode. Response from instrument: 01 83 02 C0 F1 (5 bytes), roundtrip time: 0.8 ms. Timeout for reading: 700.0 ms.

< Traceback (most recent call last):
  File "...\ReadSerial.py", line 127, in <module>
    response = instrument.read_registers(VOLT_REG, 10, READ_MODE_NB)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "...\minimalmodbus.py", line 904, in read_registers
    returnvalue = self._generic_command(
                  ^^^^^^^^^^^^^^^^^^^^^^
  File "...\minimalmodbus.py", line 1245, in _generic_command
    payload_from_slave = self._perform_command(functioncode, payload_to_slave)
                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "...\minimalmodbus.py", line 1329, in _perform_command
    payload_from_slave = _extract_payload(
                         ^^^^^^^^^^^^^^^^^
  File "...\minimalmodbus.py", line 1880, in _extract_payload
    _check_response_slaveerrorcode(response)
  File "...\minimalmodbus.py", line 3538, in _check_response_slaveerrorcode
    raise error
minimalmodbus.IllegalRequestError: Slave reported illegal data address

I matched everything I could with the Simply Modbus Master example, except for the query mode, which value should be 4 (minimalmodbus default read mode is 3).

Update from above

I finally found the error in my code, which was very stupid, but errors are often stupid like a missing ";".

I still have to figure out why the read_register() command doesn't work (without the "s" for reading one register at a time). I can't pass the 7th register without errors and the returned data is wrong.

I leave the question and the answer for the community, in case someone uses the same PZEM-014 -> PZEM0-17 and looks for a python solution to retrieve the data


问:
How to restrict user to access ".htaccess, web.config and mix-manifest.json" file from public folder through url?
How to restrict user to access ".htaccess, web.config and mix-manifest.json" file from public folder through url ?
Or Is it okay to keep it open for users?
One of the method i tried to block from url is

```<code>Route::get('/mix-manifest.json',function(){
    abort(404);
});
</code>```

Also tried placing

```<code><Files web.config>
        order allow,deny
        deny from all
    </Files>
</code>```

in .htaccess Nothing worked.

But i might actually need this .
I am trying to restrict user to access sensitive files like .htaccess, web.config present inside the public folder through url.

Body:
How to restrict user to access ".htaccess, web.config and mix-manifest.json" file from public folder through url ?
Or Is it okay to keep it open for users?
One of the method i tried to block from url is

Route::get('/mix-manifest.json',function(){
    abort(404);
});

Also tried placing

<Files web.config>
        order allow,deny
        deny from all
    </Files>

in .htaccess Nothing worked.

But i might actually need this .
I am trying to restrict user to access sensitive files like .htaccess, web.config present inside the public folder through url.


问:
Autodesk Forge Viewer: arc measure value only in milimeters
why arc measure value is in only milimeters? I change unit type to meters, but arc measure value is still in milimeters.

milimeters

meters

I would expect a arc value in meters


问:
fastapi & psycopg2 : password authentication failed for user "root"
I am getting this issue on

```<code>`docker-compose up`
</code>```

This is my configuration files:-

Dockerfile:

```<code>FROM python:3.9
WORKDIR /usr/src/app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD [ "uvicorn", "app.main:app","--host","0.0.0.0","--port","8000 " ]

</code>```

docker-compose.yaml:

```<code>version: '3'
services:
    api:
        build: .
        depends_on:
            - postgres
        ports:
            - 8000:8000
        volumes:
            - ./:/usr/src/app:ro
        command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
        # env_file:
        #     - ./.env
        environment:
            - DATABASE_HOST_NAME=postgres
            - DATABASE_PORT=${DATABASE_PORT}
            - DATABASE_NAME=${DATABASE_NAME}
            - DATABASE_USERNAME=${DATABASE_USERNAME}
            - DATABASE_PASSWORD=${DATABASE_PASSWORD}
            - SECRET_KEY=${SECRET_KEY}
            - ALGORITHM=${ALGORITHM}
            - ACCESS_TOKEN_EXPIRE_MINUTES=${ACCESS_TOKEN_EXPIRE_MINUTES}
    postgres:
        image: postgres
        environment:
            - POSTGRES_USER=${DATABASE_USERNAME}
            - POSTGRES_PASSWORD=${DATABASE_PASSWORD}
            - POSTGRES_DB=${DATABASE_NAME}
        volumes:
            - postgres-db:/var/lib/postgresql/data

volumes:
    postgres-db:
</code>```

When i ran docker-compose build and docker-compose up -d these two commands ran succesfully but when i hit the login endpoint, it's giving the error

fastapi-api-1       | sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "postgres" (192.168.112.2), port 5432 failed: FATAL:  password authentication failed for user "root"

My DATABASE_USERNAME is root

Body:
I am getting this issue on

`docker-compose up`

This is my configuration files:-

Dockerfile:

FROM python:3.9
WORKDIR /usr/src/app
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD [ "uvicorn", "app.main:app","--host","0.0.0.0","--port","8000 " ]

docker-compose.yaml:

version: '3'
services:
    api:
        build: .
        depends_on:
            - postgres
        ports:
            - 8000:8000
        volumes:
            - ./:/usr/src/app:ro
        command: uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
        # env_file:
        #     - ./.env
        environment:
            - DATABASE_HOST_NAME=postgres
            - DATABASE_PORT=${DATABASE_PORT}
            - DATABASE_NAME=${DATABASE_NAME}
            - DATABASE_USERNAME=${DATABASE_USERNAME}
            - DATABASE_PASSWORD=${DATABASE_PASSWORD}
            - SECRET_KEY=${SECRET_KEY}
            - ALGORITHM=${ALGORITHM}
            - ACCESS_TOKEN_EXPIRE_MINUTES=${ACCESS_TOKEN_EXPIRE_MINUTES}
    postgres:
        image: postgres
        environment:
            - POSTGRES_USER=${DATABASE_USERNAME}
            - POSTGRES_PASSWORD=${DATABASE_PASSWORD}
            - POSTGRES_DB=${DATABASE_NAME}
        volumes:
            - postgres-db:/var/lib/postgresql/data

volumes:
    postgres-db:

When i ran docker-compose build and docker-compose up -d these two commands ran succesfully but when i hit the login endpoint, it's giving the error

fastapi-api-1       | sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) connection to server at "postgres" (192.168.112.2), port 5432 failed: FATAL:  password authentication failed for user "root"

My DATABASE_USERNAME is root


问:
Lost connection to Localhost
I work on a React project on Visual Studio Code, and I lost my connection with Localhost. When I run "npm start" in the terminal window, I receive an error message (see attached). Please advice me what to do. Thanks a lot!
Terminal error massage</p>

Title: Lost connection to Localhost


问:
Flutter Search Google Map Maker
this is my code mapmarker
I have problem it can find places It goes to the search location, but the marker doesn't move to the search location. It's still at the same place where it was received. please help me

I'm not sure which part I missed. can you tell me There might be something wrong, can you help me?

this is my marker

```<code>Set<Marker> mosMarker(LatLng tappedPoint) {
return <Marker>{
  Marker(
      position: tappedPoint,
      markerId: MarkerId(tappedPoint.toString()),
      onDragEnd: (dragEndPosition) {
        print(dragEndPosition);
      },
      draggable: true,
      infoWindow: InfoWindow(
          title: '${searchitems[0].address![widget.index].addr1}',
          snippet:
              'lat : ${searchitems[0].address![widget.index].latitude} lng : ${searchitems[0].address![widget.index].longitude}'))
};
}
</code>```

This is a Google Map

```<code>Widget build(BuildContext context) {
return Scaffold(
    key: homeScaffoldKey,
    appBar: AppBar(
        title: Text('MosMap'),
        backgroundColor: Color.fromARGB(255, 24, 78, 158)),
    body: Stack(
      children: <Widget>[
        GoogleMap(
          initialCameraPosition: CameraPosition(
            target: centerMap,
            zoom: 16.0,
          ),
          mapType: MapType.normal,
          onMapCreated: (controller) {
            setState(() {
              mapController = controller;
            });
          },
          markers: Set.from(mosMarker(centerMap)),
        ),
        Padding(
          padding: EdgeInsets.all(10),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              searchMap(),
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: ElevatedButton(
                  onPressed: () {
                    saveAddress();
                  },
                  style: ElevatedButton.styleFrom(
                      elevation: 12.0,
                      padding: const EdgeInsets.symmetric(
                          horizontal: 10, vertical: 10),
                      backgroundColor: backgroundColor,
                      textStyle: const TextStyle(color: Colors.white)),
                  child: const Text(
                    'Save Address',
                    style: MosTextStyle.text20Style,
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    ));
 }
</code>```

This is a Search Map

```<code> Widget searchMap() {
return InkWell(
    onTap: () async {
      var place = await PlacesAutocomplete.show(
          context: context,
          apiKey: kGoogleApiKey,
          mode: Mode.overlay,
          types: [],
          strictbounds: false,
          components: [Component(Component.country, 'th')],
          //google_map_webservice package
          onError: (err) {
            print(err);
          });

      if (place != null) {
        setState(() {
          location = place.description.toString();
        });

        //form google_maps_webservice package
        final plist = GoogleMapsPlaces(
          apiKey: kGoogleApiKey,
          apiHeaders: await GoogleApiHeaders().getHeaders(),
          //from google_api_headers package
        );
        String placeid = place.placeId ?? "0";
        final detail = await plist.getDetailsByPlaceId(placeid);
        final geometry = detail.result.geometry!;
        final lat = geometry.location.lat;
        final lang = geometry.location.lng;
        var newlatlang = LatLng(lat, lang);

        //move map camera to selected place with animation
        mapController.animateCamera(
          CameraUpdate.newCameraPosition(
            CameraPosition(
              target: newlatlang,
              zoom: 17,
            ),
          ),
        );
      }
    },
    child: Padding(
      padding: EdgeInsets.all(15),
      child: Card(
        child: Container(
            padding: EdgeInsets.all(0),
            width: MediaQuery.of(context).size.width - 40,
            child: ListTile(
              title: Text(
                location,
                style: TextStyle(fontSize: 18),
              ),
              trailing: Icon(Icons.search),
              dense: true,
            )),
      ),
    ));

Widget searchMap() {
return InkWell(
    onTap: () async {
      var place = await PlacesAutocomplete.show(
          context: context,
          apiKey: kGoogleApiKey,
          mode: Mode.overlay,
          types: [],
          strictbounds: false,
          components: [Component(Component.country, 'th')],
          //google_map_webservice package
          onError: (err) {
            print(err);
          });

      if (place != null) {
        setState(() {
          location = place.description.toString();
        });

        //form google_maps_webservice package
        final plist = GoogleMapsPlaces(
          apiKey: kGoogleApiKey,
          apiHeaders: await GoogleApiHeaders().getHeaders(),
          //from google_api_headers package
        );
        String placeid = place.placeId ?? "0";
        final detail = await plist.getDetailsByPlaceId(placeid);
        final geometry = detail.result.geometry!;
        final lat = geometry.location.lat;
        final lang = geometry.location.lng;
        var newlatlang = LatLng(lat, lang);

        //move map camera to selected place with animation
        mapController.animateCamera(
          CameraUpdate.newCameraPosition(
            CameraPosition(
              target: newlatlang,
              zoom: 17,
            ),
          ),
        );
      }
    },
    child: Padding(
      padding: EdgeInsets.all(15),
      child: Card(
        child: Container(
            padding: EdgeInsets.all(0),
            width: MediaQuery.of(context).size.width - 40,
            child: ListTile(
              title: Text(
                location,
                style: TextStyle(fontSize: 18),
              ),
              trailing: Icon(Icons.search),
              dense: true,
            )),
      ),
    ));
 }
</code>```

Title: Flutter Search Google Map Maker

Body:
this is my code mapmarker
I have problem it can find places It goes to the search location, but the marker doesn't move to the search location. It's still at the same place where it was received. please help me

I'm not sure which part I missed. can you tell me There might be something wrong, can you help me?

this is my marker

Set<Marker> mosMarker(LatLng tappedPoint) {
return <Marker>{
  Marker(
      position: tappedPoint,
      markerId: MarkerId(tappedPoint.toString()),
      onDragEnd: (dragEndPosition) {
        print(dragEndPosition);
      },
      draggable: true,
      infoWindow: InfoWindow(
          title: '${searchitems[0].address![widget.index].addr1}',
          snippet:
              'lat : ${searchitems[0].address![widget.index].latitude} lng : ${searchitems[0].address![widget.index].longitude}'))
};
}

This is a Google Map

Widget build(BuildContext context) {
return Scaffold(
    key: homeScaffoldKey,
    appBar: AppBar(
        title: Text('MosMap'),
        backgroundColor: Color.fromARGB(255, 24, 78, 158)),
    body: Stack(
      children: <Widget>[
        GoogleMap(
          initialCameraPosition: CameraPosition(
            target: centerMap,
            zoom: 16.0,
          ),
          mapType: MapType.normal,
          onMapCreated: (controller) {
            setState(() {
              mapController = controller;
            });
          },
          markers: Set.from(mosMarker(centerMap)),
        ),
        Padding(
          padding: EdgeInsets.all(10),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              searchMap(),
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: ElevatedButton(
                  onPressed: () {
                    saveAddress();
                  },
                  style: ElevatedButton.styleFrom(
                      elevation: 12.0,
                      padding: const EdgeInsets.symmetric(
                          horizontal: 10, vertical: 10),
                      backgroundColor: backgroundColor,
                      textStyle: const TextStyle(color: Colors.white)),
                  child: const Text(
                    'Save Address',
                    style: MosTextStyle.text20Style,
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    ));
 }

This is a Search Map

 Widget searchMap() {
return InkWell(
    onTap: () async {
      var place = await PlacesAutocomplete.show(
          context: context,
          apiKey: kGoogleApiKey,
          mode: Mode.overlay,
          types: [],
          strictbounds: false,
          components: [Component(Component.country, 'th')],
          //google_map_webservice package
          onError: (err) {
            print(err);
          });

      if (place != null) {
        setState(() {
          location = place.description.toString();
        });

        //form google_maps_webservice package
        final plist = GoogleMapsPlaces(
          apiKey: kGoogleApiKey,
          apiHeaders: await GoogleApiHeaders().getHeaders(),
          //from google_api_headers package
        );
        String placeid = place.placeId ?? "0";
        final detail = await plist.getDetailsByPlaceId(placeid);
        final geometry = detail.result.geometry!;
        final lat = geometry.location.lat;
        final lang = geometry.location.lng;
        var newlatlang = LatLng(lat, lang);

        //move map camera to selected place with animation
        mapController.animateCamera(
          CameraUpdate.newCameraPosition(
            CameraPosition(
              target: newlatlang,
              zoom: 17,
            ),
          ),
        );
      }
    },
    child: Padding(
      padding: EdgeInsets.all(15),
      child: Card(
        child: Container(
            padding: EdgeInsets.all(0),
            width: MediaQuery.of(context).size.width - 40,
            child: ListTile(
              title: Text(
                location,
                style: TextStyle(fontSize: 18),
              ),
              trailing: Icon(Icons.search),
              dense: true,
            )),
      ),
    ));

Widget searchMap() {
return InkWell(
    onTap: () async {
      var place = await PlacesAutocomplete.show(
          context: context,
          apiKey: kGoogleApiKey,
          mode: Mode.overlay,
          types: [],
          strictbounds: false,
          components: [Component(Component.country, 'th')],
          //google_map_webservice package
          onError: (err) {
            print(err);
          });

      if (place != null) {
        setState(() {
          location = place.description.toString();
        });

        //form google_maps_webservice package
        final plist = GoogleMapsPlaces(
          apiKey: kGoogleApiKey,
          apiHeaders: await GoogleApiHeaders().getHeaders(),
          //from google_api_headers package
        );
        String placeid = place.placeId ?? "0";
        final detail = await plist.getDetailsByPlaceId(placeid);
        final geometry = detail.result.geometry!;
        final lat = geometry.location.lat;
        final lang = geometry.location.lng;
        var newlatlang = LatLng(lat, lang);

        //move map camera to selected place with animation
        mapController.animateCamera(
          CameraUpdate.newCameraPosition(
            CameraPosition(
              target: newlatlang,
              zoom: 17,
            ),
          ),
        );
      }
    },
    child: Padding(
      padding: EdgeInsets.all(15),
      child: Card(
        child: Container(
            padding: EdgeInsets.all(0),
            width: MediaQuery.of(context).size.width - 40,
            child: ListTile(
              title: Text(
                location,
                style: TextStyle(fontSize: 18),
              ),
              trailing: Icon(Icons.search),
              dense: true,
            )),
      ),
    ));
 }


问:
Set multiple environment variables in docker file
I am writing a docker file in which at one specific step I am generating dynamic secret file which contains a lit of approx 20 env. variables, in below stand format:

```<code>export ABC=‘XXXXXXX’
export DEF=‘XXXXXXX’
export GHI=‘XXXXXXX’
export JKL=‘XXXXXXX’
</code>```

…

I want to set all this variables values in env. variables.

I ran below command but unable to set this values in ENV

```<code>RUN . ./secrets/env
</code>```

But it's unable to set all export variables as env. variables
The current option I am using now is as below:

```<code>ENV ABC ${xxxx}
</code>```

Is there option available to set all secret file values as Env. values.

Body:
I am writing a docker file in which at one specific step I am generating dynamic secret file which contains a lit of approx 20 env. variables, in below stand format:

export ABC=‘XXXXXXX’
export DEF=‘XXXXXXX’
export GHI=‘XXXXXXX’
export JKL=‘XXXXXXX’

…

I want to set all this variables values in env. variables.

I ran below command but unable to set this values in ENV

RUN . ./secrets/env

But it's unable to set all export variables as env. variables
The current option I am using now is as below:

ENV ABC ${xxxx}

Is there option available to set all secret file values as Env. values.


问:
How to Split up ajax JSOn encode on return item
i have a question
I have a json_encode getting me 2 Values:

```<code>if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
    $toolnameResult['name'] = $row["TOOL_NAME"];
    $toolnameResult['model'] = $row["MODELNUMBER"];
}
    echo json_encode($toolnameResult);
}
</code>```

In the AJAX JQuery Request i requested the 2 Values back to use one of them for autocompleting a field the other one should be handover to an hidden input field

```<code>$('#toolname').typeahead({
    source: function (query, result) {
        $.ajax({
            url: "fertigung/autocomplete/tool_name2.php",
            data: 'query=' + query,
            dataType: "json",
            type: "POST",
            success: function (data) {
                result($.map(data, function (item) {
                    return item;
                }));
            }
        });
    }
});
</code>```
```<code>echo '<td valign="top" nowrap="nowrap" colspan="1" style="padding: 10px">
          <INPUT type="text" size="20" maxlength="30" name="tool_name" autocomplete="off" id="toolname" value="'.@$_REQUEST['tool_name'].'">
      </td>';
echo '<input type="hidden" id="toolmodel" name="toolmodel">';
</code>```

Now here is the Issue currently i don't know how to split them up in my

```<code>result($.map(data, function (item) {return item;}));
</code>```

to use them independent from each other as the name as fieldinput and the model as hidden input.

Sorry for this stupid question but I'M new with Ajax/jQuery.

I expect to get the 2 Results handover to toolname and toolmodel the return item

Body:
i have a question
I have a json_encode getting me 2 Values:

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
    $toolnameResult['name'] = $row["TOOL_NAME"];
    $toolnameResult['model'] = $row["MODELNUMBER"];
}
    echo json_encode($toolnameResult);
}

In the AJAX JQuery Request i requested the 2 Values back to use one of them for autocompleting a field the other one should be handover to an hidden input field

$('#toolname').typeahead({
    source: function (query, result) {
        $.ajax({
            url: "fertigung/autocomplete/tool_name2.php",
            data: 'query=' + query,
            dataType: "json",
            type: "POST",
            success: function (data) {
                result($.map(data, function (item) {
                    return item;
                }));
            }
        });
    }
});

echo '
          <INPUT type="text" size="20" maxlength="30" name="tool_name" autocomplete="off" id="toolname" value="'.@$_REQUEST['tool_name'].'">
      	';
echo '<input type="hidden" id="toolmodel" name="toolmodel">';

Now here is the Issue currently i don't know how to split them up in my

result($.map(data, function (item) {return item;}));

to use them independent from each other as the name as fieldinput and the model as hidden input.

Sorry for this stupid question but I'M new with Ajax/jQuery.

I expect to get the 2 Results handover to toolname and toolmodel the return item


问:
How to pass a Java byte[] to the ScriptEngine Nashorn as parameter
This is my code to call a JavaScript function in Java:

// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
System.setProperty("nashorn.args", "--language=es6");
ScriptEngine engine = factory.getEngineByName("Nashorn");
engine.eval("function transformPayload(rawData) { return rawData }");
Invocable invokeEngine = (Invocable) engine;
var rawData = "{\"keyOne\": \"Value one\",\"keyTwo\": \"Value two\"}".getBytes();
return invokeEngine.invokeFunction("transformPayload", rawData);
```

After I execute the script, I have a String but not a byte[], I also can't execute the logic of processing JavaScript byte[] in this code.

How to pass a  Java byte[] to the ScriptEngine Nashorn as parameter?

Body:
This is my code to call a JavaScript function in Java:

// create a script engine manager
ScriptEngineManager factory = new ScriptEngineManager();
// create a JavaScript engine
System.setProperty("nashorn.args", "--language=es6");
ScriptEngine engine = factory.getEngineByName("Nashorn");
engine.eval("function transformPayload(rawData) { return rawData }");
Invocable invokeEngine = (Invocable) engine;
var rawData = "{\"keyOne\": \"Value one\",\"keyTwo\": \"Value two\"}".getBytes();
return invokeEngine.invokeFunction("transformPayload", rawData);

After I execute the script, I have a String but not a byte[], I also can't execute the logic of processing JavaScript byte[] in this code.

How to pass a  Java byte[] to the ScriptEngine Nashorn as parameter?


问:
Excel file with macro somethimes not opening
I have an macro enabled excel file, which, after using it few times, not works anymore or lagging as hell.

It's added to trust center etc. Only 2 things helps to run that file normally 1) restart pc; 2) start excel, then make new workbook, then open that file.Maybe someone have any idea where is the problem?It's added to trust center etc.


问:
vue-bootstrap-datetimepicker - Setting Custom Timezone on a date picker
I want to set a custom timezone in vue-bootstrap-datetimepicker. Is there any way to acheive it. I have tried searching for it but could not find any workable thing.

                <v-date-picker
                v-model="leg.date" :timezone="CustomTimezone"
                :min="hcDate(maxDate)"
                @input="leg.datepicker = false"
                @change="setUTCDate"
                disabled
                ></v-date-picker>
```

The CustomTimezone value can be any php string for timezone. (America/Los_Angeles,Asia/Karachi)

Body:
I want to set a custom timezone in vue-bootstrap-datetimepicker. Is there any way to acheive it. I have tried searching for it but could not find any workable thing.

                <v-date-picker
                v-model="leg.date" :timezone="CustomTimezone"
                :min="hcDate(maxDate)"
                @input="leg.datepicker = false"
                @change="setUTCDate"
                disabled
                ></v-date-picker>

The CustomTimezone value can be any php string for timezone. (America/Los_Angeles,Asia/Karachi)