问:
I want to put a condition on order by if 'All' order by should be descending otherwise ascending in pgplsql?
```<code>matching_ids_json = array_to_json(array(
        select jsonb_build_object(
                    'id',sbtsk.db_id ,
                    'full_count', count(sbtsk.db_id) OVER()
               )
          from public.cl_tx_sbtsk sbtsk
         inner join cl_tx_srvc_req srvc_req
            on srvc_req.db_id = sbtsk.srvc_req_id
           and srvc_req.is_deleted is not true
         inner join cl_cf_sbtsk_statuses sbtsk_status
            on sbtsk_status.status_key = sbtsk.status
           and sbtsk_status.sbtsk_type_id = sbtsk.sbtsk_type
         inner join cl_tx_users assgne
            on assgne.usr_id = any(sbtsk.assigned_to)
         where (
                    srvc_req_id_ = 0
                    or sbtsk.srvc_req_id = srvc_req_id_
               )
           and (
                    srvc_req_id_ > 0
                    or filter_sbtsk_assignee is not null
                    or filter_sbtsk_assigner is not null
                    or filter_sbtsk_by_id is not null
                    or usr_id_ = any(sbtsk.assigned_to) -- get own tasks if srvc_req_id is not sent
               )
           and (
                    filter_sbtsk_assignee is null
                    or filter_sbtsk_assignee = any(sbtsk.assigned_to) -- get task for the specific assignee
               )
           and (
                    filter_sbtsk_assigner is null
                    or filter_sbtsk_assigner = sbtsk.c_by -- get task assigned by a user
               )
           and (
                    filter_sbtsk_by_id is null
                    or sbtsk.db_id = filter_sbtsk_by_id::bigint -- get subtask by id
               )
           and (
                    search_query = ''
                    or filter_sbtsk_by_id is not null -- avoiding search query as it will contain the db id
                    or jsonb_extract_path_text(sbtsk.form_data,'sbtsk_remarks') ilike filter_search_query
                    or srvc_req.display_code ilike filter_search_query
                    or jsonb_extract_path_text(srvc_req.form_data,'cust_full_name') ilike filter_search_query
                    or jsonb_extract_path_text(srvc_req.form_data,'request_description') ilike filter_search_query
                    or assgne."name" ilike filter_search_query
               )
           and (
                    cardinality(filter_sbtsk_types) = 0
                    or
                    sbtsk.sbtsk_type = any(filter_sbtsk_types)
               )
           and (
                    cardinality(filter_sbtsk_status_category) = 0
                    or
                    sbtsk_status.status_type::text = any(filter_sbtsk_status_category)
               )
           and (
                    srvc_req_id_ > 0
                    or
                    cardinality(filter_sbtsk_status_category) > 0
                    or
                    search_query <> ''
                    or
                    sbtsk_status.status_type::text <> 'CLOSED'
               )
           and (
                    cardinality(filter_sbtsk_due_day) = 0
                    or
                    (
                        'today' = any(filter_sbtsk_due_day)
                        and DATE(sbtsk.start_time) = DATE(now() at time zone 'utc')
                        and DATE(sbtsk.start_time::timestamp at time zone 'utc' at time zone 'Asia/kolkata') = DATE(now() at time zone 'utc')
                    )
                    or
                    (
                        'upcoming' = any(filter_sbtsk_due_day)
                        and DATE(sbtsk.start_time) > DATE(now() at time zone 'utc')
                        and DATE(sbtsk.start_time::timestamp at time zone 'utc' at time zone 'Asia/kolkata') > DATE(now() at time zone 'utc')
                    )
                    or
                    (
                        'overdue' = any(filter_sbtsk_due_day)
                        and sbtsk.start_time < now() at time zone 'utc'
                        and sbtsk_status.status_type = 'ACTIVE'::status_types
                    )
                    or
                    (
                        'all' = any(filter_sbtsk_due_day)
                        and sbtsk_status.status_type = 'ACTIVE'::status_types
                    )
               )
           and (
                    cardinality(filter_priority) = 0
                    or
                    sbtsk.priority = any(filter_priority)
               )
           and (
                    cardinality(filter_sbtsk_status_key) = 0
                    or
                    sbtsk_status.title = any(filter_sbtsk_status_key)
               )
           and (
                    cardinality(filter_sbtsk_assign_date) = 0
                    or DATE((sbtsk.start_time)::timestamp at time zone 'utc' at time zone 'Asia/kolkata') >= DATE((filter_sbtsk_assign_date_from)::timestamp at time zone 'utc' at time zone 'Asia/kolkata')
                    and DATE((sbtsk.end_time)::timestamp at time zone 'utc' at time zone 'Asia/kolkata') <= DATE((filter_sbtsk_assign_date_to)::timestamp at time zone 'utc' at time zone 'Asia/kolkata')
               )
           and sbtsk.is_deleted is not true
         group by srvc_req.db_id,sbtsk.db_id
         order by sbtsk.start_time asc
         limit page_size
        offset ( (page_no - 1) * page_size )
    ));
</code>```

Here matching_ids_json  is ascending i want to make the order by conditional
if its 'All' then descending otherwise the order by should be descending.

Body:
matching_ids_json = array_to_json(array(
        select jsonb_build_object(
                    'id',sbtsk.db_id ,
                    'full_count', count(sbtsk.db_id) OVER()
               )
          from public.cl_tx_sbtsk sbtsk
         inner join cl_tx_srvc_req srvc_req
            on srvc_req.db_id = sbtsk.srvc_req_id
           and srvc_req.is_deleted is not true
         inner join cl_cf_sbtsk_statuses sbtsk_status
            on sbtsk_status.status_key = sbtsk.status
           and sbtsk_status.sbtsk_type_id = sbtsk.sbtsk_type
         inner join cl_tx_users assgne
            on assgne.usr_id = any(sbtsk.assigned_to)
         where (
                    srvc_req_id_ = 0
                    or sbtsk.srvc_req_id = srvc_req_id_
               )
           and (
                    srvc_req_id_ > 0
                    or filter_sbtsk_assignee is not null
                    or filter_sbtsk_assigner is not null
                    or filter_sbtsk_by_id is not null
                    or usr_id_ = any(sbtsk.assigned_to) -- get own tasks if srvc_req_id is not sent
               )
           and (
                    filter_sbtsk_assignee is null
                    or filter_sbtsk_assignee = any(sbtsk.assigned_to) -- get task for the specific assignee
               )
           and (
                    filter_sbtsk_assigner is null
                    or filter_sbtsk_assigner = sbtsk.c_by -- get task assigned by a user
               )
           and (
                    filter_sbtsk_by_id is null
                    or sbtsk.db_id = filter_sbtsk_by_id::bigint -- get subtask by id
               )
           and (
                    search_query = ''
                    or filter_sbtsk_by_id is not null -- avoiding search query as it will contain the db id
                    or jsonb_extract_path_text(sbtsk.form_data,'sbtsk_remarks') ilike filter_search_query
                    or srvc_req.display_code ilike filter_search_query
                    or jsonb_extract_path_text(srvc_req.form_data,'cust_full_name') ilike filter_search_query
                    or jsonb_extract_path_text(srvc_req.form_data,'request_description') ilike filter_search_query
                    or assgne."name" ilike filter_search_query
               )
           and (
                    cardinality(filter_sbtsk_types) = 0
                    or
                    sbtsk.sbtsk_type = any(filter_sbtsk_types)
               )
           and (
                    cardinality(filter_sbtsk_status_category) = 0
                    or
                    sbtsk_status.status_type::text = any(filter_sbtsk_status_category)
               )
           and (
                    srvc_req_id_ > 0
                    or
                    cardinality(filter_sbtsk_status_category) > 0
                    or
                    search_query <> ''
                    or
                    sbtsk_status.status_type::text <> 'CLOSED'
               )
           and (
                    cardinality(filter_sbtsk_due_day) = 0
                    or
                    (
                        'today' = any(filter_sbtsk_due_day)
                        and DATE(sbtsk.start_time) = DATE(now() at time zone 'utc')
                        and DATE(sbtsk.start_time::timestamp at time zone 'utc' at time zone 'Asia/kolkata') = DATE(now() at time zone 'utc')
                    )
                    or
                    (
                        'upcoming' = any(filter_sbtsk_due_day)
                        and DATE(sbtsk.start_time) > DATE(now() at time zone 'utc')
                        and DATE(sbtsk.start_time::timestamp at time zone 'utc' at time zone 'Asia/kolkata') > DATE(now() at time zone 'utc')
                    )
                    or
                    (
                        'overdue' = any(filter_sbtsk_due_day)
                        and sbtsk.start_time < now() at time zone 'utc'
                        and sbtsk_status.status_type = 'ACTIVE'::status_types
                    )
                    or
                    (
                        'all' = any(filter_sbtsk_due_day)
                        and sbtsk_status.status_type = 'ACTIVE'::status_types
                    )
               )
           and (
                    cardinality(filter_priority) = 0
                    or
                    sbtsk.priority = any(filter_priority)
               )
           and (
                    cardinality(filter_sbtsk_status_key) = 0
                    or
                    sbtsk_status.title = any(filter_sbtsk_status_key)
               )
           and (
                    cardinality(filter_sbtsk_assign_date) = 0
                    or DATE((sbtsk.start_time)::timestamp at time zone 'utc' at time zone 'Asia/kolkata') >= DATE((filter_sbtsk_assign_date_from)::timestamp at time zone 'utc' at time zone 'Asia/kolkata')
                    and DATE((sbtsk.end_time)::timestamp at time zone 'utc' at time zone 'Asia/kolkata') <= DATE((filter_sbtsk_assign_date_to)::timestamp at time zone 'utc' at time zone 'Asia/kolkata')
               )
           and sbtsk.is_deleted is not true
         group by srvc_req.db_id,sbtsk.db_id
         order by sbtsk.start_time asc
         limit page_size
        offset ( (page_no - 1) * page_size )
    ));

Here matching_ids_json  is ascending i want to make the order by conditional
if its 'All' then descending otherwise the order by should be descending.


来源: stackexchange

问:
Get name from option list <multiselect>
I need to create several <multiselects>. In doing this I must identify the clicked list in some way with the purpose of passing this name to the method that makes push into the list.

By example, given these lists:

```<code> List A               |    List B         |    List C          |
 --------------------------------------------------------------|
 {tag:xz   , code:1}  |{tag:pkrte,code:1} |{tag:Item1,code:1 } |
 {tag:ac   , code:2}, |{tag:bnetf,code:2},|{tag:Item2,code:2 },|
 {tag:bz   , code:3}, |{tag:erert,code:3},|{tag:Item3,code:3 },|
 {tag:hy   , code:4}, |{tag:kjerx,code:4},|                    |
 {tag:yjer , code:5}, |                   |                    |
</code>```

I have defined this multiselects:

(simplified code to exemplify)

<multiselect             |<multiselect             |<multiselect
  v-model="SelAlergies1" |  v-model="SelAlergies2" |  v-model="SelAlergies3"
  :height="300"          |  :height="300"          |  :height="300"
  :options="ListA"       |  :options="ListB"       |  :options="ListC"
  :multiple="true"       |  :multiple="true"       |  :multiple="true"
  :taggable="true"       |  :taggable="true"       |  :taggable="true"
  placeholder="Alergies1"|  placeholder="Alergies2"|  placeholder="Alergies3"
  @tag="addTag('ListA')" |  @tag="addTag('ListB')" |  @tag="addTag('ListC')"
  label="Tag"            |  label="Tag"            |  label="Tag"
  track-by="Code" >      |  track-by="Code">       |  track-by="Code" >
</multiselect>           |</multiselect>           |</multiselect>   ```
</div>
</div>
</p>
<p>I'm trying to send the list as a parameter in the event</p>
```@tag="addTag('ListA')"
```
<p>How can I pass as a parameter the name of the list (ListA, ListB. ListC )to indicate to the method which list should push?</p>
```addTag(newTag, listName ) {
 const tag = {
   Etiqueta: newTag,
 };
 this.listName.push(tag);
 this.listName.push(tag);`
},
```

How can I achieve this?

ContentLicense: CC BY-SA 4.0

Title: Get name from option list <multiselect>

Body:
I need to create several <multiselects>. In doing this I must identify the clicked list in some way with the purpose of passing this name to the method that makes push into the list.

By example, given these lists:

 List A               |    List B         |    List C          |
 --------------------------------------------------------------|
 {tag:xz   , code:1}  |{tag:pkrte,code:1} |{tag:Item1,code:1 } |
 {tag:ac   , code:2}, |{tag:bnetf,code:2},|{tag:Item2,code:2 },|
 {tag:bz   , code:3}, |{tag:erert,code:3},|{tag:Item3,code:3 },|
 {tag:hy   , code:4}, |{tag:kjerx,code:4},|                    |
 {tag:yjer , code:5}, |                   |                    |

I have defined this multiselects:

(simplified code to exemplify)

<multiselect             |<multiselect             |<multiselect
  v-model="SelAlergies1" |  v-model="SelAlergies2" |  v-model="SelAlergies3"
  :height="300"          |  :height="300"          |  :height="300"
  :options="ListA"       |  :options="ListB"       |  :options="ListC"
  :multiple="true"       |  :multiple="true"       |  :multiple="true"
  :taggable="true"       |  :taggable="true"       |  :taggable="true"
  placeholder="Alergies1"|  placeholder="Alergies2"|  placeholder="Alergies3"
  @tag="addTag('ListA')" |  @tag="addTag('ListB')" |  @tag="addTag('ListC')"
  label="Tag"            |  label="Tag"            |  label="Tag"
  track-by="Code" >      |  track-by="Code">       |  track-by="Code" >
</multiselect>           |</multiselect>           |</multiselect>

I'm trying to send the list as a parameter in the event

@tag="addTag('ListA')"

How can I pass as a parameter the name of the list (ListA, ListB. ListC )to indicate to the method which list should push?

addTag(newTag, listName ) {
 const tag = {
   Etiqueta: newTag,
 };
 this.listName.push(tag);
 this.listName.push(tag);`
},

How can I achieve this?


问:
In Javascript, Difference Between `new MyFunction()` and `new MyFunction`

Possible Duplicate:

  new MyClass(); vs new MyClass;

Given a Javascript function like...

```<code>var MyFunction = function() {
    /*  Any arbitrary Javascript */
}
</code>```

Are the two following lines of Javascript semantically exactly the same?

```<code>func_obj = new MyFunction()
</code>```

...

```<code>func_obj = new MyFunction
</code>```

i.e., is the () just syntactical sugar?

Thanks.

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  new MyClass(); vs new MyClass;

Given a Javascript function like...

var MyFunction = function() {
    /*  Any arbitrary Javascript */
}

Are the two following lines of Javascript semantically exactly the same?

func_obj = new MyFunction()

...

func_obj = new MyFunction

i.e., is the () just syntactical sugar?

Thanks.


问:
Raw folder in Android studio
Whenever I copy mp3 file to raw folder in Android studio it by default take it as yml file type ...please help me fix this

I try to make a app to stop and start service in background..but the raw folder store my song in yml file type...so it's not usable in my app..

Title: Raw folder in Android studio


问:
Cannot read properties of undefined reading 'getEntityValue' typeorm
I am creating a nestjs project with typeorm and postgresql. Here I am creating a user entity.

My entity will be like

```<code>{
    email: string,
    name: string,
    avatar: {
        public_key: string;
        url: string;
    }
}
</code>```

In avatar column I need to add a object with public_key and url.

I create two entity like this-

```<code>@Entity()
class Avatar {
    @Column({ type: "text", nullable: true })
    public_key: string;
    @Column({ type: "text", nullable: true })
    url: string;
}

@Entity()
@Tree("closure-table")
export class User {
    @PrimaryGeneratedColumn()
    id: number;
    @Column({ type: "text", nullable: false })
    userName: string;
    @Column({ type: "text", nullable: false })
    email: string;
    @Column({ type: "text", nullable: false })
    firstName: string;
    @Column({ type: "text", nullable: false })
    lastName: string;
    @Column({ type: "text", nullable: false, select: false })
    password: string;
    @Column({ type: "text", nullable: true })
    socket_id: string;
    @Column({ type: "text", nullable: true, select: false })
    otp: string;
    @TreeChildren()
    avatar: Avatar;
    @Column({ type: "boolean", default: false, nullable: false })
    is_verify: boolean;
    @CreateDateColumn()
    created_at: Date;
    @UpdateDateColumn()
    updated_at: Date;

    //Before Insert Injection
    @BeforeInsert()
    createUserName() {
        this.userName = uniqid.time()
    }
}
</code>```

Here I use closure-table to do nested avatar entity

Here I write

```<code> @TreeChildren()
 avatar: Avatar;
</code>```

For nesting Avatar Entity

Then in my controller I try to create my first data-

```<code>const result = await this.userRepository.create({
    ...userInput,
    otp: secret.base32,
    password: passwordHash,
});
await this.userRepository.save(result)
</code>```

Note: avatar field is not required. Avatar field will be add when user update their profile. Here I only create first user data.

But I am getting this error-

Cannot read properties of undefined (reading 'getEntityValue')

Additionally, here is my userInput

```<code>@InputType()
export class UserInput {
    @Field(() => String, { nullable: false })
    @IsString()
    @IsEmail()
    @IsNotEmpty()
    email: string;

    @Field(() => String, { nullable: false })
    @IsString()
    @IsNotEmpty()
    firstName: string;

    @Field(() => String, { nullable: false })
    @IsString()
    @IsNotEmpty()
    lastName: string;

    @Field(() => String, { nullable: false })
    @IsString()
    @MinLength(8)
    @MaxLength(20)
    @IsNotEmpty()
    @Matches(/^.*(?=.{4,10})(?=.*\d)(?=.*[a-zA-Z]).*$/, { message: "password too weak" })
    password: string
}
</code>```

Please help me. I need this is very much. Over 10 days, I can't solve this. Please help me.

Body:
I am creating a nestjs project with typeorm and postgresql. Here I am creating a user entity.

My entity will be like

{
    email: string,
    name: string,
    avatar: {
        public_key: string;
        url: string;
    }
}

In avatar column I need to add a object with public_key and url.

I create two entity like this-

@Entity()
class Avatar {
    @Column({ type: "text", nullable: true })
    public_key: string;
    @Column({ type: "text", nullable: true })
    url: string;
}

@Entity()
@Tree("closure-table")
export class User {
    @PrimaryGeneratedColumn()
    id: number;
    @Column({ type: "text", nullable: false })
    userName: string;
    @Column({ type: "text", nullable: false })
    email: string;
    @Column({ type: "text", nullable: false })
    firstName: string;
    @Column({ type: "text", nullable: false })
    lastName: string;
    @Column({ type: "text", nullable: false, select: false })
    password: string;
    @Column({ type: "text", nullable: true })
    socket_id: string;
    @Column({ type: "text", nullable: true, select: false })
    otp: string;
    @TreeChildren()
    avatar: Avatar;
    @Column({ type: "boolean", default: false, nullable: false })
    is_verify: boolean;
    @CreateDateColumn()
    created_at: Date;
    @UpdateDateColumn()
    updated_at: Date;

    //Before Insert Injection
    @BeforeInsert()
    createUserName() {
        this.userName = uniqid.time()
    }
}

Here I use closure-table to do nested avatar entity

Here I write

 @TreeChildren()
 avatar: Avatar;

For nesting Avatar Entity

Then in my controller I try to create my first data-

const result = await this.userRepository.create({
    ...userInput,
    otp: secret.base32,
    password: passwordHash,
});
await this.userRepository.save(result)

Note: avatar field is not required. Avatar field will be add when user update their profile. Here I only create first user data.

But I am getting this error-

Cannot read properties of undefined (reading 'getEntityValue')

Additionally, here is my userInput

@InputType()
export class UserInput {
    @Field(() => String, { nullable: false })
    @IsString()
    @IsEmail()
    @IsNotEmpty()
    email: string;

    @Field(() => String, { nullable: false })
    @IsString()
    @IsNotEmpty()
    firstName: string;

    @Field(() => String, { nullable: false })
    @IsString()
    @IsNotEmpty()
    lastName: string;

    @Field(() => String, { nullable: false })
    @IsString()
    @MinLength(8)
    @MaxLength(20)
    @IsNotEmpty()
    @Matches(/^.*(?=.{4,10})(?=.*\d)(?=.*[a-zA-Z]).*$/, { message: "password too weak" })
    password: string
}

Please help me. I need this is very much. Over 10 days, I can't solve this. Please help me.


问:
TypeScript and Rollup: "Cannot read properties of undefined (reading 'v4')" when using the uuid package
I am trying to use the uuid package in my TypeScript project, but I am encountering an error when I try to use the v4 method. The error message is: "Cannot read properties of undefined (reading 'v4')".

I have also included the @rollup/plugin-node-resolve, @rollup/plugin-commonjs, and @rollup/plugin-replace plugins in my rollup.config.js file in order to handle the uuid package, which is a Node.js-style package.
Here is my rollup.config.js file:

```<code>import typescript from "rollup-plugin-typescript2";
import { terser } from "rollup-plugin-terser";
import postcss from "rollup-plugin-postcss";
import image from "@rollup/plugin-image";
import json from "@rollup/plugin-json";
import commonjs from "@rollup/plugin-commonjs";
import nodeResolve from "@rollup/plugin-node-resolve";
import builtins from "rollup-plugin-node-builtins";
import replace from "@rollup/plugin-replace";

export default [
  {
    input: "src/index.ts",
    output: {
      file: "dist/bundle.js",
      format: "cjs",
    },
    external: ["uuid"],
    plugins: [
      image(),
      terser(),
      postcss(),
      nodeResolve(),
      commonjs(),
      replace({
        require: "function(){}",
        preventAssignment: true,
      }),
      builtins(),
      typescript({
        tsconfig: "tsconfig.json",
      }),
      json(),
    ],
  },
];

</code>```

In this project, I am using web components for my application. I am using the uuid package to generate unique IDs for these components, but I am encountering an error when I try to use the v4 method.

In one of my web component class, an example usage is like this:

```<code>import {v4 as uuidv4} from "uuid"

export class ExampleWebComponent extends HTMLElement{
...

private setInitialAttributes() {
    this.setAttribute("customer-id", uuidv4());
  }

...

connectedCallback() {
    if (this.shadowRoot) {
      this.setInitialAttributes();
    }
  }
}
</code>```

And then I import this web component at App.ts file:

```<code>import { ExampleWebComponent } from "./web-components/ExampleWebComponent";

</code>```

And define it to window.customElements:

```<code>function defineWebComponents() {
  window.customElements.define("example-web-component", ExampleWebComponent);
}

export default defineWebComponents;
</code>```

and I finally call the defineWebComponents function in index.ts file:

```<code>import defineWebComponents from "./App";

defineWebComponents();

const newComponent = document.createElement("example-web-component");
console.log(newComponent.getAttribute("customer-id");

</code>```

I was expecting the v4 method to generate a new UUID. I was also expecting the @rollup/plugin-node-resolve, @rollup/plugin-commonjs, and @rollup/plugin-replace plugins to correctly handle the uuid package and allow me to use it in my TypeScript code.

Body:
I am trying to use the uuid package in my TypeScript project, but I am encountering an error when I try to use the v4 method. The error message is: "Cannot read properties of undefined (reading 'v4')".

I have also included the @rollup/plugin-node-resolve, @rollup/plugin-commonjs, and @rollup/plugin-replace plugins in my rollup.config.js file in order to handle the uuid package, which is a Node.js-style package.
Here is my rollup.config.js file:

import typescript from "rollup-plugin-typescript2";
import { terser } from "rollup-plugin-terser";
import postcss from "rollup-plugin-postcss";
import image from "@rollup/plugin-image";
import json from "@rollup/plugin-json";
import commonjs from "@rollup/plugin-commonjs";
import nodeResolve from "@rollup/plugin-node-resolve";
import builtins from "rollup-plugin-node-builtins";
import replace from "@rollup/plugin-replace";

export default [
  {
    input: "src/index.ts",
    output: {
      file: "dist/bundle.js",
      format: "cjs",
    },
    external: ["uuid"],
    plugins: [
      image(),
      terser(),
      postcss(),
      nodeResolve(),
      commonjs(),
      replace({
        require: "function(){}",
        preventAssignment: true,
      }),
      builtins(),
      typescript({
        tsconfig: "tsconfig.json",
      }),
      json(),
    ],
  },
];

In this project, I am using web components for my application. I am using the uuid package to generate unique IDs for these components, but I am encountering an error when I try to use the v4 method.

In one of my web component class, an example usage is like this:

import {v4 as uuidv4} from "uuid"

export class ExampleWebComponent extends HTMLElement{
...

private setInitialAttributes() {
    this.setAttribute("customer-id", uuidv4());
  }

...

connectedCallback() {
    if (this.shadowRoot) {
      this.setInitialAttributes();
    }
  }
}

And then I import this web component at App.ts file:

import { ExampleWebComponent } from "./web-components/ExampleWebComponent";

And define it to window.customElements:

function defineWebComponents() {
  window.customElements.define("example-web-component", ExampleWebComponent);
}

export default defineWebComponents;

and I finally call the defineWebComponents function in index.ts file:

import defineWebComponents from "./App";

defineWebComponents();

const newComponent = document.createElement("example-web-component");
console.log(newComponent.getAttribute("customer-id");

I was expecting the v4 method to generate a new UUID. I was also expecting the @rollup/plugin-node-resolve, @rollup/plugin-commonjs, and @rollup/plugin-replace plugins to correctly handle the uuid package and allow me to use it in my TypeScript code.


问:
CryptoPro pycades.SignedData.Verifycades()
I have a sign and signed data. By using them I have to verify a sign. To do it I use CryptoPro's extension for Python (pycades)

I wrote such code:

```<code>import sys
import base64
sys.path.append("/home/mevarg10rg1/Desktop/derzTest/cprocsp/pycades_0.1.30636")
import pycades

sign=open("/home/mevarg10rg1/Desktop/derzTest/file_signed.sig","r").read()
data=open("/home/mevarg10rg1/Desktop/derzTest/base64","r").read()
data=data.replace(chr(0),"")

signedData=pycades.SignedData()
signedData.ContentEncoding=pycades.CADESCOM_BASE64_TO_BINARY
signedData.Content=data

_signedData=pycades.SignedData()
_signedData.ContentEncoding=pycades.CADESCOM_BASE64_TO_BINARY
_signedData.Content=signedData.Content
_signedData.VerifyCades(sign,pycades.CADESCOM_CADES_BES,True)
</code>```

But got Exception:Invalid Signature (0x80090006)

Sign is valid, I am sure

Body:
I have a sign and signed data. By using them I have to verify a sign. To do it I use CryptoPro's extension for Python (pycades)

I wrote such code:

import sys
import base64
sys.path.append("/home/mevarg10rg1/Desktop/derzTest/cprocsp/pycades_0.1.30636")
import pycades

sign=open("/home/mevarg10rg1/Desktop/derzTest/file_signed.sig","r").read()
data=open("/home/mevarg10rg1/Desktop/derzTest/base64","r").read()
data=data.replace(chr(0),"")

signedData=pycades.SignedData()
signedData.ContentEncoding=pycades.CADESCOM_BASE64_TO_BINARY
signedData.Content=data

_signedData=pycades.SignedData()
_signedData.ContentEncoding=pycades.CADESCOM_BASE64_TO_BINARY
_signedData.Content=signedData.Content
_signedData.VerifyCades(sign,pycades.CADESCOM_CADES_BES,True)

But got Exception:Invalid Signature (0x80090006)

Sign is valid, I am sure


问:
Rest Template : Mapping attribute in request and response
I have to develop an api using Rest Template , The api I am calling return a complex object with lots of attributes ,The FileResponse object in my api needs only few attributes from the api I am calling

ResponseEntity responseEntity = restTemplate.exchange(URL, HttpMethod.POST, entity, FileSearchResponse.class);

Do I have to map all attributes of the complex object or few which I need will work


问:
Invoke Lambda asynchronously form lambda in JAVA
Hi I am trying to call a lambda, from one lambda.
so my code snippet is like:

```<code>public String passPayloadThenReturn (){
....
....
   AWSLambdaAsync asynclambda = AWSLambdaAsyncClientBuilder.defaultClient();

   Payload payloadData = new Payload();
   payloadData.setSupplierId(*<someId>*);
   payloadData.setTransactionId(*<someOtherId>*);
   payloadData.setS3(*<someS3Pic>*);

   InvokeRequest lambdaCallRequest = new InvokeRequest();
   lambdaCallRequest.setInvocationType("Event");
-  lambdaCallRequest.withFunctionName("LambdaToCall")
                                        .withPayload(payloadData.toString());

   Future<InvokeResult> future_res = asynclambda.invokeAsync(lambdaCallRequest);

   return "<some_uri >"

}
</code>```

So when the code is executed I can not find the log for LambdaToCall in cloudWatch.
Not able to know whether the lambda is executed or not. If I test the lambda(LambdaToCall) it works, but not able to invoke from other lambda.
What did I do wrong?
How can I know whether the LambdaToCall is called with the payload?

Please help !!!!

Body:
Hi I am trying to call a lambda, from one lambda.
so my code snippet is like:

public String passPayloadThenReturn (){
....
....
   AWSLambdaAsync asynclambda = AWSLambdaAsyncClientBuilder.defaultClient();

   Payload payloadData = new Payload();
   payloadData.setSupplierId(*<someId>*);
   payloadData.setTransactionId(*<someOtherId>*);
   payloadData.setS3(*<someS3Pic>*);

   InvokeRequest lambdaCallRequest = new InvokeRequest();
   lambdaCallRequest.setInvocationType("Event");
-  lambdaCallRequest.withFunctionName("LambdaToCall")
                                        .withPayload(payloadData.toString());

   Future<InvokeResult> future_res = asynclambda.invokeAsync(lambdaCallRequest);

   return "<some_uri >"

}

So when the code is executed I can not find the log for LambdaToCall in cloudWatch.
Not able to know whether the lambda is executed or not. If I test the lambda(LambdaToCall) it works, but not able to invoke from other lambda.
What did I do wrong?
How can I know whether the LambdaToCall is called with the payload?

Please help !!!!


问:
Usage of VolumeShaper in Google Exoplayer (currently called androidx/media)
Im planning to port old audio play app to andriodx. My app has audio tracks crossfade, gapeless feature implemented using MediaPlayer and VolumeShaper. It's a mandatory functionality for me.
Exoplayer is missing crossfade capability - it has been in the features backlog for many years unfortunately.
Any ideas if there is a way to access MediaPlayer and VolumeShaper from within Exoplayer. Perhaps anyone knows about audio tracks crossfade implementation with Exoplayer?

Thanks in advance!
David

Find a guidance and/or source code sample.


问:
How make more than one EditText as a single List item of ListView in android in Java?
I want to add ListView item Dynamically on user choice. In the every ListView Item, I want to show more than two editText.
I mean, if user enter one for example, there will be shown one listView Item and in one listView Item, there should be more than two editText Views.
I am Very Thankful in advance. Please Help me.

```<code>
final ArrayAdapter<String> adapter = new ArrayAdapter<>
        (MainActivity.this,R.layout.list_file,R.id.propertyName,R.id.editPropertyValue, ListElementsArrayList);
listview.setAdapter(adapter);
</code>```

I am aspecting more than one editText as a single ListView Item.

Body:
I want to add ListView item Dynamically on user choice. In the every ListView Item, I want to show more than two editText.
I mean, if user enter one for example, there will be shown one listView Item and in one listView Item, there should be more than two editText Views.
I am Very Thankful in advance. Please Help me.

final ArrayAdapter<String> adapter = new ArrayAdapter<>
        (MainActivity.this,R.layout.list_file,R.id.propertyName,R.id.editPropertyValue, ListElementsArrayList);
listview.setAdapter(adapter);

I am aspecting more than one editText as a single ListView Item.


问:
Is there any way to Print Scrollable HTML View with Proper Margins and alignment for specific Page Size (Ex. A4 Page) in Angular
I'm trying to print Scrollable Screen which is developed in Angular using HTML and CSS where I'm able to print it but not getting perfect Output like its not separating Pages with proper Margins and the content inside is sticking to the borders of the page and not getting the expected result.
Expected Result is to print content Inside the Template Preview (Scrollable Area) with proper Margins and properly Separated for multiple pages for specific page Size (A4).

Given Below Link is some Solution I found Similar with my Issue but I'm unable to get proper Output after its Implementation in My Project.

https://stackblitz.com/edit/how-to-split-html-page-in-a4-size-in-angular-9?file=src%2Fapp%2Fapp.component.css

Please Help me out to get any proper Solution.


问:
Generate all partitions of a set in Parallel (java)
I have a list of millions of distinct sets (no two sets have the same values), where I have to find all partitions for every single set.

For instance the set {A, B, C} can be partitioned to the following subsets:

```<code>{ {A}, {B}, {C} },
{ {A, B}, {C} },
{ {A, C}, {B} },
{ {A}, {B, C} },
{ {A, B, C} }
</code>```

The total number of possible partitions is known as the Bell number.

To find all partitions of a set we can use the following Java code for instance.

However, since I have millions of sets, let's say 7 million set of size 6, where the total number of partitions for a set of size 6 is known to be equal to 203. Hence, the huge number of partitions to be generated (1421000000 for all 7 million sets).

I have a multiple cores on my PC, so I tried to generate the partitions of sets in parallel using the fork/join framework in Java. Not the actual partitioning is done in parallel but multiple set are partitioned in the same time on multiple cores.

However, this actually did not help to generate all partitions in a pre-defined time limit. For instance for 7,159,265 sets with 30 minutes time limit:

3,599,921 were partitioned in a sequential stream.

3,511,319 were partitioned using the below fork/join pool using 12 processors in parallel.

This is the actual code used,

First I inialize the fork/join framework.

```<code>ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());
</code>```

I used the RecursiveAction class to partition each set on a core. I inialize the ParitionsParallel class that extends RecursiveAction.

```<code>ParitionsParallel tasks = new ParitionsParallel();
pool.invoke(tasks); // invoke that goes into the compute function in class PartitionsParallel
</code>```

I put every set in an independant list. If the list size is greater than 1, I create the lists. In createsubtasks() I put every set in an independent list.

```<code>protected void compute() {
            if(list.size() <= 1) {
                //do partition on the set
                try {
                    DoParition();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else {
                List<ParitionsParallel> subtasks = createsubtasks();
                invokeAll(subtasks);
            }
    }
</code>```

I create ParitionsParallel instances where every instance contains one set. The allSets list is already saved in memory and can be called inside the class.

```<code>private List<ParitionsParallel> createsubtasks(){

        List<ParitionsParallel> subtasks = new ArrayList<>();

        for(Set s: allSets) {//allSets is saved in memory already
            ParitionsParallel pp = new ParitionsParallel();
            List<Set> list = new ArrayList<>(1); //size one = 1 set
            list.add(c);
            pp.setSet(list); //set every list for every ParitionsParallel instance
            subtasks.add(pp);
        }
        return subtasks;
    }
</code>```

My questions are: how can I improve this, or is there any way to generate the actual partitionning in parallel on multiple cores.

Thank you.

Body:
I have a list of millions of distinct sets (no two sets have the same values), where I have to find all partitions for every single set.

For instance the set {A, B, C} can be partitioned to the following subsets:

{ {A}, {B}, {C} },
{ {A, B}, {C} },
{ {A, C}, {B} },
{ {A}, {B, C} },
{ {A, B, C} }

The total number of possible partitions is known as the Bell number.

To find all partitions of a set we can use the following Java code for instance.

However, since I have millions of sets, let's say 7 million set of size 6, where the total number of partitions for a set of size 6 is known to be equal to 203. Hence, the huge number of partitions to be generated (1421000000 for all 7 million sets).

I have a multiple cores on my PC, so I tried to generate the partitions of sets in parallel using the fork/join framework in Java. Not the actual partitioning is done in parallel but multiple set are partitioned in the same time on multiple cores.

However, this actually did not help to generate all partitions in a pre-defined time limit. For instance for 7,159,265 sets with 30 minutes time limit:

3,599,921 were partitioned in a sequential stream.

3,511,319 were partitioned using the below fork/join pool using 12 processors in parallel.

This is the actual code used,

First I inialize the fork/join framework.

ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors());

I used the RecursiveAction class to partition each set on a core. I inialize the ParitionsParallel class that extends RecursiveAction.

ParitionsParallel tasks = new ParitionsParallel();
pool.invoke(tasks); // invoke that goes into the compute function in class PartitionsParallel

I put every set in an independant list. If the list size is greater than 1, I create the lists. In createsubtasks() I put every set in an independent list.

protected void compute() {
            if(list.size() <= 1) {
                //do partition on the set
                try {
                    DoParition();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else {
                List<ParitionsParallel> subtasks = createsubtasks();
                invokeAll(subtasks);
            }
    }

I create ParitionsParallel instances where every instance contains one set. The allSets list is already saved in memory and can be called inside the class.

private List<ParitionsParallel> createsubtasks(){

        List<ParitionsParallel> subtasks = new ArrayList<>();

        for(Set s: allSets) {//allSets is saved in memory already
            ParitionsParallel pp = new ParitionsParallel();
            List<Set> list = new ArrayList<>(1); //size one = 1 set
            list.add(c);
            pp.setSet(list); //set every list for every ParitionsParallel instance
            subtasks.add(pp);
        }
        return subtasks;
    }

My questions are: how can I improve this, or is there any way to generate the actual partitionning in parallel on multiple cores.

Thank you.


问:
Windows Firewall blocking HTTP Listener in C#
I have HTTP Listener application written in C# running on Win Server 2022:

```<code>HttpListener Listener = new HttpListener();
Listener.Prefixes.Add("https://test.mydomain.com:13001/");
Listener.Start();
while (true)
{
    HttpListenerContext Context = Listener.GetContext();
    HttpListenerRequest Req = Context.Request;
    HttpListenerResponse Resp = Context.Response;
    byte[] data = { };
    if (Req.HttpMethod == "POST" && Req.HasEntityBody)
    {
        StreamReader reader = new StreamReader(Req.InputStream, Req.ContentEncoding);
        string s = reader.ReadToEnd();
        string Return = manageData(s); //code here calls function to work with data from http request and returns values
        data = Encoding.UTF8.GetBytes(Return);
    }
    Resp.StatusCode = 200;
    Resp.AppendHeader("Access-Control-Allow-Origin", "*");
    Resp.ContentType = "text/plain; charset=utf-8";
    Resp.ContentEncoding = Encoding.UTF8;
    Resp.ContentLength64 = data.LongLength;
    Resp.OutputStream.WriteAsync(data, 0, data.Length);
    Resp.Close();
}
</code>```

Then I have another application for clients. This code can be executed by anyone. This is the code:

```<code>HttpContent content = new StringContent("Request string", Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(Uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
HttpStatusCode code = response.StatusCode;
</code>```

Everything works well when port 13001 is fully opened, but doesn't work when only my application has allowed access. These are the firewall settings:

This rule has allowed access but the external apps can't connect. Am I missing something in code what tells the system to allow access to program? Or is there problem with firewall? I just want to increase server security by not opening port completely but only for my application.
Thanks for all advices

Body:
I have HTTP Listener application written in C# running on Win Server 2022:

HttpListener Listener = new HttpListener();
Listener.Prefixes.Add("https://test.mydomain.com:13001/");
Listener.Start();
while (true)
{
    HttpListenerContext Context = Listener.GetContext();
    HttpListenerRequest Req = Context.Request;
    HttpListenerResponse Resp = Context.Response;
    byte[] data = { };
    if (Req.HttpMethod == "POST" && Req.HasEntityBody)
    {
        StreamReader reader = new StreamReader(Req.InputStream, Req.ContentEncoding);
        string s = reader.ReadToEnd();
        string Return = manageData(s); //code here calls function to work with data from http request and returns values
        data = Encoding.UTF8.GetBytes(Return);
    }
    Resp.StatusCode = 200;
    Resp.AppendHeader("Access-Control-Allow-Origin", "*");
    Resp.ContentType = "text/plain; charset=utf-8";
    Resp.ContentEncoding = Encoding.UTF8;
    Resp.ContentLength64 = data.LongLength;
    Resp.OutputStream.WriteAsync(data, 0, data.Length);
    Resp.Close();
}

Then I have another application for clients. This code can be executed by anyone. This is the code:

HttpContent content = new StringContent("Request string", Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(Uri, content);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
HttpStatusCode code = response.StatusCode;

Everything works well when port 13001 is fully opened, but doesn't work when only my application has allowed access. These are the firewall settings:

This rule has allowed access but the external apps can't connect. Am I missing something in code what tells the system to allow access to program? Or is there problem with firewall? I just want to increase server security by not opening port completely but only for my application.
Thanks for all advices


问:
Refactor a for loop of Active Users to improve speed
I have a dataframe of Users with their DATE_CREATION and DATE_DELETION.

```<code>ACTIVE_USERS <- data.frame(Date=c("2022-01-12", "2022-02-18", "2022-03-22", "2022-04-10", "2022-07-15" ) ,
                           USER_ID=c("user123","user311","user245","user245","user213"),
                           DATE_DELETION=c("2022-04-11","2022-04-12","2022-03-28","2022-07-12","2022-08-11"))
</code>```

I am trying to create a graph that will show Nb of Active Users each day (we consider Active if simply existing).

For that, I wrote the below script that seems to do the job, but is extremely slow and takes a few hours to render (because I have much more dates than in above dataframe example). Any help to improve the speed of this script is welcomed, see below my current method:

I created a dataframe sequence of Dates from 1st date of creation to last, and I joined these two dataframes by Date of Creation

```<code>Axis_X_Date <- data.frame(seq(as.Date(min(ACTIVE_USERS$DATE_CREATION)),as.Date(max(ACTIVE_USERS$DATE_CREATION)),by = 1))
colnames(Axis_X_Date) <- c("DATE_CREATION")

Axis_X_Date <- merge(Axis_X_Date, ACTIVE_USERS, by = "DATE_CREATION", all.x =TRUE , all.y = FALSE)
ACTIVE_USERS <- Axis_X_Date
rm(Axis_X_Date)
colnames(ACTIVE_USERS) <- c("DATE_CREATION", "USER_ID", "DATE_DELETION")
</code>```

Then I calculate the "Age" for each day.

```<code>ACTIVE_USERS$Age_Days <- ACTIVE_USERS$DATE_DELETION - ACTIVE_USERS$Date
</code>```

And then I create a for loop, and apply the following actions for each row of the dataframe:

```<code>table_page_all <- data.frame()

for(i in 1:nrow(ACTIVE_USERS)){

  # To simplify, I convert NAs of DATE_DELETION, meaning still active accounts, as active until today
  ifelse( is.na(ACTIVE_USERS$DATE_DELETION[i] ), ACTIVE_USERS$DATE_DELETION[i] <- today_date, ACTIVE_USERS$DATE_DELETION[i])

  # here I replicate USER_ID for each day where USER_ID was alive/active
  Dates_Active <- seq(ACTIVE_USERS$Date[i], ACTIVE_USERS$DATE_DELETION[i], by="days")
  Ref_ID <- rep(ACTIVE_USERS$USER_ID[i], length(Dates_Active))

  # I combine these USER_ID and Dates_Active for each row of the ACTIVE_USERS dataframe
  data_frame <- data.frame(Dates_Active, Ref_ID)

  table_page_all  <- rbind(table_page_all, data_frame)

  cat('Row: ', i , 'out of', nrow(ACTIVE_USERS), '\n')

}
</code>```

Body:
I have a dataframe of Users with their DATE_CREATION and DATE_DELETION.

ACTIVE_USERS <- data.frame(Date=c("2022-01-12", "2022-02-18", "2022-03-22", "2022-04-10", "2022-07-15" ) ,
                           USER_ID=c("user123","user311","user245","user245","user213"),
                           DATE_DELETION=c("2022-04-11","2022-04-12","2022-03-28","2022-07-12","2022-08-11"))

I am trying to create a graph that will show Nb of Active Users each day (we consider Active if simply existing).

For that, I wrote the below script that seems to do the job, but is extremely slow and takes a few hours to render (because I have much more dates than in above dataframe example). Any help to improve the speed of this script is welcomed, see below my current method:

I created a dataframe sequence of Dates from 1st date of creation to last, and I joined these two dataframes by Date of Creation

Axis_X_Date <- data.frame(seq(as.Date(min(ACTIVE_USERS$DATE_CREATION)),as.Date(max(ACTIVE_USERS$DATE_CREATION)),by = 1))
colnames(Axis_X_Date) <- c("DATE_CREATION")

Axis_X_Date <- merge(Axis_X_Date, ACTIVE_USERS, by = "DATE_CREATION", all.x =TRUE , all.y = FALSE)
ACTIVE_USERS <- Axis_X_Date
rm(Axis_X_Date)
colnames(ACTIVE_USERS) <- c("DATE_CREATION", "USER_ID", "DATE_DELETION")

Then I calculate the "Age" for each day.

ACTIVE_USERS$Age_Days <- ACTIVE_USERS$DATE_DELETION - ACTIVE_USERS$Date

And then I create a for loop, and apply the following actions for each row of the dataframe:

table_page_all <- data.frame()

for(i in 1:nrow(ACTIVE_USERS)){

  # To simplify, I convert NAs of DATE_DELETION, meaning still active accounts, as active until today
  ifelse( is.na(ACTIVE_USERS$DATE_DELETION[i] ), ACTIVE_USERS$DATE_DELETION[i] <- today_date, ACTIVE_USERS$DATE_DELETION[i])

  # here I replicate USER_ID for each day where USER_ID was alive/active
  Dates_Active <- seq(ACTIVE_USERS$Date[i], ACTIVE_USERS$DATE_DELETION[i], by="days")
  Ref_ID <- rep(ACTIVE_USERS$USER_ID[i], length(Dates_Active))

  # I combine these USER_ID and Dates_Active for each row of the ACTIVE_USERS dataframe
  data_frame <- data.frame(Dates_Active, Ref_ID)

  table_page_all  <- rbind(table_page_all, data_frame)

  cat('Row: ', i , 'out of', nrow(ACTIVE_USERS), '\n')

}


问:
How to connect reusable button with text field in Jetpack Compose
I'm trying to hide a reusable floating action button (on click - then show it again when the keyboard is not visible) and request focus for a text field I made but I'm not sure what I'm doing wrong. I used focusRequester.requestFocus() and AnimatedVisibility but nothing happens.

```<code>@file:OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MySearchViewDemoTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    MainScreen(showSearchButton = true)
                }
            }
        }
    }

    sealed interface Shoes { ... }

    // Reusable component
    @Composable
    fun MyReusableScaffold(scaffoldTitle: String,
                                   scaffoldFab: @Composable () -> Unit,
                                   scaffoldContent: @Composable (contentPadding: PaddingValues) -> Unit) {
        val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()

        Scaffold(
            modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
            topBar = {
                LargeTopAppBar(
                    title = { Text(text = scaffoldTitle) },
                    scrollBehavior = scrollBehavior
                )
            },
            floatingActionButton = scaffoldFab,
            content = { contentPadding ->
                scaffoldContent(contentPadding = contentPadding)
            }
        )
    }

    // Reusable component
    @Composable
    fun MyExtendedFAB(expandedFab: Boolean,
                      onFabClick: () -> Unit
    ) {
        ExtendedFloatingActionButton(
            text = { Text(text = "Search") },
            icon = { Icon(Icons.Rounded.Search, "") },
            onClick = onFabClick,
            expanded = expandedFab
        )
    }

    // Reusable component
    @Composable
    fun <T> MyLazyColumn(modifier: Modifier,
                         lazyItems: Array<T>,
                         onClickItem: (T) -> Unit,
                         item: @Composable RowScope.(item: T) -> Unit,
                         listState: LazyListState
    ) {
        var mText by remember { mutableStateOf("") }
        val focusRequester = remember { FocusRequester() }
        val focusManager = LocalFocusManager.current
        val keyboardController = LocalSoftwareKeyboardController.current

        Row {
            LazyColumn(
                modifier = modifier,
                state = listState
            ) {
                item {
                    if (showNotice){
                        Text(
                            text = textNotice,
                            modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp),
                            fontStyle = FontStyle.Italic,
                            style = MaterialTheme.typography.bodyLarge
                        )
                    }
                }
                item {
                    OutlinedTextField(
                        modifier = Modifier
                            .fillMaxWidth()
                            .focusRequester(focusRequester)
                        value = mText,
                        onValueChange = {
                            mText = it
                        },
                        label = {
                            Text(text = "Search")
                        },
                        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
                        keyboardActions = KeyboardActions(
                            onSearch = {
                                keyboardController?.hide()
                                focusManager.clearFocus()
                        }),
                    )
                }
                items(lazyItems) { choice ->
                    Row(modifier = Modifier
                        .fillMaxWidth()
                        .clickable {
                            onClickItem(choice)
                        }) {
                        item(choice)
                    }
                }
            }
        }
    }

    @Composable
    fun MainScreen(
        showSearchButton: Boolean
    ) {
        val keyboardController = LocalSoftwareKeyboardController.current
        val focusManager = LocalFocusManager.current

        val listState = rememberLazyListState()

        val expandedFab by remember {
            derivedStateOf {
                listState.firstVisibleItemIndex == 0
            }
        }

        val focusRequester = remember { FocusRequester() }

        MyReusableScaffold(
            scaffoldTitle = "Shoes",
            scaffoldIcon = {},
            scaffoldFab = {
                AnimatedVisibility(visible = showSearchButton) {
                    MyExtendedFAB(expandedFab) {
                        focusRequester.requestFocus()
                    }
                }
            },
            scaffoldContent = { HomeScreenContent(listState = listState, contentPadding = it) }
        )
    }

    @Composable
    fun HomeScreenContent(
        modifier: Modifier = Modifier,
        listState: LazyListState,
        contentPadding: PaddingValues = PaddingValues()
    ) {
        val keyboardController = LocalSoftwareKeyboardController.current
        val focusManager = LocalFocusManager.current

        val shoeItems = remember { arrayOf( ... ) }

        MyLazyColumn(
            modifier = Modifier.padding(contentPadding),
            lazyItems = shoeItems,
            onClickItem = {},
            item = { ReusableTitleSubtitle(it) },
            listState = listState
        )
    }
}
</code>```

Body:
I'm trying to hide a reusable floating action button (on click - then show it again when the keyboard is not visible) and request focus for a text field I made but I'm not sure what I'm doing wrong. I used focusRequester.requestFocus() and AnimatedVisibility but nothing happens.

@file:OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MySearchViewDemoTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    MainScreen(showSearchButton = true)
                }
            }
        }
    }

    sealed interface Shoes { ... }

    // Reusable component
    @Composable
    fun MyReusableScaffold(scaffoldTitle: String,
                                   scaffoldFab: @Composable () -> Unit,
                                   scaffoldContent: @Composable (contentPadding: PaddingValues) -> Unit) {
        val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()

        Scaffold(
            modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
            topBar = {
                LargeTopAppBar(
                    title = { Text(text = scaffoldTitle) },
                    scrollBehavior = scrollBehavior
                )
            },
            floatingActionButton = scaffoldFab,
            content = { contentPadding ->
                scaffoldContent(contentPadding = contentPadding)
            }
        )
    }

    // Reusable component
    @Composable
    fun MyExtendedFAB(expandedFab: Boolean,
                      onFabClick: () -> Unit
    ) {
        ExtendedFloatingActionButton(
            text = { Text(text = "Search") },
            icon = { Icon(Icons.Rounded.Search, "") },
            onClick = onFabClick,
            expanded = expandedFab
        )
    }

    // Reusable component
    @Composable
    fun <T> MyLazyColumn(modifier: Modifier,
                         lazyItems: Array<T>,
                         onClickItem: (T) -> Unit,
                         item: @Composable RowScope.(item: T) -> Unit,
                         listState: LazyListState
    ) {
        var mText by remember { mutableStateOf("") }
        val focusRequester = remember { FocusRequester() }
        val focusManager = LocalFocusManager.current
        val keyboardController = LocalSoftwareKeyboardController.current

        Row {
            LazyColumn(
                modifier = modifier,
                state = listState
            ) {
                item {
                    if (showNotice){
                        Text(
                            text = textNotice,
                            modifier = Modifier.padding(start = 16.dp, end = 16.dp, bottom = 16.dp),
                            fontStyle = FontStyle.Italic,
                            style = MaterialTheme.typography.bodyLarge
                        )
                    }
                }
                item {
                    OutlinedTextField(
                        modifier = Modifier
                            .fillMaxWidth()
                            .focusRequester(focusRequester)
                        value = mText,
                        onValueChange = {
                            mText = it
                        },
                        label = {
                            Text(text = "Search")
                        },
                        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
                        keyboardActions = KeyboardActions(
                            onSearch = {
                                keyboardController?.hide()
                                focusManager.clearFocus()
                        }),
                    )
                }
                items(lazyItems) { choice ->
                    Row(modifier = Modifier
                        .fillMaxWidth()
                        .clickable {
                            onClickItem(choice)
                        }) {
                        item(choice)
                    }
                }
            }
        }
    }

    @Composable
    fun MainScreen(
        showSearchButton: Boolean
    ) {
        val keyboardController = LocalSoftwareKeyboardController.current
        val focusManager = LocalFocusManager.current

        val listState = rememberLazyListState()

        val expandedFab by remember {
            derivedStateOf {
                listState.firstVisibleItemIndex == 0
            }
        }

        val focusRequester = remember { FocusRequester() }

        MyReusableScaffold(
            scaffoldTitle = "Shoes",
            scaffoldIcon = {},
            scaffoldFab = {
                AnimatedVisibility(visible = showSearchButton) {
                    MyExtendedFAB(expandedFab) {
                        focusRequester.requestFocus()
                    }
                }
            },
            scaffoldContent = { HomeScreenContent(listState = listState, contentPadding = it) }
        )
    }

    @Composable
    fun HomeScreenContent(
        modifier: Modifier = Modifier,
        listState: LazyListState,
        contentPadding: PaddingValues = PaddingValues()
    ) {
        val keyboardController = LocalSoftwareKeyboardController.current
        val focusManager = LocalFocusManager.current

        val shoeItems = remember { arrayOf( ... ) }

        MyLazyColumn(
            modifier = Modifier.padding(contentPadding),
            lazyItems = shoeItems,
            onClickItem = {},
            item = { ReusableTitleSubtitle(it) },
            listState = listState
        )
    }
}


问:
How do you save photos with a set height and width?
I am creating a feature to capture pictures with a height/width set and save them in the gallery. At my current stage I can take a photo and save it to the gallery, the only problem is that the saved photo is not the height and width I previously set.

It seems like something simple, but I don't know what I am overlooking.

App.js

```<code>
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, SafeAreaView, Image, TouchableOpacity } from 'react-native';
import { useEffect, useRef, useState } from 'react';
import { FontAwesome } from "@expo/vector-icons";
import { Camera } from 'expo-camera';
import { shareAsync } from 'expo-sharing';
import * as MediaLibrary from 'expo-media-library';
import styles from "./styles.js";

export default function App() {
  let cameraRef = useRef();
  const [hasCameraPermission, setHasCameraPermission] = useState();
  const [hasMediaLibraryPermission, setHasMediaLibraryPermission] = useState();
  const [photo, setPhoto] = useState();

  useEffect(() => {
    (async () => {
      const cameraPermission = await Camera.requestCameraPermissionsAsync();
      const mediaLibraryPermission = await MediaLibrary.requestPermissionsAsync();
      setHasCameraPermission(cameraPermission.status === "granted");
      setHasMediaLibraryPermission(mediaLibraryPermission.status === "granted");
    })();
  }, []);

  if (hasCameraPermission === undefined) {
    return <Text>Requesting permissions...</Text>
  } else if (!hasCameraPermission) {
    return <Text>Permission for camera not granted. Please change this in settings.</Text>
  }

  let takePic = async () => {
    let options = {
      quality: 1,
      base64: true,
      exif: false
    };
  };

  if (photo) {

    let savePhoto = () => {
      MediaLibrary.saveToLibraryAsync(photo.uri).then(() => {
        setPhoto(undefined);
      });
    };

    return (
      <SafeAreaView style={styles.container}>
        <Image style={styles.responsiveImage} source={{ uri: "data:image/jpg;base64," + photo.base64 }} resizeMode="contain"/>

        {hasMediaLibraryPermission ?
        <TouchableOpacity style={styles.buttonSave} onPress={savePhoto}>
          <FontAwesome name="save" size={23} color="#fff"></FontAwesome>
        </TouchableOpacity> : undefined}

      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
    <Camera style={styles.camera} ref={cameraRef}>
      <View style={styles.buttonContainer}>
        <TouchableOpacity style={styles.buttonCamera} onPress={takePic}>
          <FontAwesome name="camera" size={27} color="#fff"></FontAwesome>
        </TouchableOpacity>
      </View>
      <StatusBar style="auto" />
    </Camera>
    </SafeAreaView>
  );
}
</code>```

style.js

```<code>import { StyleSheet } from "react-native"

const styles = StyleSheet.create({

  responsiveImage: {
    width: '80%',
    height: 400,
  },

});
export default styles
</code>```

Body:
I am creating a feature to capture pictures with a height/width set and save them in the gallery. At my current stage I can take a photo and save it to the gallery, the only problem is that the saved photo is not the height and width I previously set.

It seems like something simple, but I don't know what I am overlooking.

App.js

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, SafeAreaView, Image, TouchableOpacity } from 'react-native';
import { useEffect, useRef, useState } from 'react';
import { FontAwesome } from "@expo/vector-icons";
import { Camera } from 'expo-camera';
import { shareAsync } from 'expo-sharing';
import * as MediaLibrary from 'expo-media-library';
import styles from "./styles.js";

export default function App() {
  let cameraRef = useRef();
  const [hasCameraPermission, setHasCameraPermission] = useState();
  const [hasMediaLibraryPermission, setHasMediaLibraryPermission] = useState();
  const [photo, setPhoto] = useState();

  useEffect(() => {
    (async () => {
      const cameraPermission = await Camera.requestCameraPermissionsAsync();
      const mediaLibraryPermission = await MediaLibrary.requestPermissionsAsync();
      setHasCameraPermission(cameraPermission.status === "granted");
      setHasMediaLibraryPermission(mediaLibraryPermission.status === "granted");
    })();
  }, []);

  if (hasCameraPermission === undefined) {
    return <Text>Requesting permissions...</Text>
  } else if (!hasCameraPermission) {
    return <Text>Permission for camera not granted. Please change this in settings.</Text>
  }

  let takePic = async () => {
    let options = {
      quality: 1,
      base64: true,
      exif: false
    };
  };

  if (photo) {

    let savePhoto = () => {
      MediaLibrary.saveToLibraryAsync(photo.uri).then(() => {
        setPhoto(undefined);
      });
    };

    return (
      <SafeAreaView style={styles.container}>
        <Image style={styles.responsiveImage} source={{ uri: "data:image/jpg;base64," + photo.base64 }} resizeMode="contain"/>

        {hasMediaLibraryPermission ?
        <TouchableOpacity style={styles.buttonSave} onPress={savePhoto}>
          <FontAwesome name="save" size={23} color="#fff"></FontAwesome>
        </TouchableOpacity> : undefined}

      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
    <Camera style={styles.camera} ref={cameraRef}>
      <View style={styles.buttonContainer}>
        <TouchableOpacity style={styles.buttonCamera} onPress={takePic}>
          <FontAwesome name="camera" size={27} color="#fff"></FontAwesome>
        </TouchableOpacity>
      </View>
      <StatusBar style="auto" />
    </Camera>
    </SafeAreaView>
  );
}

style.js

import { StyleSheet } from "react-native"

const styles = StyleSheet.create({

  responsiveImage: {
    width: '80%',
    height: 400,
  },

});
export default styles


问:
PCA plotting coloring and labeling in R
I have two variables: varieties of grapes(A, B, C...), and I have the color of wine(red, white). How can I perform a PCA and plot the data in 2 dimensions, color the data points such that all the red wines and all the white wines have the same color and on top, label the data points with the name of the variety (eg. A, B, C...)? What are the cons of coloring in this case?

```<code>plot(pc1, pc2, col = as.factor(mywines_spectra2$color %in% "red"))
legend('topleft', legend = unique(mywines_spectra2$name),
       text.col = as.numeric(unique(as.factor(mywines_spectra2$color %in% "red"))))
</code>```

This what I tried but it doesn't catch exactly the correct varieties in a correct color(for example variety G should be red and in the plot in shows white)

Title: PCA plotting coloring and labeling in R

Body:
I have two variables: varieties of grapes(A, B, C...), and I have the color of wine(red, white). How can I perform a PCA and plot the data in 2 dimensions, color the data points such that all the red wines and all the white wines have the same color and on top, label the data points with the name of the variety (eg. A, B, C...)? What are the cons of coloring in this case?

plot(pc1, pc2, col = as.factor(mywines_spectra2$color %in% "red"))
legend('topleft', legend = unique(mywines_spectra2$name),
       text.col = as.numeric(unique(as.factor(mywines_spectra2$color %in% "red"))))

This what I tried but it doesn't catch exactly the correct varieties in a correct color(for example variety G should be red and in the plot in shows white)


问:
Find out the last edited date in the discord audit log event
eg: (today: 15:32 - today: 17:26)

i want 17:26 time to timestamp

Can you help me find the time of the last data added to the batch event?


问:
How to show progress of a retrofit call?
I am uploading some files with retrofit2. Using post method. while uploading i want to show a progress bar.

below I am showing a snipper , for a non multipart request to show how I am
using the retrofit.

```<code>HashMap<String, String> map = new HashMap<>();
map.put("post_id", id);
String header = "";
if (MethodClass.isStudent()){
    header = "bearer "+PreferenceFile.getStudent().getResult().getToken();
}

if (!NetWorkChecker.check(getContext()))
    return;
CustomProgressbar.showProgressBar(getContext(), false);

ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);

Call<PostDetailsResponse> callMethod = apiInterface.STUDENT_PostDetailsResponse(header,MethodClass.Json_rpc_format_hashmap(map));

callMethod.enqueue(new Callback<PostDetailsResponse>() {
    @Override
    public void onResponse(Call<PostDetailsResponse> call, Response<PostDetailsResponse> response) {
        CustomProgressbar.hideProgressBar();
        if (MethodClass.hasError(getActivity(), response.body().getError())){
                UpdateData(response.body().getResult());
        }
    }

    @Override
    public void onFailure(Call<PostDetailsResponse> call, Throwable t) {
        CustomProgressbar.hideProgressBar();

    }
});
</code>```

Now instead of the custom progress bar, I want to show a progress in percent from 0  to 100;
Ihave search a lot in statckoverflow but everyone is suggesting to show a dummmy progressbar with intermideate situation. but I want to show in percent. Please help .

Body:
I am uploading some files with retrofit2. Using post method. while uploading i want to show a progress bar.

below I am showing a snipper , for a non multipart request to show how I am
using the retrofit.

HashMap<String, String> map = new HashMap<>();
map.put("post_id", id);
String header = "";
if (MethodClass.isStudent()){
    header = "bearer "+PreferenceFile.getStudent().getResult().getToken();
}

if (!NetWorkChecker.check(getContext()))
    return;
CustomProgressbar.showProgressBar(getContext(), false);

ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);

Call<PostDetailsResponse> callMethod = apiInterface.STUDENT_PostDetailsResponse(header,MethodClass.Json_rpc_format_hashmap(map));

callMethod.enqueue(new Callback<PostDetailsResponse>() {
    @Override
    public void onResponse(Call<PostDetailsResponse> call, Response<PostDetailsResponse> response) {
        CustomProgressbar.hideProgressBar();
        if (MethodClass.hasError(getActivity(), response.body().getError())){
                UpdateData(response.body().getResult());
        }
    }

    @Override
    public void onFailure(Call<PostDetailsResponse> call, Throwable t) {
        CustomProgressbar.hideProgressBar();

    }
});

Now instead of the custom progress bar, I want to show a progress in percent from 0  to 100;
Ihave search a lot in statckoverflow but everyone is suggesting to show a dummmy progressbar with intermideate situation. but I want to show in percent. Please help .


问:
tailwind config and className doesn't work on my react app
as I install tailwind and craco as the same tailwind document. but after all it doesn't make any change in my styles. ofcourse my app can recognize the tailwind classes but it doesn't make any change on my UI app.

tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/**/*.{js,jsx,ts,tsx}", "/public/index.html"],
  theme: {
    extend: {},
  },
  plugins: [],
};

```
<p><em>postcss.config.js</em></p>
<pre class="lang-js prettyprint-override"><code>const tailwindcss = require("tailwindcss");
module.exports = {
  plugins: [tailwindcss("./tailwind.config.js"), require("autoprefixer")],
};

</code>```

craco.config.js

module.exports = {
  style: {
    postcss: {
      plugins: [require("tailwindcss"), require("autoprefixer")],
    },
  },
};

```
<p><em>package.json</em></p>
<pre class="lang-js prettyprint-override"><code>{
  "name": "mensch",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@craco/craco": "^7.0.0",
    "@reduxjs/toolkit": "^1.6.0",
    "@testing-library/jest-dom": "^5.12.0",
    "@testing-library/react": "^11.2.6",
    "@testing-library/user-event": "^12.8.3",
    "autoprefixer": "^9.8.8",
    "postcss": "^8.4.20",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-icons": "^4.7.1",
    "react-redux": "^7.2.4",
    "react-scripts": "^5.0.1",
    "redux": "^4.1.0",
    "tailwindcss": "^3.2.4",
    "web-vitals": "^1.1.1"
  },
  "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

</code>```

styles.css

@import url("https://fonts.googleapis.com/css2?family=M+PLUS+Rounded+1c:wght@300;400;500;700;800&display=swap");

@tailwind base;
@tailwind components;
@tailwind utilities;

body,
html,
p,
h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: "M PLUS Rounded 1c", sans-serif;
}

```

it's imported to my index.jsx too.

I tried several solutions on the stack overflow and git hub but it doesn't resolve my problem

Body:
as I install tailwind and craco as the same tailwind document. but after all it doesn't make any change in my styles. ofcourse my app can recognize the tailwind classes but it doesn't make any change on my UI app.

tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/**/*.{js,jsx,ts,tsx}", "/public/index.html"],
  theme: {
    extend: {},
  },
  plugins: [],
};

postcss.config.js

const tailwindcss = require("tailwindcss");
module.exports = {
  plugins: [tailwindcss("./tailwind.config.js"), require("autoprefixer")],
};

craco.config.js

module.exports = {
  style: {
    postcss: {
      plugins: [require("tailwindcss"), require("autoprefixer")],
    },
  },
};

package.json

{
  "name": "mensch",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@craco/craco": "^7.0.0",
    "@reduxjs/toolkit": "^1.6.0",
    "@testing-library/jest-dom": "^5.12.0",
    "@testing-library/react": "^11.2.6",
    "@testing-library/user-event": "^12.8.3",
    "autoprefixer": "^9.8.8",
    "postcss": "^8.4.20",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-icons": "^4.7.1",
    "react-redux": "^7.2.4",
    "react-scripts": "^5.0.1",
    "redux": "^4.1.0",
    "tailwindcss": "^3.2.4",
    "web-vitals": "^1.1.1"
  },
  "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

styles.css

@import url("https://fonts.googleapis.com/css2?family=M+PLUS+Rounded+1c:wght@300;400;500;700;800&display=swap");

@tailwind base;
@tailwind components;
@tailwind utilities;

body,
html,
p,
h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: "M PLUS Rounded 1c", sans-serif;
}

it's imported to my index.jsx too.

I tried several solutions on the stack overflow and git hub but it doesn't resolve my problem


问:
Custom Hook in React not working on first click
I have created a custom hook to toggle between items from an array.
This is the custom hook and how we use it in a component.

const { useState } = React;

function useToggleItems (arr){
    const [count,setCount] = useState(0);
    const [item , setItem] = useState(arr[count]);

    function toggle(){
        if(count<arr.length-1)
        {
          setCount(prev=>prev+1);
        }
        else
        {
          setCount(0);
        }
        setItem(arr[count]);
    }

    console.log(count);
    return [item, toggle];
}

function App() {

  const [item , toggle] = useToggleItems([1,2]);

  return (

{item}

      <button onClick={toggle}>Button</button>

  );
}

ReactDOM.createRoot(document.querySelector("#root")).render(<App />);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>

<div id="root"></div></code>```

I have tried to make this work but i don't know why it is forming a stale closure on first click and DOM is not getting updated with current value of count from useState. But after the first click it starts to work fine. Can some one help me fix this stale closure issue.

```<code>const [item,toggle] = useToggleItems(['a','b','c']);
</code>```

Body:
I have created a custom hook to toggle between items from an array.
This is the custom hook and how we use it in a component.

const { useState } = React;

function useToggleItems (arr){
    const [count,setCount] = useState(0);
    const [item , setItem] = useState(arr[count]);

    function toggle(){
        if(count<arr.length-1)
        {
          setCount(prev=>prev+1);
        }
        else
        {
          setCount(0);
        }
        setItem(arr[count]);
    }

    console.log(count);
    return [item, toggle];
}

function App() {

  const [item , toggle] = useToggleItems([1,2]);

  return (

{item}

      <button onClick={toggle}>Button</button>

  );
}

ReactDOM.createRoot(document.querySelector("#root")).render(<App />);

I have tried to make this work but i don't know why it is forming a stale closure on first click and DOM is not getting updated with current value of count from useState. But after the first click it starts to work fine. Can some one help me fix this stale closure issue.

const [item,toggle] = useToggleItems(['a','b','c']);


问:
Regarding serial port data transmitting issue from device to application
we are using serial port device for sending and receiving data from this device to application, everything is going on perfect, but when we setting up wrong setting in device as well as in application but we got garbage value from device but we need setting value  output from device is there any idea to get setting value from the device.
is there any idea ?

when we are trying to change settings we didn't receive garbage value when again try connection with same settings then we are receiving value from device starting with garbage value.

```<code>let serial = {
      path: data.port,
      baudRate: parseInt(data.baurate),
      databits: parseInt(data.databits),
      stopbits: parseInt(data.stopbits),
      parity: data.parity,
      protocol: data.protocol,
      encoding: data.encoding,
    };

    /* here we try to make connection to the peripheral based on the settings selected.*/

    if (connect.current === 1) {

      sp = new serialport(serial);
    }

    /* Re-establish connection with new settings    */

    if (connect.current > 1) {
      console.log("second click condition connect.current > 1");

      if (spRef.current?.sp) {

        const myInterval = new Promise((resolve, reject) => {
          spRef.current.sp.lock = false;
          spRef.current?.sp?.flush((err) => {
            console.log("data will stop coming", err);
          });

          spRef.current?.sp?.close((err) => {

            if (err === null) {

              reconnect.current = true;
              if (reconnect.current) {
                resolve("connection is closed");
              } else {
                reject("connection is not closed");
              }
            }
          });
        });

        await myInterval;
        console.log("connection trying after closed conenction");
        sp = new serialport(serial);
        console.log("sp", sp);
      }
    }

    /* here we try to check connection is established or not to the peripheral.*/

    sp.on("open", () => {
      console.log("sp event open");
      let response = "Connected";
      setTraffic({ connected: response });
      setStatus(response);
      spRef.current.sp = sp;
    });

    /* Now we check to see if incoming packets have arrived. we will parse messages based on the parser
    they have selected. */

    const parser = sp.pipe(new ReadlineParser({ delimiter: "\r\n" }));

    parser.on("data", (device) => {
      console.log("device", device);
      let values = sortStr(device);
      console.log("values", values);
      let value = roundingLogic(values);
      console.log("value", value);
      if (togglePause) {
        devicevalueDemo.push({
          value: value,
          currenttime: currentdatetimeevents(),
          status: "incoming",
        });
        devicevalue.push(value);
      }
      let copy = [...newvalue];
      setNewvalue([
        ...newvalue,
        {
          uuid: data.uuid,
          peripheralvalue: value,
        },
      ]);
    });

    /* if peripheral started sending some errors then we will send erorr message */

    sp.on("error", (err) => {
      console.log("Error coming from device", err);
      let response = { Message: "Some error passed from device" };
    });

    /* Here we will find that device is disconnected from the comport then we will message to the logs */

    sp.on("close", (err) => {
      console.log("port is closed", err);
      let response = "Disconnected";
      setTraffic({ disconnected: response });
      setStatus(response);
      setNewvalue("");
      lostperipheral = `Connection error "Lost Peripheral"`;
      peripheralLogfile(lostperipheral, "Error");
    });
</code>```

Body:
we are using serial port device for sending and receiving data from this device to application, everything is going on perfect, but when we setting up wrong setting in device as well as in application but we got garbage value from device but we need setting value  output from device is there any idea to get setting value from the device.
is there any idea ?

when we are trying to change settings we didn't receive garbage value when again try connection with same settings then we are receiving value from device starting with garbage value.

let serial = {
      path: data.port,
      baudRate: parseInt(data.baurate),
      databits: parseInt(data.databits),
      stopbits: parseInt(data.stopbits),
      parity: data.parity,
      protocol: data.protocol,
      encoding: data.encoding,
    };

    /* here we try to make connection to the peripheral based on the settings selected.*/

    if (connect.current === 1) {

      sp = new serialport(serial);
    }

    /* Re-establish connection with new settings    */

    if (connect.current > 1) {
      console.log("second click condition connect.current > 1");

      if (spRef.current?.sp) {

        const myInterval = new Promise((resolve, reject) => {
          spRef.current.sp.lock = false;
          spRef.current?.sp?.flush((err) => {
            console.log("data will stop coming", err);
          });

          spRef.current?.sp?.close((err) => {

            if (err === null) {

              reconnect.current = true;
              if (reconnect.current) {
                resolve("connection is closed");
              } else {
                reject("connection is not closed");
              }
            }
          });
        });

        await myInterval;
        console.log("connection trying after closed conenction");
        sp = new serialport(serial);
        console.log("sp", sp);
      }
    }

    /* here we try to check connection is established or not to the peripheral.*/

    sp.on("open", () => {
      console.log("sp event open");
      let response = "Connected";
      setTraffic({ connected: response });
      setStatus(response);
      spRef.current.sp = sp;
    });

    /* Now we check to see if incoming packets have arrived. we will parse messages based on the parser
    they have selected. */

    const parser = sp.pipe(new ReadlineParser({ delimiter: "\r\n" }));

    parser.on("data", (device) => {
      console.log("device", device);
      let values = sortStr(device);
      console.log("values", values);
      let value = roundingLogic(values);
      console.log("value", value);
      if (togglePause) {
        devicevalueDemo.push({
          value: value,
          currenttime: currentdatetimeevents(),
          status: "incoming",
        });
        devicevalue.push(value);
      }
      let copy = [...newvalue];
      setNewvalue([
        ...newvalue,
        {
          uuid: data.uuid,
          peripheralvalue: value,
        },
      ]);
    });

    /* if peripheral started sending some errors then we will send erorr message */

    sp.on("error", (err) => {
      console.log("Error coming from device", err);
      let response = { Message: "Some error passed from device" };
    });

    /* Here we will find that device is disconnected from the comport then we will message to the logs */

    sp.on("close", (err) => {
      console.log("port is closed", err);
      let response = "Disconnected";
      setTraffic({ disconnected: response });
      setStatus(response);
      setNewvalue("");
      lostperipheral = `Connection error "Lost Peripheral"`;
      peripheralLogfile(lostperipheral, "Error");
    });


问:
Node API works on local but not on AWS Lambda
I have my nodejs API written using express. which works well on my local. After deploying to my AWS Lambda I get "Cannot GET /users". Can anyone help on what could be wrong. It looks like the endpoint is not getting detected

my code:
index.js file:

```<code>const app = require("./app")
const client = require('./connection.js') // stores db config

app.get('/', (req, res) => {
    res.send('Welcome')
})

app.get('/users', (req, res)=>{
    client.query(`Select * from public.user_roles`, (err, result)=>{
        if(!err){
            res.send(result.rows);
        }
    });
    client.end;
})

app.listen(process.env.PORT || 3300, ()=>{
    console.log("Sever is now listening at port 3300");
})

client.connect();
</code>```

my app.js file:

```<code>const express = require('express');
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.json());
const cors = require('cors')
app.use(cors({
    origin:"*",
}));
module.exports = app
</code>```

my handler.js:

```<code>'use strict';
const app = require("./app")
const serverless = require("serverless-http")
module.exports.hello = serverless(app);
</code>```

serverless.yml file:

```<code>service: myAPI

frameworkVersion: '3'

provider:
  name: aws
  memorySize: 2048
  stage: dev
  timeout: 15
  runtime: nodejs12.x

functions:
  hello:
    handler: handler.hello
    events:
      - http: ANY /{proxy+}
      - http: ANY /
</code>```

Body:
I have my nodejs API written using express. which works well on my local. After deploying to my AWS Lambda I get "Cannot GET /users". Can anyone help on what could be wrong. It looks like the endpoint is not getting detected

my code:
index.js file:

const app = require("./app")
const client = require('./connection.js') // stores db config

app.get('/', (req, res) => {
    res.send('Welcome')
})

app.get('/users', (req, res)=>{
    client.query(`Select * from public.user_roles`, (err, result)=>{
        if(!err){
            res.send(result.rows);
        }
    });
    client.end;
})

app.listen(process.env.PORT || 3300, ()=>{
    console.log("Sever is now listening at port 3300");
})

client.connect();

my app.js file:

const express = require('express');
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.json());
const cors = require('cors')
app.use(cors({
    origin:"*",
}));
module.exports = app

my handler.js:

'use strict';
const app = require("./app")
const serverless = require("serverless-http")
module.exports.hello = serverless(app);

serverless.yml file:

service: myAPI

frameworkVersion: '3'

provider:
  name: aws
  memorySize: 2048
  stage: dev
  timeout: 15
  runtime: nodejs12.x

functions:
  hello:
    handler: handler.hello
    events:
      - http: ANY /{proxy+}
      - http: ANY /


问:
Firebase - This app cannot be installed because its integrity could not be verified
I got the message This app cannot be installed because its integrity could not be verified after downloading my application from Firebase.

But after I release the new version of my application, the problem has disappeared and I can download my application normally, also a previous version of the application which got the same error message is back to normal again.

Why did that error occur?


问:
Error building Quarkus native image with Kafka streams
I am battling down to build a simple Kafka Stream project as a native image. Maybe some build settings are missing or not well documented. I'd appreciate any comment.
This is happening to me only building Kafka Streams. Building other Kafka clients (producer/consumer) are perfectly ok.

Thank you

Framework: Quarkus 14.x
OS: MacOS (BigSur)

```<code>Error: Classes that should be initialized at run time got initialized during image building:
 io.netty.buffer.PooledByteBufAllocator the class was requested to be initialized at run time (from 'META-INF/native-image/io.netty/netty-buffer/native-image.properties' in 'file:///project/lib/io.netty.netty-buffer-4.1.86.Final.jar' with 'io.netty.buffer.PooledByteBufAllocator'). To see why io.netty.buffer.PooledByteBufAllocator got initialized use --trace-class-initialization=io.netty.buffer.PooledByteBufAllocator
To see how the classes got initialized, use --trace-class-initialization=io.netty.buffer.PooledByteBufAllocator
com.oracle.svm.core.util.UserError$UserException: Classes that should be initialized at run time got initialized during image building:
 io.netty.buffer.PooledByteBufAllocator the class was requested to be initialized at run time (from 'META-INF/native-image/io.netty/netty-buffer/native-image.properties' in 'file:///project/lib/io.netty.netty-buffer-4.1.86.Final.jar' with 'io.netty.buffer.PooledByteBufAllocator'). To see why io.netty.buffer.PooledByteBufAllocator got initialized use --trace-class-initialization=io.netty.buffer.PooledByteBufAllocator
To see how the classes got initialized, use --trace-class-initialization=io.netty.buffer.PooledByteBufAllocator
        at org.graalvm.nativeimage.builder/com.oracle.svm.core.util.UserError.abort(UserError.java:73)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.classinitialization.ProvenSafeClassInitializationSupport.checkDelayedInitialization(ProvenSafeClassInitializationSupport.java:273)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.classinitialization.ClassInitializationFeature.duringAnalysis(ClassInitializationFeature.java:164)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.lambda$runPointsToAnalysis$10(NativeImageGenerator.java:748)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.FeatureHandler.forEachFeature(FeatureHandler.java:85)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.lambda$runPointsToAnalysis$11(NativeImageGenerator.java:748)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.AbstractAnalysisEngine.runAnalysis(AbstractAnalysisEngine.java:162)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:745)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:578)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.run(NativeImageGenerator.java:535)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.buildImage(NativeImageGeneratorRunner.java:403)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.build(NativeImageGeneratorRunner.java:580)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.main(NativeImageGeneratorRunner.java:128)
------------------------------------------------------------------------------------------------------------------------
</code>```

Body:
I am battling down to build a simple Kafka Stream project as a native image. Maybe some build settings are missing or not well documented. I'd appreciate any comment.
This is happening to me only building Kafka Streams. Building other Kafka clients (producer/consumer) are perfectly ok.

Thank you

Framework: Quarkus 14.x
OS: MacOS (BigSur)

Error: Classes that should be initialized at run time got initialized during image building:
 io.netty.buffer.PooledByteBufAllocator the class was requested to be initialized at run time (from 'META-INF/native-image/io.netty/netty-buffer/native-image.properties' in 'file:///project/lib/io.netty.netty-buffer-4.1.86.Final.jar' with 'io.netty.buffer.PooledByteBufAllocator'). To see why io.netty.buffer.PooledByteBufAllocator got initialized use --trace-class-initialization=io.netty.buffer.PooledByteBufAllocator
To see how the classes got initialized, use --trace-class-initialization=io.netty.buffer.PooledByteBufAllocator
com.oracle.svm.core.util.UserError$UserException: Classes that should be initialized at run time got initialized during image building:
 io.netty.buffer.PooledByteBufAllocator the class was requested to be initialized at run time (from 'META-INF/native-image/io.netty/netty-buffer/native-image.properties' in 'file:///project/lib/io.netty.netty-buffer-4.1.86.Final.jar' with 'io.netty.buffer.PooledByteBufAllocator'). To see why io.netty.buffer.PooledByteBufAllocator got initialized use --trace-class-initialization=io.netty.buffer.PooledByteBufAllocator
To see how the classes got initialized, use --trace-class-initialization=io.netty.buffer.PooledByteBufAllocator
        at org.graalvm.nativeimage.builder/com.oracle.svm.core.util.UserError.abort(UserError.java:73)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.classinitialization.ProvenSafeClassInitializationSupport.checkDelayedInitialization(ProvenSafeClassInitializationSupport.java:273)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.classinitialization.ClassInitializationFeature.duringAnalysis(ClassInitializationFeature.java:164)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.lambda$runPointsToAnalysis$10(NativeImageGenerator.java:748)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.FeatureHandler.forEachFeature(FeatureHandler.java:85)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.lambda$runPointsToAnalysis$11(NativeImageGenerator.java:748)
        at org.graalvm.nativeimage.pointsto/com.oracle.graal.pointsto.AbstractAnalysisEngine.runAnalysis(AbstractAnalysisEngine.java:162)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.runPointsToAnalysis(NativeImageGenerator.java:745)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.doRun(NativeImageGenerator.java:578)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGenerator.run(NativeImageGenerator.java:535)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.buildImage(NativeImageGeneratorRunner.java:403)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.build(NativeImageGeneratorRunner.java:580)
        at org.graalvm.nativeimage.builder/com.oracle.svm.hosted.NativeImageGeneratorRunner.main(NativeImageGeneratorRunner.java:128)
------------------------------------------------------------------------------------------------------------------------