问:
How to drag to pan a view in Android?
I have a LinearLayoutCompat that doesn't fit into the screen. So, I decided to implement 'drag to pan' feature for the user to scroll to any part of the layout (in all directions). It's suggested that we should do it like the code snippet on Android's official website:

// The current viewport. This rectangle represents the currently visible
// chart domain and range.
private val mCurrentViewport = RectF(AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX, AXIS_Y_MAX)

// The current destination rectangle (in pixel coordinates) into which the
// chart data should be drawn.
private val mContentRect: Rect? = null

private val mGestureListener = object : GestureDetector.SimpleOnGestureListener() {
    ...
    override fun onScroll(
            e1: MotionEvent,
            e2: MotionEvent,
            distanceX: Float,
            distanceY: Float
    ): Boolean {
        // Scrolling uses math based on the viewport (as opposed to math using pixels).

        mContentRect?.apply {
            // Pixel offset is the offset in screen pixels, while viewport offset is the
            // offset within the current viewport.
            val viewportOffsetX = distanceX * mCurrentViewport.width() / width()
            val viewportOffsetY = -distanceY * mCurrentViewport.height() / height()

            // Updates the viewport, refreshes the display.
            setViewportBottomLeft(
                    mCurrentViewport.left + viewportOffsetX,
                    mCurrentViewport.bottom + viewportOffsetY
            )
        }

        return true
    }
}
```

The problem is I don't understand what the mCurrentViewPort variable is and how I should obtain the values for AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX and AXIS_Y_MAX to pass to the RecF object. Also, setViewPortBottomLeft(...) is marked as unresolved reference for me.

Title: How to drag to pan a view in Android?

Body:
I have a LinearLayoutCompat that doesn't fit into the screen. So, I decided to implement 'drag to pan' feature for the user to scroll to any part of the layout (in all directions). It's suggested that we should do it like the code snippet on Android's official website:

// The current viewport. This rectangle represents the currently visible
// chart domain and range.
private val mCurrentViewport = RectF(AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX, AXIS_Y_MAX)

// The current destination rectangle (in pixel coordinates) into which the
// chart data should be drawn.
private val mContentRect: Rect? = null

private val mGestureListener = object : GestureDetector.SimpleOnGestureListener() {
    ...
    override fun onScroll(
            e1: MotionEvent,
            e2: MotionEvent,
            distanceX: Float,
            distanceY: Float
    ): Boolean {
        // Scrolling uses math based on the viewport (as opposed to math using pixels).

        mContentRect?.apply {
            // Pixel offset is the offset in screen pixels, while viewport offset is the
            // offset within the current viewport.
            val viewportOffsetX = distanceX * mCurrentViewport.width() / width()
            val viewportOffsetY = -distanceY * mCurrentViewport.height() / height()

            // Updates the viewport, refreshes the display.
            setViewportBottomLeft(
                    mCurrentViewport.left + viewportOffsetX,
                    mCurrentViewport.bottom + viewportOffsetY
            )
        }

        return true
    }
}

The problem is I don't understand what the mCurrentViewPort variable is and how I should obtain the values for AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX and AXIS_Y_MAX to pass to the RecF object. Also, setViewPortBottomLeft(...) is marked as unresolved reference for me.


来源: stackexchange

问:
GraphQL - How can I tell if my delete mutation has been created?
My react, apollo, prisma, nextjs typescript app seems to think I have not made a deleteIssueGroup mutation. I think I have.

I am using:

```<code>"devDependencies": {
    "@graphql-codegen/add": "3.2.1",
    "@graphql-codegen/cli": "2.13.7",
    "@graphql-codegen/typescript": "2.8.0",
    "@graphql-codegen/typescript-operations": "2.5.5",
    "@graphql-codegen/typescript-react-apollo": "3.3.5",
    "@types/cookie": "0.5.1",
    "@types/react": "17.0.51",
    "@types/react-dom": "17.0.17",
    "eslint-config-next": "12.3.1"

</code>```

It's strange because I defined a deleteGroup mutation at the same time as I made the createGroup mutation and the AllGroups query, but my app thinks I don't have a deleteGroup mutation (it's right, the @generated file doesn't have it in there - except for it being listed in the list of mutations - there are no individual line items in graphql.tsx that define useDeleteIssueMutation in the same way that there are such lines for the create type). I don't know why. Is there a way to force the creation, or the recognition that there is only one of everything?

I can see in my graphql.tsx that I have:

```<code>export type MutationDeleteGroupArgs = {
  id: Scalars['String'];
};
</code>```

which I think means I should have the delete mutation, but in the form, when I'm trying to use it, I get an error in the terminal that says it doesn't exist.

When I run my yarn db:migrate script, it goes through the motions of running the prisma migrations (they are all up to date, but it then runs the code gen and concludes successfully).

My code is (I made a new one called IssueGroup to try and see if it was just a random unlucky twist that is causing this mess):

Prisma model

```<code>model IssueGroup {
  id              String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  title           String
  description     String
  issues          Issue[]
  createdAt       DateTime @default(now()) @db.Timestamptz(6)
  updatedAt       DateTime @default(now()) @updatedAt @db.Timestamptz(6)
}
</code>```

model

```<code>import * as Prisma from "@prisma/client"
import { Field, ObjectType } from "type-graphql"

import { BaseModel } from "../shared/base.model"

@ObjectType()
export class IssueGroup extends BaseModel implements Prisma.IssueGroup {
  @Field()
  title: string

  @Field()
  description: string

  @Field(type => String)
  issues: Prisma.Issue[];

}
</code>```

group service:

```<code>import { prisma } from "../../lib/prisma"
import { Service } from "typedi"
import { IssueGroupInput } from "./inputs/create.input"

import { Resolver } from "type-graphql"
import { IssueGroup } from "./issueGroup.model"

@Service()
@Resolver(() => IssueGroup)
export class IssueGroupService {
  async createIssueGroup(data: IssueGroupInput) {
    return await prisma.issueGroup.create({
      data,
    })
  }

  async deleteIssueGroup(id: string) {
    return await prisma.issueGroup.delete({ where: { id } })
  }

  async updateIssueGroup(id: string, data: IssueGroupInput) {
    const issueGroup = await prisma.issueGroup.findUnique({ where: { id } })
    if (!issueGroup) {
      throw new Error("Issue not found")
    }
    return await prisma.issueGroup.update({ where: { id }, data })
  }

  async getAllIssueGroups() {
    return await (await prisma.issueGroup.findMany({orderBy: {title: 'asc'}}))
  }

  async getIssueGroup(id: string) {
    return await prisma.issueGroup.findUnique({
      where: {
        id,
      },
    })
  }
}
</code>```

resolver

```<code>import { Arg,  Mutation,  Query, Resolver } from "type-graphql"
import { IssueGroup } from "./issueGroup.model"
import { IssueGroupService } from "./issueGroup.service"
import { IssueGroupInput } from "./inputs/create.input"
import { Inject, Service } from "typedi"

@Service()

@Resolver(() => IssueGroup)

export default class IssueGroupResolver {
    @Inject(() => IssueGroupService)
        issueGroupService: IssueGroupService

    @Query(() => [IssueGroup])
        async issueGroups() {
            return await this.issueGroupService.getAllIssueGroups()
        }

    @Query(() => IssueGroup)
    async issueGroup(@Arg("id") id: string) {
        return await this.issueGroupService.getIssueGroup(id)
    }

    @Mutation(() => IssueGroup)
    async createIssueGroup(@Arg("data") data: IssueGroupInput) {
        return await this.issueGroupService.createIssueGroup(data)
    }
        // : Promise<IssueGroup[]> {

    @Mutation(() => IssueGroup)
    async updateIssueGroup(
        @Arg("id") id: string,
        @Arg("data") data: IssueGroupInput
    ) {
        return this.issueGroupService.updateIssueGroup(id, data)
    }

    @Mutation(() => IssueGroup)
    async deleteIssueGroup(@Arg("id") id: string) {
        return this.issueGroupService.deleteIssueGroup(id)
    }
}
</code>```

I have seen this post and can see the warning about naming queries uniquely - but I cannot see how I have offended the principle.

I have seen this post and tried following the suggestion to change my codegen.yml from:

```<code>documents:
  - "src/components/**/*.{ts,tsx}"
  - "src/lib/**/*.{ts,tsx}"
  - "src/pages/**/*.{ts,tsx}"
</code>```

to:

```<code>documents:
  - "src/components/**/!(*.types).{ts,tsx}"
  - "src/lib/**/!(*.types).{ts,tsx}"
  - "src/pages/**/!(*.types).{ts,tsx}"
</code>```

but I still get the same issue - my vsCode is suggesting I might want to use create instead of delete.

ContentLicense: CC BY-SA 4.0

Body:
My react, apollo, prisma, nextjs typescript app seems to think I have not made a deleteIssueGroup mutation. I think I have.

I am using:

"devDependencies": {
    "@graphql-codegen/add": "3.2.1",
    "@graphql-codegen/cli": "2.13.7",
    "@graphql-codegen/typescript": "2.8.0",
    "@graphql-codegen/typescript-operations": "2.5.5",
    "@graphql-codegen/typescript-react-apollo": "3.3.5",
    "@types/cookie": "0.5.1",
    "@types/react": "17.0.51",
    "@types/react-dom": "17.0.17",
    "eslint-config-next": "12.3.1"

It's strange because I defined a deleteGroup mutation at the same time as I made the createGroup mutation and the AllGroups query, but my app thinks I don't have a deleteGroup mutation (it's right, the @generated file doesn't have it in there - except for it being listed in the list of mutations - there are no individual line items in graphql.tsx that define useDeleteIssueMutation in the same way that there are such lines for the create type). I don't know why. Is there a way to force the creation, or the recognition that there is only one of everything?

I can see in my graphql.tsx that I have:

export type MutationDeleteGroupArgs = {
  id: Scalars['String'];
};

which I think means I should have the delete mutation, but in the form, when I'm trying to use it, I get an error in the terminal that says it doesn't exist.

When I run my yarn db:migrate script, it goes through the motions of running the prisma migrations (they are all up to date, but it then runs the code gen and concludes successfully).

My code is (I made a new one called IssueGroup to try and see if it was just a random unlucky twist that is causing this mess):

Prisma model

model IssueGroup {
  id              String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  title           String
  description     String
  issues          Issue[]
  createdAt       DateTime @default(now()) @db.Timestamptz(6)
  updatedAt       DateTime @default(now()) @updatedAt @db.Timestamptz(6)
}

model

import * as Prisma from "@prisma/client"
import { Field, ObjectType } from "type-graphql"

import { BaseModel } from "../shared/base.model"

@ObjectType()
export class IssueGroup extends BaseModel implements Prisma.IssueGroup {
  @Field()
  title: string

  @Field()
  description: string

  @Field(type => String)
  issues: Prisma.Issue[];

}

group service:

import { prisma } from "../../lib/prisma"
import { Service } from "typedi"
import { IssueGroupInput } from "./inputs/create.input"

import { Resolver } from "type-graphql"
import { IssueGroup } from "./issueGroup.model"

@Service()
@Resolver(() => IssueGroup)
export class IssueGroupService {
  async createIssueGroup(data: IssueGroupInput) {
    return await prisma.issueGroup.create({
      data,
    })
  }

  async deleteIssueGroup(id: string) {
    return await prisma.issueGroup.delete({ where: { id } })
  }

  async updateIssueGroup(id: string, data: IssueGroupInput) {
    const issueGroup = await prisma.issueGroup.findUnique({ where: { id } })
    if (!issueGroup) {
      throw new Error("Issue not found")
    }
    return await prisma.issueGroup.update({ where: { id }, data })
  }

  async getAllIssueGroups() {
    return await (await prisma.issueGroup.findMany({orderBy: {title: 'asc'}}))
  }

  async getIssueGroup(id: string) {
    return await prisma.issueGroup.findUnique({
      where: {
        id,
      },
    })
  }
}

resolver

import { Arg,  Mutation,  Query, Resolver } from "type-graphql"
import { IssueGroup } from "./issueGroup.model"
import { IssueGroupService } from "./issueGroup.service"
import { IssueGroupInput } from "./inputs/create.input"
import { Inject, Service } from "typedi"

@Service()

@Resolver(() => IssueGroup)

export default class IssueGroupResolver {
    @Inject(() => IssueGroupService)
        issueGroupService: IssueGroupService

    @Query(() => [IssueGroup])
        async issueGroups() {
            return await this.issueGroupService.getAllIssueGroups()
        }

    @Query(() => IssueGroup)
    async issueGroup(@Arg("id") id: string) {
        return await this.issueGroupService.getIssueGroup(id)
    }

    @Mutation(() => IssueGroup)
    async createIssueGroup(@Arg("data") data: IssueGroupInput) {
        return await this.issueGroupService.createIssueGroup(data)
    }
        // : Promise<IssueGroup[]> {

    @Mutation(() => IssueGroup)
    async updateIssueGroup(
        @Arg("id") id: string,
        @Arg("data") data: IssueGroupInput
    ) {
        return this.issueGroupService.updateIssueGroup(id, data)
    }

    @Mutation(() => IssueGroup)
    async deleteIssueGroup(@Arg("id") id: string) {
        return this.issueGroupService.deleteIssueGroup(id)
    }
}

I have seen this post and can see the warning about naming queries uniquely - but I cannot see how I have offended the principle.

I have seen this post and tried following the suggestion to change my codegen.yml from:

documents:
  - "src/components/**/*.{ts,tsx}"
  - "src/lib/**/*.{ts,tsx}"
  - "src/pages/**/*.{ts,tsx}"

to:

documents:
  - "src/components/**/!(*.types).{ts,tsx}"
  - "src/lib/**/!(*.types).{ts,tsx}"
  - "src/pages/**/!(*.types).{ts,tsx}"

but I still get the same issue - my vsCode is suggesting I might want to use create instead of delete.


问:
Need help why the invalid command message keeps popping up
I've been working on a project that repeatedly asks for user input using commands until the user enters "quit", then uses a switch statement to run the corresponding function and I'm getting this issue where the invalid command error message pops up when it is not supposed to, any and all help is appreciated. I have condensed the code down as far as I can to reproduce the issue

```<code>import java.util.Scanner;

public class Main {
    private static Scanner usrInput;

    static void checkCommand(String command) {
        switch (command) {
            case "add" -> addPlayer();
            case "quit" -> System.out.println("");
            default -> {
                System.out.println("Invalid command, please try again");
            }
        }
    }

    static void enterCommand() {
        String input;
        do {
            System.out.print(">>> ");
            input = usrInput.nextLine();
            checkCommand(input);
        } while (!input.equals("quit"));
    }
    static void addPlayer() {
        System.out.print("Enter name:\n   >>> ");
        String name = usrInput.nextLine();
        System.out.print("How old are you " + name + "\n   >>> ");
        int age = usrInput.nextInt();

        System.out.println("Name: " + name + "\nAge: " + age);
    }

    public static void main(String[] args) {
        usrInput = new Scanner(System.in);
        System.out.println("Enter command(add):");
        enterCommand();
    }
}
</code>```

The program should only print out that error message when an incorrect command is entered, I am pretty sure the issue is something with the usrInput.nextInt() for the age variable but I don't know what to do from here

Body:
I've been working on a project that repeatedly asks for user input using commands until the user enters "quit", then uses a switch statement to run the corresponding function and I'm getting this issue where the invalid command error message pops up when it is not supposed to, any and all help is appreciated. I have condensed the code down as far as I can to reproduce the issue

import java.util.Scanner;

public class Main {
    private static Scanner usrInput;

    static void checkCommand(String command) {
        switch (command) {
            case "add" -> addPlayer();
            case "quit" -> System.out.println("");
            default -> {
                System.out.println("Invalid command, please try again");
            }
        }
    }

    static void enterCommand() {
        String input;
        do {
            System.out.print(">>> ");
            input = usrInput.nextLine();
            checkCommand(input);
        } while (!input.equals("quit"));
    }
    static void addPlayer() {
        System.out.print("Enter name:\n   >>> ");
        String name = usrInput.nextLine();
        System.out.print("How old are you " + name + "\n   >>> ");
        int age = usrInput.nextInt();

        System.out.println("Name: " + name + "\nAge: " + age);
    }

    public static void main(String[] args) {
        usrInput = new Scanner(System.in);
        System.out.println("Enter command(add):");
        enterCommand();
    }
}

The program should only print out that error message when an incorrect command is entered, I am pretty sure the issue is something with the usrInput.nextInt() for the age variable but I don't know what to do from here


问:
System.StackOverflowException in automatically generated file
I'm making a form in c# visual studio, and the Designer.cs gives an error.

```<code> this.ClientSize = new System.Drawing.Size(409, 528); //Gives System.StackOverflowException error
</code>```

I didn't have any problems with this until now, when I wrote this code.

```<code>            operation = '÷';
            if (operand1 == "")
            {
                operand1 = input;
                input = string.Empty;
            }
            else
            {
                operand1 = calculate(operand1,input,operation);
                input = string.Empty;
            }

</code>```

(Pretty sure that this has absolutely nothing to do with the error)

Any help would be appreciated, thanks in advance.

Error

Body:
I'm making a form in c# visual studio, and the Designer.cs gives an error.

 this.ClientSize = new System.Drawing.Size(409, 528); //Gives System.StackOverflowException error

I didn't have any problems with this until now, when I wrote this code.

            operation = '÷';
            if (operand1 == "")
            {
                operand1 = input;
                input = string.Empty;
            }
            else
            {
                operand1 = calculate(operand1,input,operation);
                input = string.Empty;
            }

(Pretty sure that this has absolutely nothing to do with the error)

Any help would be appreciated, thanks in advance.

Error


问:
How can I get SE for smooth.spline()?
I use smooth.spline() on two large numeric vectors, x and y. I now want to visualize it, showing confidence intervals (or standard errors).

Ideally, I would just use geom_smooth(method="spline"), but that doesn't exist. So I tried method = "loess", which is similar, but than it runs out of memory (unless I set se=F) and I already set it to the maximum capacity.

I than used base R function smooth.spline(), but that doesn't calculate standard errors or confidence intervals. I tried using the function predict(model, se = T), but it does not produce standard errors for smooth.spline models.

What can I do? please help, I am trying for days now, and even GPT couldn't do it

Title: How can I get SE for smooth.spline()?


问:
No way of implementing page size on restHighLevelClient in java
I have such problem now, I have a requirement to migrate from spring data elasticsearch to restHighLevelClient, and also have to implement pagination, which was pretty easy in Spring data.

```<code>SearchResponse response = esClient.search(new SearchRequest("person")
    .source(new SearchSourceBuilder()
            .query(query)
            .from(from)
            .size(size)
    ));
</code>```

with this we can specify the whole size of items only, which has nothing to do with pageSize (i.e the item size on each page).
Now please any way of specifying the pageSize on "restHighLevelClient"

Body:
I have such problem now, I have a requirement to migrate from spring data elasticsearch to restHighLevelClient, and also have to implement pagination, which was pretty easy in Spring data.

SearchResponse response = esClient.search(new SearchRequest("person")
    .source(new SearchSourceBuilder()
            .query(query)
            .from(from)
            .size(size)
    ));

with this we can specify the whole size of items only, which has nothing to do with pageSize (i.e the item size on each page).
Now please any way of specifying the pageSize on "restHighLevelClient"


问:
Bandwidth usage of unicast, multicast and broadcast transmissions
Basically, I know that Unicast is one to one, Multicast is one to many (the ones that requested the data) and Broadcast is one to all (whether they want the data or not).

In unicast, a data is duplicated and sent one by one by the transmitter to all the receivers that need it. Bandwidth usage here is simply equal to data size * number of receivers, right ?

But how does that work for multicast and broadcast transmissions ?
I understood that it is simpler (and more cost effective) for the transmitter that has to send the data just once to the switch (no matter how many receivers). Then the switch takes care of  it by forwarding the data to many (multicast) or to all (broadcast).
But in the end, the bandwidth usage will increase with the number of receivers too. That means (as before) multiplying the data size by the number of receivers, right ?

For example, is the bandwidth usage of 100 unicast transmissions different from 1 broadcast (or multicast) transmission to 100 receivers ? If so, what’s the trick ?

Many thanks for your time


问:
Unable to connect to Confluent Kafka in Python
I am trying to connect to confluent cloud hosted in Azure and consume the messages but on running the python code it give me the below error which I am unable to gauge.

2022-12-12 11:37:16,249 ERROR    FAIL [python-example-consumer#consumer-1] [thrd:sasl_ssl://<NAME>.eastus.azure.confluent.cloud:9093/bootstra]: sasl_ssl://<NAME>.eastus.azure.confluent.cloud:9093/bootstrap: Connect to ipv4#20.XXX.XXX.XXX:9093 failed: Unknown error (after 21236ms in state CONNECT, 2 identical error(s) suppressed)

How do I check out the identical errors that are suppressed?

These are my configurations for consumer:

```<code>conf = {
        'bootstrap.servers': '<NAME>.eastus.azure.confluent.cloud:9093',
        'security.protocol': 'SASL_SSL',
        'sasl.mechanism': 'PLAIN',
        'sasl.username': client_key,
        'sasl.password': client_secret,
        'group.id': 'consumer1',
        'client.id': 'python-example-consumer',
        'session.timeout.ms': 60000,
        'default.topic.config': {'auto.offset.reset': 'smallest'}
    }
</code>```

Testing out with confluent-kafka=1.9.2

This is my code:

```<code>from confluent_kafka import Consumer, KafkaException, KafkaError

c = Consumer(conf)
c.subscribe([topic])
try:
        while True:
            msg = c.poll(timeout=200.0)
            if msg is None:
                continue
            if msg.error():
                # Error or event
                if msg.error().code() == KafkaError._PARTITION_EOF:
                    # End of partition event
                    sys.stderr.write('%% %s [%d] reached end at offset %d\n' %
                                     (msg.topic(), msg.partition(), msg.offset()))
                else:
                    # Error
                    raise KafkaException(msg.error())
            else:
                print(msg.value())

    except KeyboardInterrupt:
        print('\nAborted by user\n')
    finally:
        c.close()
</code>```

I have rechecked the client key and client secret and they are correct as well.

Body:
I am trying to connect to confluent cloud hosted in Azure and consume the messages but on running the python code it give me the below error which I am unable to gauge.

2022-12-12 11:37:16,249 ERROR    FAIL [python-example-consumer#consumer-1] [thrd:sasl_ssl://<NAME>.eastus.azure.confluent.cloud:9093/bootstra]: sasl_ssl://<NAME>.eastus.azure.confluent.cloud:9093/bootstrap: Connect to ipv4#20.XXX.XXX.XXX:9093 failed: Unknown error (after 21236ms in state CONNECT, 2 identical error(s) suppressed)

How do I check out the identical errors that are suppressed?

These are my configurations for consumer:

conf = {
        'bootstrap.servers': '<NAME>.eastus.azure.confluent.cloud:9093',
        'security.protocol': 'SASL_SSL',
        'sasl.mechanism': 'PLAIN',
        'sasl.username': client_key,
        'sasl.password': client_secret,
        'group.id': 'consumer1',
        'client.id': 'python-example-consumer',
        'session.timeout.ms': 60000,
        'default.topic.config': {'auto.offset.reset': 'smallest'}
    }

Testing out with confluent-kafka=1.9.2

This is my code:

from confluent_kafka import Consumer, KafkaException, KafkaError

c = Consumer(conf)
c.subscribe([topic])
try:
        while True:
            msg = c.poll(timeout=200.0)
            if msg is None:
                continue
            if msg.error():
                # Error or event
                if msg.error().code() == KafkaError._PARTITION_EOF:
                    # End of partition event
                    sys.stderr.write('%% %s [%d] reached end at offset %d\n' %
                                     (msg.topic(), msg.partition(), msg.offset()))
                else:
                    # Error
                    raise KafkaException(msg.error())
            else:
                print(msg.value())

    except KeyboardInterrupt:
        print('\nAborted by user\n')
    finally:
        c.close()

I have rechecked the client key and client secret and they are correct as well.


问:
Trying to connect to the production database through IP Address but facing errors

Errors I am facing

Error creating bean with name 'entityManagerFactory' defined in class path resource \[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class\]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service \[org.hibernate.engine.jdbc.env.spi.JdbcEnvironment\]Unable to create requested service \[org.hibernate.engine.jdbc.env.spi.JdbcEnvironment\]Access to DialectResolutionInfo cannot be null when 'hibernate. dialect' not set

Configurations
Spring boot 2.7
Rest API
MS SQL Server 11.0(Production)
MS SQL Server 15.0(Local)

My application.properties

//my local database where I can connect and perform tasks

#spring.datasource.url=jdbc:sqlserver://SACHINSAVITA\\SQLEXPRESS:1433;encrypt=false;databaseName=employee #spring.datasource.username=root #spring.datasource.password=root #server.port=8090 #server.address=10.6.10.193

Production where I am facing errors

spring.datasource.url=jdbc:sqlserver://10.6.1.165:1433/employee?; spring.datasource.username=root spring.datasource.password=root spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=none server.port=8099 server.address=10.6.10.193 spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect

Pom.xml file

`

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gcc.biometric.api</groupId>
    <artifactId>GccBioMetricApi</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>GccBioMetricApi</name>
    <description>Spring Boot Api</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--#########################################-->

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>

        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>

        </dependency>

        <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20171018</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>

        </dependency> <!--$NO-MVN-MAN-VER$-->

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

`

I tried with different dialects but not able to understand whats the problem, please help!

Body:
Errors I am facing

Error creating bean with name 'entityManagerFactory' defined in class path resource \[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class\]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service \[org.hibernate.engine.jdbc.env.spi.JdbcEnvironment\]Unable to create requested service \[org.hibernate.engine.jdbc.env.spi.JdbcEnvironment\]Access to DialectResolutionInfo cannot be null when 'hibernate. dialect' not set

Configurations
Spring boot 2.7
Rest API
MS SQL Server 11.0(Production)
MS SQL Server 15.0(Local)

My application.properties

//my local database where I can connect and perform tasks

#spring.datasource.url=jdbc:sqlserver://SACHINSAVITA\\SQLEXPRESS:1433;encrypt=false;databaseName=employee #spring.datasource.username=root #spring.datasource.password=root #server.port=8090 #server.address=10.6.10.193

Production where I am facing errors

spring.datasource.url=jdbc:sqlserver://10.6.1.165:1433/employee?; spring.datasource.username=root spring.datasource.password=root spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto=none server.port=8099 server.address=10.6.10.193 spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2008Dialect

Pom.xml file

`

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.5</version>
        <relativePath />
    </parent>
    <groupId>com.gcc.biometric.api</groupId>
    <artifactId>GccBioMetricApi</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>GccBioMetricApi</name>
    <description>Spring Boot Api</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>

        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>

        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20171018</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>

        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

`

I tried with different dialects but not able to understand whats the problem, please help!


问:
Questions on interface condition convergence in PINNs(Physics-Informed Neural Network)
I am solving a magnetostatic problem using PINN.

I have succeeded in solving a simple Poisson equation. However, in the analysis considering the geometry, a problem was found in which the interface condition loss did not converge.

I've tried numerous things including changing the mini-batch addition model.

I'd appreciate it if you could let me know what's wrong with my code.

```<code>class ironmaxwell(Model):

    def __init__(self):
        super(ironmaxwell, self).__init__()

        initializer = tf.keras.initializers.GlorotUniform

        self.id1 = tf.keras.layers.Dropout(rate=0.2)
        self.ih1 = Dense(40, activation='elu', kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.id2 = tf.keras.layers.Dropout(rate=0.2)
        self.ih2 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.id3 = tf.keras.layers.Dropout(rate=0.2)
        self.ih3 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.id4 = tf.keras.layers.Dropout(rate=0.2)
        self.ih4 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.id5 = tf.keras.layers.Dropout(rate=0.2)
        self.ih5 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.id6 = tf.keras.layers.Dropout(rate=0.2)
        self.ih6 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))

        self.iu1 = Dense(40, activation='linear',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.iw1 = Dense(40, activation='linear',kernel_regularizer=tf.keras.regularizers.L2(0.001))

        self.iu = Dense(1, activation='linear')

    def call(self, state):
        ix = self.id1(state)
        iy = self.iu1(state)
        iz = self.iw1(state)
        ix = (1-self.ih1(ix))*iy + self.ih1(ix)*iz
        ix = self.id2(ix)
        ix = (1-self.ih2(ix))*iy + self.ih2(ix)*iz
        ix = self.id3(ix)
        ix = (1-self.ih3(ix))*iy + self.ih4(ix)*iz
        ix = self.id4(ix)
        ix = (1-self.ih4(ix))*iy + self.ih4(ix)*iz
        ix = self.id5(ix)
        ix = (1-self.ih5(ix))*iy + self.ih5(ix)*iz
        ix = self.id6(ix)
        ix = (1-self.ih6(ix))*iy + self.ih6(ix)*iz
        iout = self.iu(ix)
        return iout

class coilmaxwell(Model):

    def __init__(self):
        super(coilmaxwell, self).__init__()

        initializer = tf.keras.initializers.GlorotUniform

        self.d1 = tf.keras.layers.Dropout(rate=0.2)
        self.h1 = Dense(40, activation='elu', kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.d2 = tf.keras.layers.Dropout(rate=0.2)
        self.h2 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.d3 = tf.keras.layers.Dropout(rate=0.2)
        self.h3 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.d4 = tf.keras.layers.Dropout(rate=0.2)
        self.h4 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.d5 = tf.keras.layers.Dropout(rate=0.2)
        self.h5 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.d6 = tf.keras.layers.Dropout(rate=0.2)
        self.h6 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))

        self.u1 = Dense(40, activation='linear',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.w1 = Dense(40, activation='linear',kernel_regularizer=tf.keras.regularizers.L2(0.001))

        self.u = Dense(1, activation='linear')

    def call(self, state):
        x = self.d1(state)
        y = self.u1(state)
        z = self.w1(state)
        x = (1-self.h1(x))*y + self.h1(x)*z
        x = self.d2(x)
        x = (1-self.h2(x))*y + self.h2(x)*z
        x = self.d3(x)
        x = (1-self.h3(x))*y + self.h4(x)*z
        x = self.d4(x)
        x = (1-self.h4(x))*y + self.h4(x)*z
        x = self.d5(x)
        x = (1-self.h5(x))*y + self.h5(x)*z
        x = self.d6(x)
        x = (1-self.h6(x))*y + self.h6(x)*z
        out = self.u(x)
        return out

##############################################################################################################################
class MaxwellPinn(object):

    def __init__(self):

        self.lr = 0.001

        #self.lr = tf.keras.optimizers.schedules.ExponentialDecay(initial_learning_rate=.001, decay_steps=10, decay_rate=.01)
        self.opt_iron = Adam(self.lr)
        self.opt_coil = Adam(self.lr)
        self.ironmaxwell = ironmaxwell()
        self.ironmaxwell.build(input_shape=(None, 2))
        self.coilmaxwell = coilmaxwell()
        self.coilmaxwell.build(input_shape=(None, 2))

        self.train_loss_history = []
        self.iter_count = 0
        self.instant_loss = 0
        self.bnd_loss = 0
        self.ic_loss = 0
        self.lamda = 0.1
        self.pde_loss = 0
        self.max_value = 0.012315021035034
        self.iron_loss = 0
        self.coil_loss = 0
################################################################################################################################
    @tf.function
    def physics_net_iron(self, xt,jmu):
        x_i = xt[:, 0:1]
        t_i = xt[:, 1:2]
        with tf.GradientTape(persistent=True) as tape:
            tape.watch(t_i)
            tape.watch(x_i)
            xt_t_i = tf.concat([x_i,t_i], axis=1)
            u_i = self.ironmaxwell(xt_t_i)
            u_x_i = tape.gradient(u_i, x_i)
            u_t_i = tape.gradient(u_i, t_i)
        u_xx_i = tape.gradient(u_x_i, x_i)
        u_tt_i = tape.gradient(u_t_i, t_i)
        del tape

        return (u_xx_i+u_tt_i+jmu)

    @tf.function
    def physics_net_coil(self, xt,jmu):
        x_c = xt[:, 0:1]
        t_c = xt[:, 1:2]
        with tf.GradientTape(persistent=True) as tape:
            tape.watch(t_c)
            tape.watch(x_c)
            xt_t_c = tf.concat([x_c,t_c], axis=1)
            u_c = self.coilmaxwell(xt_t_c)
            u_x_c = tape.gradient(u_c, x_c)
            u_t_c = tape.gradient(u_c, t_c)
        u_xx_c = tape.gradient(u_x_c, x_c)
        u_tt_c = tape.gradient(u_t_c, t_c)
        del tape

        return (u_xx_c+u_tt_c+jmu)
 ####################################################################################################################
    @tf.function
    def physics_net_for_ic(self, xt,in_mu,nom,out_mu):   # 경계조건 물리정보
        x = xt[:, 0:1]
        t = xt[:, 1:2]
        with tf.GradientTape(persistent=True) as tape:
            tape.watch(t)
            tape.watch(x)
            xt_t = tf.concat([x,t], axis=1)
            out_u = self.ironmaxwell(xt_t)
            out_u_x = tape.gradient(out_u, x)
            out_u_y = tape.gradient(out_u, t)
            in_u = self.coilmaxwell(xt_t)
            in_u_x = tape.gradient(in_u, x)
            in_u_y = tape.gradient(in_u, t)
        del tape

        out_b_x = out_u_y
        out_b_y = out_u_x

        out_h_x = out_b_x/out_mu
        out_h_y = out_b_y/out_mu

        in_b_x = in_u_y
        in_b_y = in_u_x

        in_h_x = in_b_x/in_mu
        in_h_y = in_b_y/in_mu

        loss_b = tf.add(tf.multiply((in_b_x-out_b_x),nom),tf.multiply((in_b_y-out_b_y),(1-nom)))

        loss_h = tf.add(tf.multiply((in_h_x-out_h_x),(1-nom)),tf.multiply((in_h_y-out_h_y),nom))

        return loss_b, loss_h

 #############################################################################################################
    def save_weights(self, path):
        self.ironmaxwell.save_weights(path + 'ironmaxwell.h5')
        self.coilmaxwell.save_weights(path + 'coilmaxwell.h5')
 #############################################################################################################
    def load_weights(self, path):
        self.ironmaxwell.load_weights(path + 'ironmaxwell.h5')
        self.coilmaxwell.load_weights(path + 'coilmaxwell.h5')
 #############################################################################################################
    def compute_loss_iron(self, f, u_bnd_hat, u_bnd_sol,penalty,loss_b,loss_h):

        loss_col = tf.reduce_mean(tf.square(f))
        loss_bnd = tf.reduce_mean(tf.square(u_bnd_hat - u_bnd_sol))
        loss_mag = tf.reduce_mean(tf.square(loss_b))
        loss_field =tf.reduce_mean(tf.square(loss_h))

        loss = loss_col + loss_bnd + loss_mag + loss_field

        self.iron_loss = loss.numpy()

        return loss

    def compute_loss_coil(self, f,penalty,loss_b,loss_h):

        loss_col = tf.reduce_mean(tf.square(f))
        loss_mag = tf.reduce_mean(tf.square(loss_b))
        loss_field =tf.reduce_mean(tf.square(loss_h))

        loss = loss_col + loss_mag + loss_field

        self.coil_loss = loss.numpy()

        return loss
 #############################################################################################################

    def compute_grad(self, xt_col_iron,xt_col_coil, xt_bnd, u_bnd_sol,ic,nom):
        with tf.GradientTape(persistent=True) as tape:

            J_coil = 9800
            J_iron = 0
            mu_coil = 1.2566e-06
            mu_iron = mu_coil*2000

            f_iron = self.physics_net_iron(xt_col_iron,J_iron*mu_iron)  # iron의 PDE 손실

            f_coil = self.physics_net_coil(xt_col_coil,J_coil*mu_coil) # coil의 PDE 손실

            u_bnd_hat = self.ironmaxwell(xt_bnd) # IRON이 OUT

            loss_b, loss_h = self.physics_net_for_ic(ic,mu_coil,nom,mu_iron)

            loss_iron = self.compute_loss_iron(f_iron, u_bnd_hat, u_bnd_sol,1,loss_b,loss_h)
            loss_coil = self.compute_loss_coil(f_coil,1,loss_b,loss_h)

            iron_grads = tape.gradient(loss_iron, self.ironmaxwell.trainable_variables)
            coil_grads = tape.gradient(loss_coil, self.coilmaxwell.trainable_variables)

            loss = loss_iron + loss_coil

        return loss, iron_grads, coil_grads

 #############################################################################################################
    def callback(self, arg=None):
        if self.iter_count % 10 == 0:
            print('iter=', self.iter_count, ', loss=', self.instant_loss,'iron_loss=',self.iron_loss,'coil_loss=',self.coil_loss)
            self.train_loss_history.append([self.iter_count, self.instant_loss])
        self.iter_count += 1
 #############################################################################################################

    def train_with_adam(self,xt_col_iron,xt_col_coil, xt_bnd, u_bnd_sol, adam_num,ic,nom):

        def learn():
            loss, iron_grads, coil_grads = self.compute_grad(xt_col_iron,xt_col_coil, xt_bnd, u_bnd_sol,ic,nom)

            self.opt_iron.apply_gradients(zip(iron_grads, self.ironmaxwell.trainable_variables))

            self.opt_coil.apply_gradients(zip(coil_grads, self.coilmaxwell.trainable_variables))

            return loss

        for iter in range(int(adam_num)):

            loss = learn()

            self.instant_loss = loss.numpy()

            self.opt_iron = Adam(self.lr/(1+0.001*iter))
            self.opt_coil = Adam(self.lr/(1+0.001*iter))

            self.callback()
 #############################################################################################################

    def train_with_lbfgs(self, xt_col, xt_bnd, u_bnd_sol, lbfgs_num,J,mu,penalty,ii,ic,ii_mu,ic_mu,nom):

        def vec_weight():
            # vectorize weights
            weight_vec = []

            # Loop over all weights
            for v in self.burgers.trainable_variables:
                weight_vec.extend(v.numpy().flatten())

            weight_vec = tf.convert_to_tensor(weight_vec)
            return weight_vec
        w0 = vec_weight().numpy()

        def restore_weight(weight_vec):
            # restore weight vector to model weights
            idx = 0
            for v in self.burgers.trainable_variables:
                vs = v.shape

                # weight matrices
                if len(vs) == 2:
                    sw = vs[0] * vs[1]
                    updated_val = tf.reshape(weight_vec[idx:idx + sw], (vs[0], vs[1]))
                    idx += sw

                # bias vectors
                elif len(vs) == 1:
                    updated_val = weight_vec[idx:idx + vs[0]]
                    idx += vs[0]

                # assign variables (Casting necessary since scipy requires float64 type)
                v.assign(tf.cast(updated_val, dtype=tf.float32))

        def loss_grad(w):
            # update weights in model
            restore_weight(w)
            loss, grads, loss_bnd = self.compute_grad(xt_col, xt_bnd, u_bnd_sol,J,mu,penalty,ii,ic,ii_mu,ic_mu,nom)
            # vectorize gradients
            grad_vec = []
            for g in grads:
                grad_vec.extend(g.numpy().flatten())

            # gradient list to array
            # scipy-routines requires 64-bit floats
            loss = loss.numpy().astype(np.float64)
            self.instant_loss = loss
            grad_vec = np.array(grad_vec, dtype=np.float64)

            return loss, grad_vec

        return scipy.optimize.minimize(fun=loss_grad,
                                       x0=w0,
                                       jac=True,
                                       method='L-BFGS-B',
                                       callback=self.callback,
                                       options={'maxiter': lbfgs_num,
                                                'maxfun': 5000,
                                                'maxcor': 500,
                                                'maxls': 500,
                                                'ftol': 1.0 * np.finfo(float).eps}) #1.0 * np.finfo(float).eps
 ########################################################################################################################

    def predict_iron(self, xt):
        u_pred = self.ironmaxwell(xt)
        return u_pred
    def predict_coil(self, xt):
        u_pred = self.coilmaxwell(xt)
        return u_pred
 #############################################################################################################

    def train(self, adam_num, lbfgs_num):

        iron_x = scipy.io.loadmat('iron_x.mat') # iron 좌표
        iron_y = scipy.io.loadmat('iron_y.mat')

        coil_x = scipy.io.loadmat('coil_x.mat') # coil 좌표
        coil_y = scipy.io.loadmat('coil_y.mat')

        iron_J = scipy.io.loadmat('iron_J.mat')
        iron_mu = scipy.io.loadmat('iron_mu.mat')
        coil_J = scipy.io.loadmat('iron_J.mat')
        coil_mu = scipy.io.loadmat('iron_mu.mat')

        ini = scipy.io.loadmat('bnd.mat')

        inter_coil_x = scipy.io.loadmat('inter_coil_x.mat')
        inter_coil_y = scipy.io.loadmat('inter_coil_y.mat')
        icx = inter_coil_x['coil_inter_x']
        icy = inter_coil_y['coil_inter_y']
        ic = np.concatenate([icx, icy], axis=1) # interface 코일 데이터

        inter_coil_mu = scipy.io.loadmat('inter_coil_mu.mat')
        ic_mu = np.transpose(inter_coil_mu['mu_inter_coil'])

        nomvec = scipy.io.loadmat('nom_vec.mat')
        nom = nomvec['nom_vec']
        nom = tf.convert_to_tensor(nom, dtype=tf.float32)
        x_ini = np.transpose(ini['iron_bnd_x'])
        y_ini = np.transpose(ini['iron_bnd_y'])
        xt_bnd_data = np.concatenate([x_ini, y_ini], axis=1)
        tu_bnd_data = []

        for xt in xt_bnd_data:
            tu_bnd_data.append(0)
        tu_bnd_data = np.transpose(tu_bnd_data)

        # collocation point iron
        x_col_data = (iron_x['x'])
        y_col_data = (iron_y['y'])
        xy_col_data_iron = np.concatenate([x_col_data, y_col_data], axis=1)
        # coil
        x_col_data = (coil_x['coil_x'])
        y_col_data = (coil_y['coil_y'])
        xy_col_data_coil = np.concatenate([x_col_data, y_col_data], axis=1)

        xt_col_iron = tf.convert_to_tensor(xy_col_data_iron, dtype=tf.float32)
        xt_col_coil = tf.convert_to_tensor(xy_col_data_coil, dtype=tf.float32)

        xt_bnd = tf.convert_to_tensor(xt_bnd_data, dtype=tf.float32)
        u_bnd_sol = tf.convert_to_tensor(tu_bnd_data, dtype=tf.float32)

        ic = tf.convert_to_tensor(ic, dtype=tf.float32)
        ic_mu = tf.convert_to_tensor(ic_mu, dtype=tf.float32)
        # Start timer

        self.load_weights("C:/Users/user/Desktop/1-Cars (2 cases)/save_weights/maxwell/new_test/")

        t0 = time()

        self.train_with_adam(xt_col_iron,xt_col_coil, xt_bnd, u_bnd_sol, adam_num,ic,nom)

        print('\nComputation time of adam: {} seconds'.format(time() - t0))

        self.save_weights("C:/Users/user/Desktop/1-Cars (2 cases)/save_weights/maxwell/new_test/")
        np.savetxt('C:/Users/user/Desktop/1-Cars (2 cases)/save_weights/maxwell/new_test/loss.txt', self.train_loss_history)
        train_loss_history = np.array(self.train_loss_history)

        plt.plot(train_loss_history[:, 0], train_loss_history[:, 1])
        plt.yscale("log")
        plt.show()

 #############################################################################################################
# main
def main():

    adam_num = 100000
    lbfgs_num = 1000
    agent = MaxwellPinn()

    agent.train(adam_num, lbfgs_num)

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

It's my code.

Including mini-batch. Changing the model

Body:
I am solving a magnetostatic problem using PINN.

I have succeeded in solving a simple Poisson equation. However, in the analysis considering the geometry, a problem was found in which the interface condition loss did not converge.

I've tried numerous things including changing the mini-batch addition model.

I'd appreciate it if you could let me know what's wrong with my code.

class ironmaxwell(Model):

    def __init__(self):
        super(ironmaxwell, self).__init__()

        initializer = tf.keras.initializers.GlorotUniform

        self.id1 = tf.keras.layers.Dropout(rate=0.2)
        self.ih1 = Dense(40, activation='elu', kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.id2 = tf.keras.layers.Dropout(rate=0.2)
        self.ih2 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.id3 = tf.keras.layers.Dropout(rate=0.2)
        self.ih3 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.id4 = tf.keras.layers.Dropout(rate=0.2)
        self.ih4 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.id5 = tf.keras.layers.Dropout(rate=0.2)
        self.ih5 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.id6 = tf.keras.layers.Dropout(rate=0.2)
        self.ih6 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))

        self.iu1 = Dense(40, activation='linear',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.iw1 = Dense(40, activation='linear',kernel_regularizer=tf.keras.regularizers.L2(0.001))

        self.iu = Dense(1, activation='linear')

    def call(self, state):
        ix = self.id1(state)
        iy = self.iu1(state)
        iz = self.iw1(state)
        ix = (1-self.ih1(ix))*iy + self.ih1(ix)*iz
        ix = self.id2(ix)
        ix = (1-self.ih2(ix))*iy + self.ih2(ix)*iz
        ix = self.id3(ix)
        ix = (1-self.ih3(ix))*iy + self.ih4(ix)*iz
        ix = self.id4(ix)
        ix = (1-self.ih4(ix))*iy + self.ih4(ix)*iz
        ix = self.id5(ix)
        ix = (1-self.ih5(ix))*iy + self.ih5(ix)*iz
        ix = self.id6(ix)
        ix = (1-self.ih6(ix))*iy + self.ih6(ix)*iz
        iout = self.iu(ix)
        return iout

class coilmaxwell(Model):

    def __init__(self):
        super(coilmaxwell, self).__init__()

        initializer = tf.keras.initializers.GlorotUniform

        self.d1 = tf.keras.layers.Dropout(rate=0.2)
        self.h1 = Dense(40, activation='elu', kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.d2 = tf.keras.layers.Dropout(rate=0.2)
        self.h2 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.d3 = tf.keras.layers.Dropout(rate=0.2)
        self.h3 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.d4 = tf.keras.layers.Dropout(rate=0.2)
        self.h4 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.d5 = tf.keras.layers.Dropout(rate=0.2)
        self.h5 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.d6 = tf.keras.layers.Dropout(rate=0.2)
        self.h6 = Dense(40, activation='elu',kernel_regularizer=tf.keras.regularizers.L2(0.001))

        self.u1 = Dense(40, activation='linear',kernel_regularizer=tf.keras.regularizers.L2(0.001))
        self.w1 = Dense(40, activation='linear',kernel_regularizer=tf.keras.regularizers.L2(0.001))

        self.u = Dense(1, activation='linear')

    def call(self, state):
        x = self.d1(state)
        y = self.u1(state)
        z = self.w1(state)
        x = (1-self.h1(x))*y + self.h1(x)*z
        x = self.d2(x)
        x = (1-self.h2(x))*y + self.h2(x)*z
        x = self.d3(x)
        x = (1-self.h3(x))*y + self.h4(x)*z
        x = self.d4(x)
        x = (1-self.h4(x))*y + self.h4(x)*z
        x = self.d5(x)
        x = (1-self.h5(x))*y + self.h5(x)*z
        x = self.d6(x)
        x = (1-self.h6(x))*y + self.h6(x)*z
        out = self.u(x)
        return out

##############################################################################################################################
class MaxwellPinn(object):

    def __init__(self):

        self.lr = 0.001

        #self.lr = tf.keras.optimizers.schedules.ExponentialDecay(initial_learning_rate=.001, decay_steps=10, decay_rate=.01)
        self.opt_iron = Adam(self.lr)
        self.opt_coil = Adam(self.lr)
        self.ironmaxwell = ironmaxwell()
        self.ironmaxwell.build(input_shape=(None, 2))
        self.coilmaxwell = coilmaxwell()
        self.coilmaxwell.build(input_shape=(None, 2))

        self.train_loss_history = []
        self.iter_count = 0
        self.instant_loss = 0
        self.bnd_loss = 0
        self.ic_loss = 0
        self.lamda = 0.1
        self.pde_loss = 0
        self.max_value = 0.012315021035034
        self.iron_loss = 0
        self.coil_loss = 0
################################################################################################################################
    @tf.function
    def physics_net_iron(self, xt,jmu):
        x_i = xt[:, 0:1]
        t_i = xt[:, 1:2]
        with tf.GradientTape(persistent=True) as tape:
            tape.watch(t_i)
            tape.watch(x_i)
            xt_t_i = tf.concat([x_i,t_i], axis=1)
            u_i = self.ironmaxwell(xt_t_i)
            u_x_i = tape.gradient(u_i, x_i)
            u_t_i = tape.gradient(u_i, t_i)
        u_xx_i = tape.gradient(u_x_i, x_i)
        u_tt_i = tape.gradient(u_t_i, t_i)
        del tape

        return (u_xx_i+u_tt_i+jmu)

    @tf.function
    def physics_net_coil(self, xt,jmu):
        x_c = xt[:, 0:1]
        t_c = xt[:, 1:2]
        with tf.GradientTape(persistent=True) as tape:
            tape.watch(t_c)
            tape.watch(x_c)
            xt_t_c = tf.concat([x_c,t_c], axis=1)
            u_c = self.coilmaxwell(xt_t_c)
            u_x_c = tape.gradient(u_c, x_c)
            u_t_c = tape.gradient(u_c, t_c)
        u_xx_c = tape.gradient(u_x_c, x_c)
        u_tt_c = tape.gradient(u_t_c, t_c)
        del tape

        return (u_xx_c+u_tt_c+jmu)
 ####################################################################################################################
    @tf.function
    def physics_net_for_ic(self, xt,in_mu,nom,out_mu):   # 경계조건 물리정보
        x = xt[:, 0:1]
        t = xt[:, 1:2]
        with tf.GradientTape(persistent=True) as tape:
            tape.watch(t)
            tape.watch(x)
            xt_t = tf.concat([x,t], axis=1)
            out_u = self.ironmaxwell(xt_t)
            out_u_x = tape.gradient(out_u, x)
            out_u_y = tape.gradient(out_u, t)
            in_u = self.coilmaxwell(xt_t)
            in_u_x = tape.gradient(in_u, x)
            in_u_y = tape.gradient(in_u, t)
        del tape

        out_b_x = out_u_y
        out_b_y = out_u_x

        out_h_x = out_b_x/out_mu
        out_h_y = out_b_y/out_mu

        in_b_x = in_u_y
        in_b_y = in_u_x

        in_h_x = in_b_x/in_mu
        in_h_y = in_b_y/in_mu

        loss_b = tf.add(tf.multiply((in_b_x-out_b_x),nom),tf.multiply((in_b_y-out_b_y),(1-nom)))

        loss_h = tf.add(tf.multiply((in_h_x-out_h_x),(1-nom)),tf.multiply((in_h_y-out_h_y),nom))

        return loss_b, loss_h

 #############################################################################################################
    def save_weights(self, path):
        self.ironmaxwell.save_weights(path + 'ironmaxwell.h5')
        self.coilmaxwell.save_weights(path + 'coilmaxwell.h5')
 #############################################################################################################
    def load_weights(self, path):
        self.ironmaxwell.load_weights(path + 'ironmaxwell.h5')
        self.coilmaxwell.load_weights(path + 'coilmaxwell.h5')
 #############################################################################################################
    def compute_loss_iron(self, f, u_bnd_hat, u_bnd_sol,penalty,loss_b,loss_h):

        loss_col = tf.reduce_mean(tf.square(f))
        loss_bnd = tf.reduce_mean(tf.square(u_bnd_hat - u_bnd_sol))
        loss_mag = tf.reduce_mean(tf.square(loss_b))
        loss_field =tf.reduce_mean(tf.square(loss_h))

        loss = loss_col + loss_bnd + loss_mag + loss_field

        self.iron_loss = loss.numpy()

        return loss

    def compute_loss_coil(self, f,penalty,loss_b,loss_h):

        loss_col = tf.reduce_mean(tf.square(f))
        loss_mag = tf.reduce_mean(tf.square(loss_b))
        loss_field =tf.reduce_mean(tf.square(loss_h))

        loss = loss_col + loss_mag + loss_field

        self.coil_loss = loss.numpy()

        return loss
 #############################################################################################################

    def compute_grad(self, xt_col_iron,xt_col_coil, xt_bnd, u_bnd_sol,ic,nom):
        with tf.GradientTape(persistent=True) as tape:

            J_coil = 9800
            J_iron = 0
            mu_coil = 1.2566e-06
            mu_iron = mu_coil*2000

            f_iron = self.physics_net_iron(xt_col_iron,J_iron*mu_iron)  # iron의 PDE 손실

            f_coil = self.physics_net_coil(xt_col_coil,J_coil*mu_coil) # coil의 PDE 손실

            u_bnd_hat = self.ironmaxwell(xt_bnd) # IRON이 OUT

            loss_b, loss_h = self.physics_net_for_ic(ic,mu_coil,nom,mu_iron)

            loss_iron = self.compute_loss_iron(f_iron, u_bnd_hat, u_bnd_sol,1,loss_b,loss_h)
            loss_coil = self.compute_loss_coil(f_coil,1,loss_b,loss_h)

            iron_grads = tape.gradient(loss_iron, self.ironmaxwell.trainable_variables)
            coil_grads = tape.gradient(loss_coil, self.coilmaxwell.trainable_variables)

            loss = loss_iron + loss_coil

        return loss, iron_grads, coil_grads

 #############################################################################################################
    def callback(self, arg=None):
        if self.iter_count % 10 == 0:
            print('iter=', self.iter_count, ', loss=', self.instant_loss,'iron_loss=',self.iron_loss,'coil_loss=',self.coil_loss)
            self.train_loss_history.append([self.iter_count, self.instant_loss])
        self.iter_count += 1
 #############################################################################################################

    def train_with_adam(self,xt_col_iron,xt_col_coil, xt_bnd, u_bnd_sol, adam_num,ic,nom):

        def learn():
            loss, iron_grads, coil_grads = self.compute_grad(xt_col_iron,xt_col_coil, xt_bnd, u_bnd_sol,ic,nom)

            self.opt_iron.apply_gradients(zip(iron_grads, self.ironmaxwell.trainable_variables))

            self.opt_coil.apply_gradients(zip(coil_grads, self.coilmaxwell.trainable_variables))

            return loss

        for iter in range(int(adam_num)):

            loss = learn()

            self.instant_loss = loss.numpy()

            self.opt_iron = Adam(self.lr/(1+0.001*iter))
            self.opt_coil = Adam(self.lr/(1+0.001*iter))

            self.callback()
 #############################################################################################################

    def train_with_lbfgs(self, xt_col, xt_bnd, u_bnd_sol, lbfgs_num,J,mu,penalty,ii,ic,ii_mu,ic_mu,nom):

        def vec_weight():
            # vectorize weights
            weight_vec = []

            # Loop over all weights
            for v in self.burgers.trainable_variables:
                weight_vec.extend(v.numpy().flatten())

            weight_vec = tf.convert_to_tensor(weight_vec)
            return weight_vec
        w0 = vec_weight().numpy()

        def restore_weight(weight_vec):
            # restore weight vector to model weights
            idx = 0
            for v in self.burgers.trainable_variables:
                vs = v.shape

                # weight matrices
                if len(vs) == 2:
                    sw = vs[0] * vs[1]
                    updated_val = tf.reshape(weight_vec[idx:idx + sw], (vs[0], vs[1]))
                    idx += sw

                # bias vectors
                elif len(vs) == 1:
                    updated_val = weight_vec[idx:idx + vs[0]]
                    idx += vs[0]

                # assign variables (Casting necessary since scipy requires float64 type)
                v.assign(tf.cast(updated_val, dtype=tf.float32))

        def loss_grad(w):
            # update weights in model
            restore_weight(w)
            loss, grads, loss_bnd = self.compute_grad(xt_col, xt_bnd, u_bnd_sol,J,mu,penalty,ii,ic,ii_mu,ic_mu,nom)
            # vectorize gradients
            grad_vec = []
            for g in grads:
                grad_vec.extend(g.numpy().flatten())

            # gradient list to array
            # scipy-routines requires 64-bit floats
            loss = loss.numpy().astype(np.float64)
            self.instant_loss = loss
            grad_vec = np.array(grad_vec, dtype=np.float64)

            return loss, grad_vec

        return scipy.optimize.minimize(fun=loss_grad,
                                       x0=w0,
                                       jac=True,
                                       method='L-BFGS-B',
                                       callback=self.callback,
                                       options={'maxiter': lbfgs_num,
                                                'maxfun': 5000,
                                                'maxcor': 500,
                                                'maxls': 500,
                                                'ftol': 1.0 * np.finfo(float).eps}) #1.0 * np.finfo(float).eps
 ########################################################################################################################

    def predict_iron(self, xt):
        u_pred = self.ironmaxwell(xt)
        return u_pred
    def predict_coil(self, xt):
        u_pred = self.coilmaxwell(xt)
        return u_pred
 #############################################################################################################

    def train(self, adam_num, lbfgs_num):

        iron_x = scipy.io.loadmat('iron_x.mat') # iron 좌표
        iron_y = scipy.io.loadmat('iron_y.mat')

        coil_x = scipy.io.loadmat('coil_x.mat') # coil 좌표
        coil_y = scipy.io.loadmat('coil_y.mat')

        iron_J = scipy.io.loadmat('iron_J.mat')
        iron_mu = scipy.io.loadmat('iron_mu.mat')
        coil_J = scipy.io.loadmat('iron_J.mat')
        coil_mu = scipy.io.loadmat('iron_mu.mat')

        ini = scipy.io.loadmat('bnd.mat')

        inter_coil_x = scipy.io.loadmat('inter_coil_x.mat')
        inter_coil_y = scipy.io.loadmat('inter_coil_y.mat')
        icx = inter_coil_x['coil_inter_x']
        icy = inter_coil_y['coil_inter_y']
        ic = np.concatenate([icx, icy], axis=1) # interface 코일 데이터

        inter_coil_mu = scipy.io.loadmat('inter_coil_mu.mat')
        ic_mu = np.transpose(inter_coil_mu['mu_inter_coil'])

        nomvec = scipy.io.loadmat('nom_vec.mat')
        nom = nomvec['nom_vec']
        nom = tf.convert_to_tensor(nom, dtype=tf.float32)
        x_ini = np.transpose(ini['iron_bnd_x'])
        y_ini = np.transpose(ini['iron_bnd_y'])
        xt_bnd_data = np.concatenate([x_ini, y_ini], axis=1)
        tu_bnd_data = []

        for xt in xt_bnd_data:
            tu_bnd_data.append(0)
        tu_bnd_data = np.transpose(tu_bnd_data)

        # collocation point iron
        x_col_data = (iron_x['x'])
        y_col_data = (iron_y['y'])
        xy_col_data_iron = np.concatenate([x_col_data, y_col_data], axis=1)
        # coil
        x_col_data = (coil_x['coil_x'])
        y_col_data = (coil_y['coil_y'])
        xy_col_data_coil = np.concatenate([x_col_data, y_col_data], axis=1)

        xt_col_iron = tf.convert_to_tensor(xy_col_data_iron, dtype=tf.float32)
        xt_col_coil = tf.convert_to_tensor(xy_col_data_coil, dtype=tf.float32)

        xt_bnd = tf.convert_to_tensor(xt_bnd_data, dtype=tf.float32)
        u_bnd_sol = tf.convert_to_tensor(tu_bnd_data, dtype=tf.float32)

        ic = tf.convert_to_tensor(ic, dtype=tf.float32)
        ic_mu = tf.convert_to_tensor(ic_mu, dtype=tf.float32)
        # Start timer

        self.load_weights("C:/Users/user/Desktop/1-Cars (2 cases)/save_weights/maxwell/new_test/")

        t0 = time()

        self.train_with_adam(xt_col_iron,xt_col_coil, xt_bnd, u_bnd_sol, adam_num,ic,nom)

        print('\nComputation time of adam: {} seconds'.format(time() - t0))

        self.save_weights("C:/Users/user/Desktop/1-Cars (2 cases)/save_weights/maxwell/new_test/")
        np.savetxt('C:/Users/user/Desktop/1-Cars (2 cases)/save_weights/maxwell/new_test/loss.txt', self.train_loss_history)
        train_loss_history = np.array(self.train_loss_history)

        plt.plot(train_loss_history[:, 0], train_loss_history[:, 1])
        plt.yscale("log")
        plt.show()

 #############################################################################################################
# main
def main():

    adam_num = 100000
    lbfgs_num = 1000
    agent = MaxwellPinn()

    agent.train(adam_num, lbfgs_num)

if __name__=="__main__":
    main()

It's my code.

Including mini-batch. Changing the model


问:
Android - Overlay view is drawn at status bar in only tablet or foldable model
I made overlay view and I set this layout params like that.

```<code>DisplayMetrics matrix = new DisplayMetrics();
mManager.getDefaultDisplay().getMetrics(matrix);
mParams = new WindowManager.LayoutParams(
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
        WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
        PixelFormat.TRANSLUCENT
);

mParams.alpha = 0.8f;
mParams.gravity = Gravity.TOP | Gravity.LEFT;
mParams.x = 0;
mParams.y = 0;
</code>```

But in this case, in tablet or fold model, overlay view is drawn from status bar.
Any other phone are not.. It didn't approach status bar..

how do i solve it??

I want to make overlay view is not drawn at status bar. Only under the status bar.

I put params.y to specific value but all tablet and foldable model have not same status bar.
So It is not what i want.

Body:
I made overlay view and I set this layout params like that.

DisplayMetrics matrix = new DisplayMetrics();
mManager.getDefaultDisplay().getMetrics(matrix);
mParams = new WindowManager.LayoutParams(
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.WRAP_CONTENT,
        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
        WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
        PixelFormat.TRANSLUCENT
);

mParams.alpha = 0.8f;
mParams.gravity = Gravity.TOP | Gravity.LEFT;
mParams.x = 0;
mParams.y = 0;

But in this case, in tablet or fold model, overlay view is drawn from status bar.
Any other phone are not.. It didn't approach status bar..

how do i solve it??

I want to make overlay view is not drawn at status bar. Only under the status bar.

I put params.y to specific value but all tablet and foldable model have not same status bar.
So It is not what i want.


问:
Cannot instrument class XXX because it or one of its supertypes could not be initialized
Because jdk17 not compatible with, so i change to mockito 4.9.0. And that leads to @SuppressStaticInitializationFor will can't be used, but i need some classes not initialized statically

```<code>@RunWith(MockitoJUnitRunner.class)
//@PrepareForTest({NonWorkingDayHelper.class, TaskService.class})
//@SuppressStaticInitializationFor("com.ecquaria.cloud.entity.nonworkingday.NonWorkingDayHelper")
public class TaskManagerTest {

    @Before
    public void setUp(){
        Mockito.mockStatic(NonWorkingDayHelper.class);
        Mockito.mockStatic(TaskService.class);
    }
    @Test
    public void testUpdateSLARemainInDays() throws Exception {
        Mockito.when(NonWorkingDayHelper.isNonWorkingDay(any(Date.class))).thenReturn(false);
        Mockito.when(TaskService.getInstance()).thenReturn(Mockito.mock(TaskService.class));
        TaskManager.updateSLARemainInDays();

    }
}
</code>```

error info

in mockito 4.X, have any ways can Instead of @SuppressStaticInitializationFor

Body:
Because jdk17 not compatible with, so i change to mockito 4.9.0. And that leads to @SuppressStaticInitializationFor will can't be used, but i need some classes not initialized statically

@RunWith(MockitoJUnitRunner.class)
//@PrepareForTest({NonWorkingDayHelper.class, TaskService.class})
//@SuppressStaticInitializationFor("com.ecquaria.cloud.entity.nonworkingday.NonWorkingDayHelper")
public class TaskManagerTest {

    @Before
    public void setUp(){
        Mockito.mockStatic(NonWorkingDayHelper.class);
        Mockito.mockStatic(TaskService.class);
    }
    @Test
    public void testUpdateSLARemainInDays() throws Exception {
        Mockito.when(NonWorkingDayHelper.isNonWorkingDay(any(Date.class))).thenReturn(false);
        Mockito.when(TaskService.getInstance()).thenReturn(Mockito.mock(TaskService.class));
        TaskManager.updateSLARemainInDays();

    }
}

error info

in mockito 4.X, have any ways can Instead of @SuppressStaticInitializationFor


问:
Displaying keyboard below the the selected line using multi-line TextField
so I've got the following layout with the following  TextInputEditText :

```<code><com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/note"
    android:layout_marginTop="@dimen/layout_margin_default"
    app:startIconDrawable="@drawable/baseline_notes_24">
    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        />
</com.google.android.material.textfield.TextInputLayout>
</code>```

Right now, when I select to write inside the TextInputEditText the keyboard automatically displays below the TextInputEditText:

Now, what I want to is that rather displaying the keyboard below the TextInputEditText, I want the display to keyboard below the current "selected" line, which should look like this:

Example video how it should look like:
https://jumpshare.com/v/TAO6jo1jdnRZDhYyzrkY

How can this be solved in the right way?
I've tried using android:windowsoftinputmode, but I couldn't find the appropriate attribute.

I'm assuming there is not much leeway when it comes to the displaying the keyboard?

Body:
so I've got the following layout with the following  TextInputEditText :

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/note"
    android:layout_marginTop="@dimen/layout_margin_default"
    app:startIconDrawable="@drawable/baseline_notes_24">
    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        />
</com.google.android.material.textfield.TextInputLayout>

Right now, when I select to write inside the TextInputEditText the keyboard automatically displays below the TextInputEditText:

Now, what I want to is that rather displaying the keyboard below the TextInputEditText, I want the display to keyboard below the current "selected" line, which should look like this:

Example video how it should look like:
https://jumpshare.com/v/TAO6jo1jdnRZDhYyzrkY

How can this be solved in the right way?
I've tried using android:windowsoftinputmode, but I couldn't find the appropriate attribute.

I'm assuming there is not much leeway when it comes to the displaying the keyboard?


问:
Where doe the init code go in AWS C++ lambda functions?
The AWS Lambda docs emphasize the importance of static initialization; the example code is in Python. My question is where initialization code goes in a C++ function (using the AWS C++ runtime).

The S3 example seems relevant (quoted below). If it's possible to do my expensive initialization code in main(), and then pass any relevant objects to a (C++) lambda function, then that's the answer to my question. I'm just uncertain how AWS uses the C++ code.

```<code>int main()
{
    using namespace Aws;
    SDKOptions options;
    options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace;
    options.loggingOptions.logger_create_fn = GetConsoleLoggerFactory();
    InitAPI(options);
    {
        Client::ClientConfiguration config;
        config.region = Aws::Environment::GetEnv("AWS_REGION");
        config.caFile = "/etc/pki/tls/certs/ca-bundle.crt";

        auto credentialsProvider = Aws::MakeShared<Aws::Auth::EnvironmentAWSCredentialsProvider>(TAG);
        S3::S3Client client(credentialsProvider, config);
        auto handler_fn = [&client](aws::lambda_runtime::invocation_request const& req) {
            return my_handler(req, client);
        };
        run_handler(handler_fn);
    }
    ShutdownAPI(options);
    return 0;
}
</code>```

Body:
The AWS Lambda docs emphasize the importance of static initialization; the example code is in Python. My question is where initialization code goes in a C++ function (using the AWS C++ runtime).

The S3 example seems relevant (quoted below). If it's possible to do my expensive initialization code in main(), and then pass any relevant objects to a (C++) lambda function, then that's the answer to my question. I'm just uncertain how AWS uses the C++ code.

int main()
{
    using namespace Aws;
    SDKOptions options;
    options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Trace;
    options.loggingOptions.logger_create_fn = GetConsoleLoggerFactory();
    InitAPI(options);
    {
        Client::ClientConfiguration config;
        config.region = Aws::Environment::GetEnv("AWS_REGION");
        config.caFile = "/etc/pki/tls/certs/ca-bundle.crt";

        auto credentialsProvider = Aws::MakeShared<Aws::Auth::EnvironmentAWSCredentialsProvider>(TAG);
        S3::S3Client client(credentialsProvider, config);
        auto handler_fn = [&client](aws::lambda_runtime::invocation_request const& req) {
            return my_handler(req, client);
        };
        run_handler(handler_fn);
    }
    ShutdownAPI(options);
    return 0;
}


问:
PrintJS : With repeatable header and footer, tbody content overlaps with header and footer in chrome but not on firefox
I am trying to use printJS to print a report using the content inside an html div and it is required to have repeating headers and footers on each page of the report. I used the solution I found in this link to generate the repeating headers and footers. However, the problem is that the content inside the tbody element overlaps with the content in the footer and header on chrome but not on firefox.  The html code for the report is as something like this:

```<code><div class="d-none font-weight-bold" id="printable_report">
    <table>
        <thead>
            <tr>
                <th class="text-center"><div class="header-space"> </div></th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <td class="text-center"><div class="footer-space"> </div></td>
            </tr>
        </tfoot>
        <tbody>

                    <tr>
                        <td>
                            <div class="page">
                             ……content……

                            </div>
                            <div class="header-fill">I am  the header</div>
                            <div class="footer-fill">I am the footer</div>
                        </td>
                    </tr>

        </tbody>
    </table>
</div>
</code>```

I am using printJS plugin (https://github.com/crabbly/Print.js) for printing the document.

The printJS code for printing the report is this:

```<code>printJS({
   documentTitle:"ETP Water Report",
   printable: 'printable_report',
   type: 'html',
   targetStyles:"['*']",
   font_size:"",
 style:"@page{size: A4;margin-top:20mm;margin-bottom:20mm;}.page{page-break-after:always;} .header-space{height:100px !important;}.footer-space{height:100px !important;} .header-fill{position: fixed !important;top: 0 !important;height: 100px !important;width: 100% !important;}.footer-fill{position: fixed !important;bottom: 0 !important;height: 100px !important;width: 100% !important;} thead{display: table-header-group !important;}tfoot{display: table-footer-group !important;}"
});
</code>```

Here are the images showing the mentioned problem:

Content overlap on chrome

No content overlap on firefox

The overlap is happening  on google-chrome and not on firefox.
Is there a way to resolve this issue? How do I prevent content overlap with header & footer on chrome? Somebody please help.

Body:
I am trying to use printJS to print a report using the content inside an html div and it is required to have repeating headers and footers on each page of the report. I used the solution I found in this link to generate the repeating headers and footers. However, the problem is that the content inside the tbody element overlaps with the content in the footer and header on chrome but not on firefox.  The html code for the report is as something like this:

                             ……content……

I am  the header

I am the footer

I am using printJS plugin (https://github.com/crabbly/Print.js) for printing the document.

The printJS code for printing the report is this:

printJS({
   documentTitle:"ETP Water Report",
   printable: 'printable_report',
   type: 'html',
   targetStyles:"['*']",
   font_size:"",
 style:"@page{size: A4;margin-top:20mm;margin-bottom:20mm;}.page{page-break-after:always;} .header-space{height:100px !important;}.footer-space{height:100px !important;} .header-fill{position: fixed !important;top: 0 !important;height: 100px !important;width: 100% !important;}.footer-fill{position: fixed !important;bottom: 0 !important;height: 100px !important;width: 100% !important;} thead{display: table-header-group !important;}tfoot{display: table-footer-group !important;}"
});

Here are the images showing the mentioned problem:

Content overlap on chrome

No content overlap on firefox

The overlap is happening  on google-chrome and not on firefox.
Is there a way to resolve this issue? How do I prevent content overlap with header & footer on chrome? Somebody please help.


问:
How can i update a number of records with one Rest call?
I currently make this call to update a field in a db

```<code>            var client = new RestClient(myurl);
            var request = new RestRequest($"api/user/{userId}", Method.PATCH);
            request.AddHeader("Authorization", $"Bearer {MyToken}");
            dynamic body = new JObject();
            body.Satus = isActive;
            request.AddJsonBody(body.ToString());
            var response = client.Execute(request);
            return response.IsSuccessful ?
                string.Empty : response.Content;
</code>```

isActive is a boolean , true or false depending on what is passed in

But I have a list of userId's like

ListId is
123
879
323
580
902

So I want to update the Status flag for all of these . So do I have to call this in a loop (which is a bit time intensive) or is there a quicker way

Is there a better way than this ?

```<code>foreach (id in ListId)
{
       var client = new RestClient(myurl);
       var request = new RestRequest($"api/user/{userId}", Method.PATCH);
       request.AddHeader("Authorization", $"Bearer {MyToken}");
       dynamic body = new JObject();
       body.Satus = isActive;
       request.AddJsonBody(body.ToString());
       var response = client.Execute(request);
       return response.IsSuccessful ?
            string.Empty : response.Content;
</code>```

}

Body:
I currently make this call to update a field in a db

            var client = new RestClient(myurl);
            var request = new RestRequest($"api/user/{userId}", Method.PATCH);
            request.AddHeader("Authorization", $"Bearer {MyToken}");
            dynamic body = new JObject();
            body.Satus = isActive;
            request.AddJsonBody(body.ToString());
            var response = client.Execute(request);
            return response.IsSuccessful ?
                string.Empty : response.Content;

isActive is a boolean , true or false depending on what is passed in

But I have a list of userId's like

ListId is
123
879
323
580
902

So I want to update the Status flag for all of these . So do I have to call this in a loop (which is a bit time intensive) or is there a quicker way

Is there a better way than this ?

foreach (id in ListId)
{
       var client = new RestClient(myurl);
       var request = new RestRequest($"api/user/{userId}", Method.PATCH);
       request.AddHeader("Authorization", $"Bearer {MyToken}");
       dynamic body = new JObject();
       body.Satus = isActive;
       request.AddJsonBody(body.ToString());
       var response = client.Execute(request);
       return response.IsSuccessful ?
            string.Empty : response.Content;

}


问:
Reading kinesis streams continuously and do CRUD in Postgres or any DBMS tables
I am looking for a way to read kinesis structured streaming in Databricks. I am able to use a spark cluster to continuously read streaming data. However I need a way now to get those timely records and do CRUD into Postgres or any DBMS tables. Is there a way I can do this only via Databricks?</p>


问:
Problem transferring data to firebase using Sim7600CE, http
I am using ESP32 integrated Sim7600CE module to transfer data to Firebase Realtime database using http and got 400 Bad Request, please help me to solve this.

13:36:48.693 -> Status code: 400

13:36:48.833 -> Response:

13:36:48.833 -> <title>400 The plain HTTP request was sent to HTTPS port</title>

13:36:48.833 ->

13:36:48.833 ->
400 Bad Request

```<code>#define TINY_GSM_MODEM_SIM7600
#define TINY_GSM_RX_BUFFER 650

#include <ArduinoJson.h>
#include <TinyGsmClient.h>
#include <ArduinoHttpClient.h> //https://github.com/arduino-libraries/ArduinoHttpClient
#include "TinyGsmClient.h"

#define SIM_RESET_PIN 15
#define SIM_AT_BAUDRATE 115200
#define GSM_PIN ""
#define SIM_TX 17
#define SIM_RX 16

const char FIREBASE_HOST[] = "smartgrid1-930b0-default-rtdb.firebaseio.com";
const String FIREBASE_AUTH  = "zezoyo69fX9eqPDpjaom6CJAyXhnW081GlJ4ah5c";
const String FIREBASE_PATH  = "/";
const int SSL_PORT          = 443;

char APN[]  = "v-internet"; //
char USER[] = "";
char PASS[] = "";

TinyGsm modem(Serial2);
TinyGsmClient gsm_client_secure_modem(modem);
HttpClient http_client = HttpClient(gsm_client_secure_modem, FIREBASE_HOST, SSL_PORT);

unsigned long previousMillis = 0;

// Hàm dùng để thiết lập modem SIM tạo kết nối GPRS
bool connectToGPRS() {
  // Unlock SIM (nếu có)
  if (GSM_PIN && modem.getSimStatus() != 3)
    modem.simUnlock(GSM_PIN);

  Serial.println("Ket noi toi nha mang...");
  while (!modem.waitForNetwork(60000L)) {
    Serial.println("._.");
    delay(5000);
  }

  // Nếu không thấy sóng từ nhà mạng thì thoát hàm
  if (!modem.isNetworkConnected())
    return false;

  Serial.println("Ket noi GPRS");
  if (!modem.gprsConnect(APN)) {// Hàm kết nối tới gprs trả về true/false cho biết có kết nối được hay chưa
    Serial.print("Khong the ket noi GPRS - ");
    Serial.println(APN);
    return false;
  }

  // Kiểm tra lại lần nữa để chắc cú
  if (modem.isGprsConnected()){
    Serial.println("Da ket noi duoc GPRS!");
    return true;
  }
  return false;
}

// Hàm khởi động module SIM
bool initModemSIM() {
  Serial.println("Bat dau khoi dong module SIM");

  // Đặt chân reset của module xuống LOW để chạy
  pinMode(SIM_RESET_PIN, OUTPUT);
  digitalWrite(SIM_RESET_PIN, LOW);
  delay(5000);

  Serial2.begin(SIM_AT_BAUDRATE);// Module SIM giao tiếp với ESP qua cổng Serial2 bằng AT cmds

  if (!modem.restart()) {
    Serial.println("Khong the khoi dong lai module SIM => Co loi");
    return false;
  }
  return true;
}

void setup() {
  Serial.begin(115200);

  if (initModemSIM()){
    while(!connectToGPRS()) delay(100);
  }
   if (modem.isGprsConnected()) {
    Serial.print(F("Connecting to "));
    Serial.println(APN);
  if (!modem.gprsConnect(APN, USER, PASS))
  {
    Serial.println(" fail");
    delay(1000);
    return;
  }
}
  if (initModemSIM()){
    while(!connectToGPRS()) delay(100);
  }
  modem.restart();
  String modemInfo = modem.getModemInfo();
  Serial.print("Modem: ");
  Serial.println(modemInfo);

  http_client.setHttpResponseTimeout(10 * 1000); //^0 secs timeout
}

void loop() {
    Serial.print(F("Connecting to "));
    Serial.println(APN);

  if (!modem.gprsConnect(APN, USER, PASS))
  {
    Serial.println(" fail");
    delay(1000);
    return;
  }
 Serial.println(" OK");

  http_client.connect(FIREBASE_HOST, SSL_PORT);

  while (true) {
    if (!http_client.connected())
    {
      Serial.println();
      http_client.stop();// Shutdown
      Serial.println("HTTP  not connect");
      break;
    }
    else
    {
      dht_loop();
    }
  }
}

void PostToFirebase(const char* method, const String & path , const String & data, HttpClient* http)
{
  String response;
  int statusCode = 0;
  http->connectionKeepAlive(); // Currently, this is needed for HTTPS

  String url;
  if (path[0] != '/')
  {
    url = "/";
  }
  url += path + ".json";
  url += "?auth=" + FIREBASE_AUTH;
  Serial.print("POST:");
  Serial.println(url);
  Serial.print("Data:");
  Serial.println(data);

  String contentType = "application/json";
  http->put(url, contentType, data);

  statusCode = http->responseStatusCode();
  Serial.print("Status code: ");
  Serial.println(statusCode);
  response = http->responseBody();
  Serial.print("Response: ");
  Serial.println(response);

//  if (!http->connected())
//  {
//    Serial.println();
//    http->stop();// Shutdown
//    Serial.println("HTTP POST disconnected");
//  }
}

void dht_loop()
{
  String h = String(random(1,100));
  delay(100);

  Serial.print("h = ");
  Serial.println(h);

  String Data = "{";
  Data += "\"Sim\":" + h + "";
  Data += "}";

  PostToFirebase("PATCH", FIREBASE_PATH, Data, &http_client);

}
</code>```

Body:
I am using ESP32 integrated Sim7600CE module to transfer data to Firebase Realtime database using http and got 400 Bad Request, please help me to solve this.

13:36:48.693 -> Status code: 400

13:36:48.833 -> Response:

13:36:48.833 -> <title>400 The plain HTTP request was sent to HTTPS port</title>

13:36:48.833 ->

13:36:48.833 ->
400 Bad Request

#define TINY_GSM_MODEM_SIM7600
#define TINY_GSM_RX_BUFFER 650

#include <ArduinoJson.h>
#include <TinyGsmClient.h>
#include <ArduinoHttpClient.h> //https://github.com/arduino-libraries/ArduinoHttpClient
#include "TinyGsmClient.h"

#define SIM_RESET_PIN 15
#define SIM_AT_BAUDRATE 115200
#define GSM_PIN ""
#define SIM_TX 17
#define SIM_RX 16

const char FIREBASE_HOST[] = "smartgrid1-930b0-default-rtdb.firebaseio.com";
const String FIREBASE_AUTH  = "zezoyo69fX9eqPDpjaom6CJAyXhnW081GlJ4ah5c";
const String FIREBASE_PATH  = "/";
const int SSL_PORT          = 443;

char APN[]  = "v-internet"; //
char USER[] = "";
char PASS[] = "";

TinyGsm modem(Serial2);
TinyGsmClient gsm_client_secure_modem(modem);
HttpClient http_client = HttpClient(gsm_client_secure_modem, FIREBASE_HOST, SSL_PORT);

unsigned long previousMillis = 0;

// Hàm dùng để thiết lập modem SIM tạo kết nối GPRS
bool connectToGPRS() {
  // Unlock SIM (nếu có)
  if (GSM_PIN && modem.getSimStatus() != 3)
    modem.simUnlock(GSM_PIN);

  Serial.println("Ket noi toi nha mang...");
  while (!modem.waitForNetwork(60000L)) {
    Serial.println("._.");
    delay(5000);
  }

  // Nếu không thấy sóng từ nhà mạng thì thoát hàm
  if (!modem.isNetworkConnected())
    return false;

  Serial.println("Ket noi GPRS");
  if (!modem.gprsConnect(APN)) {// Hàm kết nối tới gprs trả về true/false cho biết có kết nối được hay chưa
    Serial.print("Khong the ket noi GPRS - ");
    Serial.println(APN);
    return false;
  }

  // Kiểm tra lại lần nữa để chắc cú
  if (modem.isGprsConnected()){
    Serial.println("Da ket noi duoc GPRS!");
    return true;
  }
  return false;
}

// Hàm khởi động module SIM
bool initModemSIM() {
  Serial.println("Bat dau khoi dong module SIM");

  // Đặt chân reset của module xuống LOW để chạy
  pinMode(SIM_RESET_PIN, OUTPUT);
  digitalWrite(SIM_RESET_PIN, LOW);
  delay(5000);

  Serial2.begin(SIM_AT_BAUDRATE);// Module SIM giao tiếp với ESP qua cổng Serial2 bằng AT cmds

  if (!modem.restart()) {
    Serial.println("Khong the khoi dong lai module SIM => Co loi");
    return false;
  }
  return true;
}

void setup() {
  Serial.begin(115200);

  if (initModemSIM()){
    while(!connectToGPRS()) delay(100);
  }
   if (modem.isGprsConnected()) {
    Serial.print(F("Connecting to "));
    Serial.println(APN);
  if (!modem.gprsConnect(APN, USER, PASS))
  {
    Serial.println(" fail");
    delay(1000);
    return;
  }
}
  if (initModemSIM()){
    while(!connectToGPRS()) delay(100);
  }
  modem.restart();
  String modemInfo = modem.getModemInfo();
  Serial.print("Modem: ");
  Serial.println(modemInfo);

  http_client.setHttpResponseTimeout(10 * 1000); //^0 secs timeout
}

void loop() {
    Serial.print(F("Connecting to "));
    Serial.println(APN);

  if (!modem.gprsConnect(APN, USER, PASS))
  {
    Serial.println(" fail");
    delay(1000);
    return;
  }
 Serial.println(" OK");

  http_client.connect(FIREBASE_HOST, SSL_PORT);

  while (true) {
    if (!http_client.connected())
    {
      Serial.println();
      http_client.stop();// Shutdown
      Serial.println("HTTP  not connect");
      break;
    }
    else
    {
      dht_loop();
    }
  }
}

void PostToFirebase(const char* method, const String & path , const String & data, HttpClient* http)
{
  String response;
  int statusCode = 0;
  http->connectionKeepAlive(); // Currently, this is needed for HTTPS

  String url;
  if (path[0] != '/')
  {
    url = "/";
  }
  url += path + ".json";
  url += "?auth=" + FIREBASE_AUTH;
  Serial.print("POST:");
  Serial.println(url);
  Serial.print("Data:");
  Serial.println(data);

  String contentType = "application/json";
  http->put(url, contentType, data);

  statusCode = http->responseStatusCode();
  Serial.print("Status code: ");
  Serial.println(statusCode);
  response = http->responseBody();
  Serial.print("Response: ");
  Serial.println(response);

//  if (!http->connected())
//  {
//    Serial.println();
//    http->stop();// Shutdown
//    Serial.println("HTTP POST disconnected");
//  }
}

void dht_loop()
{
  String h = String(random(1,100));
  delay(100);

  Serial.print("h = ");
  Serial.println(h);

  String Data = "{";
  Data += "\"Sim\":" + h + "";
  Data += "}";

  PostToFirebase("PATCH", FIREBASE_PATH, Data, &http_client);

}


问:
Is it ok to throw exceptions in Laravel AppServiceProvider.php?
I've created a Facade named "CartService" and I've bound it in AppServiceProvider.php
CartService should work only if a user is authenticated; if not, an exception must be thrown.

I have 3 questions:

Is it ok to throw exceptions in AppServiceProvider.php?

If it is ok, how should my colleague know the Facade throws an exception? Because there is no docBlock.

is there a better way to handle this task?

My AppServiceProvider.php is like below:

public function register()
    {
        $this->app->bind(CartService::class, function () {
            if ($userId = Auth::id()) {
                return new CartService($userId);
            }

            throw new LoginRequiredException("CartService works only if the user is authenticated.");
        });
    }
```