问:
not able to get SQLite database in python
1) I am new to python and I am using SQLITE database. While setting up the connection I am not able to get the database(Which I already made in SQLite and tables as well)

2) While executing the insert query I am getting the following error :
    "sqlite3.OperationalError: no such table: MemberDetails"

HERE IS THE CODE:

```<code>import sqlite3
my_cursor = ""
conn = ""

# setting the connection with database
# def con_database_connection():
# try:
globals()
conn = sqlite3.connect('CareForNation.db')
# new_con = sqlite3.connect('CareForNation.db')
print("connection established successfully")
my_cursor = conn.cursor()
# except sqlite3 as error
# print("Connection failed")

# Login Admin Control
user_name = input("Enter user name")
user_password = input("Enter Password")
if user_name == "123" and user_password == "123":
    print("Login successful")
else:
    print("Invalid user name or password")

# Inserting member information
# con_database_connection()
mid = input("Enter Member ID")
member_name = input("Enter member name")
member_phone_number = input("enter phone number")
member_address = input("Enter address")

insert_data = my_cursor.execute("insert into MemberDetails(Member_ID, Member_Name, Phone_Number, address) "
                                "values('mid', 'member_name', 'member_phone_number', member_address)")

# abc = conn.executescript("select * from MemberDetails")

print("New data entered to Member details module")
conn.close()
</code>```

答:
First create the table:

```<code>my_cursor.execute("""CREATE TABLE MemberDetails(
            mid text,
            member_name text,
            member_phone_number text,
            member_address text
            )""")
</code>```

Then, replace

```<code>insert_data = my_cursor.execute("insert into MemberDetails(Member_ID, Member_Name, Phone_Number, address)"
                                "values('mid', 'member_name', 'member_phone_number', member_address)"
                                )
</code>```

With:

```<code>with conn:
    my_cursor.execute("INSERT INTO MemberDetails VALUES (:mid, :member_name, :member_phone_number, :member_address)",
                      {'mid': mid, 'member_name': member_name, 'member_phone_number': member_phone_number, 'member_address': member_address})
</code>```

Body:
1) I am new to python and I am using SQLITE database. While setting up the connection I am not able to get the database(Which I already made in SQLite and tables as well)

2) While executing the insert query I am getting the following error :
    "sqlite3.OperationalError: no such table: MemberDetails"

HERE IS THE CODE:

import sqlite3
my_cursor = ""
conn = ""

# setting the connection with database
# def con_database_connection():
# try:
globals()
conn = sqlite3.connect('CareForNation.db')
# new_con = sqlite3.connect('CareForNation.db')
print("connection established successfully")
my_cursor = conn.cursor()
# except sqlite3 as error
# print("Connection failed")

# Login Admin Control
user_name = input("Enter user name")
user_password = input("Enter Password")
if user_name == "123" and user_password == "123":
    print("Login successful")
else:
    print("Invalid user name or password")

# Inserting member information
# con_database_connection()
mid = input("Enter Member ID")
member_name = input("Enter member name")
member_phone_number = input("enter phone number")
member_address = input("Enter address")

insert_data = my_cursor.execute("insert into MemberDetails(Member_ID, Member_Name, Phone_Number, address) "
                                "values('mid', 'member_name', 'member_phone_number', member_address)")

# abc = conn.executescript("select * from MemberDetails")

print("New data entered to Member details module")
conn.close()

Body:
First create the table:

my_cursor.execute("""CREATE TABLE MemberDetails(
            mid text,
            member_name text,
            member_phone_number text,
            member_address text
            )""")

Then, replace

insert_data = my_cursor.execute("insert into MemberDetails(Member_ID, Member_Name, Phone_Number, address)"
                                "values('mid', 'member_name', 'member_phone_number', member_address)"
                                )

With:

with conn:
    my_cursor.execute("INSERT INTO MemberDetails VALUES (:mid, :member_name, :member_phone_number, :member_address)",
                      {'mid': mid, 'member_name': member_name, 'member_phone_number': member_phone_number, 'member_address': member_address})


来源: stackexchange

问:
Property 'rawValue' does not exist on type 'EventTarget & HTMLInputElement' error while using typescript with cleave.js
I am having the above error in onChange event while using cleave with typescript. Ts throws error stating it doesn't have 'rawValue' in event.target.
My code is as below:

```<code>import React, { useCallback, useState, useEffect, useMemo } from 'react';
import PropTypes from 'prop-types';
import { StyledCleaveInput } from './style';
import { getCleaveOptions } from './helper';

interface Props {
  error?: string;
  id?: string;
  value?: string;
  onChange?: (arg: any) => any;
  disabled?: boolean;
  placeholder?: string;
  deviceType?: string;
  additional?: object;
}

const FormattedNumberInput: React.FC<Props> = (props): JSX.Element => {
  const { id, placeholder, onChange, error, disabled, deviceType, value } = props;

  type cleaveState = {
    setRawValue: (arg: any) => any
  };

  const [cleave, setCleave] = useState<cleaveState | null>(null);

  const options = useMemo(() => getCleaveOptions(props), []);

  const handleChange = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      if(onChange){
        onChange(event.target.rawValue);
      }
    },
    [onChange]
  );

  useEffect(() => {
    if (cleave && value) cleave.setRawValue(value);
  }, [cleave, value]);

  return (
    <StyledCleaveInput
      data-id={id}
      placeholder={placeholder}
      isError={error}
      disabled={disabled}
      deviceType={deviceType}
      onChange={handleChange}
      options={options}
      onInit={setCleave}
    />
  );
};

FormattedNumberInput.propTypes = {
  error: PropTypes.string,
  id: PropTypes.string,
  value: PropTypes.string,
  onChange: PropTypes.func,
  disabled: PropTypes.bool,
  placeholder: PropTypes.string,
  deviceType: PropTypes.string,
  additional: PropTypes.object,
};

export default FormattedNumberInput;
</code>```

Error is in:   event.target.rawValue of handleChange
StyledCleaveInput imported above uses 'cleave.js' Input and hence we can have event.target.rawValue inside the event object available in onChange of input.
Installed @@types/cleave also but error is still there.

Thanks in advance for help

答:
It seems like you are making use of the Cleave.js library. In that case, for the handleChange event handler method, you should not be using HTMLInputElement as the type parameter for ChangeEvent. Instead, you might need to use Cleave (or any equivalent, as I am not too familiar with this library) as the type parameter.

```<code>const handleChange = useCallback(
  (event: React.ChangeEvent<Cleave>) => {
    if(onChange){
      onChange(event.target.rawValue);
    }
  },
  [onChange]
);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am having the above error in onChange event while using cleave with typescript. Ts throws error stating it doesn't have 'rawValue' in event.target.
My code is as below:

import React, { useCallback, useState, useEffect, useMemo } from 'react';
import PropTypes from 'prop-types';
import { StyledCleaveInput } from './style';
import { getCleaveOptions } from './helper';

interface Props {
  error?: string;
  id?: string;
  value?: string;
  onChange?: (arg: any) => any;
  disabled?: boolean;
  placeholder?: string;
  deviceType?: string;
  additional?: object;
}

const FormattedNumberInput: React.FC<Props> = (props): JSX.Element => {
  const { id, placeholder, onChange, error, disabled, deviceType, value } = props;

  type cleaveState = {
    setRawValue: (arg: any) => any
  };

  const [cleave, setCleave] = useState<cleaveState | null>(null);

  const options = useMemo(() => getCleaveOptions(props), []);

  const handleChange = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
      if(onChange){
        onChange(event.target.rawValue);
      }
    },
    [onChange]
  );

  useEffect(() => {
    if (cleave && value) cleave.setRawValue(value);
  }, [cleave, value]);

  return (

Body:
It seems like you are making use of the Cleave.js library. In that case, for the handleChange event handler method, you should not be using HTMLInputElement as the type parameter for ChangeEvent. Instead, you might need to use Cleave (or any equivalent, as I am not too familiar with this library) as the type parameter.

const handleChange = useCallback(
  (event: React.ChangeEvent<Cleave>) => {
    if(onChange){
      onChange(event.target.rawValue);
    }
  },
  [onChange]
);


问:
How to use and input from a user as argument in fopen() function?
I am trying to make a code that will open a file in a given mode using fopen, but I want the user to be able to tell the program the name or path of the file he wants to open, but the compiler shouts at me, the code I wrote is the one that follows:

```<code>printf("Path/Name of the file: \n");
char input_user = getchar();

filePointer = fopen(input_user, "r");
</code>```

The error the compiler returns is this: "warning: passing argument 1 of ‘fopen’ makes pointer from integer without a cast [-Wint-conversion]
     filePointer = fopen(input_user, "r");"

and this: "note: expected ‘const char * restrict’ but argument is of type ‘char’
 extern FILE *fopen (const char *__restrict __filename,"

答:
As "some programmer dude" stated, fopen takes a char * (a pointer to char), not a single char. Using an array will do, as he also stated.

I will just compile his comments into an answer.

```<code>#include <stdio.h>

int main()
{
    printf("Path/Name of the file: \n");
    char filename[128];
    scanf("%127s", filename);

    FILE *filePointer = fopen(filename, "r");
    return 0;
}
</code>```

I suggest you use this scanf syntax (%NUMBERs) to avoid an easy buffer overflow that could lead to a crash and a security flaw. Don't forget the additional \0 for your buffer size (I refer to the filename variable as your buffer), and be careful with user input in any real word application, especially when it is for something as important as accessing files. With an access to this program, one could just open any file even above this one in the file tree using ../ .

I also suggest you learn to read compiler output as it is very useful for problems like this one (don't worry you should naturally learn it over time after seeing  similar errors often :) ).

In your case, the compiler explicitly tells you that the function wants a char * and you are giving it a char (it says const char * restrict but const and restrict are here to tell you that the pointer will not be modified in the function).

```<code>expected ‘const char * restrict’ but argument is of type ‘char’
</code>```

I hope that you understand better what was wrong and that this was clear enough !

Body:
I am trying to make a code that will open a file in a given mode using fopen, but I want the user to be able to tell the program the name or path of the file he wants to open, but the compiler shouts at me, the code I wrote is the one that follows:

printf("Path/Name of the file: \n");
char input_user = getchar();

filePointer = fopen(input_user, "r");

The error the compiler returns is this: "warning: passing argument 1 of ‘fopen’ makes pointer from integer without a cast [-Wint-conversion]
     filePointer = fopen(input_user, "r");"

and this: "note: expected ‘const char * restrict’ but argument is of type ‘char’
 extern FILE *fopen (const char *__restrict __filename,"

Body:
As "some programmer dude" stated, fopen takes a char * (a pointer to char), not a single char. Using an array will do, as he also stated.

I will just compile his comments into an answer.

#include <stdio.h>

int main()
{
    printf("Path/Name of the file: \n");
    char filename[128];
    scanf("%127s", filename);

    FILE *filePointer = fopen(filename, "r");
    return 0;
}

I suggest you use this scanf syntax (%NUMBERs) to avoid an easy buffer overflow that could lead to a crash and a security flaw. Don't forget the additional \0 for your buffer size (I refer to the filename variable as your buffer), and be careful with user input in any real word application, especially when it is for something as important as accessing files. With an access to this program, one could just open any file even above this one in the file tree using ../ .

I also suggest you learn to read compiler output as it is very useful for problems like this one (don't worry you should naturally learn it over time after seeing  similar errors often :) ).

In your case, the compiler explicitly tells you that the function wants a char * and you are giving it a char (it says const char * restrict but const and restrict are here to tell you that the pointer will not be modified in the function).

expected ‘const char * restrict’ but argument is of type ‘char’

I hope that you understand better what was wrong and that this was clear enough !


问:
Flutter UI breaks when "smallest width" is changed in developer options
I am new into flutter programming. I have been working on a certain UI as shown below.

If I attempt to change the "smallest width" option in the developer options and set to some other value than the default, the whole UI breaks as shown.

I must add that the middle area which got completely broken was a stack widget.

```<code>@override
  Widget build(BuildContext context) {
    return Consumer<SinglePlayerGameState>(
      builder: (context, gameState, child) => Expanded(
        flex: 48,
        child: Container(
          color: gameState.getGameColor(),
          child: Center(
            child: Stack(
              overflow: Overflow.visible,
              children: <Widget>[
                Positioned(
                  child: Transform.rotate(
                    angle: 45,
                    child: UNOcard(UNOcardData(CardTypes.BACK)),
                  ),
                  top: -30,
                  left: 90,
                ),
                Positioned(
                  child: Transform.rotate(
                    angle: 65,
                    child: UNOcard(UNOcardData(CardTypes.BACK)),
                  ),
                  top: 20,
                  left: 50,
                ),
                Positioned(
                  child: Transform.rotate(
                    angle: 180,
                    child: UNOcard(UNOcardData(CardTypes.BACK)),
                  ),
                  top: 100,
                  left: 65,
                ),
                Positioned(
                  child: Transform.rotate(
                    angle: 45,
                    child: UNOcard(UNOcardData(CardTypes.BACK)),
                  ),
                  top: 10,
                  right: 10,
                ),
                Positioned(
                  child: Transform.rotate(
                    angle: 65,
                    child: UNOcard(UNOcardData(CardTypes.BACK)),
                  ),
                  top: 120,
                  right: 50,
                ),
                Positioned(
                  child: Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(30),
                        color: Colors.black),
                    child: Text(
                      "${gameState.playingCards.length}",
                      style: TextStyle(
                          fontSize: 20,
                          fontFamily: 'Frijole',
                          color: Colors.white),
                    ),
                    padding: EdgeInsets.all(7),
                  ),
                  top: 10,
                  left: 10,
                ),
                Positioned(
                  child: SizedBox(
                    child: Center(
                        child: FlatButton(
                      onPressed: () {
                        gameState.nextTurn();
                      },
                      child: Icon(
                        FontAwesomeIcons.undoAlt,
                        size: 25,
                      ),
                      color: Colors.white,
                    )),
                    height: 35,
                    width: 60,
                  ),
                  bottom: 10,
                  left: 10,
                ),
                Positioned(
                  child: DragTarget<UNOcardData>(
                    onWillAccept: (UNOcardData data) {
                      var res = isValidMove(
                          data, gameState.onGoingCards.last, gameState);
                      if(res){
                        print(res);
                        return true;
                      }else{
                        vibrate();
                         return false;
                      }
                    },
                    onAccept: (UNOcardData data) {
                      print(data);
                      performAction(data, gameState);
                    },
                    builder: (context, candidateData, rejectedData) =>
                        Transform.rotate(
                      angle: 0,
                      child: gameState.onGoingCards.last,
                    ),
                  ),
                  top: 60,
                  right: 100,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
</code>```

Like we use units like "vmin , vmax , vh " etc in html/css for responsive texts and sizes, what are the alternatives in flutter ? How do we responsive apps in flutter exactly ? I am not talking about scaling to other screen sizes, but to slightly different resolutions and logical pixel densities.

Thanks for your time.

答:
That's because you are using margins from the edges with

```<code>Positioned(
  child: Transform.rotate(
    angle: 180,
    child: UNOcard(UNOcardData(CardTypes.BACK)),
  ),
  top: 100,
  left: 65,
),
</code>```

This top means that it's going to position itself 100 units from the top. What you actually want is some percentage offset from the center. You can do it like this:

```<code>Positioned.fill(
  child: Align(
    // (0, 0) is the center, (1, 1) is right bottom, (-1, -1) is left top and so on
    alignment: Alignment(0.25, 0.25),
    child: YOUR_WIDGET
  )
);
</code>```

For more responsive UI you can get screen_sizes with MediaQuery.of(context) or use a package like flutter_screenutil to scale your UI according to a sample, like for example 1080x1920 screen.

Body:
I am new into flutter programming. I have been working on a certain UI as shown below.

If I attempt to change the "smallest width" option in the developer options and set to some other value than the default, the whole UI breaks as shown.

I must add that the middle area which got completely broken was a stack widget.

@override
  Widget build(BuildContext context) {
    return Consumer<SinglePlayerGameState>(
      builder: (context, gameState, child) => Expanded(
        flex: 48,
        child: Container(
          color: gameState.getGameColor(),
          child: Center(
            child: Stack(
              overflow: Overflow.visible,
              children: <Widget>[
                Positioned(
                  child: Transform.rotate(
                    angle: 45,
                    child: UNOcard(UNOcardData(CardTypes.BACK)),
                  ),
                  top: -30,
                  left: 90,
                ),
                Positioned(
                  child: Transform.rotate(
                    angle: 65,
                    child: UNOcard(UNOcardData(CardTypes.BACK)),
                  ),
                  top: 20,
                  left: 50,
                ),
                Positioned(
                  child: Transform.rotate(
                    angle: 180,
                    child: UNOcard(UNOcardData(CardTypes.BACK)),
                  ),
                  top: 100,
                  left: 65,
                ),
                Positioned(
                  child: Transform.rotate(
                    angle: 45,
                    child: UNOcard(UNOcardData(CardTypes.BACK)),
                  ),
                  top: 10,
                  right: 10,
                ),
                Positioned(
                  child: Transform.rotate(
                    angle: 65,
                    child: UNOcard(UNOcardData(CardTypes.BACK)),
                  ),
                  top: 120,
                  right: 50,
                ),
                Positioned(
                  child: Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(30),
                        color: Colors.black),
                    child: Text(
                      "${gameState.playingCards.length}",
                      style: TextStyle(
                          fontSize: 20,
                          fontFamily: 'Frijole',
                          color: Colors.white),
                    ),
                    padding: EdgeInsets.all(7),
                  ),
                  top: 10,
                  left: 10,
                ),
                Positioned(
                  child: SizedBox(
                    child: Center(
                        child: FlatButton(
                      onPressed: () {
                        gameState.nextTurn();
                      },
                      child: Icon(
                        FontAwesomeIcons.undoAlt,
                        size: 25,
                      ),
                      color: Colors.white,
                    )),
                    height: 35,
                    width: 60,
                  ),
                  bottom: 10,
                  left: 10,
                ),
                Positioned(
                  child: DragTarget<UNOcardData>(
                    onWillAccept: (UNOcardData data) {
                      var res = isValidMove(
                          data, gameState.onGoingCards.last, gameState);
                      if(res){
                        print(res);
                        return true;
                      }else{
                        vibrate();
                         return false;
                      }
                    },
                    onAccept: (UNOcardData data) {
                      print(data);
                      performAction(data, gameState);
                    },
                    builder: (context, candidateData, rejectedData) =>
                        Transform.rotate(
                      angle: 0,
                      child: gameState.onGoingCards.last,
                    ),
                  ),
                  top: 60,
                  right: 100,
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Like we use units like "vmin , vmax , vh " etc in html/css for responsive texts and sizes, what are the alternatives in flutter ? How do we responsive apps in flutter exactly ? I am not talking about scaling to other screen sizes, but to slightly different resolutions and logical pixel densities.

Thanks for your time.

Body:
That's because you are using margins from the edges with

Positioned(
  child: Transform.rotate(
    angle: 180,
    child: UNOcard(UNOcardData(CardTypes.BACK)),
  ),
  top: 100,
  left: 65,
),

This top means that it's going to position itself 100 units from the top. What you actually want is some percentage offset from the center. You can do it like this:

Positioned.fill(
  child: Align(
    // (0, 0) is the center, (1, 1) is right bottom, (-1, -1) is left top and so on
    alignment: Alignment(0.25, 0.25),
    child: YOUR_WIDGET
  )
);

For more responsive UI you can get screen_sizes with MediaQuery.of(context) or use a package like flutter_screenutil to scale your UI according to a sample, like for example 1080x1920 screen.


问:
Minio / Keycloak integration: connection refused
I am trying to connect MinIO with KeyCloak and I follow the instructions provided in this documentation:
https://github.com/minio/minio/blob/master/docs/sts/keycloak.md

What I have done so far is deploy a Docker container for the MinIO server, another one for the MinioClient and a third one used for the KeyCloak server.

As you can see in the following snippet the configuration of the Minio Client container is done correctly, since I can list the buckets available in the Minio Server:

mc ls myminio
[2020-05-14 11:54:59 UTC]      0B bucket1/
[2020-05-06 12:23:01 UTC]      0B bucket2/
```

<hr>

<p>I have an issue arising when I try to configure MinIO as depicted in <strong>step 3 (Configure MinIO)</strong> of the documentation. In more detail, the command that I run is this one:</p>

```mc admin config set myminio identity_openid config_url="http://localhost:8080/auth/realms/demo/.well-known/openid-configuration" client_id="account"
```

<p>And the error I get is this one: </p>

```mc: <ERROR> Cannot set 'identity_openid config_url=http://localhost:8080/auth/realms/demo/.well-known/openid-configuration client_id=account' to server. Get http://localhost:8080/auth/realms/demo/.well-known/openid-configuration: dial tcp 127.0.0.1:8080: connect: connection refused.
```

When I curl this address http://localhost:8080/auth/realms/demo/.well-known/openid-configuration from the MinIO Client container though,  I retrieve the JSON file.

答:
Turns out, all I had to do is change the localhost in the config_url, from localhost to the IP of the KeyCloak container (172.17.0.3).

This is just a temporary solution that works for now, but I will continue searching for something more concrete than just hardcoding the IP.

When I figure out the solution, this answer will be updated.

Update

I had to create a docker-compose.yml file as the one below in order to overcome the issues without having to manually place the IP of the KeyCloak container.

```<code>version: '2'
services:

  miniod:
    image: minio/minio
    restart: always
    container_name: miniod
    ports:
    - 9000:9000
    volumes:
    - "C:/data:/data"
    environment:
    - "MINIO_ACCESS_KEY=access_key"
    - "MINIO_SECRET_KEY=secret_key"
    command: ["server", "/data"]
    networks:
    - minionw

  mcd:
    image: minio/mc
    container_name: mcd
    networks:
    - minionw

  kcd:
    image: quay.io/keycloak/keycloak:10.0.1
    container_name: kcd
    restart: always
    ports:
    - 8080:8080
    environment:
    - "KEYCLOAK_USER=admin"
    - "KEYCLOAK_PASSWORD=pass"
    networks:
    - minionw

networks:
  minionw:
    driver: "bridge"

</code>```

Body:
I am trying to connect MinIO with KeyCloak and I follow the instructions provided in this documentation:
https://github.com/minio/minio/blob/master/docs/sts/keycloak.md

What I have done so far is deploy a Docker container for the MinIO server, another one for the MinioClient and a third one used for the KeyCloak server.

As you can see in the following snippet the configuration of the Minio Client container is done correctly, since I can list the buckets available in the Minio Server:

mc ls myminio
[2020-05-14 11:54:59 UTC]      0B bucket1/
[2020-05-06 12:23:01 UTC]      0B bucket2/

I have an issue arising when I try to configure MinIO as depicted in step 3 (Configure MinIO) of the documentation. In more detail, the command that I run is this one:

mc admin config set myminio identity_openid config_url="http://localhost:8080/auth/realms/demo/.well-known/openid-configuration" client_id="account"

And the error I get is this one:

mc: <ERROR> Cannot set 'identity_openid config_url=http://localhost:8080/auth/realms/demo/.well-known/openid-configuration client_id=account' to server. Get http://localhost:8080/auth/realms/demo/.well-known/openid-configuration: dial tcp 127.0.0.1:8080: connect: connection refused.

When I curl this address http://localhost:8080/auth/realms/demo/.well-known/openid-configuration from the MinIO Client container though,  I retrieve the JSON file.

Body:
Turns out, all I had to do is change the localhost in the config_url, from localhost to the IP of the KeyCloak container (172.17.0.3).

This is just a temporary solution that works for now, but I will continue searching for something more concrete than just hardcoding the IP.

When I figure out the solution, this answer will be updated.

Update

I had to create a docker-compose.yml file as the one below in order to overcome the issues without having to manually place the IP of the KeyCloak container.

version: '2'
services:

  miniod:
    image: minio/minio
    restart: always
    container_name: miniod
    ports:
    - 9000:9000
    volumes:
    - "C:/data:/data"
    environment:
    - "MINIO_ACCESS_KEY=access_key"
    - "MINIO_SECRET_KEY=secret_key"
    command: ["server", "/data"]
    networks:
    - minionw

  mcd:
    image: minio/mc
    container_name: mcd
    networks:
    - minionw

  kcd:
    image: quay.io/keycloak/keycloak:10.0.1
    container_name: kcd
    restart: always
    ports:
    - 8080:8080
    environment:
    - "KEYCLOAK_USER=admin"
    - "KEYCLOAK_PASSWORD=pass"
    networks:
    - minionw

networks:
  minionw:
    driver: "bridge"


问:
Remove Overlapping Intervals & Divide into Non-overlapping Intervals Python
I have a sorted list of intervals List1:
[1,10], [2,4], [6,8], [20,30], [24,28], [35,40], [45,50]

where I know that the overlapping intervals are List2: [2,4], [6,8], [24,28]

from which I want to get the non-overlapping intervals, such that the Output is: [1,2], [4,6], [8,10], [20,24], [28,30], [35,40], [45,50]

How can I do this efficiently in Python?

My first thought is that I should create a new list List1 of divided intervals for every overlapping interval I come across in List2, and delete the corresponding element of List2 (continue this until List2 is empty), but I've been having some trouble getting this to work. This seems different in nature than many interval problems, so any suggestion would be great!

答:
I don't know if it's the most efficient way but it might be a good starting point for you:</p>

```<code>data = [[1, 10], [2, 4], [6, 8], [20, 30], [24, 28], [35, 40], [45, 50]]
flat_data = sorted([x for sublist in data for x in sublist])
new_intevals = [flat_data[i:i + 2] for i in range(0, len(flat_data), 2)]

print(new_intevals)
# output: [[1, 2], [4, 6], [8, 10], [20, 24], [28, 30], [35, 40], [45, 50]]
</code>```

Body:
I don't know if it's the most efficient way but it might be a good starting point for you:

data = [[1, 10], [2, 4], [6, 8], [20, 30], [24, 28], [35, 40], [45, 50]]
flat_data = sorted([x for sublist in data for x in sublist])
new_intevals = [flat_data[i:i + 2] for i in range(0, len(flat_data), 2)]

print(new_intevals)
# output: [[1, 2], [4, 6], [8, 10], [20, 24], [28, 30], [35, 40], [45, 50]]


问:
Bootstrap fluid img with svg filter
I am applying an SVG filter to responsive images on Bootstrap 4. I am applying class="img-fluid"

I don´t know how to keep same separation between images for every resolution. Works for desktop but on mobile the separation is too big

Code snippet here https://codepen.io/fernandocomet/pen/ExVBrrR?editors=1100

On my container I have:

```<code>.container {
  position: relative;
  width: 100vw;
  height: 100vh;
}
</code>```

Any help is welcome

答:
I have modified the code to have the separation gap remains at margin 5% (you may adjust according to your need) between the container.

.container {
  position: relative;
  margin: 5%;
  /*width: 100%;*/
  /*height: 100vh;*/
}

/*
.container img {
  position: absolute;
}
*/

.filtered {
  width: 100%;
  filter: url(#duotone);
  transition: opacity 1s;
}

.filtered:hover {
  opacity: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  <title>Document</title>
</head>

<body>
  <svg version="1.1" width="0" height="0" class="filter-rot">
    <filter id="duotone" color-interpolation-filters="sRGB">
      <feColorMatrix type="matrix" values="0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0" result="gray"></feColorMatrix>
    </filter>
  </svg>

  <div class="container px-0">
    <img src="https://www.fernandocomet.com/img/desktop/adcrackdown.png" class="img-fluid position-absolute" />
    <img src="https://www.fernandocomet.com/img/desktop/adcrackdown.png" class="img-fluid filtered" />
  </div>

  <div class="container px-0">
    <img src="https://www.fernandocomet.com/img/desktop/ifemafitur.png" class="img-fluid position-absolute" />
    <img src="https://www.fernandocomet.com/img/desktop/ifemafitur.png" class="img-fluid filtered" />
  </div>
</body>

</html></code>```

Title: Bootstrap fluid img with svg filter

Body:
I am applying an SVG filter to responsive images on Bootstrap 4. I am applying class="img-fluid"

I don´t know how to keep same separation between images for every resolution. Works for desktop but on mobile the separation is too big

Code snippet here https://codepen.io/fernandocomet/pen/ExVBrrR?editors=1100

On my container I have:

.container {
  position: relative;
  width: 100vw;
  height: 100vh;
}

Any help is welcome

Body:
I have modified the code to have the separation gap remains at margin 5% (you may adjust according to your need) between the container.

.container {
  position: relative;
  margin: 5%;
  /*width: 100%;*/
  /*height: 100vh;*/
}

/*
.container img {
  position: absolute;
}
*/

.filtered {
  width: 100%;
  filter: url(#duotone);
  transition: opacity 1s;
}

.filtered:hover {
  opacity: 0;
}

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
  <title>Document</title>
</head>

<body>
  <svg version="1.1" width="0" height="0" class="filter-rot">
    <filter id="duotone" color-interpolation-filters="sRGB">
      <feColorMatrix type="matrix" values="0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0" result="gray"></feColorMatrix>
    </filter>
  </svg>

  <div class="container px-0">
    <img src="https://www.fernandocomet.com/img/desktop/adcrackdown.png" class="img-fluid position-absolute" />
    <img src="https://www.fernandocomet.com/img/desktop/adcrackdown.png" class="img-fluid filtered" />
  </div>

  <div class="container px-0">
    <img src="https://www.fernandocomet.com/img/desktop/ifemafitur.png" class="img-fluid position-absolute" />
    <img src="https://www.fernandocomet.com/img/desktop/ifemafitur.png" class="img-fluid filtered" />
  </div>
</body>

</html>


问:
Script for extract Medline abstracts with PMID in c#
I want to split below text files with serial number. with C# or vb.net

```<code>3 selected items

PubMed Results

Items 1-3 of 3 (Display the 3 citations in PubMed)

1.

Interventions for Anesthetic Success in Symptomatic Irreversible Pulpitis: A Network Meta-Analysis of Randomized Controlled Trials
J Dent Anesth Pain Med. 2019 Dec;19(6):323-341. doi: 10.17245/jdapm.2019.19.6.323. Epub 2019 Dec 27.

Authors

Affiliations

1 Dental Training Department, Ministry of Health, Bahrain.
2 Department of Pharmacology & Therapeutics, College of Medicine and Medical Sciences, Arabian Gulf University, Manama, Bahrain.
PMID: 31942448
PMCID: PMC6946831
DOI: 10.17245/jdapm.2019.19.6.323
Free PMC article

Abstract
Background: Local anesthetics alone or in combination with adjuncts, such as oral medications, have routinely been used for pain control during endodontic treatment. The best clinical choice amongst the vast numbers of agents and techniques available for pain control for irreversible pulpitis is unclear. This network meta-analysis combined the available evidence on agents and techniques for pulpal anesthesia in the maxilla and mandible, in order to identify the best amongst these approaches statistically, as a basis for future clinical trials.

Keywords: Pain; Pulpitis; Root Canal Therapy.

Copyright © 2019 Journal of Dental Anesthesia and Pain Medicine.

Conflict of interest statement
CONFLICT OF INTEREST: None declared.

87 references
5 figures
Full-text links
full-text provider logoThe Korean Dental Society of Anesthesiology Free PMC article

2.

Attitude and Awareness of Dentists Practicing in Southern India Toward Non-steroidal Anti-inflammatory Drugs
J Pharm Bioallied Sci. 2019 May;11(Suppl 2):S355-S359. doi: 10.4103/JPBS.JPBS_33_19.

Authors

Affiliations

1 Department of Oral Medicine and Radiology, Sree Mookambika Institute of Dental Sciences, Kanyakumari Tamil Nadu, India.
2 Department of Pedodontics, Azeezia College of Dental Sciences and Research, Kollam, India.
3 Department of Pedodontics, Government Dental College, Kottayam, Kerala, India.
PMID: 31198368
PMCID: PMC6555374
DOI: 10.4103/JPBS.JPBS_33_19
Free PMC article

Abstract
Background: Pain management is an everyday challenge in dentistry. Analgesics are the group of drugs prescribed for effective pain management, of which nonsteroidal anti-inflammatory drugs (NSAIDs) are the most commonly prescribed drugs. Selection of NSAIDs must be judiciously made considering their pharmacological properties and adverse effects.

Keywords: Analgesics; cyclooxygenase; nonsteroidal anti-inflammatory drugs; pain.

Conflict of interest statement
There are no conflicts of interest.

23 references
2 figures
Full-text links
full-text provider logoMedknow Publications and Media Pvt Ltd Free PMC article

3.

Study of Efficiency and Spectral Resolution for Mathematical Filtration Technique Using Novel Unlimited Derivative Ratio and Classical Univariate Spectrophotometric Methods for the Multicomponent Determination-Stability Analysis
Heliyon. 2019 May 9;5(5):e01669. doi: 10.1016/j.heliyon.2019.e01669. eCollection 2019 May.

Authors

Affiliations

1 Analytical Chemistry Department, Faculty of Pharmacy, Cairo University, Kasr El- Aini Street, 11562 Cairo, Egypt.
2 Pharmaceutical Chemistry Department, Faculty of Pharmaceutical Science and Pharmaceutical Industries, Future University in Egypt, 5th Settlement, 11835 Cairo, Egypt.
PMID: 31193052
PMCID: PMC6514739
DOI: 10.1016/j.heliyon.2019.e01669
Free PMC article

Abstract
Six simple, sensitive and selective spectrophotometric methods based on mathematical filtration technique are presented for concurrent determination of aceclofenac (ACE) and paracetamol (PAR) in presence of their degradation products, namely; diclofenac sodium (DIC) and 4-aminophenol (4-AP), respectively without preliminary physical separation procedures. This technique consists of several consecutive steps applied on built-in spectrophotometer software utilizing zero and/or derivative and/or ratio spectra of the studied components.

Keywords: Analytical chemistry.
</code>```

I want to split paragraph with serial Number. like 1, 2, 3,

答:
The following code splits the text into four sections (header, and 3 abstracts)</p>

```<code>using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.txt";

        static void Main(string[] args)
        {
            string input = File.ReadAllText(FILENAME);
            string pattern = @"\r\n\r\n^\d+.\r\n\r\n";

            string[] splitData = Regex.Split(input, pattern, RegexOptions.Multiline);
        }
    }
}
</code>```

Body:
I want to split below text files with serial number. with C# or vb.net

3 selected items

PubMed Results

Items 1-3 of 3 (Display the 3 citations in PubMed)

1.

Interventions for Anesthetic Success in Symptomatic Irreversible Pulpitis: A Network Meta-Analysis of Randomized Controlled Trials
J Dent Anesth Pain Med. 2019 Dec;19(6):323-341. doi: 10.17245/jdapm.2019.19.6.323. Epub 2019 Dec 27.

Authors

Affiliations

1 Dental Training Department, Ministry of Health, Bahrain.
2 Department of Pharmacology & Therapeutics, College of Medicine and Medical Sciences, Arabian Gulf University, Manama, Bahrain.
PMID: 31942448
PMCID: PMC6946831
DOI: 10.17245/jdapm.2019.19.6.323
Free PMC article

Abstract
Background: Local anesthetics alone or in combination with adjuncts, such as oral medications, have routinely been used for pain control during endodontic treatment. The best clinical choice amongst the vast numbers of agents and techniques available for pain control for irreversible pulpitis is unclear. This network meta-analysis combined the available evidence on agents and techniques for pulpal anesthesia in the maxilla and mandible, in order to identify the best amongst these approaches statistically, as a basis for future clinical trials.

Keywords: Pain; Pulpitis; Root Canal Therapy.

Copyright © 2019 Journal of Dental Anesthesia and Pain Medicine.

Conflict of interest statement
CONFLICT OF INTEREST: None declared.

87 references
5 figures
Full-text links
full-text provider logoThe Korean Dental Society of Anesthesiology Free PMC article

2.

Attitude and Awareness of Dentists Practicing in Southern India Toward Non-steroidal Anti-inflammatory Drugs
J Pharm Bioallied Sci. 2019 May;11(Suppl 2):S355-S359. doi: 10.4103/JPBS.JPBS_33_19.

Authors

Affiliations

1 Department of Oral Medicine and Radiology, Sree Mookambika Institute of Dental Sciences, Kanyakumari Tamil Nadu, India.
2 Department of Pedodontics, Azeezia College of Dental Sciences and Research, Kollam, India.
3 Department of Pedodontics, Government Dental College, Kottayam, Kerala, India.
PMID: 31198368
PMCID: PMC6555374
DOI: 10.4103/JPBS.JPBS_33_19
Free PMC article

Abstract
Background: Pain management is an everyday challenge in dentistry. Analgesics are the group of drugs prescribed for effective pain management, of which nonsteroidal anti-inflammatory drugs (NSAIDs) are the most commonly prescribed drugs. Selection of NSAIDs must be judiciously made considering their pharmacological properties and adverse effects.

Keywords: Analgesics; cyclooxygenase; nonsteroidal anti-inflammatory drugs; pain.

Conflict of interest statement
There are no conflicts of interest.

23 references
2 figures
Full-text links
full-text provider logoMedknow Publications and Media Pvt Ltd Free PMC article

3.

Study of Efficiency and Spectral Resolution for Mathematical Filtration Technique Using Novel Unlimited Derivative Ratio and Classical Univariate Spectrophotometric Methods for the Multicomponent Determination-Stability Analysis
Heliyon. 2019 May 9;5(5):e01669. doi: 10.1016/j.heliyon.2019.e01669. eCollection 2019 May.

Authors

Affiliations

1 Analytical Chemistry Department, Faculty of Pharmacy, Cairo University, Kasr El- Aini Street, 11562 Cairo, Egypt.
2 Pharmaceutical Chemistry Department, Faculty of Pharmaceutical Science and Pharmaceutical Industries, Future University in Egypt, 5th Settlement, 11835 Cairo, Egypt.
PMID: 31193052
PMCID: PMC6514739
DOI: 10.1016/j.heliyon.2019.e01669
Free PMC article

Abstract
Six simple, sensitive and selective spectrophotometric methods based on mathematical filtration technique are presented for concurrent determination of aceclofenac (ACE) and paracetamol (PAR) in presence of their degradation products, namely; diclofenac sodium (DIC) and 4-aminophenol (4-AP), respectively without preliminary physical separation procedures. This technique consists of several consecutive steps applied on built-in spectrophotometer software utilizing zero and/or derivative and/or ratio spectra of the studied components.

Keywords: Analytical chemistry.

I want to split paragraph with serial Number. like 1, 2, 3,

Body:
The following code splits the text into four sections (header, and 3 abstracts)

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.txt";

        static void Main(string[] args)
        {
            string input = File.ReadAllText(FILENAME);
            string pattern = @"\r\n\r\n^\d+.\r\n\r\n";

            string[] splitData = Regex.Split(input, pattern, RegexOptions.Multiline);
        }
    }
}


问:
How to integrate PayTM payment gateway with ANGULAR 9 app and how to handle the CALLBACK_URL
I have integrated the payment gateway of PayTM in Angular 9 app. But I don't know how to handle the CALLBACK_URL.
PayTM is sending the Form data using POST method. And I want to read the data in my component(CALLBACK_URL).
This is the incoming response of paytm that I can see in network chrome developer tool after success.

and I want to read this response in my component.

答: Merchant need to handle this from their backend not from front end Angular component. please confirm if it answers your query.</p>


问:
Power Automate Create a Channel in Microsft Teams and make visible to all Team Members
I have created a Flow in Power Automate to create a new team channel when a new item is added to a SharePoint list. Each item/channel represents a project with various metadata assigned for each item.

The flow is working perfectly but when the channel is created it is not visible to the people within the Team and they must manually make it visible and update their channel notification settings.

When manually creating a channel in Teams there is an option to make visible for everyone, I wondered is this exposed in an API somewhere but not as part of the connector?

My Question:
Is there a way when the channel is created via Power Automate to make the channel visible to everyone in the team?

答: Currently this can be done only from Teams client and it is not exposed to outside APIs.</p>


问:
Get Row value as Column Header
I have two tables as below. I want to join these two tables and need to set the column values of second table as column header as shown  below. How can I achieve this?

Table1

```<code>ID       NAME
---------------
1        AAA
2        BBB
</code>```

table2

```<code>ID         QUESTION         ANSWER
----------------------------------
1              Q1             YES
1              Q2             NO
1              Q3             YES
1              Q4             NO
1              Q5             YES
2              Q1             YES
2              Q2             YES
2              Q3             YES
2              Q4             YES
2              Q5             YES
</code>```

The output table should be

```<code>   ID      NAME       Q1     Q2      Q3     Q4      Q5
   ----------------------------------------------------
   1       AAA        YES    NO     YES     NO      YES
   2       BBB        YES    YES    YES     YES     YES
</code>```

答: Isn't this something you typically want to do in your presentation layer?  Reporting tools are made for this.</p>

Title: Get Row value as Column Header

Body:
I have two tables as below. I want to join these two tables and need to set the column values of second table as column header as shown  below. How can I achieve this?

Table1

ID       NAME
---------------
1        AAA
2        BBB

table2

ID         QUESTION         ANSWER
----------------------------------
1              Q1             YES
1              Q2             NO
1              Q3             YES
1              Q4             NO
1              Q5             YES
2              Q1             YES
2              Q2             YES
2              Q3             YES
2              Q4             YES
2              Q5             YES

The output table should be

   ID      NAME       Q1     Q2      Q3     Q4      Q5
   ----------------------------------------------------
   1       AAA        YES    NO     YES     NO      YES
   2       BBB        YES    YES    YES     YES     YES


问:
How do I copy a file with a variable name into a different folder?
I am trying to copy a file from a folder and paste it to another. Hence, the function FileCopy seemed a great solution. However, the file I want to copy will change name every day, therefore I called it value3 in my code and the name follows a cell in my workbook.

However, I have an error (File not found, error 53), at the last line of the code :

```<code>FileCopy myFPName, myNewDir & value3
</code>```

```<code>Sub copytxtfileinfolder()

    Dim myFPName As String
    Dim myNewDir As String
    Dim value3 As String
    value3 = Worksheets("Offset Helper Sheet").Range("B29").Value
'   Full name and path of original file
    myFPName = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Pepper sync\" & " value3"
'   Name of new directory to copy to
    myNewDir = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Payments Holidays\Payment Holidays txt\"
'   Copy file to new directory with same name
    FileCopy myFPName, myNewDir & value3

End Sub
</code>```

答:
Your problem lies with this line:

```<code>myFPName = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Pepper sync\" & " value3"
</code>```

Assuming value3 holds something like File.txt, there are no parentheses needed. If you enclose it with parentheses, the file it is looking for is G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Pepper sync\value3 (initial space removed automatically by Excel; instead value of value3 it looks for literrally a file named value3) (edited)

Correction:

```<code>myFPName = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Pepper sync\" & value3
</code>```

Body:
I am trying to copy a file from a folder and paste it to another. Hence, the function FileCopy seemed a great solution. However, the file I want to copy will change name every day, therefore I called it value3 in my code and the name follows a cell in my workbook.

However, I have an error (File not found, error 53), at the last line of the code :

FileCopy myFPName, myNewDir & value3

Sub copytxtfileinfolder()

    Dim myFPName As String
    Dim myNewDir As String
    Dim value3 As String
    value3 = Worksheets("Offset Helper Sheet").Range("B29").Value
'   Full name and path of original file
    myFPName = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Pepper sync\" & " value3"
'   Name of new directory to copy to
    myNewDir = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Payments Holidays\Payment Holidays txt\"
'   Copy file to new directory with same name
    FileCopy myFPName, myNewDir & value3

End Sub

Body:
Your problem lies with this line:

myFPName = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Pepper sync\" & " value3"

Assuming value3 holds something like File.txt, there are no parentheses needed. If you enclose it with parentheses, the file it is looking for is G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Pepper sync\value3 (initial space removed automatically by Excel; instead value of value3 it looks for literrally a file named value3) (edited)

Correction:

myFPName = "G:\Shared drives\Reporting\Power BI Source Files- DO NOT TOUCH\Pepper Automation\Pepper sync\" & value3


问:
How do I submit a batch set of images for OCR analysis to Azure Computer Vision API in a single transaction?
I'm looking to see if Azure Computer Vision API supports submitting a collection of images/documents for batch processing for OCR analysis for dense text document (text heavy).
Specifically, I'm looking to see if this is offered as a transactional operation.
Is my only option to use the single image per request?

Is my only option to engineer code that does the batching myself?
Any insight is appreciated.
Ive looked at the documentation here and dont see batch processing mentioned.

v2.0

https://westus.dev.cognitive.microsoft.com/docs/services/5adf991815e1060e6355ad44/operations/2afb498089f74080d7ef85eb

v3.0

https://westcentralus.dev.cognitive.microsoft.com/docs/services/computer-vision-v3-ga/operations/5d986960601faab4bf452005

If I have (as an input) a set of images (pdf,tiff,etc) and would like to get OCR for each in a transactional way (all or nothing), what existing endpoints are available?

答:
You are right, the Read operation of Azure Cognitive Services takes only 1 document (whether direct send or by URL) at a time.

It can process several pages at a time for PDF and TIFF (up to 2000 pages are processed).

Processing multiple pages at once does not improve the cost, as each processed page is count as a "feature" which is the cost unit


问:
what is the use of ! sign in some ruby methods

Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

```<code>before_filter :authenticated!
</code>```

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera

答:
In Ruby, certain types of punctuation are used at the ends of method names to denote some type of special functionality. The exclamation mark is used to mark functions that change one or more of the parameters passed into them. See the difference between gsub and gsub! for instance.

The other common one is the question mark, which denotes that the method is a question about the object and returns a boolean. For instance, include?. Most of these functions if implemented in other languages will typically start with an is or has prefix or similar.

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  Why are exclamation marks used in Ruby methods?

Hi All,

In ruby/rails I have seen some methods ended up with ! sign like

before_filter :authenticated!

just wonder what does mean by authenticated!, '!' sign

thanks in advance

cheers

sameera


问:
How execute bat from mac? Is it possible to rewrite it to python or bash script?
I have a problem with .bat file. There is a .bat file that starts the server. But on a Mac OS system, this is impossible. Are there any options to rewrite it to python or bash so that it would be possible to start from MacBook?

This is .bat file:

```<code>echo start web server..
start cmd /k node webServer.js
echo start chrome..
start chrome.exe /k http://localhost:8080
</code>```

Thanks for helping!

答:
Ok, so it would be better to use bash scripts. They are much more powerful than bat and they work on all Unix like OS-s (Linux, Mac ..) and can work on windows with some modifications.
This will show you how to run node:

Running node from a bash script

This will show you how to run the app:

https://askubuntu.com/questions/682913/how-to-write-shell-script-to-start-some-programs

Also, look at this link for an introduction to bash, it is a good thing to know it:

https://linuxconfig.org/bash-scripting-tutorial-for-beginners

Also on the https://www.mac-forums.com/forums/switcher-hangout/302162-execute-bat-file-mac.html you can see how to run it on mac but as they pointed out there it doesn't work 100%.

Edit1:
This is the code:

```<code>#!/bin/bash

echo "Star server .."
node webServer.js
echo "Open chrome"
open http://localhost:8080
</code>```

For node just add the path to file, like you would usually run it.
For last line it opens default browser with link.

Body:
I have a problem with .bat file. There is a .bat file that starts the server. But on a Mac OS system, this is impossible. Are there any options to rewrite it to python or bash so that it would be possible to start from MacBook?

This is .bat file:

echo start web server..
start cmd /k node webServer.js
echo start chrome..
start chrome.exe /k http://localhost:8080

Thanks for helping!

Body:
Ok, so it would be better to use bash scripts. They are much more powerful than bat and they work on all Unix like OS-s (Linux, Mac ..) and can work on windows with some modifications.
This will show you how to run node:

Running node from a bash script

This will show you how to run the app:

https://askubuntu.com/questions/682913/how-to-write-shell-script-to-start-some-programs

Also, look at this link for an introduction to bash, it is a good thing to know it:

https://linuxconfig.org/bash-scripting-tutorial-for-beginners

Also on the https://www.mac-forums.com/forums/switcher-hangout/302162-execute-bat-file-mac.html you can see how to run it on mac but as they pointed out there it doesn't work 100%.

Edit1:
This is the code:

#!/bin/bash

echo "Star server .."
node webServer.js
echo "Open chrome"
open http://localhost:8080

For node just add the path to file, like you would usually run it.
For last line it opens default browser with link.


问:
Vuejs equivalent of jquery-cron
does anybody know an equivalent of jquery-cron (https://github.com/shawnchin/jquery-cron) with similar, very simple, text/select interface?

I have seen vue-cron and point-vue-cron but they are too complex.

答:
Checkout vue-cron-editor it has the best UI i've seen so far, might get you halfway there.

*disclaimer, I haven't actually used this yet, just found it during my search.

Title: Vuejs equivalent of jquery-cron


问:
How to include column values as null even when condition is not met?

Write a query to show ALL building names, their metering company name and meter type for all buildings that do not have postpaid meters.

The image 1 is the result that I should get and image 2 is the results that i am getting:

```<code>USE Ultimate_DataBase
GO

SELECT [Bld_Name], [Elec_company_name], [Mtype_Name]
FROM [dbo].[Metering_Company] A
FULL OUTER JOIN [dbo].[Metering_Type] D
ON A.[MType_ID]= D.MType_ID
FULL OUTER JOIN [dbo].[Building_metering] B
ON A.[Elec_ID]= B.[Elec_ID]
FULL OUTER JOIN [dbo].[Building] C
ON C.[Bld_ID]= B.[Bld_ID]
WHERE [Mtype_Name] != 'POSTPAID'
</code>```

答:
Try moving the WHERE logic to the corresponding ON clause:

```<code>SELECT [Bld_Name], [Elec_company_name], [Mtype_Name]
FROM [dbo].[Metering_Company] A
FULL OUTER JOIN [dbo].[Metering_Type] D
    ON A.[MType_ID]= D.MType_ID AND
       [Mtype_Name] != 'POSTPAID'              -- change is here
FULL OUTER JOIN [dbo].[Building_metering] B
    ON A.[Elec_ID]= B.[Elec_ID]
FULL OUTER JOIN [dbo].[Building] C
    ON C.[Bld_ID]= B.[Bld_ID];
</code>```

Note: Please add aliases to your select clause.  They are not mandatory, assuming no two tables ever have columns by the same name, but just having aliases would have made your question easier to answer.

Body:
Write a query to show ALL building names, their metering company name and meter type for all buildings that do not have postpaid meters.

The image 1 is the result that I should get and image 2 is the results that i am getting:

USE Ultimate_DataBase
GO

SELECT [Bld_Name], [Elec_company_name], [Mtype_Name]
FROM [dbo].[Metering_Company] A
FULL OUTER JOIN [dbo].[Metering_Type] D
ON A.[MType_ID]= D.MType_ID
FULL OUTER JOIN [dbo].[Building_metering] B
ON A.[Elec_ID]= B.[Elec_ID]
FULL OUTER JOIN [dbo].[Building] C
ON C.[Bld_ID]= B.[Bld_ID]
WHERE [Mtype_Name] != 'POSTPAID'

Body:
Try moving the WHERE logic to the corresponding ON clause:

SELECT [Bld_Name], [Elec_company_name], [Mtype_Name]
FROM [dbo].[Metering_Company] A
FULL OUTER JOIN [dbo].[Metering_Type] D
    ON A.[MType_ID]= D.MType_ID AND
       [Mtype_Name] != 'POSTPAID'              -- change is here
FULL OUTER JOIN [dbo].[Building_metering] B
    ON A.[Elec_ID]= B.[Elec_ID]
FULL OUTER JOIN [dbo].[Building] C
    ON C.[Bld_ID]= B.[Bld_ID];

Note: Please add aliases to your select clause.  They are not mandatory, assuming no two tables ever have columns by the same name, but just having aliases would have made your question easier to answer.


问:
ReverseManyToOneDescriptor object has no attribute order_by django 2.1
im learning from the book the python crash course and i'm trying to create ids for topic here's the code:

```<code>def topic(request, topic_id):
    """show a single topic and all its entries."""
    topic = Topic.objects.get(id=topic_id)
    entries = Topic.entry_set.order_by('-date_added')
    context = {'topic': topic, 'entries': entries}
    return render(request, 'learning_logs/topic.html', context)
</code>```

django raises an error when i go to http://localhost:8000/topics/1/

答:
Sorry for resurrecting this, but I have the same issue and the above solutions don't work for me.
Here is my code:</p>

```<code>from django.shortcuts import render
from .models import Topic

def index(request):
    """The home page for learning log"""
    return render(request, 'learning_logs/index.html')

def topics(request):
    """Show all topics."""
    topics = Topic.objects.order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_logs/topics.html', context)

def topic(request, topic_id):
    """Show a single topic and all its entries"""
    topic = Topic.objects.get(id=topic_id)
    entries = topic.entry_set.order_by('-date_added')  # lowercase "t"
    context = {'topic': topic, 'entries': entries}
    return render(request, 'learning_logs/topic.html', context)
</code>```

Body:
im learning from the book the python crash course and i'm trying to create ids for topic here's the code:

def topic(request, topic_id):
    """show a single topic and all its entries."""
    topic = Topic.objects.get(id=topic_id)
    entries = Topic.entry_set.order_by('-date_added')
    context = {'topic': topic, 'entries': entries}
    return render(request, 'learning_logs/topic.html', context)

django raises an error when i go to http://localhost:8000/topics/1/

Body:
Sorry for resurrecting this, but I have the same issue and the above solutions don't work for me.
Here is my code:

from django.shortcuts import render
from .models import Topic

def index(request):
    """The home page for learning log"""
    return render(request, 'learning_logs/index.html')

def topics(request):
    """Show all topics."""
    topics = Topic.objects.order_by('date_added')
    context = {'topics': topics}
    return render(request, 'learning_logs/topics.html', context)

def topic(request, topic_id):
    """Show a single topic and all its entries"""
    topic = Topic.objects.get(id=topic_id)
    entries = topic.entry_set.order_by('-date_added')  # lowercase "t"
    context = {'topic': topic, 'entries': entries}
    return render(request, 'learning_logs/topic.html', context)


问:
Java Library Commons Lang3 'ClassNotFoundException' error
```<code>import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;

public class MonsterGame {

    public static void main(String[] args)
    {

        Monster.buildBattleBoard();

        char[][] tempBattleBoard = new char[10][10];

        // ObjectName[] ArrayName = new ObjectName[4];

        Monster[] Monsters = new Monster[4];

        // Monster(int health, int attack, int movement, String name)

        Monsters[0] = new Monster(1000, 20, 1, "Frank");
        Monsters[1] = new Monster(500, 40, 2, "Drac");
        Monsters[2] = new Monster(1000, 20, 1, "Paul");
        Monsters[3] = new Monster(1000, 20, 1, "George");

        Monster.redrawBoard();

    for (Monster m : Monsters) {
        if(m.getAlive()) {
            int arrayItemIndex = ArrayUtils.indexOf(Monsters, m);
            m.moveMonster(Monsters, arrayItemIndex);
        }
    }

    Monster.redrawBoard();

}
}
</code>```

When trying to run this code, I get this error:

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang3/ArrayUtils
    at MonsterGame.main(MonsterGame.java:55)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang3.ArrayUtils
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    ... 1 more
</code>```

I have two files, in the same package. I've only shown this one because I do not believe the other file is the problem.
I followed a tutorial on how to use java libraries: download, import, build path etc.

The problem here is, the import seems to be fine but actually using the library is the problem.

I'm very new to Java so sorry if this is a very simple error to fix.

Thank you for any response/feedback in advance.

答:
The referenced library you are using (apache common lang3) and any other library for that matter is used in three different ways.

First, you need the library during development, so your IDE can
validate your code, when you call classes, objects and methods from
the library.

During compilation you need the library, so the java
compiler can reference the right paths, and optimize your code,
where possible.

You need the library during runtime, when your program is run by the Java Virtual Machine, so it can find whatever you used from the library.

The first 2 are usually seen as one, because both is usually considered 'compile time', though strictly speaking only the second one actually is. This means that you need to have the library in place for the IDE (for points 1 and 2) and for the program (point 3). Your exception is thrown, because during runtime, your library is not found by the ClassLoader. The ClassLoader is the way the JVM loads classes for the programs it uses. If the JVM does not find a class, it cannot continue to execute the Thread you are running, and you are probably only running one Thread (a main thread).

Therefore your program breaks, and stops running. Please either recheck the tutorial you are using on how to correctly import libraries or export the library to the lib folder next to the jar you are exporting.

Edit: When using an up to date version of eclipse, and exporting a project as runnable jar, you are asked what way you want to handle libraries:

If you do not see this subsection of the export dialog, you are doing something wrong (probably you are not exporting as runnable jar).

Body:
import java.util.Arrays;
import org.apache.commons.lang3.ArrayUtils;

public class MonsterGame {

    public static void main(String[] args)
    {

        Monster.buildBattleBoard();

        char[][] tempBattleBoard = new char[10][10];

        // ObjectName[] ArrayName = new ObjectName[4];

        Monster[] Monsters = new Monster[4];

        // Monster(int health, int attack, int movement, String name)

        Monsters[0] = new Monster(1000, 20, 1, "Frank");
        Monsters[1] = new Monster(500, 40, 2, "Drac");
        Monsters[2] = new Monster(1000, 20, 1, "Paul");
        Monsters[3] = new Monster(1000, 20, 1, "George");

        Monster.redrawBoard();

    for (Monster m : Monsters) {
        if(m.getAlive()) {
            int arrayItemIndex = ArrayUtils.indexOf(Monsters, m);
            m.moveMonster(Monsters, arrayItemIndex);
        }
    }

    Monster.redrawBoard();

}
}

When trying to run this code, I get this error:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang3/ArrayUtils
    at MonsterGame.main(MonsterGame.java:55)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang3.ArrayUtils
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    ... 1 more

I have two files, in the same package. I've only shown this one because I do not believe the other file is the problem.
I followed a tutorial on how to use java libraries: download, import, build path etc.

The problem here is, the import seems to be fine but actually using the library is the problem.

I'm very new to Java so sorry if this is a very simple error to fix.

Thank you for any response/feedback in advance.


问:
How to add a jar in External Libraries in Android Studio?
I am new to Android Studio.

How can I add a few jar files in the External Libraries below the < JDK > folder?

答:
In Android Studio version 3.0 or more I have used bellow like :

Create libs to the app directory if not exist folder like

Set Project view in upper left corner

Go to project

Go to app

click on apps->New->Directory

name the folder libs

paste the jar to the libs folder

directory will look like bellow image

In build.gradle add these lines

```<code>// Add this line if was not added before.
implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation files('libs/com.ibm.icu_3.4.4.1.jar')
</code>```

Body:
In Android Studio version 3.0 or more I have used bellow like :

Create libs to the app directory if not exist folder like

Set Project view in upper left corner

Go to project

Go to app

click on apps->New->Directory

name the folder libs

paste the jar to the libs folder

directory will look like bellow image

In build.gradle add these lines

// Add this line if was not added before.
implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation files('libs/com.ibm.icu_3.4.4.1.jar')


问:
What is cflags's function?
In this issue, CFLAGS set as path:

https://unix.stackexchange.com/questions/149359/what-is-the-correct-syntax-to-add-cflags-and-ldflags-to-configure

In this issue, CFLAGS set as compile option:

How to use LDFLAGS in makefile

I am confused.

答:
CFLAGS stands for compiler flags. LDFLAGS is for linker flags.

CFLAGS is used to pass flags to tell the compiler information on how to build a file(s).

In your link it is used to pass the path of header file so that the compiler knows where to find them. This is done with the -I flag and is used like this: -I<path>. There are many flags you can pass to the compiler. Some common ones are:

-c : compile only (don't link). This is used to compile a c/cpp file into an object (.o) file.

-o : output name. This is used to specify the output name. E.g. gcc -c fred.c -o fred.o or gcc fred.c -o fred

-I : this is used (as explained above) to add an include path: -I. includes the current directory. -Ianother/sub/dir includes ./another/sub/dir. Note there is no space after the -I.

Your best bet is to start with a really basic tutorial (don't worry it gets advance quite quickly):

Like this or this

Title: What is cflags's function?


问:
Javascript scope chaining inheritance
I am a student studying programming.

I have a question.

```<code>function a () {

}

a.prototype.prtSomething = function(arg) { console.log(arg); }

function b () {

}

var myObj = new b();
</code>```

If I want to use the method of a in myObj, we use this code.

```<code>b.prototype = Object.create(a.prototype);
b.prototype.constructor = b;
</code>```

That means changing the target of scope chaining. But why don't we use this code?

```<code>b.prototype.__proto__ = a.prototype;
</code>```

I think there must be a reason to creating and using a new object. but I don't know. Please teach me. Thank you.

答:
But why don't we use this code?

You could, and it would work, but:

Changing an object's prototype is generally not a good idea and may make JavaScript engines not optimize that object as well.

__proto__ used to be non-standard (and still is outside of web browsers) and until ES2015 there was no standard way to change an object's prototype. ES2015 added Object.setPrototypeOf (and added __proto__ to its web-only Annex B).

So rather than changing the prototype of b.prototype, typically we used to replace it instead.

(I say "used to" because I wouldn't write that code in modern JavaScript, I'd use class syntax if I wanted an inheritance hierarchy of constructor functions.)

Side note: Don't use __proto__. It's purely there for backward compatibility with old code, is not specified for JavaScript outside of browsers, and isn't present on objects that don't inherit from Object.prototype. (For instance, if you do const x = Object.create(null);, then "__proto__" in x is false and assigning to x.__proto__ won't change its prototype.)

Instead, if you have a reason to change the prototype of an object, use Object.setPrototypeOf:

function A() {
}

A.prototype.prtSomething = function(arg) {
    console.log(arg);
};

function B() {
}
Object.setPrototypeOf(B.prototype, A.prototype);

const myObj = new B();
myObj.prtSomething("x");```

Also note that I've changed a to A and b to B to conform with standard JavaScript naming (constructor functions start with a capital letter).

Title: Javascript scope chaining inheritance

Body:
I am a student studying programming.

I have a question.

function a () {

}

a.prototype.prtSomething = function(arg) { console.log(arg); }

function b () {

}

var myObj = new b();

If I want to use the method of a in myObj, we use this code.

b.prototype = Object.create(a.prototype);
b.prototype.constructor = b;

That means changing the target of scope chaining. But why don't we use this code?

b.prototype.__proto__ = a.prototype;

I think there must be a reason to creating and using a new object. but I don't know. Please teach me. Thank you.

Body:
But why don't we use this code?

You could, and it would work, but:

Changing an object's prototype is generally not a good idea and may make JavaScript engines not optimize that object as well.

__proto__ used to be non-standard (and still is outside of web browsers) and until ES2015 there was no standard way to change an object's prototype. ES2015 added Object.setPrototypeOf (and added __proto__ to its web-only Annex B).

So rather than changing the prototype of b.prototype, typically we used to replace it instead.

(I say "used to" because I wouldn't write that code in modern JavaScript, I'd use class syntax if I wanted an inheritance hierarchy of constructor functions.)

Side note: Don't use __proto__. It's purely there for backward compatibility with old code, is not specified for JavaScript outside of browsers, and isn't present on objects that don't inherit from Object.prototype. (For instance, if you do const x = Object.create(null);, then "__proto__" in x is false and assigning to x.__proto__ won't change its prototype.)

Instead, if you have a reason to change the prototype of an object, use Object.setPrototypeOf:

function A() {
}

A.prototype.prtSomething = function(arg) {
    console.log(arg);
};

function B() {
}
Object.setPrototypeOf(B.prototype, A.prototype);

const myObj = new B();
myObj.prtSomething("x");

Also note that I've changed a to A and b to B to conform with standard JavaScript naming (constructor functions start with a capital letter).


问:
Proguard enabled NoSuchMethodException
I'm not getting this issue, If I do not enable Proguard like this:

```<code>buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}
</code>```

Logcat:

```<code>java.lang.RuntimeException: java.lang.NoSuchMethodException: com.example.NewUsers$f.<init> [class android.view.View]
    at i.c.a.b.f.b(:147)
    at androidx.recyclerview.widget.RecyclerView$g.a(:7078)
    at androidx.recyclerview.widget.RecyclerView$v.a(:6235)
    at androidx.recyclerview.widget.RecyclerView$v.b(:6118)
    at androidx.recyclerview.widget.RecyclerView$v.d(:6114)
    at androidx.recyclerview.widget.LinearLayoutManager$c.a(:2303)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1627)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1587)
    at androidx.recyclerview.widget.LinearLayoutManager.c(:665)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(:4134)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayout(:3851)
    at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(:1897)
    at androidx.recyclerview.widget.RecyclerView$a.run(:414)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:996)
    at android.view.Choreographer.doCallbacks(Choreographer.java:794)
    at android.view.Choreographer.doFrame(Choreographer.java:725)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:981)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:237)
    at android.app.ActivityThread.main(ActivityThread.java:7807)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)
 Caused by: java.lang.NoSuchMethodException: com.example.NewUsers$f.<init> [class android.view.View]
    at java.lang.Class.getConstructor0(Class.java:2332)
    at java.lang.Class.getConstructor(Class.java:1728)
    at i.c.a.b.f.b(:144)
    at androidx.recyclerview.widget.RecyclerView$g.a(:7078)
    at androidx.recyclerview.widget.RecyclerView$v.a(:6235)
    at androidx.recyclerview.widget.RecyclerView$v.b(:6118)
    at androidx.recyclerview.widget.RecyclerView$v.d(:6114)
    at androidx.recyclerview.widget.LinearLayoutManager$c.a(:2303)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1627)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1587)
    at androidx.recyclerview.widget.LinearLayoutManager.c(:665)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(:4134)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayout(:3851)
    at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(:1897)
    at androidx.recyclerview.widget.RecyclerView$a.run(:414)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:996)
    at android.view.Choreographer.doCallbacks(Choreographer.java:794)
    at android.view.Choreographer.doFrame(Choreographer.java:725)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:981)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:237)
    at android.app.ActivityThread.main(ActivityThread.java:7807)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)
</code>```

Current proguard:

```<code>-keep class com.example.models.** { *; }
</code>```

Java class:

```<code>public class NewUsers extends AppCompatActivity {

    ....

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_users);

        ....

        mNewUsersList = findViewById(R.id.newUsers);
        mNewUsersList.setHasFixedSize(true);
        mNewUsersList.setLayoutManager(new LinearLayoutManager(this));

        onStart();

    }

    @Override
    protected void onStart() {
        super.onStart();
        FirebaseRecyclerAdapter<Users, UsersViewHolder> adapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
                Users.class,
                R.layout.users_list,
                UsersViewHolder.class,
                mDatabaseReference
        ) {

            @Override
            protected void populateViewHolder(UsersViewHolder usersViewHolder, Users users, int position) {
                usersViewHolder.setName(users.getName());

            }
        };
        mNewUsersList.setAdapter(adapter);
    }

    public static class UsersViewHolder extends RecyclerView.ViewHolder {
        View mView;

        public UsersViewHolder(@NonNull View itemView) {
            super(itemView);
            mView = itemView;
        }

        public void setName(String name) {
            TextView mUserNameView = mView.findViewById(R.id.textViewUserName);
            mUserNameView.setText(name);
        }
    }
}
</code>```

Is there any possibilities, I just want to enable minify and shrink for release

Model:

```<code>public class Users {

    String name;

    public Users() {
    }

    public Users(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}
</code>```

答:
java.lang.RuntimeException: java.lang.NoSuchMethodException:
  com.example.NewUsers$f. [class android.view.View]
      at i.c.a.b.f.b(:147)

Above exceptions thrown when a particular method cannot be found. Here due to proguard. You should try with

```<code>-keep class com.example.** { *; }
-keepclassmembers class com.example.** { *; }
</code>```

Adding @Keep on a entire package keeps the entire class as-is. Adding it on a method or field will keep the method/field (and it's name) as well as the class name intact.

OP will be

```<code>public class HomeActivity extends AppCompatActivity {

private TextView f2032b;
private Button f2033c;
</code>```

FYI

You can enable these additional optimizations by including the following in your project’s gradle.properties file:

```<code>android.enableR8.fullMode=true
</code>```

It may require you to include additional ProGuard rules to avoid runtime issues. Read official guideline about Enable more aggressive optimizations

Title: Proguard enabled NoSuchMethodException

Body:
I'm not getting this issue, If I do not enable Proguard like this:

buildTypes {
    release {
        minifyEnabled true
        shrinkResources true
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
}

Logcat:

java.lang.RuntimeException: java.lang.NoSuchMethodException: com.example.NewUsers$f.<init> [class android.view.View]
    at i.c.a.b.f.b(:147)
    at androidx.recyclerview.widget.RecyclerView$g.a(:7078)
    at androidx.recyclerview.widget.RecyclerView$v.a(:6235)
    at androidx.recyclerview.widget.RecyclerView$v.b(:6118)
    at androidx.recyclerview.widget.RecyclerView$v.d(:6114)
    at androidx.recyclerview.widget.LinearLayoutManager$c.a(:2303)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1627)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1587)
    at androidx.recyclerview.widget.LinearLayoutManager.c(:665)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(:4134)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayout(:3851)
    at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(:1897)
    at androidx.recyclerview.widget.RecyclerView$a.run(:414)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:996)
    at android.view.Choreographer.doCallbacks(Choreographer.java:794)
    at android.view.Choreographer.doFrame(Choreographer.java:725)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:981)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:237)
    at android.app.ActivityThread.main(ActivityThread.java:7807)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)
 Caused by: java.lang.NoSuchMethodException: com.example.NewUsers$f.<init> [class android.view.View]
    at java.lang.Class.getConstructor0(Class.java:2332)
    at java.lang.Class.getConstructor(Class.java:1728)
    at i.c.a.b.f.b(:144)
    at androidx.recyclerview.widget.RecyclerView$g.a(:7078)
    at androidx.recyclerview.widget.RecyclerView$v.a(:6235)
    at androidx.recyclerview.widget.RecyclerView$v.b(:6118)
    at androidx.recyclerview.widget.RecyclerView$v.d(:6114)
    at androidx.recyclerview.widget.LinearLayoutManager$c.a(:2303)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1627)
    at androidx.recyclerview.widget.LinearLayoutManager.a(:1587)
    at androidx.recyclerview.widget.LinearLayoutManager.c(:665)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(:4134)
    at androidx.recyclerview.widget.RecyclerView.dispatchLayout(:3851)
    at androidx.recyclerview.widget.RecyclerView.consumePendingUpdateOperations(:1897)
    at androidx.recyclerview.widget.RecyclerView$a.run(:414)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:996)
    at android.view.Choreographer.doCallbacks(Choreographer.java:794)
    at android.view.Choreographer.doFrame(Choreographer.java:725)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:981)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:237)
    at android.app.ActivityThread.main(ActivityThread.java:7807)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1047)

Current proguard:

-keep class com.example.models.** { *; }

Java class:

public class NewUsers extends AppCompatActivity {

    ....

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_users);

        ....

        mNewUsersList = findViewById(R.id.newUsers);
        mNewUsersList.setHasFixedSize(true);
        mNewUsersList.setLayoutManager(new LinearLayoutManager(this));

        onStart();

    }

    @Override
    protected void onStart() {
        super.onStart();
        FirebaseRecyclerAdapter<Users, UsersViewHolder> adapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
                Users.class,
                R.layout.users_list,
                UsersViewHolder.class,
                mDatabaseReference
        ) {

            @Override
            protected void populateViewHolder(UsersViewHolder usersViewHolder, Users users, int position) {
                usersViewHolder.setName(users.getName());

            }
        };
        mNewUsersList.setAdapter(adapter);
    }

    public static class UsersViewHolder extends RecyclerView.ViewHolder {
        View mView;

        public UsersViewHolder(@NonNull View itemView) {
            super(itemView);
            mView = itemView;
        }

        public void setName(String name) {
            TextView mUserNameView = mView.findViewById(R.id.textViewUserName);
            mUserNameView.setText(name);
        }
    }
}

Is there any possibilities, I just want to enable minify and shrink for release

Model:

public class Users {

    String name;

    public Users() {
    }

    public Users(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Body:
java.lang.RuntimeException: java.lang.NoSuchMethodException:
  com.example.NewUsers$f. [class android.view.View]
      at i.c.a.b.f.b(:147)

Above exceptions thrown when a particular method cannot be found. Here due to proguard. You should try with

-keep class com.example.** { *; }
-keepclassmembers class com.example.** { *; }

Adding @Keep on a entire package keeps the entire class as-is. Adding it on a method or field will keep the method/field (and it's name) as well as the class name intact.

OP will be

public class HomeActivity extends AppCompatActivity {

private TextView f2032b;
private Button f2033c;

FYI

You can enable these additional optimizations by including the following in your project’s gradle.properties file:

android.enableR8.fullMode=true

It may require you to include additional ProGuard rules to avoid runtime issues. Read official guideline about Enable more aggressive optimizations


问:
Corda wont load my cordapp in nondev mode
When corda is in devmode false it does not load my cordapps. the documentation briefly mentions signing but does not explain how to do it or what to do with the has after it has been signed. does any one know why they are not loading and if singing is the issue how to sign the cordapps and then add them to the cordaserver.</p>

答:
One of the reasons why cordapps may not be loaded is because of the minimum platform version of the cordapp. The minimum platform version is provided in the build.gradle file using the below:

```<code>cordapp {
    info {
        name "CorDapp Template"
        vendor "Corda Open Source"
        targetPlatformVersion [TargetPlatformVersion]
        minimumPlatformVersion [MinimumPlatformVersion]
    }
}
</code>```

The Corda node doesn't load a cordapp if the node's platform version is less than the minimum platform version.

Body:
One of the reasons why cordapps may not be loaded is because of the minimum platform version of the cordapp. The minimum platform version is provided in the build.gradle file using the below:

cordapp {
    info {
        name "CorDapp Template"
        vendor "Corda Open Source"
        targetPlatformVersion [TargetPlatformVersion]
        minimumPlatformVersion [MinimumPlatformVersion]
    }
}

The Corda node doesn't load a cordapp if the node's platform version is less than the minimum platform version.


问:
Do I need to initialize Logger.Log in ASP.NET Core 3 application
I'm planning to use Serilog in my ASP.NET Core 3 application and I would like to use inline initialization.
I'm only going to use the ILogger<T> interface from my application.

Is there any particular reason for assigning a new logger instance to the Log.Logger property if I don't intend to directly use the logging methods inside the Log class?

I found the following sample on the Serilog integration for ASP.NET Core page:

```<code>Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .CreateLogger();
</code>```

I understand that for logging application start-up errors I need to create a new logger instance, but couldn't I just use it like:

```<code>using Serilog;

public class Program
{
    public static int Main(string[] args)
    {
        using var startupLogger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .WriteTo.Console()
            .CreateLogger();

        try
        {
            startupLogger.Information("Starting web host");
            CreateHostBuilder(args).Build().Run();
            return 0;
        }
        catch (Exception ex)
        {
            startupLogger.Fatal(ex, "Host terminated unexpectedly");
            return 1;
        }
    }
}
</code>```

答:
By setting

```<code>Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .CreateLogger();
</code>```

And

```<code>    public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .UseSerilog(); // <-- Add this line;
                }
</code>```

You setup your logger "globally" and it is accessible in the whole application without need to be injected.

In any other class in the project or projects referencing it, you can log using by:

```<code>Log.Error("");
</code>```

using the logger settings you set in the start up.

Answering your question if it is possible to inject Serilog logger, the answer is negative. You cannot access Serilog through DI in Net Core. It's a static. You could probably hack it around if you want it, that I would not recommend. You could find some examples here.

Body:
I'm planning to use Serilog in my ASP.NET Core 3 application and I would like to use inline initialization.
I'm only going to use the ILogger<T> interface from my application.

Is there any particular reason for assigning a new logger instance to the Log.Logger property if I don't intend to directly use the logging methods inside the Log class?

I found the following sample on the Serilog integration for ASP.NET Core page:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .CreateLogger();

I understand that for logging application start-up errors I need to create a new logger instance, but couldn't I just use it like:

using Serilog;

public class Program
{
    public static int Main(string[] args)
    {
        using var startupLogger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .WriteTo.Console()
            .CreateLogger();

        try
        {
            startupLogger.Information("Starting web host");
            CreateHostBuilder(args).Build().Run();
            return 0;
        }
        catch (Exception ex)
        {
            startupLogger.Fatal(ex, "Host terminated unexpectedly");
            return 1;
        }
    }
}

Body:
By setting

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .CreateLogger();

And

    public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .UseSerilog(); // <-- Add this line;
                }

You setup your logger "globally" and it is accessible in the whole application without need to be injected.

In any other class in the project or projects referencing it, you can log using by:

Log.Error("");

using the logger settings you set in the start up.

Answering your question if it is possible to inject Serilog logger, the answer is negative. You cannot access Serilog through DI in Net Core. It's a static. You could probably hack it around if you want it, that I would not recommend. You could find some examples here.


问:
Average over Group By SQL
I have the command:

```<code>SELECT
  number_of_pairs,
  COUNT(*) --/(SUM(COUNT)) AS Percentage
FROM result
WHERE number_of_pairs!= 'NULL'
GROUP BY 1;
</code>```

Which results in :

But my objective is not to know the count of each group but the percentage of each group count with respect the total.
I have tried:

```<code>COUNT(*)/(SUM(COUNT)) AS Percentage
</code>```

But doesn't return anything.

I would like to get 379/(379+371)=0.505 in the first row and 371/(379+371)=... in the second

SQLite version : 3.11.0

答:
You can use SUM() window function to get the total:

```<code>SELECT
  number_of_pairs,
  1.0 * COUNT(*) / SUM(COUNT(*)) OVER() AS Percentage
FROM result
WHERE number_of_pairs <> 'NULL'
GROUP BY number_of_pairs;
</code>```

Unless you actually have 'NULL' as a string literal in column number_of_pairs, you must change the condition to:

```<code>number_of_pairs IS NOT NULL
</code>```

For older versions of SQLite that do not support window functions:

```<code>SELECT
  r.number_of_pairs,
  1.0 * COUNT(*) / MAX(t.counter) AS Percentage
FROM result r
CROSS JOIN (SELECT COUNT(*) counter FROM result WHERE number_of_pairs <> 'NULL') t
WHERE r.number_of_pairs <> 'NULL'
GROUP BY r.number_of_pairs;
</code>```

See a simplified demo.

Title: Average over Group By SQL

Body:
I have the command:

SELECT
  number_of_pairs,
  COUNT(*) --/(SUM(COUNT)) AS Percentage
FROM result
WHERE number_of_pairs!= 'NULL'
GROUP BY 1;

Which results in :

But my objective is not to know the count of each group but the percentage of each group count with respect the total.
I have tried:

COUNT(*)/(SUM(COUNT)) AS Percentage

But doesn't return anything.

I would like to get 379/(379+371)=0.505 in the first row and 371/(379+371)=... in the second

SQLite version : 3.11.0

Body:
You can use SUM() window function to get the total:

SELECT
  number_of_pairs,
  1.0 * COUNT(*) / SUM(COUNT(*)) OVER() AS Percentage
FROM result
WHERE number_of_pairs <> 'NULL'
GROUP BY number_of_pairs;

Unless you actually have 'NULL' as a string literal in column number_of_pairs, you must change the condition to:

number_of_pairs IS NOT NULL

For older versions of SQLite that do not support window functions:

SELECT
  r.number_of_pairs,
  1.0 * COUNT(*) / MAX(t.counter) AS Percentage
FROM result r
CROSS JOIN (SELECT COUNT(*) counter FROM result WHERE number_of_pairs <> 'NULL') t
WHERE r.number_of_pairs <> 'NULL'
GROUP BY r.number_of_pairs;

See a simplified demo.