问:
How to Add Doubles Using Getter Method on Multiple Objects from Multiple Abstract Subclasses
I have a school project I am working on, I am a beginner at java and have started to learn abstract classes. As of right now, I have covered inheritence and interfaces and my teacher has provided me with some source code. The main goal of the project is to create an invoice of a group of objects from subclasses part of other subclasses that are part of one superclass. The invoice has to have the summary of the objects (its name, cost, and flavour/seats) along with the total price, its tax and grand total that is to be printed using a method called getDescription() that is overwritten for each sub class. Keep in mind that some 'objects' have a luxury tax involved that is 15% and there is a total 8% sales tax also added. The invoice (with luxury tax already added) is supposed to look like this:

```<code>Chocolate Croissant $1.99
Evinrude 5-seat motorboat $3,475.00
Oceano 12-cabin yacht $1,045,000.00 ** Luxury tax added **
Beluga caviar from Caspian Sea $655.50 ** Luxury tax added **
Total price: $1,049,132.49
Tax        : $83,930.60
Grand total: $1,133,063.09
</code>```

However, I am getting two problems when I try this, first, the numbers I have (the seperate costs with the luxury tax), aren't adding up to the total price because I am not able to add the objects separate prices together as I have declared that in the parameters, and not as separate variables inside the main class itself, and so I cannot call on the method that lets me calculate the luxury tax before calculating for the total cost.

The second problem I have is not being able to put the correct decimal points for the price output, my teacher has provide a toString method in the superclass but I am not sure how to use it since, again, the cost itself is in the parameters of the object and not as an object or variable itself. This is not as big of a priority however, so it's alright if a solution for this is not provided.

Here is my Item superclass code, only part of it for context, and the part of my Boat subclass, and it's two 'Motorboat' and 'Yacht' subclasses. Yacht subclass also implements an interface class called LuxuryItem which only has one abstract method called 'calculateLuxuryTax' that we overwrite for each of the subclasses, which is why I won't provide that. Along with that, there is also the main class that has the object creation for each of the four subclass (Caviar, Pastry, Yacht, Motorboat) and in the constructors there are the same general format of the parameters (name, cost, horsepower/calories, flavour/origin/cabin #/seat #)

Item Class

```<code>import java.text.NumberFormat; //do I have to import this to each sub class? is that why there are no two decimal places for each output??
abstract class Item {
  double cost;
  String name;

  public Item() {
        cost = 0.0;
        name = "";
    }

  public Item(String name, double cost) {
        this.name = name;
        this.cost = cost;
    }

// a set cost method is also here, just not including it
  public double getCost() {
        return this.cost;
    }
//over here, i have deleted are getters and setters for name property
  public String toString() {
        NumberFormat currency = NumberFormat.getCurrencyInstance();
        String result;
        result = name + " -- Cost: " + currency.format(cost);
        return result;
    }

  public String getDescription() {
        return this.name;
    }

}
</code>```

Boat Subclass & Motorboat and Yacht subclasses of Boat subclass

```<code>//all three classes are in one file
abstract class Boat extends Item {
  //boat class with state variable
  int horsepower;
  public Boat(String name, double cost, int horsepower) {
    super(name, cost);
    this.horsepower = horsepower;
  } //constructor that calls everything

  public int getHorsepower() {
        return this.horsepower;
    }

  public void setHorsepower(int horsepower) {
        this.horsepower = horsepower;
    }

  public String toString() {
        return super.toString() + " Horsepower: " + horsepower;
    }

}

class Motorboat extends Boat {
  int seats;
  public Motorboat(String name, double cost, int horsepower, int seats) {
    super(name, cost, horsepower);
    this.seats = seats;
  }

  public String getDescription() {
    String description = (name + " " + seats + "-seat motorboat $" + cost);
    System.out.println(description);
    return description;
  }

  public void setSeats(int seats) {
    this.seats = seats;
  }

  public int getSeats() {
    System.out.println("The amount of seats in the motoboat is " + seats);
    return seats;
  }

}

class Yacht extends Boat implements LuxuryItem {
  int cabins;
  public Yacht(String name, double cost, int horsepower, int cabins) {
    super(name, cost, horsepower);
    this.cabins = cabins;
  }

  public void setCabins(int cabins) {
    this.cabins = cabins;
  }
  public int getCabins() {
    System.out.println("The people with cabins in the yacht are " + cabins);
    return cabins;
  }

  public double calculateLuxuryTax() {
    final double tax = 0.10;
    double luxuryTax = (cost*tax);
    return luxuryTax;
  }

  public String getDescription() {
    String description = (name + " " + cabins + "-cabin yacht $" + cost + " ** Luxury tax added **");
    System.out.println(description);
    return description;
  }

}

</code>```

Main class where my objects are created in the main method

```<code>class Main {
  public static void main(String[] args) {

    //these are my objects created, name and cost are the first two parameters for each, and then the rest are dependant on the individual constructors, the costs for each object have the original price and no luxury tax added yet because its supposed to be calculate after creating object

    Food pastryItem = new Pastry("Croissont", 1.99, 200, "Chocolate");

    Boat motorItem = new Motorboat("Evinrude", 3475.00, 400, 5);

    Boat yachtItem = new Yacht("Oceano", 950000.00, 1500, 12);

    Food fishItem = new Caviar("Beluga", 570.00, 800, "Caspian Sea");

    //I know that my inital value prices are right, but I can't calculate the separate luxury taxes for the luxury items (yacht and caviar) and I can't calculate the total sales tax without the total price, which i am unable to get below

    pastryItem.getDescription();

    motorItem.getDescription();

    yachtItem.getDescription().toString();

    fishItem.getDescription();

    System.out.println("\nTotal price: $" + (pastryItem.getCost() + motorItem.getCost() + yachtItem.getCost() + fishItem.getCost()));

    //The output is continously 'Total price: $954046.99' which i know is just the individual digits adding together then carrying over, but that isn't what I want, I want the entire prices to add together than calculate sales tax, print that then print the total price wiht the sales tax for the grand total

  }
}
</code>```

I apoligize for the long writing and thank you in advance for any help! Please bear in mind that I am a beginner and so I won't know a lot of advanced methods or solutions that aren't well known. Thanks.

Body:
I have a school project I am working on, I am a beginner at java and have started to learn abstract classes. As of right now, I have covered inheritence and interfaces and my teacher has provided me with some source code. The main goal of the project is to create an invoice of a group of objects from subclasses part of other subclasses that are part of one superclass. The invoice has to have the summary of the objects (its name, cost, and flavour/seats) along with the total price, its tax and grand total that is to be printed using a method called getDescription() that is overwritten for each sub class. Keep in mind that some 'objects' have a luxury tax involved that is 15% and there is a total 8% sales tax also added. The invoice (with luxury tax already added) is supposed to look like this:

Chocolate Croissant $1.99
Evinrude 5-seat motorboat $3,475.00
Oceano 12-cabin yacht $1,045,000.00 ** Luxury tax added **
Beluga caviar from Caspian Sea $655.50 ** Luxury tax added **
Total price: $1,049,132.49
Tax        : $83,930.60
Grand total: $1,133,063.09

However, I am getting two problems when I try this, first, the numbers I have (the seperate costs with the luxury tax), aren't adding up to the total price because I am not able to add the objects separate prices together as I have declared that in the parameters, and not as separate variables inside the main class itself, and so I cannot call on the method that lets me calculate the luxury tax before calculating for the total cost.

The second problem I have is not being able to put the correct decimal points for the price output, my teacher has provide a toString method in the superclass but I am not sure how to use it since, again, the cost itself is in the parameters of the object and not as an object or variable itself. This is not as big of a priority however, so it's alright if a solution for this is not provided.

Here is my Item superclass code, only part of it for context, and the part of my Boat subclass, and it's two 'Motorboat' and 'Yacht' subclasses. Yacht subclass also implements an interface class called LuxuryItem which only has one abstract method called 'calculateLuxuryTax' that we overwrite for each of the subclasses, which is why I won't provide that. Along with that, there is also the main class that has the object creation for each of the four subclass (Caviar, Pastry, Yacht, Motorboat) and in the constructors there are the same general format of the parameters (name, cost, horsepower/calories, flavour/origin/cabin #/seat #)

Item Class

import java.text.NumberFormat; //do I have to import this to each sub class? is that why there are no two decimal places for each output??
abstract class Item {
  double cost;
  String name;

  public Item() {
        cost = 0.0;
        name = "";
    }

  public Item(String name, double cost) {
        this.name = name;
        this.cost = cost;
    }

// a set cost method is also here, just not including it
  public double getCost() {
        return this.cost;
    }
//over here, i have deleted are getters and setters for name property
  public String toString() {
        NumberFormat currency = NumberFormat.getCurrencyInstance();
        String result;
        result = name + " -- Cost: " + currency.format(cost);
        return result;
    }

  public String getDescription() {
        return this.name;
    }

}

Boat Subclass & Motorboat and Yacht subclasses of Boat subclass

//all three classes are in one file
abstract class Boat extends Item {
  //boat class with state variable
  int horsepower;
  public Boat(String name, double cost, int horsepower) {
    super(name, cost);
    this.horsepower = horsepower;
  } //constructor that calls everything

  public int getHorsepower() {
        return this.horsepower;
    }

  public void setHorsepower(int horsepower) {
        this.horsepower = horsepower;
    }

  public String toString() {
        return super.toString() + " Horsepower: " + horsepower;
    }

}

class Motorboat extends Boat {
  int seats;
  public Motorboat(String name, double cost, int horsepower, int seats) {
    super(name, cost, horsepower);
    this.seats = seats;
  }

  public String getDescription() {
    String description = (name + " " + seats + "-seat motorboat $" + cost);
    System.out.println(description);
    return description;
  }

  public void setSeats(int seats) {
    this.seats = seats;
  }

  public int getSeats() {
    System.out.println("The amount of seats in the motoboat is " + seats);
    return seats;
  }

}

class Yacht extends Boat implements LuxuryItem {
  int cabins;
  public Yacht(String name, double cost, int horsepower, int cabins) {
    super(name, cost, horsepower);
    this.cabins = cabins;
  }

  public void setCabins(int cabins) {
    this.cabins = cabins;
  }
  public int getCabins() {
    System.out.println("The people with cabins in the yacht are " + cabins);
    return cabins;
  }

  public double calculateLuxuryTax() {
    final double tax = 0.10;
    double luxuryTax = (cost*tax);
    return luxuryTax;
  }

  public String getDescription() {
    String description = (name + " " + cabins + "-cabin yacht $" + cost + " ** Luxury tax added **");
    System.out.println(description);
    return description;
  }

}

Main class where my objects are created in the main method

class Main {
  public static void main(String[] args) {

    //these are my objects created, name and cost are the first two parameters for each, and then the rest are dependant on the individual constructors, the costs for each object have the original price and no luxury tax added yet because its supposed to be calculate after creating object

    Food pastryItem = new Pastry("Croissont", 1.99, 200, "Chocolate");

    Boat motorItem = new Motorboat("Evinrude", 3475.00, 400, 5);

    Boat yachtItem = new Yacht("Oceano", 950000.00, 1500, 12);

    Food fishItem = new Caviar("Beluga", 570.00, 800, "Caspian Sea");

    //I know that my inital value prices are right, but I can't calculate the separate luxury taxes for the luxury items (yacht and caviar) and I can't calculate the total sales tax without the total price, which i am unable to get below

    pastryItem.getDescription();

    motorItem.getDescription();

    yachtItem.getDescription().toString();

    fishItem.getDescription();

    System.out.println("\nTotal price: $" + (pastryItem.getCost() + motorItem.getCost() + yachtItem.getCost() + fishItem.getCost()));

    //The output is continously 'Total price: $954046.99' which i know is just the individual digits adding together then carrying over, but that isn't what I want, I want the entire prices to add together than calculate sales tax, print that then print the total price wiht the sales tax for the grand total

  }
}

I apoligize for the long writing and thank you in advance for any help! Please bear in mind that I am a beginner and so I won't know a lot of advanced methods or solutions that aren't well known. Thanks.


来源: stackexchange

问:
Function Rendering Too Many Times
This is an issue that I have encountered many times while working on other projects but could not figure it out then. I hope I have luck this time with some help.

I am using Next.js 12 for this project. The configs are

```<code>{
  "name": "next12firebase",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "eslint": "8.28.0",
    "eslint-config-next": "13.0.5",
    "firebase": "^9.14.0",
    "next": "13.0.5",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-firebase-hooks": "^5.1.1",
    "react-icons": "^4.7.1"
  },
  "devDependencies": {
    "autoprefixer": "^10.4.13",
    "postcss": "^8.4.19",
    "tailwindcss": "^3.2.4"
  }
}

</code>```

I am trying to run a function that only runs after loading becomes false. loading is set via useCollectionData, which is a hook from react-firebase-hooks. I want to call a function, fixData, so that it sets the state of a map that I can use later to map through. The code I am presenting now is a bootleg version that has the functions of fixData run whenever loading becomes false.

```<code>export defualt function portfio() {
  ......

  const [docs, loading, error] = useCollectionData(q);

        return (
           ......
           {!loading &&
            docs.map((doc) => {
                console.log(doc)
                let tic =  doc.stockTicker
                let data = {
                     shares: doc.shares,
                     price: doc.price,
                     type: doc.type
                }

                let map  = datamap;
                console.log(datamap)
                if(Array.from(datamap.keys).includes(tic) === false) {
                    setDatamap(datamap.set(tic, [data]));
                    console.log(tic + " " + data)

                }
                else {
                    setDatamap((map.get(tic)).push(data))
                }
                console.log(datamap)

            }
        )}
        ......
)}
</code>```

There's a lot of code missing from here for simplicities sake, but feel free to msg me for any questions on the code. I have tried many different configurations and different versions but i keep getting the same errors, that it's rerendering too many times and that a function cannot be called inside of a react child.

ContentLicense: CC BY-SA 4.0

Title: Function Rendering Too Many Times

Body:
This is an issue that I have encountered many times while working on other projects but could not figure it out then. I hope I have luck this time with some help.

I am using Next.js 12 for this project. The configs are

{
  "name": "next12firebase",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "eslint": "8.28.0",
    "eslint-config-next": "13.0.5",
    "firebase": "^9.14.0",
    "next": "13.0.5",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-firebase-hooks": "^5.1.1",
    "react-icons": "^4.7.1"
  },
  "devDependencies": {
    "autoprefixer": "^10.4.13",
    "postcss": "^8.4.19",
    "tailwindcss": "^3.2.4"
  }
}

I am trying to run a function that only runs after loading becomes false. loading is set via useCollectionData, which is a hook from react-firebase-hooks. I want to call a function, fixData, so that it sets the state of a map that I can use later to map through. The code I am presenting now is a bootleg version that has the functions of fixData run whenever loading becomes false.

export defualt function portfio() {
  ......

  const [docs, loading, error] = useCollectionData(q);

        return (
           ......
           {!loading &&
            docs.map((doc) => {
                console.log(doc)
                let tic =  doc.stockTicker
                let data = {
                     shares: doc.shares,
                     price: doc.price,
                     type: doc.type
                }

                let map  = datamap;
                console.log(datamap)
                if(Array.from(datamap.keys).includes(tic) === false) {
                    setDatamap(datamap.set(tic, [data]));
                    console.log(tic + " " + data)

                }
                else {
                    setDatamap((map.get(tic)).push(data))
                }
                console.log(datamap)

            }
        )}
        ......
)}

There's a lot of code missing from here for simplicities sake, but feel free to msg me for any questions on the code. I have tried many different configurations and different versions but i keep getting the same errors, that it's rerendering too many times and that a function cannot be called inside of a react child.


问:
my procedure is executing twice, what is the problem?
I have buffet table and I want to replace an ingredient with another, but my cursor replacing twice, and I get wrong answer.
Note: I'm using MySQL Workbench v 8.0.30</p>
```<code>CREATE PROCEDURE cur_snak(in name_snak varchar(20), in old_ingred text,
in new_ingred text)
BEGIN
declare res text;
declare d int default 0;
declare c_id int ;
declare get_cur_ingred cursor for select id from buffet where `name`=name_snak;
declare continue handler  for sqlstate '02000'
set d=1;
declare continue handler  for sqlstate '23000'
set d=1;
open get_cur_ingred ;
lbl: loop
if d=1 then
leave lbl;
end if;
if not d=1 then
fetch get_cur_ingred into c_id ;
select insert((select ingredients from buffet where id=c_id ),
(select locate(old_ingred,ingredients) from buffet where id=c_id ),
(select length(old_ingred)),new_ingred) into res;
update buffet
set ingredients =res
where id=c_id;
end if;
end loop.
close get_cur_ingred;
END
</code>```

Body:
I have buffet table and I want to replace an ingredient with another, but my cursor replacing twice, and I get wrong answer.
Note: I'm using MySQL Workbench v 8.0.30

CREATE PROCEDURE cur_snak(in name_snak varchar(20), in old_ingred text,
in new_ingred text)
BEGIN
declare res text;
declare d int default 0;
declare c_id int ;
declare get_cur_ingred cursor for select id from buffet where `name`=name_snak;
declare continue handler  for sqlstate '02000'
set d=1;
declare continue handler  for sqlstate '23000'
set d=1;
open get_cur_ingred ;
lbl: loop
if d=1 then
leave lbl;
end if;
if not d=1 then
fetch get_cur_ingred into c_id ;
select insert((select ingredients from buffet where id=c_id ),
(select locate(old_ingred,ingredients) from buffet where id=c_id ),
(select length(old_ingred)),new_ingred) into res;
update buffet
set ingredients =res
where id=c_id;
end if;
end loop.
close get_cur_ingred;
END


问:
How do I, refresh rebuild the swiftui color assets after color change
I'm struggling with colors, color names, appearance modes, their names in Assets Catalogs etc. within Xcode 14.1 and SwiftUI.

It appears that something somewhere does some sort of compile on the Assets catalog.  But I cannot find it or get it to refresh after a clean/build.

How do I get Xcode and my App to use the new/refreshed color after a change to the shade in Assets?


问:
React useForm Hook with array of elemens
I have to handle a form and I'm using the useForm library of "react-hook-form", the problem is that I need to handle multiple data, such as arrays and objects, for now I've only managed to handle one array, but I can't handle two for I can't duplicate this part of the code:

```<code>
const {
    register,
    handleSubmit,
    formState: { errors },
    control,
  } = useForm();

 const { fields, append, remove } = useFieldArray({
    control,
    name: "habilidades",
  });
</code>```

I have this two fields:

```<code><div>
  <label>Habilidades</label>
  {fields.map((item, index) => {
    return (
      <div key={item.id}>
        <input
          {...register(`habilidades.${index}`, { required: true })}
        />

        <button type="button" onClick={() => remove(index)}>
          Eliminar
        </button>
      </div>
    );
  })}
  <button
    type="button"
    onClick={() => {
      append("");
    }}>
    Nueva habilidad
  </button>
</div>

<div>
  <label>Aptitudes</label>

  {fields.map((item, index) => {
    return (
      <div key={item.id}>
        <input {...register(`aptitudes.${index}`, { required: true })} />

        <button type="button" onClick={() => remove(index)}>
          Eliminar
        </button>
      </div>
    );
  })}

  <button
    type="button"
    onClick={() => {
      append("");
    }}>
    Nueva habilidad
  </button>
</div>
</code>```

How can I manage each of the fields independently? The problem is that it only recognizes the "habilidades" field and I need to also handle the "aptitudes" field without the two coming together.

```<code> const { fields, append, remove } = useFieldArray({
    control,
    name: "habilidades",
    name: "aptitudes"
  });
</code>```

I have tried to put two names but it does not work.

What I expect is that the form returns something like this:

```<code>{
   habilidades: ["example1", "example2", "example3"]
   aptitudes: ["example4", "example5", "example6"],
}
</code>```

Body:
I have to handle a form and I'm using the useForm library of "react-hook-form", the problem is that I need to handle multiple data, such as arrays and objects, for now I've only managed to handle one array, but I can't handle two for I can't duplicate this part of the code:

const {
    register,
    handleSubmit,
    formState: { errors },
    control,
  } = useForm();

 const { fields, append, remove } = useFieldArray({
    control,
    name: "habilidades",
  });

I have this two fields:

  Habilidades
  {fields.map((item, index) => {
    return (

        <input
          {...register(`habilidades.${index}`, { required: true })}
        />

        <button type="button" onClick={() => remove(index)}>
          Eliminar
        </button>

    );
  })}
  <button
    type="button"
    onClick={() => {
      append("");
    }}>
    Nueva habilidad
  </button>

  Aptitudes

  {fields.map((item, index) => {
    return (

        <input {...register(`aptitudes.${index}`, { required: true })} />

        <button type="button" onClick={() => remove(index)}>
          Eliminar
        </button>

    );
  })}

  <button
    type="button"
    onClick={() => {
      append("");
    }}>
    Nueva habilidad
  </button>

How can I manage each of the fields independently? The problem is that it only recognizes the "habilidades" field and I need to also handle the "aptitudes" field without the two coming together.

 const { fields, append, remove } = useFieldArray({
    control,
    name: "habilidades",
    name: "aptitudes"
  });

I have tried to put two names but it does not work.

What I expect is that the form returns something like this:

{
   habilidades: ["example1", "example2", "example3"]
   aptitudes: ["example4", "example5", "example6"],
}


问:
Rollup build a React project import the modules in Node.js environment and get "TypeError: Cannot set properties of undefined (setting 'Headers')"
I have a Github package built with React by Rollup.

In a project where it imports the modules from the Github package, I'm trying to run tests by Jest.

In every line of module import in the test files, I get the following error.

TypeError: Cannot set properties of undefined (setting 'Headers')

I'm assuming the rollup build config is the problem.

```<code>import typescript from '@rollup/plugin-typescript';
import commonjs from '@rollup/plugin-commonjs';
import external from 'rollup-plugin-peer-deps-external';
import resolve from '@rollup/plugin-node-resolve';
import json from '@rollup/plugin-json';
import packageJson from './package.json';

export default {
  input: 'src/index.tsx',
  output: [
    {
      file: packageJson.main,
      format: 'cjs',
      sourcemap: true,
      exports: 'named',
    },
    {
      file: packageJson.module,
      format: 'cjs',
      sourcemap: true,
      exports: 'named',
    },
  ],
  plugins: [
    external(),
    resolve({
      browser: true,
    }),
    typescript({
      exclude: ['**/**.stories.tsx', '**/*.test.ts'],
    }),
    commonjs({
      include: ['node_modules/**'],
    }),
    json(),
  ],
};

</code>```

The above is my rollup build settings.

Does anyone know what the problem is?

Body:
I have a Github package built with React by Rollup.

In a project where it imports the modules from the Github package, I'm trying to run tests by Jest.

In every line of module import in the test files, I get the following error.

TypeError: Cannot set properties of undefined (setting 'Headers')

I'm assuming the rollup build config is the problem.

import typescript from '@rollup/plugin-typescript';
import commonjs from '@rollup/plugin-commonjs';
import external from 'rollup-plugin-peer-deps-external';
import resolve from '@rollup/plugin-node-resolve';
import json from '@rollup/plugin-json';
import packageJson from './package.json';

export default {
  input: 'src/index.tsx',
  output: [
    {
      file: packageJson.main,
      format: 'cjs',
      sourcemap: true,
      exports: 'named',
    },
    {
      file: packageJson.module,
      format: 'cjs',
      sourcemap: true,
      exports: 'named',
    },
  ],
  plugins: [
    external(),
    resolve({
      browser: true,
    }),
    typescript({
      exclude: ['**/**.stories.tsx', '**/*.test.ts'],
    }),
    commonjs({
      include: ['node_modules/**'],
    }),
    json(),
  ],
};

The above is my rollup build settings.

Does anyone know what the problem is?


问:
Replicated Latin Square Design Analysis Using lm and ANOVA
I'm looking to run lm and ANOVA for the following Latin Square design:

```<code>                     Time
      Subject   1     2     3
</code>```

Square 1    1       9 (B) 3 (C) 6 (A)
2       18(A) 6 (B) 12(C)
3       12(C) 15(A) 5 (B)

Square 2    4       14(C) 8 (B) 11(A)
5       17(A) 9 (C) 9 (B)
6       7 (B) 7 (A) 7 (C)

I found that, if the replication occurs with different rows and the same columns, as in we'll have 6 different subjects and the subjects are nested in each replication (R/S), then the command is:

lm.1 <- lm(A ~ R/S + D + T + R)
anova(lm.1)

But, if we assume now that the replication occurs with the same rows and columns, as in S1=S4, S2=S5, and S3=S6, how would the lm code change?

Thank you.

Body:
I'm looking to run lm and ANOVA for the following Latin Square design:

                     Time
      Subject   1     2     3

Square 1    1       9 (B) 3 (C) 6 (A)
2       18(A) 6 (B) 12(C)
3       12(C) 15(A) 5 (B)

Square 2    4       14(C) 8 (B) 11(A)
5       17(A) 9 (C) 9 (B)
6       7 (B) 7 (A) 7 (C)

I found that, if the replication occurs with different rows and the same columns, as in we'll have 6 different subjects and the subjects are nested in each replication (R/S), then the command is:

lm.1 <- lm(A ~ R/S + D + T + R)
anova(lm.1)

But, if we assume now that the replication occurs with the same rows and columns, as in S1=S4, S2=S5, and S3=S6, how would the lm code change?

Thank you.


问:
Postgres grouping sets - Show count zero or named groups
I have the following query:

```<code>select count(*)
from "my_table"
where field1 = true and field2 = 'delivered'
group by grouping sets((field3), (field4), (field5))
having field3 = true or field4 = true or field5
</code>```

For each group in the grouping set, I want to get the count of the true values. The problem with this query however is that it has no labels attach to it. In case there are no results for a group, the group is excluded in the end result. Is it possible to include groups with count 0 or create a set of labels so that it becomes clear to which group the count corresponds in the result?

Current result:

```<code>count
_____
1
2
</code>```

Where field5 doesn't have any results so it isn't included.

Desired result:

```<code>count
-----
1
2
0
</code>```

Or:

```<code>count_field3 | count_field4 | count_field5
------------------------------------------
1            | 2            | 0
</code>```

Body:
I have the following query:

select count(*)
from "my_table"
where field1 = true and field2 = 'delivered'
group by grouping sets((field3), (field4), (field5))
having field3 = true or field4 = true or field5

For each group in the grouping set, I want to get the count of the true values. The problem with this query however is that it has no labels attach to it. In case there are no results for a group, the group is excluded in the end result. Is it possible to include groups with count 0 or create a set of labels so that it becomes clear to which group the count corresponds in the result?

Current result:

count
_____
1
2

Where field5 doesn't have any results so it isn't included.

Desired result:

count
-----
1
2
0

Or:

count_field3 | count_field4 | count_field5
------------------------------------------
1            | 2            | 0


问:
Search Google books api using RTK query in React
I am using RTK query with react for searching books using google api. I have one input search field where the user can enter the book name and after clicking on the search button it will fetch data from google api.

For now, I am setting React as the default search keyword but I want that to be blank by default. Below is the component and apiSlice code where the fetching happens.

```<code>// Main Component
const BookFinder = () => {
  const [searchTerm, setSearchTerm] = useState('React');

  return (
    <>
      <Container>
        <Row className='mt-5'>
          <h1>Book Finder</h1>
          <SearchBar {...{searchTerm, setSearchTerm}}/>
        </Row>
        <Row xs={2} md={4} className='g-5 mt-3'>
          <BookList {...{searchTerm}} />
        </Row>
      </Container>
    </>
  );
}
</code>```

I am using react-bootstrap, font-awesome libraries here.

```<code>// Search Bar
const SearchBar = ({ searchTerm, setSearchTerm }) => {
  const searchBar = useRef()

  return (
    <>
      <InputGroup className="mb-3 pt-3">
        <Form.Control
          placeholder={searchTerm}
          aria-label="Search"
          aria-describedby="search"
          ref={searchBar}
        />
      <Button variant="outline-primary" id="search" onClick={() => setSearchTerm(searchBar.current.value)}>
        <FontAwesomeIcon icon={faMagnifyingGlass} />
      </Button>
      </InputGroup>
    </>
  );
}
</code>```

import { useGetBooksQuery } from '../../services/bookSlice';

```<code>const BookList = ({ searchTerm }) => {
  const { data: books, isLoading, isSuccess, isError, error } = useGetBooksQuery(searchTerm)

  if(isLoading) {
    return (
      <div className="d-flex align-items-center justify-content-center">
        <strong>Loading...</strong>
        <div className="spinner-border" role="status" aria-hidden="true"></div>
      </div>
    )
  }

  if(isError) {
    return <div>{error.toString()}</div>
  }

  if(isSuccess) {
    const { items } = books
    // return jsx code using books
  }
}
</code>```

The above code is using useGetBooksQuery hook to get the data.

```<code>import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const bookSlice = createApi({
  reducerPath: 'bookApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://www.googleapis.com/books/v1' }),
  tagTypes: ['Book'],
  endpoints: (builder) => ({
    getBooks: builder.query({
      query: (searchTerm) => `/volumes?q=${searchTerm}`,
      providesTags: ['Book'],
    }),
  }),
})

export const {
  useGetBooksQuery,
} = bookSlice
</code>```

My problem is if I don't set the default value the api fails and gets an error. Is there any way I can omit the default value? So, the list will be empty the first time or will not call the google api when there is no value in text input. I think of using mutation instead of query but not sure if will it be the right thing to do. So use this platform to get some ideas to handle the above case. Thanks

Body:
I am using RTK query with react for searching books using google api. I have one input search field where the user can enter the book name and after clicking on the search button it will fetch data from google api.

For now, I am setting React as the default search keyword but I want that to be blank by default. Below is the component and apiSlice code where the fetching happens.

// Main Component
const BookFinder = () => {
  const [searchTerm, setSearchTerm] = useState('React');

  return (
    <>
      <Container>
        <Row className='mt-5'>

Book Finder

          <SearchBar {...{searchTerm, setSearchTerm}}/>
        </Row>
        <Row xs={2} md={4} className='g-5 mt-3'>
          <BookList {...{searchTerm}} />
        </Row>
      </Container>
    </>
  );
}

I am using react-bootstrap, font-awesome libraries here.

// Search Bar
const SearchBar = ({ searchTerm, setSearchTerm }) => {
  const searchBar = useRef()

  return (
    <>
      <InputGroup className="mb-3 pt-3">
        <Form.Control
          placeholder={searchTerm}
          aria-label="Search"
          aria-describedby="search"
          ref={searchBar}
        />
      <Button variant="outline-primary" id="search" onClick={() => setSearchTerm(searchBar.current.value)}>
        <FontAwesomeIcon icon={faMagnifyingGlass} />
      </Button>
      </InputGroup>
    </>
  );
}

import { useGetBooksQuery } from '../../services/bookSlice';

const BookList = ({ searchTerm }) => {
  const { data: books, isLoading, isSuccess, isError, error } = useGetBooksQuery(searchTerm)

  if(isLoading) {
    return (

        Loading...

    )
  }

  if(isError) {
    return
{error.toString()}

  }

  if(isSuccess) {
    const { items } = books
    // return jsx code using books
  }
}

The above code is using useGetBooksQuery hook to get the data.

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

export const bookSlice = createApi({
  reducerPath: 'bookApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://www.googleapis.com/books/v1' }),
  tagTypes: ['Book'],
  endpoints: (builder) => ({
    getBooks: builder.query({
      query: (searchTerm) => `/volumes?q=${searchTerm}`,
      providesTags: ['Book'],
    }),
  }),
})

export const {
  useGetBooksQuery,
} = bookSlice

My problem is if I don't set the default value the api fails and gets an error. Is there any way I can omit the default value? So, the list will be empty the first time or will not call the google api when there is no value in text input. I think of using mutation instead of query but not sure if will it be the right thing to do. So use this platform to get some ideas to handle the above case. Thanks


问:
How to decode map to struct when target struct uses a pointer, but map does not
I have an auto-generated struct which outputs the following:

Playlist    []*PlaylistItem `protobuf:"bytes,2,rep,name=playlist,proto3" json:"playlist,omitempty"`
```
<p>This is saved in the DB with the same schema, although, when I retrieve the item back (as a <code>[]map[string]any</code>), I cannot decode it back to the original struct, because the <code>PlaylistItem</code> is a pointer.</p>
<p>Currently I'm manually iterating through the map slice, to be able to correctly decode it:</p>
<pre class="lang-golang prettyprint-override"><code>plItems := row["playlist"].([]map[string]any)
playlist := []*v1.PlaylistItem{}

for _, pl := range plItems {
   // make it a pointer and append
}
</code>```

Is there any way to easily decode this back to the matching struct without this hack?

Body:
I have an auto-generated struct which outputs the following:

Playlist    []*PlaylistItem `protobuf:"bytes,2,rep,name=playlist,proto3" json:"playlist,omitempty"`

This is saved in the DB with the same schema, although, when I retrieve the item back (as a []map[string]any), I cannot decode it back to the original struct, because the PlaylistItem is a pointer.

Currently I'm manually iterating through the map slice, to be able to correctly decode it:

plItems := row["playlist"].([]map[string]any)
playlist := []*v1.PlaylistItem{}

for _, pl := range plItems {
   // make it a pointer and append
}

Is there any way to easily decode this back to the matching struct without this hack?


问:
How do I set screen size using winbgi? (without graphics.h, winbgim, but pure winbgi)
How do I set window size using winbgi?

Default window size is left half of my screen=
Complile result

MY professor wants me to 'only' use winbgi

```<code>WinBGI& win = WinBGI::instance();
// then what??
</code>```

winbgi does not include initwindow() that can set window size

```<code>int initwindow (int width, int height, const char* title="Windows BGI", int left=0, int top=0, bool dbflag=false, bool closeflag=true);
</code>```

I've looked up the documention and I couldn't find one

bgi

I want to set BGI window size (height, width)

I am using Visual Studio 2022

Body:
How do I set window size using winbgi?

Default window size is left half of my screen=
Complile result

MY professor wants me to 'only' use winbgi

WinBGI& win = WinBGI::instance();
// then what??

winbgi does not include initwindow() that can set window size

int initwindow (int width, int height, const char* title="Windows BGI", int left=0, int top=0, bool dbflag=false, bool closeflag=true);

I've looked up the documention and I couldn't find one

bgi

I want to set BGI window size (height, width)

I am using Visual Studio 2022


问:
Can Ctree() predict classification?
```<code>CondInfTree <- ctree(DEFAULT ~ .,
                     data = train)
</code>```

Using the above code, I get DEFAULT binary predictions which is what I'm seeking.

If I use:

```<code>CondInfTree <- ctree(Surv(DURATION,DEFAULT)~ .,
                     data = train)
</code>```

I get time until default (Kaplan-Meier) predictions.

My goal is to include DURATION time as a variable but I want to predict whether a new, unseen, observation would default.

Would using the first tree work or would I be ignoring censored data that way?

... or is there something I'm missing altogether?

Title: Can Ctree() predict classification?

Body:
CondInfTree <- ctree(DEFAULT ~ .,
                     data = train)

Using the above code, I get DEFAULT binary predictions which is what I'm seeking.

If I use:

CondInfTree <- ctree(Surv(DURATION,DEFAULT)~ .,
                     data = train)

I get time until default (Kaplan-Meier) predictions.

My goal is to include DURATION time as a variable but I want to predict whether a new, unseen, observation would default.

Would using the first tree work or would I be ignoring censored data that way?

... or is there something I'm missing altogether?


问:
What are the rules regarding undefined values and lists in DynamoDB GetItem ProjectionExpressions and UpdateItem ReturnValues?
I regularly use the AWS SDK for JavaScript (Typescript, really) to perform DynamoDB DocumentClient queries and am looking to make my type assertions of the response accurate. Specifically, when using a ProjectionExpression in the GetItem, Query, and Scan functions, and when using ReturnValues in UpdateItem.

However I can't seem to find a reference anywhere explaining how the response is returned in more complicated scenarios. I am hoping one exists!

EDIT: It seems the AWS CLI docs are pretty explicit about ProjectionExpressions, stating: "If any of the requested attributes are not found, they do not appear in the result", which explains points 1-4 below. Very typical of them to not include it in the general docs. Sigh... Still searching for ReturnValues clarification though...

EDIT2: whoops, seems my example for ReturnValues was a little too simple. Tried it again on a larger array and things seem to be making more sense. It does appear that for both UPDATED_OLD and UPDATED_NEW, when REMOVEing/SETing list indices, only the modified indices are returned in both cases. And, similar to ProjectionExpressions, if you REMOVE index 0 from an list of length 1 if specifying UPDATED_NEW, nothing is returned.

Through some experiments, I've gleaned a few things about ProjectionExpressions.

When using a ProjectionExpression to select a non-existent attribute, the attribute is not returned. For example, if the Item is the following:

{
  "a": "a",
  "b": "b",
  "c": "c"
}
```
<p>and the <code>ProjectionExpression</code> is: <code>"a, b, d"</code>, <code>d</code> is not returned, i.e. the response is simply:</p>
<pre class="lang-json prettyprint-override"><code>{
  "a": "a",
  "b": "b"
}
</code>```

It makes perfect sense to me that d is undefined.

A similar thing happens when selecting a non-existent nested attribute. For example, in this Item:

{
  "a": {
    "b": {}
  }
}
```
<p>with the <code>ProjectionExpression</code>: <code>"a.b.c"</code>, an empty object is returned, i.e. <code>{}</code>.</p>
<p>This also makes sense to me, and while it may not be the actual reason, my guess is it doesn't make sense to return <code>a.b</code>, with <code>b</code> equal to an empty object, because that would increase the size of the response. (After all, using a<code>ProjectionExpression</code> doesn't save you read units, just reduces the amount of data in the network request.)</p>
<ol start="3">
<li>From what I can tell, when selecting multiple indices in a list, the non-selected indices are removed from the returned list. For example, with Item</li>
</ol>
<pre class="lang-json prettyprint-override"><code>{
  "a": [1, 2, 3]
}
</code>```

and ProjectionExpression: "a[0], a[2]", index 1 is removed from the array, yielding

{
  "a": [1, 3]
}
```
<ol start="4">
<li><p>Lists also appear to follow a similar philosophy to the nested attribute case <code>2</code>. If you select a non-existent index in a list, the list isn't even returned. For example, with the same item as in case <code>3</code> and ProjectionExpression <code>"a[3]"</code>, the response is an empty object: <code>{}</code>. I imagine the reasoning is also to have the smallest response possible to reduce network overhead.</p>
</li>
<li><p>Moving on to the <code>ReturnValues</code> argument in <code>UpdateItem</code>, at first glance, the response seemed to follow similar rules to a <code>ProjectionExpression</code>, but I was thrown off once I tried the <code>REMOVE</code> clause in the <code>UpdateExpression</code> on a list <em>index</em>. (And, when the R.V. is <code>"UPDATED_NEW"</code>.)</p>
</li>
</ol>
<p>Sticking with item in case <code>3</code>, if the <code>UpdateExpression</code> is <code>REMOVE a[0], SET a[1] = :thing</code>, (<code>:thing</code> is just an <code>ExpressionAttributeValue</code>, let's say it's equal to <code>"thing"</code>) it appears the response is</p>
<pre class="lang-json prettyprint-override"><code>{
  "a": ["thing", 3]
}
</code>```

However, if we remove the REMOVE clause and just use the SET clause, the response is

{
  "a": ["thing"]
}
```

Both of these behaviors make sense to me given what I presume is the goal: to make the size of the response as small as possible while returning relevant information. i.e., see EDIT 2, I was mistaken on this! <s>when REMOVE-ing an index in a list, you'd probably want to get the whole list back</s>, but if you just SET an index in a list, it seems reasonable to me to just return the indices that were updated.

I could go on, but at this point I'm a little confused, because it seems there doesn't exist an article explaining how this works in the docs, and I'm not confident in my ability to exhaustively test every scenario that could arise when using these options. If anyone knows of an article explaining this, or could otherwise just provide some guidance, it would be much appreciated. Thanks in advance!

Body:
I regularly use the AWS SDK for JavaScript (Typescript, really) to perform DynamoDB DocumentClient queries and am looking to make my type assertions of the response accurate. Specifically, when using a ProjectionExpression in the GetItem, Query, and Scan functions, and when using ReturnValues in UpdateItem.

However I can't seem to find a reference anywhere explaining how the response is returned in more complicated scenarios. I am hoping one exists!

EDIT: It seems the AWS CLI docs are pretty explicit about ProjectionExpressions, stating: "If any of the requested attributes are not found, they do not appear in the result", which explains points 1-4 below. Very typical of them to not include it in the general docs. Sigh... Still searching for ReturnValues clarification though...

EDIT2: whoops, seems my example for ReturnValues was a little too simple. Tried it again on a larger array and things seem to be making more sense. It does appear that for both UPDATED_OLD and UPDATED_NEW, when REMOVEing/SETing list indices, only the modified indices are returned in both cases. And, similar to ProjectionExpressions, if you REMOVE index 0 from an list of length 1 if specifying UPDATED_NEW, nothing is returned.

Through some experiments, I've gleaned a few things about ProjectionExpressions.

When using a ProjectionExpression to select a non-existent attribute, the attribute is not returned. For example, if the Item is the following:

{
  "a": "a",
  "b": "b",
  "c": "c"
}

and the ProjectionExpression is: "a, b, d", d is not returned, i.e. the response is simply:

{
  "a": "a",
  "b": "b"
}

It makes perfect sense to me that d is undefined.

A similar thing happens when selecting a non-existent nested attribute. For example, in this Item:

{
  "a": {
    "b": {}
  }
}

with the ProjectionExpression: "a.b.c", an empty object is returned, i.e. {}.

This also makes sense to me, and while it may not be the actual reason, my guess is it doesn't make sense to return a.b, with b equal to an empty object, because that would increase the size of the response. (After all, using aProjectionExpression doesn't save you read units, just reduces the amount of data in the network request.)

From what I can tell, when selecting multiple indices in a list, the non-selected indices are removed from the returned list. For example, with Item

{
  "a": [1, 2, 3]
}

and ProjectionExpression: "a[0], a[2]", index 1 is removed from the array, yielding

{
  "a": [1, 3]
}

Lists also appear to follow a similar philosophy to the nested attribute case 2. If you select a non-existent index in a list, the list isn't even returned. For example, with the same item as in case 3 and ProjectionExpression "a[3]", the response is an empty object: {}. I imagine the reasoning is also to have the smallest response possible to reduce network overhead.

Moving on to the ReturnValues argument in UpdateItem, at first glance, the response seemed to follow similar rules to a ProjectionExpression, but I was thrown off once I tried the REMOVE clause in the UpdateExpression on a list index. (And, when the R.V. is "UPDATED_NEW".)

Sticking with item in case 3, if the UpdateExpression is REMOVE a[0], SET a[1] = :thing, (:thing is just an ExpressionAttributeValue, let's say it's equal to "thing") it appears the response is

{
  "a": ["thing", 3]
}

However, if we remove the REMOVE clause and just use the SET clause, the response is

{
  "a": ["thing"]
}

Both of these behaviors make sense to me given what I presume is the goal: to make the size of the response as small as possible while returning relevant information. i.e., see EDIT 2, I was mistaken on this! <s>when REMOVE-ing an index in a list, you'd probably want to get the whole list back</s>, but if you just SET an index in a list, it seems reasonable to me to just return the indices that were updated.

I could go on, but at this point I'm a little confused, because it seems there doesn't exist an article explaining how this works in the docs, and I'm not confident in my ability to exhaustively test every scenario that could arise when using these options. If anyone knows of an article explaining this, or could otherwise just provide some guidance, it would be much appreciated. Thanks in advance!


问:
What is the meaning of abbreviate D in command -Djava.security.properties=<URL>?
I read comment in JDK, at path C:\Program Files\Java\jdk-19\conf\security\java.security

```<code>#
# This is the "master security properties file".
#
# An alternate java.security properties file may be specified
# from the command line via the system property
#
#    -Djava.security.properties=<URL>
#
# This properties file appends to the master security properties file.
# If both properties files specify values for the same key, the value
# from the command-line properties file is selected, as it is the last
# one loaded.
#
# Also, if you specify
#
#    -Djava.security.properties==<URL> (2 equals),
#
# then that properties file completely overrides the master security
# properties file.
</code>```

What is the meaning of abbreviate D in command -Djava.security.properties=<URL>? Why should not use M, K or Z?

Body:
I read comment in JDK, at path C:\Program Files\Java\jdk-19\conf\security\java.security

#
# This is the "master security properties file".
#
# An alternate java.security properties file may be specified
# from the command line via the system property
#
#    -Djava.security.properties=<URL>
#
# This properties file appends to the master security properties file.
# If both properties files specify values for the same key, the value
# from the command-line properties file is selected, as it is the last
# one loaded.
#
# Also, if you specify
#
#    -Djava.security.properties==<URL> (2 equals),
#
# then that properties file completely overrides the master security
# properties file.

What is the meaning of abbreviate D in command -Djava.security.properties=<URL>? Why should not use M, K or Z?


问:
mock subprocess.run before importing a python file
File 1: env_test .py -> No Issue , everything is working as expected

```<code>BASE_PATH = 'C:/Users/mm13854/Desktop/FileCopy_Dec_122/cftp_tableau_filecopy/deploy/'

_ENV = os.environ['RPM_ENVIRONMENT']
_FID = os.environ['USER']
_HOST = os.environ['HOST_NAME']
_PUBLISH_TYPE = os.environ['TABLEAU_PUBLISH_TYPE']
_TABCMD_PATH = os.environ['TABCMD_PATH']
_CYBERARK = os.environ['CYBERARK_TYPE']
_PROJECT_FOLDER = os.environ['PROJECT_FOLDER']
_JOB_TYPE = os.environ['JOB_TYPE']
_JOB_FILE=os.environ['JOB_FILE']
_API_LOG_TYPE=os.environ['RESTAPI_LOG_TYPE']
VALUE=subprocess.run(["sh",BASE_PATH + "bin/cyberark.sh",APPID,SAFE,LDAP_GROUP],capture_output=True,text=True).stdout.strip()
</code>```

File 2 : Unit TestCase
How can i mock subprocess.run to return a specific value in my test_case.py
Currently i am facing issue running my below code script is because inside env_test , there is subprocess.run . i have written below scripts but i a

```<code>with mock.patch.dict(os.environ, {'PROJECT_FOLDER':'CitiFTP Reports','RPM_ENVIRONMENT': 'DEV', 'HOST_NAME': 'dot-dot-dot.nam.nsroot.net', 'USER': 'farid','TABLEAU_PUBLISH_TYPE':'TABCMD','TABCMD_PATH':'/home/farid/tabcmd','CYBERARK_TYPE':'DYNAMIC','JOB_TYPE':'workbook_TP','JOB_FILE':'publish_workbook_TP','RESTAPI_LOG_TYPE':'TP'}):
    sys.path.insert(1, 'C:/Users/mm13854/Desktop/FileCopy_Dec_122/cftp_tableau_filecopy/deploy/src')

    @mock.patch('subprocess.run')
    def test_mockProcess(self, mock_subprocess_run):
        process_mock = mock.Mock()
        mock_subprocess_run.return_value = '123'

    # Should import file and return no error. need to mock subprocess return value
    import env_test as conf
</code>```

When i tried to import , it was sepcifying that the file was not found . i check on my path and it was correct.

FileNotFoundError: [WinError 2] The system cannot find the file specified

Body:
File 1: env_test .py -> No Issue , everything is working as expected

BASE_PATH = 'C:/Users/mm13854/Desktop/FileCopy_Dec_122/cftp_tableau_filecopy/deploy/'

_ENV = os.environ['RPM_ENVIRONMENT']
_FID = os.environ['USER']
_HOST = os.environ['HOST_NAME']
_PUBLISH_TYPE = os.environ['TABLEAU_PUBLISH_TYPE']
_TABCMD_PATH = os.environ['TABCMD_PATH']
_CYBERARK = os.environ['CYBERARK_TYPE']
_PROJECT_FOLDER = os.environ['PROJECT_FOLDER']
_JOB_TYPE = os.environ['JOB_TYPE']
_JOB_FILE=os.environ['JOB_FILE']
_API_LOG_TYPE=os.environ['RESTAPI_LOG_TYPE']
VALUE=subprocess.run(["sh",BASE_PATH + "bin/cyberark.sh",APPID,SAFE,LDAP_GROUP],capture_output=True,text=True).stdout.strip()

File 2 : Unit TestCase
How can i mock subprocess.run to return a specific value in my test_case.py
Currently i am facing issue running my below code script is because inside env_test , there is subprocess.run . i have written below scripts but i a

with mock.patch.dict(os.environ, {'PROJECT_FOLDER':'CitiFTP Reports','RPM_ENVIRONMENT': 'DEV', 'HOST_NAME': 'dot-dot-dot.nam.nsroot.net', 'USER': 'farid','TABLEAU_PUBLISH_TYPE':'TABCMD','TABCMD_PATH':'/home/farid/tabcmd','CYBERARK_TYPE':'DYNAMIC','JOB_TYPE':'workbook_TP','JOB_FILE':'publish_workbook_TP','RESTAPI_LOG_TYPE':'TP'}):
    sys.path.insert(1, 'C:/Users/mm13854/Desktop/FileCopy_Dec_122/cftp_tableau_filecopy/deploy/src')

    @mock.patch('subprocess.run')
    def test_mockProcess(self, mock_subprocess_run):
        process_mock = mock.Mock()
        mock_subprocess_run.return_value = '123'

    # Should import file and return no error. need to mock subprocess return value
    import env_test as conf

When i tried to import , it was sepcifying that the file was not found . i check on my path and it was correct.

FileNotFoundError: [WinError 2] The system cannot find the file specified


问:
Elasticsearch 8.5.2 Kubernetes configuration for s3 bucket
I am trying to bring up master Statefulset with 3 pods. I previously had to run the following script in Elasticsearch Dockerfile:

```<code>yes | bin/elasticsearch-plugin install repository-s3
</code>```

Now that s3 snapshot is built into 8.5, how do I configure it using ConfigMap? I don't use ECK operator but manual manifest. Any reference documentation would be helpful. Thanks.

Body:
I am trying to bring up master Statefulset with 3 pods. I previously had to run the following script in Elasticsearch Dockerfile:

yes | bin/elasticsearch-plugin install repository-s3

Now that s3 snapshot is built into 8.5, how do I configure it using ConfigMap? I don't use ECK operator but manual manifest. Any reference documentation would be helpful. Thanks.


问:
Using Python to search for hidden data
I have a possibly weird question that I have searched a million ways for a solution without success. I'm hoping it's simply because I don't know how to ask the Google.

We've recently discovered a problem with how pdf documents were redacted in an effort to keep them readable and thus searchable by AI.

However, this is creating issues with hidden sensitive data that becomes hidden to us but, could be extracted by the wrong people. Those of you working in cybersecurity know exactly how, I know:)

We can see there are types of data come up in a partial sanitization process but within Adobe we cannot view it.

My boss wants me to find out what's in these different subtypes of what Adobe views as "sensitive" data to see if we need to run this on thousands upon thousands of previously processed pdf documents (personally, I'm in the better safe than sorry camp but...)

I'm currently using Python and PyPDF2 to practice on a report I created on my own computer. But the problem I'm running into is that I'm not searching for specific data. It's like I'm searching for all data under a tag that I don't know the tag that Adobe uses (if that makes any sense.) For instance, they use: "Metadata", "Bookmarks", "Comments and "Markup", "Hidden Text", "Links, actions and javascripts", "Overlapping objects"

How can I use Python to search for the data in these tags? They don't readily display.

Thanks in advance!

This is the bare bones script to read the PDF that everything is based on:

```<code>import PyPDF2

pdfFileObj = open("MRA.pdf",'rb')

pdfReader = PyPDF2.PdfFileReader(pdfFileObj)

print(pdfReader.numPages)

pageObj = pdfReader.getPages(0)

print(pageObj.extractText())

pdfFileObj.close()

</code>```

We've tried doing keyword searches in individual documents where we know sensitive data exists because it came up in an initial partial sanitization review in Adobe DC. That code is long and not available as it's on my work computer and involves keywords I can't share.

Title: Using Python to search for hidden data

Body:
I have a possibly weird question that I have searched a million ways for a solution without success. I'm hoping it's simply because I don't know how to ask the Google.

We've recently discovered a problem with how pdf documents were redacted in an effort to keep them readable and thus searchable by AI.

However, this is creating issues with hidden sensitive data that becomes hidden to us but, could be extracted by the wrong people. Those of you working in cybersecurity know exactly how, I know:)

We can see there are types of data come up in a partial sanitization process but within Adobe we cannot view it.

My boss wants me to find out what's in these different subtypes of what Adobe views as "sensitive" data to see if we need to run this on thousands upon thousands of previously processed pdf documents (personally, I'm in the better safe than sorry camp but...)

I'm currently using Python and PyPDF2 to practice on a report I created on my own computer. But the problem I'm running into is that I'm not searching for specific data. It's like I'm searching for all data under a tag that I don't know the tag that Adobe uses (if that makes any sense.) For instance, they use: "Metadata", "Bookmarks", "Comments and "Markup", "Hidden Text", "Links, actions and javascripts", "Overlapping objects"

How can I use Python to search for the data in these tags? They don't readily display.

Thanks in advance!

This is the bare bones script to read the PDF that everything is based on:

import PyPDF2

pdfFileObj = open("MRA.pdf",'rb')

pdfReader = PyPDF2.PdfFileReader(pdfFileObj)

print(pdfReader.numPages)

pageObj = pdfReader.getPages(0)

print(pageObj.extractText())

pdfFileObj.close()

We've tried doing keyword searches in individual documents where we know sensitive data exists because it came up in an initial partial sanitization review in Adobe DC. That code is long and not available as it's on my work computer and involves keywords I can't share.


问:
Navicat's import of an entity diagram from a remote database causes the program to hang up
Navicat Version：Premium 16

Mysql Version：5.6.16-log

The program always stays on this page

Trying to stop won't work

But, I don't have this problem importing local tables.

Any help would be highly appreciated.

Thanks in advance.


问:
GAS .rept does not receive a label?
In NASM, I can easily do it using label like this

```<code>times 510-($-$$) db 0
                 db 0x55, 0xaa
</code>```

However, I can not use label in a GAS .rept command, It is invalid

```<code>current:
.rept 510-current-_start
.byte 0
.endr
; Error occures `Error: bad or irreducible absolute expression`
</code>```

I wonder what is a absolute expression(I saw it in a gas document), I think 510-current-_start should be accepcted because the value of this is calculated while compiling.

How can I elegantly put 0x55 and 0xaa in a right position?

I found .space works but .rept doesn't, why?

```<code>; It works
current:
.space 510-current-_start

; Error: bad or irreducible absolute expression
current:
.rept 510-current-_start
.byte 0
.endr
</code>```

EDITED:

It does't work too(using parentheses), I think It might be a bug?

```<code>; Error: bad or irreducible absolute expression
current:
.rept 510-(current-_start)
.byte 0
.endr
</code>```

Title: GAS .rept does not receive a label?

Body:
In NASM, I can easily do it using label like this

times 510-($-$$) db 0
                 db 0x55, 0xaa

However, I can not use label in a GAS .rept command, It is invalid

current:
.rept 510-current-_start
.byte 0
.endr
; Error occures `Error: bad or irreducible absolute expression`

I wonder what is a absolute expression(I saw it in a gas document), I think 510-current-_start should be accepcted because the value of this is calculated while compiling.

How can I elegantly put 0x55 and 0xaa in a right position?

I found .space works but .rept doesn't, why?

; It works
current:
.space 510-current-_start

; Error: bad or irreducible absolute expression
current:
.rept 510-current-_start
.byte 0
.endr

EDITED:

It does't work too(using parentheses), I think It might be a bug?

; Error: bad or irreducible absolute expression
current:
.rept 510-(current-_start)
.byte 0
.endr


问:
How to add an event to outlook calendar programmatically from react
I want to add an event to the outlook calendar programmatically from react. Is this possible to do so ? I cant find any such react library to perform such action.
Also is it advisable to keep this logic in frontend or backend ?
Your answer will be much appreciated, thanks.</p>


问:
Hovering to cell in the same column doesn't change the row hover
I created a table and are trying to make it so it hovers and highlight rows and column depending on cell. My current issue is when I hover to a cell and move my cursor to any cell in the same column, the row highlight doesn't change with it.

If I hover my cursor on number 1 or 2 in the same column, without going out of the column, the highlighted rows are still the same. I followed css-trick to create the same highlighting function.

```<code>    tbody tr:hover td, tbody tr:hover th {
    background-color: rgba(0,162,226,0.5) !important;
    }
    tbody td:hover::after {
        content: '';
        height: 200vh;
        left: 0;
        position: absolute;
        top: -100vh;
        width: 100%;
        z-index: 1;
    }
    td:hover::after{
        background-color: rgba(0,162,226,0.5) !important;
    }
</code>```

I placed z-index as 1 so that it does not nest with the bg-color which is gray in the picture but this means i cant detect cell changes on column. Is there a way this is possible?

Body:
I created a table and are trying to make it so it hovers and highlight rows and column depending on cell. My current issue is when I hover to a cell and move my cursor to any cell in the same column, the row highlight doesn't change with it.

If I hover my cursor on number 1 or 2 in the same column, without going out of the column, the highlighted rows are still the same. I followed css-trick to create the same highlighting function.

    tbody tr:hover td, tbody tr:hover th {
    background-color: rgba(0,162,226,0.5) !important;
    }
    tbody td:hover::after {
        content: '';
        height: 200vh;
        left: 0;
        position: absolute;
        top: -100vh;
        width: 100%;
        z-index: 1;
    }
    td:hover::after{
        background-color: rgba(0,162,226,0.5) !important;
    }

I placed z-index as 1 so that it does not nest with the bg-color which is gray in the picture but this means i cant detect cell changes on column. Is there a way this is possible?


问:
No matching distribution found <package>
I'm trying to install this package but I'm getting the erorr in the title along with "Could not find a version that satisfies the requirement vtk (from versions: none)". Does anyone know why it won't work when it's available on PyPI?

Edit: Found out it's because I'm on the latest Python version. A commenter kindly provided an unofficial build but I'm unsure of the process in installing it. I used the link pip install --find-links wheels.pyvista.org pyvista and it seems to have installed one package called appdirs but no vtk package. If I follow the link there's build instructions but it says for Ubuntu/Linux so not sure which one I should follow on Windows.. Also, I'd like to check if wheels for Python 3.10 are forward compatible with 3.11 since I'm on the latest version


问:
Sending Base64 as a JSON to ASP.NET WebMethod results in a 500 Error
I am attempting to send a Base64 string of a PDF file to my WebMethod from JavaScript code. I've confirmed that the Base64 and the JSON object are valid. However, it results in a 500 server error in the console:

Server Error 500
https://localhost:44345/invoice-purchase-order.aspx/UploadPDF
```
<p><strong>This is my JavaScript code:</strong></p>
```var pdfBase64 = "<base 64 string here. I didn’t post here because of length>";

var xhr = new XMLHttpRequest();
xhr.open('POST', '/invoice-purchase-order.aspx/UploadPDF', true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.onload = function() {
    if (xhr.status === 200) {

    }
};
var data = {
    base64String: pdfBase64
};
xhr.send(JSON.stringify(data));
```
<p><strong>WebMethod in the ASPX page:</strong></p>
```[WebMethod]
public static void UploadPDF(string base64String) {
    // Do something with the base64 string
}
```

It doesn't say any reason for the 500 error. Is it because of the length of the Base64 content? What should I change here?

Body:
I am attempting to send a Base64 string of a PDF file to my WebMethod from JavaScript code. I've confirmed that the Base64 and the JSON object are valid. However, it results in a 500 server error in the console:

Server Error 500
https://localhost:44345/invoice-purchase-order.aspx/UploadPDF

This is my JavaScript code:

var pdfBase64 = "<base 64 string here. I didn’t post here because of length>";

var xhr = new XMLHttpRequest();
xhr.open('POST', '/invoice-purchase-order.aspx/UploadPDF', true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.onload = function() {
    if (xhr.status === 200) {

    }
};
var data = {
    base64String: pdfBase64
};
xhr.send(JSON.stringify(data));

WebMethod in the ASPX page:

[WebMethod]
public static void UploadPDF(string base64String) {
    // Do something with the base64 string
}

It doesn't say any reason for the 500 error. Is it because of the length of the Base64 content? What should I change here?


问:
Loki Distributed with S3 backend not pulling data to Grafana dashboard
Loki Distributed with S3 backend not pulling data to Grafana dashboard, data is pushing to the S3 bucket but not shown in the dashboard.

While checking the pod logs we can see the following error,

level=warn ts=2022-12-07T21:56:10.957376174Z caller=client.go:369 component=client host=loki-stack:3100 msg="error sending batch, will retry" status=-1 error="Post "http://loki-stack:3100/loki/api/v1/push": dial tcp 172.20.215.236:3100: connect: connection refused"

Please helps to fix this issue.

Thanks.


问:
Keeping row focused/selected in AG Grid
I'm facing an issue while keeping a row focused/selected in AG Grid. I'm expecting it to be highlighted/selected even after I do certain actions like API calls, Does anyone know what is the fix?

This is my AGGridComponent

```<code><CustomAgGrid
    ref={gridRef}
    animateRows={false}
    filter={false}
    className="ag-theme-balham charity-grid"
    columnDefs={[
      {
        field: 'num',
        headerName: 'Num',
        width: 58, //53 + 17
      },
      {
        field: 'campaignName',
        headerName: 'Campaign Name',
        width: 151,
      },
      {
        field: 'description',
        headerName: 'Description',
        width: 140,
      },
      {
        field: 'isActive',
        headerName: 'Status',
        width: 110, //53 + 17
        cellRenderer: 'StatusIndicator',
      },
    ]}
    detailCellRenderer=""
    frameworkComponents={{
      exceptionMessage: function noRefCheck() {},
      StatusIndicator: StatusIndicator,
    }}
    masterDetail={false}
    noRowsOverlayComponent=""
    noRowsOverlayComponentParams={{
      messageHeader: '',
      messageInfo: ['No data to display'],
      messageType: 'info',
    }}
    rowData={campaignDataClone}
    context={{ gridApi }}
    rowSelection="single"
    onGridReady={onGridReady}
    onSelectionChanged={onSelectionChanged}
    onFirstDataRendered={onFirstDataRendered}
  />
</code>```

These are grid event handler

```<code> const onGridReady = params => {
params.api.sizeColumnsToFit();
window.addEventListener('resize', function() {
  setTimeout(function() {
    params.api.sizeColumnsToFit();
  });
});
gridRef.current.api.sizeColumnsToFit();
setGridApi(params.api);
</code>```

};

```<code>const onFirstDataRendered = () => {
    const rows = gridRef.current.api.clientSideRowModel.rowsToDisplay;
    if(rows?.length){
      rows[0].setSelected(true);
      setGridLoaded(true)
    }
  };
</code>```

This is how i dispatch actions to perform an API request

```<code>buttons={[
      {
        buttonLabel: 'No - Go Back',
        className: `btn-secondary btn-lg btn-block`,
        onClick: () => {
          toggleCampaignStatusConfirm(false);
          const selectedRows = gridRef.current.api.getSelectedRows();
          toggleCampaignEnable(selectedRows[0]?.isActive ? 'first_toggle' : 'second_toggle');
        },
      },
      {
        buttonLabel: `${isActive ? 'Yes - Disable' : 'Yes - Enable'}`,
        className: `${isActive ? 'btn-danger' : 'btn-success'} btn-lg btn-block`,
        onClick: () => {
          toggleCampaignStatusConfirm(false);
          dispatch(changeCampaignStatus(selectedCampaign?.campaignId, !isActive));
        },
      },
    ]}
</code>```

Once the API requests are done it just updates the redux and the component will be rendered. Here I'm expecting it to maintain the focus and the row should be selected. Can anyone please help me with how to achieve/fix this?

Title: Keeping row focused/selected in AG Grid

Body:
I'm facing an issue while keeping a row focused/selected in AG Grid. I'm expecting it to be highlighted/selected even after I do certain actions like API calls, Does anyone know what is the fix?

This is my AGGridComponent

<CustomAgGrid
    ref={gridRef}
    animateRows={false}
    filter={false}
    className="ag-theme-balham charity-grid"
    columnDefs={[
      {
        field: 'num',
        headerName: 'Num',
        width: 58, //53 + 17
      },
      {
        field: 'campaignName',
        headerName: 'Campaign Name',
        width: 151,
      },
      {
        field: 'description',
        headerName: 'Description',
        width: 140,
      },
      {
        field: 'isActive',
        headerName: 'Status',
        width: 110, //53 + 17
        cellRenderer: 'StatusIndicator',
      },
    ]}
    detailCellRenderer=""
    frameworkComponents={{
      exceptionMessage: function noRefCheck() {},
      StatusIndicator: StatusIndicator,
    }}
    masterDetail={false}
    noRowsOverlayComponent=""
    noRowsOverlayComponentParams={{
      messageHeader: '',
      messageInfo: ['No data to display'],
      messageType: 'info',
    }}
    rowData={campaignDataClone}
    context={{ gridApi }}
    rowSelection="single"
    onGridReady={onGridReady}
    onSelectionChanged={onSelectionChanged}
    onFirstDataRendered={onFirstDataRendered}
  />

These are grid event handler

 const onGridReady = params => {
params.api.sizeColumnsToFit();
window.addEventListener('resize', function() {
  setTimeout(function() {
    params.api.sizeColumnsToFit();
  });
});
gridRef.current.api.sizeColumnsToFit();
setGridApi(params.api);

};

const onFirstDataRendered = () => {
    const rows = gridRef.current.api.clientSideRowModel.rowsToDisplay;
    if(rows?.length){
      rows[0].setSelected(true);
      setGridLoaded(true)
    }
  };

This is how i dispatch actions to perform an API request

buttons={[
      {
        buttonLabel: 'No - Go Back',
        className: `btn-secondary btn-lg btn-block`,
        onClick: () => {
          toggleCampaignStatusConfirm(false);
          const selectedRows = gridRef.current.api.getSelectedRows();
          toggleCampaignEnable(selectedRows[0]?.isActive ? 'first_toggle' : 'second_toggle');
        },
      },
      {
        buttonLabel: `${isActive ? 'Yes - Disable' : 'Yes - Enable'}`,
        className: `${isActive ? 'btn-danger' : 'btn-success'} btn-lg btn-block`,
        onClick: () => {
          toggleCampaignStatusConfirm(false);
          dispatch(changeCampaignStatus(selectedCampaign?.campaignId, !isActive));
        },
      },
    ]}

Once the API requests are done it just updates the redux and the component will be rendered. Here I'm expecting it to maintain the focus and the row should be selected. Can anyone please help me with how to achieve/fix this?


问:
How do I successfully install the package "mordecai", given the installation guide?
I am trying to install the package mordecai. The installation guide is here:https://github.com/openeventdata/mordecai

I tried installing it using the terminal in VS Code via the command pip install mordecai, which resulted in a long error that ends with this:

```<code>        note: This error originates from a subprocess, and is likely not a problem with pip.
        ERROR: Failed building wheel for blis
        Running setup.py clean for blis
      Failed to build thinc preshed blis
      Installing collected packages: wrapt, wasabi, plac, cymem, wheel, tqdm, srsly, six, setuptools, preshed, numpy, murmurhash, Cython, thinc_gpu_ops, blis, thinc
        Running setup.py install for preshed: started
        Running setup.py install for preshed: finished with status 'error'
        error: subprocess-exited-with-error

        × Running setup.py install for preshed did not run successfully.
        │ exit code: 1
        ╰─> [13 lines of output]
            /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/setuptools/installer.py:27: SetuptoolsDeprecationWarning: setuptools.installer is deprecated. Requirements should be satisfied by a PEP 517 installer.
              warnings.warn(
            running install
            /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
              warnings.warn(
            running build
            running build_py
            running build_ext
            building 'preshed.maps' extension
            clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch arm64 -arch x86_64 -g -I/Library/Frameworks/Python.framework/Versions/3.10/include/python3.10 -I/Library/Frameworks/Python.framework/Versions/3.10/include/python3.10 -c preshed/maps.cpp -o build/temp.macosx-10.9-universal2-cpython-310/preshed/maps.o -O3 -Wno-strict-prototypes -Wno-unused-function
            clang: error: no such file or directory: 'preshed/maps.cpp'
            clang: error: no input files
            error: command '/usr/bin/clang' failed with exit code 1
            [end of output]

        note: This error originates from a subprocess, and is likely not a problem with pip.
      error: legacy-install-failure

      × Encountered error while trying to install package.
      ╰─> preshed

      note: This is an issue with the package mentioned above, not pip.
      hint: See above for output from the failure.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.
</code>```

I thought that these questions might have an answer, but they have not been able to answer my question.

How can I install packages using pip according to the requirements.txt file from a local directory?

How to install PIL with pip on Mac OS?

How to update/upgrade a package using pip?

How do I install pandas into visual studios code?

I looked through many questions on this site, but cannot seem to find an answer as to what I can do to install this package.

I have also tried the following, which produces the same error message:

```<code>python3 -m venv mordecai-env
source mordecai-env/bin/activate
pip3 install mordecai
</code>```

Please let me know if I can make my attempts or the question more clear, or if any other information is needed.

Body:
I am trying to install the package mordecai. The installation guide is here:https://github.com/openeventdata/mordecai

I tried installing it using the terminal in VS Code via the command pip install mordecai, which resulted in a long error that ends with this:

        note: This error originates from a subprocess, and is likely not a problem with pip.
        ERROR: Failed building wheel for blis
        Running setup.py clean for blis
      Failed to build thinc preshed blis
      Installing collected packages: wrapt, wasabi, plac, cymem, wheel, tqdm, srsly, six, setuptools, preshed, numpy, murmurhash, Cython, thinc_gpu_ops, blis, thinc
        Running setup.py install for preshed: started
        Running setup.py install for preshed: finished with status 'error'
        error: subprocess-exited-with-error

        × Running setup.py install for preshed did not run successfully.
        │ exit code: 1
        ╰─> [13 lines of output]
            /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/setuptools/installer.py:27: SetuptoolsDeprecationWarning: setuptools.installer is deprecated. Requirements should be satisfied by a PEP 517 installer.
              warnings.warn(
            running install
            /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
              warnings.warn(
            running build
            running build_py
            running build_ext
            building 'preshed.maps' extension
            clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch arm64 -arch x86_64 -g -I/Library/Frameworks/Python.framework/Versions/3.10/include/python3.10 -I/Library/Frameworks/Python.framework/Versions/3.10/include/python3.10 -c preshed/maps.cpp -o build/temp.macosx-10.9-universal2-cpython-310/preshed/maps.o -O3 -Wno-strict-prototypes -Wno-unused-function
            clang: error: no such file or directory: 'preshed/maps.cpp'
            clang: error: no input files
            error: command '/usr/bin/clang' failed with exit code 1
            [end of output]

        note: This error originates from a subprocess, and is likely not a problem with pip.
      error: legacy-install-failure

      × Encountered error while trying to install package.
      ╰─> preshed

      note: This is an issue with the package mentioned above, not pip.
      hint: See above for output from the failure.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error

× pip subprocess to install build dependencies did not run successfully.
│ exit code: 1
╰─> See above for output.

note: This error originates from a subprocess, and is likely not a problem with pip.

I thought that these questions might have an answer, but they have not been able to answer my question.

How can I install packages using pip according to the requirements.txt file from a local directory?

How to install PIL with pip on Mac OS?

How to update/upgrade a package using pip?

How do I install pandas into visual studios code?

I looked through many questions on this site, but cannot seem to find an answer as to what I can do to install this package.

I have also tried the following, which produces the same error message:

python3 -m venv mordecai-env
source mordecai-env/bin/activate
pip3 install mordecai

Please let me know if I can make my attempts or the question more clear, or if any other information is needed.


问:
How To Initiate Multiple Properties In Livewire On mount() Method
Does anyone know how to initiate these properties to "Data is not set yet." simultaneously without initiating each of them in an array?</p>
```<code>    class HomeroomClass extends Component
    {
        public $homeroomClassName;
        public $homeroomClassSemester;
        public $homeroomClassStudent;

        public function mount()
        {
            if (auth()->user()->student->homeroomclass_id != NULL)
            {
                $this->homeroomClassName = Auth::user()->student->homeroomclass->name;
                $this->homeroomClassSemester = Auth::user()->student->homeroomclass->semester;
                $this->homeroomClassStudent = Student::query()->where('homeroom_class_id', auth()->user()->student->homeroomclass->id)->count();
            }
            else
            {
                $this->fill(['homeroomClassName' => 'Data is not set yet.', 'homeroomClassSemester' => 'Data is not set yet.', 'homeroomClassStudent' => 'Data is not set yet.']);
            }
        }
    }
</code>```

Body:
Does anyone know how to initiate these properties to "Data is not set yet." simultaneously without initiating each of them in an array?

    class HomeroomClass extends Component
    {
        public $homeroomClassName;
        public $homeroomClassSemester;
        public $homeroomClassStudent;

        public function mount()
        {
            if (auth()->user()->student->homeroomclass_id != NULL)
            {
                $this->homeroomClassName = Auth::user()->student->homeroomclass->name;
                $this->homeroomClassSemester = Auth::user()->student->homeroomclass->semester;
                $this->homeroomClassStudent = Student::query()->where('homeroom_class_id', auth()->user()->student->homeroomclass->id)->count();
            }
            else
            {
                $this->fill(['homeroomClassName' => 'Data is not set yet.', 'homeroomClassSemester' => 'Data is not set yet.', 'homeroomClassStudent' => 'Data is not set yet.']);
            }
        }
    }


问:
Maven 3.0.3 ignoring environment variables
I have an interesting issue with Maven 3 in eclipse choosing which environment variables it wishes to run.  Some environment variables I pass into my MSVC compiler work properly, such as setting this variable...

```<code>            <linkerStartOption>/LIBPATH:"${env.JAVA_X86HOME}/lib"</linkerStartOption>
</code>```

will result in CL output...

```<code>            cmd.exe /X /C "link.exe /LIBPATH:"C:\PROGRA~2\Java\jdk1.6.0_24/lib"
</code>```

however other variables written in the same way will result in output like this...

```<code>            cmd.exe /X /C "link.exe /LIBPATH:"${env.ExampleVar}\lib\amd64"
</code>```

and is simply not stripping the value I need from that environment variable.  I have googled the issue and simply ran into other people also having the issue, however no solution is defined for it.  Anyone run into this problem before?

ContentLicense: CC BY-SA 3.0

Body:
I have an interesting issue with Maven 3 in eclipse choosing which environment variables it wishes to run.  Some environment variables I pass into my MSVC compiler work properly, such as setting this variable...

            <linkerStartOption>/LIBPATH:"${env.JAVA_X86HOME}/lib"</linkerStartOption>

will result in CL output...

            cmd.exe /X /C "link.exe /LIBPATH:"C:\PROGRA~2\Java\jdk1.6.0_24/lib"

however other variables written in the same way will result in output like this...

            cmd.exe /X /C "link.exe /LIBPATH:"${env.ExampleVar}\lib\amd64"

and is simply not stripping the value I need from that environment variable.  I have googled the issue and simply ran into other people also having the issue, however no solution is defined for it.  Anyone run into this problem before?


问:
SSL Certificate expiry data collection using python
im using the below code to get the SSL certificate expiry details for the input file
but not able to write a new csv file with the required data.

```<code>Code :

</code>```

import socket
import ssl
from _datetime import datetime
import csv

with open('url_domain.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader)
for hostname in csv_reader:
print(hostname[0])
ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
context = ssl.create_default_context()
conn = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=hostname[0])
conn.settimeout(3.0)
conn.connect((hostname[0], 443))
ssl_info = conn.getpeercert()
exp_on = datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)
days_remaining = exp_on - datetime.utcnow()
with open('cert_exp_details.csv', 'a', encoding='UTF8', newline='') as file:
header = ['URL', 'Expiry date', 'Remaining days']
data = [hostname[0], exp_on, days_remaining]
writer = csv.writer(file)
writer.writerow(header)
writer.writerows(data)
print(exp_on)
print(days_remaining)
print("---------------------")

```<code>expected Result :
in cert_exp_details.csv file we need to have the URL,expiry date and days remaining for every input URL from url_domain.csv
</code>```

Body:
im using the below code to get the SSL certificate expiry details for the input file
but not able to write a new csv file with the required data.

Code :

import socket
import ssl
from _datetime import datetime
import csv

with open('url_domain.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
next(csv_reader)
for hostname in csv_reader:
print(hostname[0])
ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
context = ssl.create_default_context()
conn = context.wrap_socket(socket.socket(socket.AF_INET), server_hostname=hostname[0])
conn.settimeout(3.0)
conn.connect((hostname[0], 443))
ssl_info = conn.getpeercert()
exp_on = datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)
days_remaining = exp_on - datetime.utcnow()
with open('cert_exp_details.csv', 'a', encoding='UTF8', newline='') as file:
header = ['URL', 'Expiry date', 'Remaining days']
data = [hostname[0], exp_on, days_remaining]
writer = csv.writer(file)
writer.writerow(header)
writer.writerows(data)
print(exp_on)
print(days_remaining)
print("---------------------")

expected Result :
in cert_exp_details.csv file we need to have the URL,expiry date and days remaining for every input URL from url_domain.csv


问:
visibilityChange and pagehide do not work in IOS
I'm creating a game page with JavaScript.
I am currently registering the Visibility Change event listener to turn on/off the BGM, but if I close the screen in IOS, the application will no longer move.
So I commented out the Visibility Change event. On Android, the BGM continues to play when the screen is closed, but iOS stops playing even without a BGM OFF event.
I tried the pagehide event, but it doesn't seem to work.

```<code>var hidden, visibilityChange;
        if (typeof document.hidden !== "undefined")
        {
            hidden = "hidden";
            visibilityChange = "visibilitychange";
        }
        else if (typeof document.mozHidden !== "undefined")
        {
            hidden = "mozHidden";
            visibilityChange = "mozvisibilitychange";
        }
        else if (typeof document.msHidden !== "undefined")
        {
            hidden = "msHidden";
            visibilityChange = "msvisibilitychange";
        }
        else if (typeof document.webkitHidden !== "undefined")
        {
            hidden = "webkitHidden";
            visibilityChange = "webkitvisibilitychange";
        }
        document.addEventListener(visibilityChange, SnlPixiMgr.VisibilityChange, false );
          window.addEventListener("pageshow", function(evt){
            alert('show');
        }, false);
        window.addEventListener("pagehide", function(evt){
            alert('hide');
        }, false);
</code>```
```<code>arguments.callee.VisibilityChange = function()
    {
        console.log("VisibilityChange called");
        if(document.hidden)
        {
            for( var i=0; i<SnlPixiMgr.m_HiddenEvent.length; i++ )
            {
                SnlPixiMgr.m_HiddenEvent[i]();
            }
        }
        else
        {
            for( var i=0; i<SnlPixiMgr.m_VisibleEvent.length; i++ )
            {
                SnlPixiMgr.m_VisibleEvent[i]();
            }
        }
    }
</code>```

I want the BGM to be turned on and off properly when I turn the screen off and on in iOS.

Body:
I'm creating a game page with JavaScript.
I am currently registering the Visibility Change event listener to turn on/off the BGM, but if I close the screen in IOS, the application will no longer move.
So I commented out the Visibility Change event. On Android, the BGM continues to play when the screen is closed, but iOS stops playing even without a BGM OFF event.
I tried the pagehide event, but it doesn't seem to work.

var hidden, visibilityChange;
        if (typeof document.hidden !== "undefined")
        {
            hidden = "hidden";
            visibilityChange = "visibilitychange";
        }
        else if (typeof document.mozHidden !== "undefined")
        {
            hidden = "mozHidden";
            visibilityChange = "mozvisibilitychange";
        }
        else if (typeof document.msHidden !== "undefined")
        {
            hidden = "msHidden";
            visibilityChange = "msvisibilitychange";
        }
        else if (typeof document.webkitHidden !== "undefined")
        {
            hidden = "webkitHidden";
            visibilityChange = "webkitvisibilitychange";
        }
        document.addEventListener(visibilityChange, SnlPixiMgr.VisibilityChange, false );
          window.addEventListener("pageshow", function(evt){
            alert('show');
        }, false);
        window.addEventListener("pagehide", function(evt){
            alert('hide');
        }, false);

arguments.callee.VisibilityChange = function()
    {
        console.log("VisibilityChange called");
        if(document.hidden)
        {
            for( var i=0; i<SnlPixiMgr.m_HiddenEvent.length; i++ )
            {
                SnlPixiMgr.m_HiddenEvent[i]();
            }
        }
        else
        {
            for( var i=0; i<SnlPixiMgr.m_VisibleEvent.length; i++ )
            {
                SnlPixiMgr.m_VisibleEvent[i]();
            }
        }
    }

I want the BGM to be turned on and off properly when I turn the screen off and on in iOS.


问:
GPU Instancing with multiple Materials
I'm making use of GPU Instancing in my 3D game in Unity.
Currently I'm using single material for each mesh.
But is there a way to do that with multiple material?
I have mesh's with just material colors without any textures, so texture atlas not helping in this case, is there way to Instance single mesh with multiple material.

Trying to find the solution of this from long time, requesting the solution.

Title: GPU Instancing with multiple Materials


问:
Pytorch CNN Input for Guitar Tab CNN
I am trying to implement the architecture I have attached.

The output of my DataLoader has size: torch.Size([128, 192, 9, 1])

I am using a batch size of 128

View just reshapes the output of the dense layer

```<code> model = nn.Sequential(nn.Conv2d(192, 32, 3),
                              nn.ReLU(),
                              nn.Conv2d(32, 64, 3),
                              nn.ReLU(),
                              nn.Conv2d(64, 64, 3),
                              nn.MaxPool2d(2),
                              nn.Dropout(0.25),
                              nn.Flatten(),
                              nn.Linear(5952, 128),
                              nn.ReLU(),
                              nn.Dropout(0.5),
                              nn.Linear(128, 126),
                              View((6, 21)),
                              nn.Softmax(dim=1))
</code>```

this is the architecture I currently have and I don't know if my input to the Conv2d are correct

I keep getting errors with my dimensions and kernel sizes. I am unsure how to proceed.

CNN Architecture

Title: Pytorch CNN Input for Guitar Tab CNN

Body:
I am trying to implement the architecture I have attached.

The output of my DataLoader has size: torch.Size([128, 192, 9, 1])

I am using a batch size of 128

View just reshapes the output of the dense layer

 model = nn.Sequential(nn.Conv2d(192, 32, 3),
                              nn.ReLU(),
                              nn.Conv2d(32, 64, 3),
                              nn.ReLU(),
                              nn.Conv2d(64, 64, 3),
                              nn.MaxPool2d(2),
                              nn.Dropout(0.25),
                              nn.Flatten(),
                              nn.Linear(5952, 128),
                              nn.ReLU(),
                              nn.Dropout(0.5),
                              nn.Linear(128, 126),
                              View((6, 21)),
                              nn.Softmax(dim=1))

this is the architecture I currently have and I don't know if my input to the Conv2d are correct

I keep getting errors with my dimensions and kernel sizes. I am unsure how to proceed.

CNN Architecture


问:
MSAccess and pyodbc - General error Unable to open registry key Temporary (volatile)
I am using pyodbc to access an MSAccess DB and getting the below error:

('HY000', "[HY000] [Microsoft][ODBC Microsoft Access Driver]General error Unable to open registry key Temporary (volatile) Ace DSN for process 0x43e0 Thread 0x3334 DBC 0xc8f892c).

I know this is related to access rights but couldn't find an answer to resolve (tried to copy the file to another folder, etc.). What puzzles me is that if I create a new DB in the same folder it works (checked access permissions through right click on the DB file and seems to be the same). The only other thing I could think of is that it's a split db (i.e. back end tables in one file and queries/forms in another - but my code tries to access the back end where the tables are). Any ideas?

```<code>import pyodbc
import pandas as pd

db_driver = '{Microsoft Access Driver (*.mdb, *.accdb)}'
db_path = 'C:\\Users\Kevin\\Desktop\\Watercolourhoarder_v8_backend.accdb'
conn_str = (rf'DRIVER={db_driver};'
            rf'DBQ={db_path};'r'Mode=Read;')

conn = pyodbc.connect(conn_str)

df = pd.read_sql(sql="select * from tbl_clients", con=conn)
print(df)

conn.close()
</code>```

Body:
I am using pyodbc to access an MSAccess DB and getting the below error:

('HY000', "[HY000] [Microsoft][ODBC Microsoft Access Driver]General error Unable to open registry key Temporary (volatile) Ace DSN for process 0x43e0 Thread 0x3334 DBC 0xc8f892c).

I know this is related to access rights but couldn't find an answer to resolve (tried to copy the file to another folder, etc.). What puzzles me is that if I create a new DB in the same folder it works (checked access permissions through right click on the DB file and seems to be the same). The only other thing I could think of is that it's a split db (i.e. back end tables in one file and queries/forms in another - but my code tries to access the back end where the tables are). Any ideas?

import pyodbc
import pandas as pd

db_driver = '{Microsoft Access Driver (*.mdb, *.accdb)}'
db_path = 'C:\\Users\Kevin\\Desktop\\Watercolourhoarder_v8_backend.accdb'
conn_str = (rf'DRIVER={db_driver};'
            rf'DBQ={db_path};'r'Mode=Read;')

conn = pyodbc.connect(conn_str)

df = pd.read_sql(sql="select * from tbl_clients", con=conn)
print(df)

conn.close()