问:
Table test not working on Golang with Receiver Function
I am trying to do some unit testing in Golang. I have this filter structure:

```<code>tests/
|_ rcv-func.go
|_ rcv-func_test.go

</code>```

My rcv-func.go looks like this:

```<code>package main

import "fmt"

type Player struct {
    health, maxHealth int
    energy, maxEnergy int
    name              string
}

func (p *Player) modifyHealth(newHealth int) {
    p.health = newHealth
}

func (p *Player) modifyEnergy(newEnergy int) {
    p.energy = newEnergy
}

func main() {
    player := Player{
        health:    50,
        maxHealth: 300,
        energy:    20,
        maxEnergy: 100,
        name:      "Jose",
    }
    fmt.Println("Before resting:", player)
    (&player).modifyHealth(150)
    (&player).modifyEnergy(100)
    fmt.Println("After resting:", player)
}
</code>```

And my rcv-func_test.go like this:

```<code>package main

import (
    "fmt"
    "testing"
)

var tests = []struct {
    health int
    energy int
    expect int
    name   string
    goal   bool
}{
    {200, 300, 50, "test1", true},
    {100, 300, 0, "test2", true},
}

func TestModifyEnergy(t *testing.T) {
    for _, tt := range tests {
        (&tt).modifyEnergy(11)

    }
}
</code>```

When I try to test the receiver function .modifyEnergy(), the line (&tt).modifyEnergy(11) is giving me the following error:

```<code>(&tt).modifyEnergy undefined (type *struct{health int; energy int; expect int; name string; goal bool} has no field or method modifyEnergy) (exit status 2)
</code>```

What would be the mistake here? It feels it is not defined but the method is clearly defined in the rcv-func.go file.

I tried making both receiver functions Public but to no avail.

Thank you in advance!

Body:
I am trying to do some unit testing in Golang. I have this filter structure:

tests/
|_ rcv-func.go
|_ rcv-func_test.go

My rcv-func.go looks like this:

package main

import "fmt"

type Player struct {
    health, maxHealth int
    energy, maxEnergy int
    name              string
}

func (p *Player) modifyHealth(newHealth int) {
    p.health = newHealth
}

func (p *Player) modifyEnergy(newEnergy int) {
    p.energy = newEnergy
}

func main() {
    player := Player{
        health:    50,
        maxHealth: 300,
        energy:    20,
        maxEnergy: 100,
        name:      "Jose",
    }
    fmt.Println("Before resting:", player)
    (&player).modifyHealth(150)
    (&player).modifyEnergy(100)
    fmt.Println("After resting:", player)
}

And my rcv-func_test.go like this:

package main

import (
    "fmt"
    "testing"
)

var tests = []struct {
    health int
    energy int
    expect int
    name   string
    goal   bool
}{
    {200, 300, 50, "test1", true},
    {100, 300, 0, "test2", true},
}

func TestModifyEnergy(t *testing.T) {
    for _, tt := range tests {
        (&tt).modifyEnergy(11)

    }
}

When I try to test the receiver function .modifyEnergy(), the line (&tt).modifyEnergy(11) is giving me the following error:

(&tt).modifyEnergy undefined (type *struct{health int; energy int; expect int; name string; goal bool} has no field or method modifyEnergy) (exit status 2)

What would be the mistake here? It feels it is not defined but the method is clearly defined in the rcv-func.go file.

I tried making both receiver functions Public but to no avail.

Thank you in advance!


来源: stackexchange

问:
How to aggregate high resolution array to a coarse array based on row and column mapping keys arrays faster in python?
I'm having a problem to come with an efficient way to aggregate a high resolution numpy array to a coarse array based  on row and column mapping keys that shows the corresponding row and column numbers in the coarse resolution for each cell in the fine resolution, a very simplified toy version of the problem:
Note: there is no mathematical pattern for the keys that might simplify the transformation.

#Fine resolution value array (6 by 6):

```<code>
 FIN=np.array([[44., 92., 65., 38., 44., 53.],
               [ 3., 24., 33., 60., 74., 55.],
               [89.,  1.,  9., 16., 79., 22.],
               [55., 69., 37., 97., 55., 89.],
               [ 4., 35., 81., 81.,  2., 20.],
               [63.,  6., 16., 59., 14., 37.]]

#Coarse resolution value array (3 by 3):

 COR=np.array([[0., 0., 0.],
               [0., 0., 0.],
               [0., 0., 0.]]
#ROWS (row number of the coarse resolution):
 ROWS=np.array([[0, 0, 0, 0, 1, 1],
                [0, 0, 0, 0, 1, 1],
                [1, 1, 1, 1, 1, 1],
                [1, 1, 1, 1, 1, 1],
                [2, 2, 2, 2, 2, 2],
                [2, 2, 2, 2, 2, 2]]
#COLS (col number of the coarse resolution):
 COLS=np.array([[0, 0, 1, 1, 2, 2],
               [0, 0, 1, 1, 2, 2],
               [0, 0, 1, 1, 2, 2],
               [0, 0, 1, 1, 2, 2],
               [1, 1, 1, 1, 2, 2],
               [1, 1, 1, 1, 2, 2]])

#My brute force solution is to loop over the rows and columns as follows:

    for i in range(len(FIN.shape[0])):
         for j in range(len(FIN.shape[0])):
             COR[i,j]=np.mean(FIN[np.logical_and(ROWS==i,COLS[1]==j)])

</code>```

This becomes very slow when the sizes of the arrays become very large.
Is there more efficient way to aggregate based on row/col mapping keys?

ContentLicense: CC BY-SA 4.0

Body:
I'm having a problem to come with an efficient way to aggregate a high resolution numpy array to a coarse array based  on row and column mapping keys that shows the corresponding row and column numbers in the coarse resolution for each cell in the fine resolution, a very simplified toy version of the problem:
Note: there is no mathematical pattern for the keys that might simplify the transformation.

#Fine resolution value array (6 by 6):

 FIN=np.array([[44., 92., 65., 38., 44., 53.],
               [ 3., 24., 33., 60., 74., 55.],
               [89.,  1.,  9., 16., 79., 22.],
               [55., 69., 37., 97., 55., 89.],
               [ 4., 35., 81., 81.,  2., 20.],
               [63.,  6., 16., 59., 14., 37.]]

#Coarse resolution value array (3 by 3):

 COR=np.array([[0., 0., 0.],
               [0., 0., 0.],
               [0., 0., 0.]]
#ROWS (row number of the coarse resolution):
 ROWS=np.array([[0, 0, 0, 0, 1, 1],
                [0, 0, 0, 0, 1, 1],
                [1, 1, 1, 1, 1, 1],
                [1, 1, 1, 1, 1, 1],
                [2, 2, 2, 2, 2, 2],
                [2, 2, 2, 2, 2, 2]]
#COLS (col number of the coarse resolution):
 COLS=np.array([[0, 0, 1, 1, 2, 2],
               [0, 0, 1, 1, 2, 2],
               [0, 0, 1, 1, 2, 2],
               [0, 0, 1, 1, 2, 2],
               [1, 1, 1, 1, 2, 2],
               [1, 1, 1, 1, 2, 2]])

#My brute force solution is to loop over the rows and columns as follows:

    for i in range(len(FIN.shape[0])):
         for j in range(len(FIN.shape[0])):
             COR[i,j]=np.mean(FIN[np.logical_and(ROWS==i,COLS[1]==j)])

This becomes very slow when the sizes of the arrays become very large.
Is there more efficient way to aggregate based on row/col mapping keys?


问:
Can not find the URL to download (Web scraping by using R)
I just want to use R to scrap the webpage and download the file automatically.

https://www.maklarstatistik.se/omrade/riket/stockholms-lan/stockholm/#/bostadsratter/arshistorik-prisutveckling

If you open this webpage and you can find buttom like this

enter image description here

I checked the source code, check the element which corresponds to the download button
and try to find out the xlsx file name

but I cannot find anything.

I only found this, but it is not the file url.
enter image description here

I just wonder how I can find the download file URL.
or How I can simulate to generate the xlsx file just like I clicking the button by using R

Thank you so much!


问:
Unable to pass on or retrieve data to another class
Trying to create a custom drop-down and facing issues in passing on data and retrieving the user selection from the custom drop-down. The solution however works when I use static var.

In the below code, I have a viewController class from where I am programmatically calling a popOver.

```<code>let countryDropDown = customDropdown()

    @IBAction func btMultiCountry(_ sender: Any) {
        ViewController.countryDropDown.removeAll() //fuction to clear the array before load
        for c in g.country{ //Array from which all items are loaded on the custom dropdown
            countryDropDown.addItems(labelText: c.countryName!, toggleState: 1) //passing the values in the add function to update the Array
        }
        countryDropDown.showDropdown(btMultiCountry) //programatically calling the function to display popover that has the collection view with the countries as items.
    }
</code>```
```<code>class customDropdown: NSViewController {

@IBOutlet weak var cvDropDown: NSCollectionView!

var pop = NSPopover() // if I put static var, the popover closes with the OK button as required, however, without static the OK button doest do anything
    var dropDownLabelText = [String]() //if I put static var, the values are shown on the collection view without any issue. Without static the array is blank that was load from additems function
    var dropDownToggle = [Int]() // same as above
    var selectedItemsIndex: [Int] {
        var a = [Int]()
        for (i,t) in dropDownToggle.enumerated() {
            if t == 1 {
                a.append(i)
                print(a)
            }
        }
        return a
    }

    func showDropdown(_ sender: NSButton){
        let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
        let VC = storyboard.instantiateController(withIdentifier: "dropDownForm") as? customDropdown
        pop.contentViewController = VC
        pop.behavior = NSPopover.Behavior.transient
        pop.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
        print(pop)
    }

    @IBAction func btOK(_ sender: Any) { //this function does not close the popover if there is not static mention above
        pop.close()
    }
</code>```

I tried putting static when declaring the variables and it worked. I do not want static and want to create different instances of the class that gives me selectedItemsIndex

For eg:

```<code>let countryDropDown = customDropdown()
let personDropDown = customDropdown()
</code>```

I should be able to get a different values for countryDropDown.selectedItemsIndex and personDropDown.selectedItemsIndex

Any help is appreciated.

Body:
Trying to create a custom drop-down and facing issues in passing on data and retrieving the user selection from the custom drop-down. The solution however works when I use static var.

In the below code, I have a viewController class from where I am programmatically calling a popOver.

let countryDropDown = customDropdown()

    @IBAction func btMultiCountry(_ sender: Any) {
        ViewController.countryDropDown.removeAll() //fuction to clear the array before load
        for c in g.country{ //Array from which all items are loaded on the custom dropdown
            countryDropDown.addItems(labelText: c.countryName!, toggleState: 1) //passing the values in the add function to update the Array
        }
        countryDropDown.showDropdown(btMultiCountry) //programatically calling the function to display popover that has the collection view with the countries as items.
    }

class customDropdown: NSViewController {

@IBOutlet weak var cvDropDown: NSCollectionView!

var pop = NSPopover() // if I put static var, the popover closes with the OK button as required, however, without static the OK button doest do anything
    var dropDownLabelText = [String]() //if I put static var, the values are shown on the collection view without any issue. Without static the array is blank that was load from additems function
    var dropDownToggle = [Int]() // same as above
    var selectedItemsIndex: [Int] {
        var a = [Int]()
        for (i,t) in dropDownToggle.enumerated() {
            if t == 1 {
                a.append(i)
                print(a)
            }
        }
        return a
    }

    func showDropdown(_ sender: NSButton){
        let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
        let VC = storyboard.instantiateController(withIdentifier: "dropDownForm") as? customDropdown
        pop.contentViewController = VC
        pop.behavior = NSPopover.Behavior.transient
        pop.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.minY)
        print(pop)
    }

    @IBAction func btOK(_ sender: Any) { //this function does not close the popover if there is not static mention above
        pop.close()
    }

I tried putting static when declaring the variables and it worked. I do not want static and want to create different instances of the class that gives me selectedItemsIndex

For eg:

let countryDropDown = customDropdown()
let personDropDown = customDropdown()

I should be able to get a different values for countryDropDown.selectedItemsIndex and personDropDown.selectedItemsIndex

Any help is appreciated.


问:
Can i use Prisma-Client as a nested dependency
I was making a restful APIs framework I decided to add Prisma for database support I want to provide Prisma-client to users in an appropriate way.
here is what I'm trying to do:

// @my/pkg

import {PrismaClient} from '@prisma/client'; // here the prisma client is nested dependency for client

// base class for all routes, the user will extend this class to create a route
abstract class BaseRouter {
    public get (req: Request, res: Response): Promise <void> {}

   public  db = new PrimaClient ();
}

 // client side
 // note! prisma init and database will setup on client side
import BaseRouter from '@my/pkg'

class Client extends BaseRouter {
  public get (req: Request, res: Response): Promise <void> {
      const users = db.Users.findMany (); // I'm getting error here
  }
}

```
<blockquote>
<p>so my question is can I use <code>pirsma-client</code> as a nested dependency and is there any way to achieve similar results?</p>
</blockquote>
<h2>Reason for that Design:</h2>
<p>I'm providing <code>database</code> access from the base class because I also want to provide other databases like <code>Redis, firebase, etc...</code> according to the flavor of the database chosen by the user.
here how it looks like:-</p>
<pre class="lang-bash prettyprint-override"><code>   which database do you want to choose for your app:
   - Prisma (SQL/MongoDB)
   - firebase (NON-SQL)
   - Redis (caching)
</code>```

According to APIS design, all databases will access through the base class object db.

Thanks in Advance

Body:
I was making a restful APIs framework I decided to add Prisma for database support I want to provide Prisma-client to users in an appropriate way.
here is what I'm trying to do:

// @my/pkg

import {PrismaClient} from '@prisma/client'; // here the prisma client is nested dependency for client

// base class for all routes, the user will extend this class to create a route
abstract class BaseRouter {
    public get (req: Request, res: Response): Promise <void> {}

   public  db = new PrimaClient ();
}

 // client side
 // note! prisma init and database will setup on client side
import BaseRouter from '@my/pkg'

class Client extends BaseRouter {
  public get (req: Request, res: Response): Promise <void> {
      const users = db.Users.findMany (); // I'm getting error here
  }
}

so my question is can I use pirsma-client as a nested dependency and is there any way to achieve similar results?

Reason for that Design:

I'm providing database access from the base class because I also want to provide other databases like Redis, firebase, etc... according to the flavor of the database chosen by the user.
here how it looks like:-

   which database do you want to choose for your app:
   - Prisma (SQL/MongoDB)
   - firebase (NON-SQL)
   - Redis (caching)

According to APIS design, all databases will access through the base class object db.

Thanks in Advance


问:
Magento2 DataDump
How to get Data Dump from magento cloud. I have tried magento-cloud db:dump. It has given me .sql file. I dont know where to run that file.

I tried Magento CLI. I got sql file using magento-cloud db:dump in my terminal.

P.S. I am using Mac

Title: Magento2 DataDump


问:
Why aren't assertions such as $ and ^ part of a regular grammar?
I read that $ and ^ are not elements of a (formal) regular expression. Why is this so? First of all, wouldn't the ^ start-of-string essentially be the initial state of the state diagram? So, for example, why couldn't a FSM look like this to capture ^a$?

```<code>       a
-> q1 ---> q2
</code>```

And, if this isn't allowed, is it because there is something that would inherently disobey how Regular Expression are defined? Or is merely that assertions were introduced after Regular Expressions were first defined, and so aren't included?

Body:
I read that $ and ^ are not elements of a (formal) regular expression. Why is this so? First of all, wouldn't the ^ start-of-string essentially be the initial state of the state diagram? So, for example, why couldn't a FSM look like this to capture ^a$?

       a
-> q1 ---> q2

And, if this isn't allowed, is it because there is something that would inherently disobey how Regular Expression are defined? Or is merely that assertions were introduced after Regular Expressions were first defined, and so aren't included?


问:
Push content inside SingleChildScrollView up
I have a login form which has 2 input fields (username and password) and has a button at the bottom of the screen (with expanded). I have the functionality of when the keyboard is visible, the button would be above the keyboard , but the form content is not going up.

```<code>    return SingleChildScrollView(
      child: Container(
          height: MediaQuery.of(context).size.height - Scaffold.of(context).appBarMaxHeight!,
          padding: EdgeInsets.only(
              top: 16,
              bottom: MediaQuery.of(context).viewInsets.bottom,
              left: 16,
              right: 16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    LoginSignUpHeader(
                      title: 'Login!',
                      description:
                          'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et',
                      googleFacebookPressed: (value) {},
                    ),
                    Padding(
                      padding: const EdgeInsets.only(bottom: 16),
                      child: TextFormField(
                        controller: _usernameController,
                        autofocus: false,
                        cursorColor: Styles.pinkColor,
                        textInputAction: TextInputAction.next,
                        focusNode: _usernameFocusNode,
                        style: const TextStyle(
                            fontSize: 16, color: Color(0xFFbdc6cf)),
                        decoration: InputDecoration(
                          focusedBorder: const OutlineInputBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(5)),
                              borderSide:
                                  BorderSide(color: Styles.pinkColor)),
                          filled: true,
                          isDense: true,
                          contentPadding: const EdgeInsets.all(12),
                          fillColor: Styles.secondLayerColor,
                          hintText: 'Username or Email',
                          hintStyle: TextStyle(
                              fontSize: 16.0,
                              color: Colors.white.withOpacity(0.3)),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5),
                            borderSide: const BorderSide(
                              width: 0,
                              style: BorderStyle.none,
                            ),
                          ),
                        ),
                        onFieldSubmitted: (_) {
                          FocusScope.of(context)
                              .requestFocus(_usernameFocusNode);
                        },
                        onSaved: (value) {},
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(bottom: 8),
                      child: TextFormField(
                        controller: _passwordController,
                        autofocus: false,
                        cursorColor: Styles.pinkColor,
                        textInputAction: TextInputAction.next,
                        focusNode: _passwordFocusNode,
                        obscureText: true,
                        enableSuggestions: false,
                        autocorrect: false,
                        style: const TextStyle(
                            fontSize: 16, color: Color(0xFFbdc6cf)),
                        decoration: InputDecoration(
                          focusedBorder: const OutlineInputBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(5)),
                              borderSide:
                                  BorderSide(color: Styles.pinkColor)),
                          filled: true,
                          isDense: true,
                          contentPadding: const EdgeInsets.all(12),
                          fillColor: Styles.secondLayerColor,
                          hintText: 'Password',
                          hintStyle: TextStyle(
                              fontSize: 16.0,
                              color: Colors.white.withOpacity(0.3)),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5),
                            borderSide: const BorderSide(
                              width: 0,
                              style: BorderStyle.none,
                            ),
                          ),
                        ),
                        onFieldSubmitted: (_) {
                          FocusScope.of(context)
                              .requestFocus(_passwordFocusNode);
                        },
                        onSaved: (value) {},
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(bottom: 100),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          GestureDetector(
                            onTap: () {
                              print("tapped");
                            },
                            behavior: HitTestBehavior.opaque,
                            child: const Text("Forgot Password?",
                                textAlign: TextAlign.end,
                                style:
                                    TextStyle(color: Styles.pinkColor)),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 12),
                child: Container(child:
                    BlocBuilder<LoginBloc, LoginState>(
                        builder: (ctx, state) {
                  var buttonText = 'Login';
                  if (state is LoginLoading) {
                    buttonText = 'Loading';
                  }
                  return ElevatedButton(
                    onPressed: () {
                      submitLogin(BlocProvider.of<LoginBloc>(ctx));
                    },
                    style: ElevatedButton.styleFrom(
                      padding: EdgeInsets.zero,
                      shape: const StadiumBorder(),
                      backgroundColor:
                          Styles.firstLayerColor, // Background color
                    ),
                    child: Ink(
                      decoration: BoxDecoration(
                          gradient: const LinearGradient(colors: [
                            Styles.pinkColor,
                            Styles.purpleColor
                          ]),
                          borderRadius: BorderRadius.circular(40)),
                      child: Container(
                        height: 40,
                        alignment: Alignment.center,
                        child: AutoSizeText(
                          // style: TextStyle(fontSize: constraints.maxHeight * 0.06),
                          buttonText,
                        ),
                      ),
                    ),
                  );
                })),
              )
            ],
          )),
    );
  }
</code>```

I already have on the scaffold resizeToAvoidBottomInset: false  I just need the Expanded widget to get pushed up. Is it posible or what other way can I have a form with the button being on top of keyboard and form content being pushed up?

Body:
I have a login form which has 2 input fields (username and password) and has a button at the bottom of the screen (with expanded). I have the functionality of when the keyboard is visible, the button would be above the keyboard , but the form content is not going up.

    return SingleChildScrollView(
      child: Container(
          height: MediaQuery.of(context).size.height - Scaffold.of(context).appBarMaxHeight!,
          padding: EdgeInsets.only(
              top: 16,
              bottom: MediaQuery.of(context).viewInsets.bottom,
              left: 16,
              right: 16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    LoginSignUpHeader(
                      title: 'Login!',
                      description:
                          'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et',
                      googleFacebookPressed: (value) {},
                    ),
                    Padding(
                      padding: const EdgeInsets.only(bottom: 16),
                      child: TextFormField(
                        controller: _usernameController,
                        autofocus: false,
                        cursorColor: Styles.pinkColor,
                        textInputAction: TextInputAction.next,
                        focusNode: _usernameFocusNode,
                        style: const TextStyle(
                            fontSize: 16, color: Color(0xFFbdc6cf)),
                        decoration: InputDecoration(
                          focusedBorder: const OutlineInputBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(5)),
                              borderSide:
                                  BorderSide(color: Styles.pinkColor)),
                          filled: true,
                          isDense: true,
                          contentPadding: const EdgeInsets.all(12),
                          fillColor: Styles.secondLayerColor,
                          hintText: 'Username or Email',
                          hintStyle: TextStyle(
                              fontSize: 16.0,
                              color: Colors.white.withOpacity(0.3)),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5),
                            borderSide: const BorderSide(
                              width: 0,
                              style: BorderStyle.none,
                            ),
                          ),
                        ),
                        onFieldSubmitted: (_) {
                          FocusScope.of(context)
                              .requestFocus(_usernameFocusNode);
                        },
                        onSaved: (value) {},
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(bottom: 8),
                      child: TextFormField(
                        controller: _passwordController,
                        autofocus: false,
                        cursorColor: Styles.pinkColor,
                        textInputAction: TextInputAction.next,
                        focusNode: _passwordFocusNode,
                        obscureText: true,
                        enableSuggestions: false,
                        autocorrect: false,
                        style: const TextStyle(
                            fontSize: 16, color: Color(0xFFbdc6cf)),
                        decoration: InputDecoration(
                          focusedBorder: const OutlineInputBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(5)),
                              borderSide:
                                  BorderSide(color: Styles.pinkColor)),
                          filled: true,
                          isDense: true,
                          contentPadding: const EdgeInsets.all(12),
                          fillColor: Styles.secondLayerColor,
                          hintText: 'Password',
                          hintStyle: TextStyle(
                              fontSize: 16.0,
                              color: Colors.white.withOpacity(0.3)),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(5),
                            borderSide: const BorderSide(
                              width: 0,
                              style: BorderStyle.none,
                            ),
                          ),
                        ),
                        onFieldSubmitted: (_) {
                          FocusScope.of(context)
                              .requestFocus(_passwordFocusNode);
                        },
                        onSaved: (value) {},
                      ),
                    ),
                    Padding(
                      padding: const EdgeInsets.only(bottom: 100),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          GestureDetector(
                            onTap: () {
                              print("tapped");
                            },
                            behavior: HitTestBehavior.opaque,
                            child: const Text("Forgot Password?",
                                textAlign: TextAlign.end,
                                style:
                                    TextStyle(color: Styles.pinkColor)),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(vertical: 12),
                child: Container(child:
                    BlocBuilder<LoginBloc, LoginState>(
                        builder: (ctx, state) {
                  var buttonText = 'Login';
                  if (state is LoginLoading) {
                    buttonText = 'Loading';
                  }
                  return ElevatedButton(
                    onPressed: () {
                      submitLogin(BlocProvider.of<LoginBloc>(ctx));
                    },
                    style: ElevatedButton.styleFrom(
                      padding: EdgeInsets.zero,
                      shape: const StadiumBorder(),
                      backgroundColor:
                          Styles.firstLayerColor, // Background color
                    ),
                    child: Ink(
                      decoration: BoxDecoration(
                          gradient: const LinearGradient(colors: [
                            Styles.pinkColor,
                            Styles.purpleColor
                          ]),
                          borderRadius: BorderRadius.circular(40)),
                      child: Container(
                        height: 40,
                        alignment: Alignment.center,
                        child: AutoSizeText(
                          // style: TextStyle(fontSize: constraints.maxHeight * 0.06),
                          buttonText,
                        ),
                      ),
                    ),
                  );
                })),
              )
            ],
          )),
    );
  }

I already have on the scaffold resizeToAvoidBottomInset: false  I just need the Expanded widget to get pushed up. Is it posible or what other way can I have a form with the button being on top of keyboard and form content being pushed up?


问:
maven-shade-plugin: Cannot load implementation hint
I want to create a simple uber-jar for my non-modular project using shade. I followed the documentation at

[https://maven.apache.org/plugins/maven-shade-plugin/examples/executable-jar.html]

but somehow, i keep getting this error:

```<code>Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:3.4.1:shade (default) on project SharkTouch: Unable to parse configuration of mojo org.apache.maven.plugins:maven-shade-plugin:3.4.1:shade for parameter transformers: Cannot load implementation hint 'org.example.Main'
</code>```

here is my pom.xml:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>SharkTouch</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>19</maven.compiler.source>
        <maven.compiler.target>19</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.7.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.10.1</version>
        </dependency>
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.reactfx</groupId>
            <artifactId>reactfx</artifactId>
            <version>1.4.1</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.4.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.example.Main">
                                    <mainClass>org.example.Main</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

Body:
I want to create a simple uber-jar for my non-modular project using shade. I followed the documentation at

[https://maven.apache.org/plugins/maven-shade-plugin/examples/executable-jar.html]

but somehow, i keep getting this error:

Failed to execute goal org.apache.maven.plugins:maven-shade-plugin:3.4.1:shade (default) on project SharkTouch: Unable to parse configuration of mojo org.apache.maven.plugins:maven-shade-plugin:3.4.1:shade for parameter transformers: Cannot load implementation hint 'org.example.Main'

here is my pom.xml:

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>SharkTouch</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>19</maven.compiler.source>
        <maven.compiler.target>19</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.7.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.10.1</version>
        </dependency>
        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.reactfx</groupId>
            <artifactId>reactfx</artifactId>
            <version>1.4.1</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.4.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.example.Main">
                                    <mainClass>org.example.Main</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


问:
Remote debug Qt app running over EGLFS platform
I am developing a qml application using QtCreator which must be run and debugged over a remote linux machine. The application must be run over eglfs platfrom and hence remote machine does not have X or wayland running.
The GUI must be displayed over the remote machine display and not to be forwarded over ssh tunnel to the local machine.
How can I make it done?

QtCreator 9.0.0

Qt 5.15.2

Both remote and local machines run Linux.

If I don't set any specific settings in QtCreator, by running the application, I get

```<code>Starting /home/pi/app/app --platform eglfs on RaspberryPi...
Cannot create window: no screens available
</code>```

and if set enable checkbox Forward to local display in Project > Run settings, I'll get the app running on the local display over eglfs platform which I don't want to.

Body:
I am developing a qml application using QtCreator which must be run and debugged over a remote linux machine. The application must be run over eglfs platfrom and hence remote machine does not have X or wayland running.
The GUI must be displayed over the remote machine display and not to be forwarded over ssh tunnel to the local machine.
How can I make it done?

QtCreator 9.0.0

Qt 5.15.2

Both remote and local machines run Linux.

If I don't set any specific settings in QtCreator, by running the application, I get

Starting /home/pi/app/app --platform eglfs on RaspberryPi...
Cannot create window: no screens available

and if set enable checkbox Forward to local display in Project > Run settings, I'll get the app running on the local display over eglfs platform which I don't want to.


问:
Error handling in large uploads to Express using Formidable and AJAX
I have created a private server and web application for uploading movies and playing them. Unfortunately, uploads often interupt and fail. The console log shows the upload is to be terminated, but progress continues until the end where it reaches 100%, but never completes. I would like it to either stop the upload in the event of a network interruption, or better yet, gracefully catch the error and continue such that the upload completes correctly. I am using formidable, a nodejs library in an express framework with Ajax on the front end to display a progress bar.
Here is my code:

```<code>app.post('/upload', (req, res) => {

// create an incoming form object
  var form = new formidable.IncomingForm();

  form.maxFileSize = 2500 * 1024 * 1024;
  form.multiples = true;

  form.uploadDir = path.join(__dirname, '/public/dropbox/');

  form.on('file', function(field, file) {
     fs.rename(file.path, path.join(form.uploadDir, file.name), () => {
         console.log(file.name + " uploaded")
     });
  });

  form.on('progress', (bytesReceived, bytesExpected) => {
  });

  process.on('uncaughtException', function(err) {  //this does nothing
     console.log(err)
     throw err;
  })

  form.on('error', function(err) {
     console.log('An error has occured: \n' + err);
     res.eventEmitter('error')
  });

  // once all the files have been uploaded, send a response to the client
  form.on('end', function() {
     console.log("finished uploading")
  });

  // parse the incoming request containing the form data
  form.parse(req);
})
</code>```

And on the front end in AJAX:

```<code>$('#upload-input').on('change', function(){
   $("#error").css("display", "none");
   var files = $(this).get(0).files;
   console.log(files[0].name);
   if (files.length > 0){
      // create a FormData object which will be sent as the data payload in the
     // AJAX request
     var formData = new FormData();
     // loop through all the selected files and add them to the formData object
     for (var i = 0; i < files.length; i++) {
        var file = files[i];
        // add the files to formData object for the data payload
        formData.append('uploads[]', file, file.name);
     }
     $.ajax({
         url:''/upload',
         type: 'POST',
         data: formData,
         processData: false,
         contentType: false,
         success: function(data){
            console.log('upload successful!\n');
             window.location.href = window.location.pathname;
             $('').html(data)
         },
         error: function(data, status, error){
             console.log(data, status, error)
             //this does nothing
         },
         xhr: function() {
             // create an XMLHttpRequest
             var xhr = new XMLHttpRequest();
             // listen to the 'progress' event
             $('.progress').show();
                xhr.upload.addEventListener('progress', function(evt) {
                   if (evt.lengthComputable) {
                      // calculate the percentage of upload completed
                      var percentComplete = evt.loaded / evt.total;
                      percentComplete = parseInt(percentComplete * 100);
                      // update the Bootstrap progress bar with the new percentage
                      $('.progress-bar').text(percentComplete + '%');
                      $('.progress-bar').width(percentComplete + '%');
                     // once the upload reaches 100%, set the progress bar text to done
                      if (percentComplete === 100) {
                          $('.progress-bar').html('Done');
                      }
                   }
                }, false);
                xhr.upload.addEventListener('error', function(err) {
                    xhr.abort()
                    $("#error").css("display", "block");
                })
                return xhr;
             }
          });
</code>```

Body:
I have created a private server and web application for uploading movies and playing them. Unfortunately, uploads often interupt and fail. The console log shows the upload is to be terminated, but progress continues until the end where it reaches 100%, but never completes. I would like it to either stop the upload in the event of a network interruption, or better yet, gracefully catch the error and continue such that the upload completes correctly. I am using formidable, a nodejs library in an express framework with Ajax on the front end to display a progress bar.
Here is my code:

app.post('/upload', (req, res) => {

// create an incoming form object
  var form = new formidable.IncomingForm();

  form.maxFileSize = 2500 * 1024 * 1024;
  form.multiples = true;

  form.uploadDir = path.join(__dirname, '/public/dropbox/');

  form.on('file', function(field, file) {
     fs.rename(file.path, path.join(form.uploadDir, file.name), () => {
         console.log(file.name + " uploaded")
     });
  });

  form.on('progress', (bytesReceived, bytesExpected) => {
  });

  process.on('uncaughtException', function(err) {  //this does nothing
     console.log(err)
     throw err;
  })

  form.on('error', function(err) {
     console.log('An error has occured: \n' + err);
     res.eventEmitter('error')
  });

  // once all the files have been uploaded, send a response to the client
  form.on('end', function() {
     console.log("finished uploading")
  });

  // parse the incoming request containing the form data
  form.parse(req);
})

And on the front end in AJAX:

$('#upload-input').on('change', function(){
   $("#error").css("display", "none");
   var files = $(this).get(0).files;
   console.log(files[0].name);
   if (files.length > 0){
      // create a FormData object which will be sent as the data payload in the
     // AJAX request
     var formData = new FormData();
     // loop through all the selected files and add them to the formData object
     for (var i = 0; i < files.length; i++) {
        var file = files[i];
        // add the files to formData object for the data payload
        formData.append('uploads[]', file, file.name);
     }
     $.ajax({
         url:''/upload',
         type: 'POST',
         data: formData,
         processData: false,
         contentType: false,
         success: function(data){
            console.log('upload successful!\n');
             window.location.href = window.location.pathname;
             $('').html(data)
         },
         error: function(data, status, error){
             console.log(data, status, error)
             //this does nothing
         },
         xhr: function() {
             // create an XMLHttpRequest
             var xhr = new XMLHttpRequest();
             // listen to the 'progress' event
             $('.progress').show();
                xhr.upload.addEventListener('progress', function(evt) {
                   if (evt.lengthComputable) {
                      // calculate the percentage of upload completed
                      var percentComplete = evt.loaded / evt.total;
                      percentComplete = parseInt(percentComplete * 100);
                      // update the Bootstrap progress bar with the new percentage
                      $('.progress-bar').text(percentComplete + '%');
                      $('.progress-bar').width(percentComplete + '%');
                     // once the upload reaches 100%, set the progress bar text to done
                      if (percentComplete === 100) {
                          $('.progress-bar').html('Done');
                      }
                   }
                }, false);
                xhr.upload.addEventListener('error', function(err) {
                    xhr.abort()
                    $("#error").css("display", "block");
                })
                return xhr;
             }
          });


问:
EF Core add-migration build failed
I have a developer that is getting an error "Build failed" when running Add-Migration in a .NET Core EF project, with no explanation as to why the build failed. How do you troubleshoot this error?

This is what he gets in the Package Manager Console:

I want to run Add-Migration

Title: EF Core add-migration build failed


问:
Convert RGB colors to 2D plane
I have three columns with RGB colors. In another set of columns, I need to convert them to X,Y coordinates per the following examples:

How?

The math is eluding me, mostly because it has to wrap back around to red.

Of note: no VB please, and I'd prefer the map jump from the second red directly to pure grayscale (i.e. no bleeding).

UPDATE: I came up with the following:

X —

```<code>=IF(AND(MAX([@R]:[@B])=[@R],MAX([@R]:[@B])<>[@B]),[@R]+[@G]-[@B],
IF(MAX([@R]:[@B])=[@G],512+[@G]+[@B]-[@R],
IF(MAX([@R]:[@B])=[@B],1024+[@B]+[@R]-[@G])))
-(256*(MAX([@R]:[@B])/256))
</code>```

Y —

```<code>=ROUNDUP(MAX(Table1[@[R]:[B]])/2*IF(MIN(Table1[@[R]:[B]])=0,1,1+MIN(Table1[@[R]:[B]])/256),0)
</code>```

Plus a separate quick calculation to wrap around negative X values. I'll also write a quick check for grayscale exceptions after I resolve colors.

But first, tell me why the above is wrong.

Title: Convert RGB colors to 2D plane

Body:
I have three columns with RGB colors. In another set of columns, I need to convert them to X,Y coordinates per the following examples:

How?

The math is eluding me, mostly because it has to wrap back around to red.

Of note: no VB please, and I'd prefer the map jump from the second red directly to pure grayscale (i.e. no bleeding).

UPDATE: I came up with the following:

X —

=IF(AND(MAX([@R]:[@B])=[@R],MAX([@R]:[@B])<>[@B]),[@R]+[@G]-[@B],
IF(MAX([@R]:[@B])=[@G],512+[@G]+[@B]-[@R],
IF(MAX([@R]:[@B])=[@B],1024+[@B]+[@R]-[@G])))
-(256*(MAX([@R]:[@B])/256))

Y —

=ROUNDUP(MAX(Table1[@[R]:[B]])/2*IF(MIN(Table1[@[R]:[B]])=0,1,1+MIN(Table1[@[R]:[B]])/256),0)

Plus a separate quick calculation to wrap around negative X values. I'll also write a quick check for grayscale exceptions after I resolve colors.

But first, tell me why the above is wrong.


问:
how to get filename from php to ajax xhttp js
Here is js and html

I want to get filename in p tag. How to do this?

I tried with above code but still not working.

```<code><div>
  <p id="filename"></p>
  <input type="file" name="file" id="file">
  <input type="button" id="btn_uploadfile"
     value="Upload"
     onclick="uploadFile();" >
</div>
<hr><br><br>
<script>
function uploadFile() {

var files = document.getElementById("file").files;

if(files.length > 0 ){

   var formData = new FormData();
   formData.append("file", files[0]);

   var xhttp = new XMLHttpRequest();

   // Set POST method and ajax file path
   xhttp.open("POST", "includes/upload.php", true);

   // call on request changes state
   xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {

        var response = this.responseText;
        var filenamenew = this.filenamenewText;
        document.getElementById("filename").innerHTML = filenamenew;
        var input = document.getElementById("btn_uploadfile");
        var a = document.getElementById("links");
        if(response == 1){
           alert("Upload successfully.");
           input.value = "Uploaded";
           input.disabled = 'true';
           var input = document.getElementById("file");
           input.disabled = 'true';
        }else{
           alert("File not uploaded.");
        }
      }
   };

   // Send request with data
   xhttp.send(formData);

}else{
   alert("Please select a file");
}

}
</script>
</code>```

Php code here

```<code><?php

if(isset($_FILES['file']['name'])){
   // file name
   $filename = $_FILES["file"]["name"];
   $newfilename = round(microtime(true)) . '_original_' . $filename ;

   // Location
   $location = '../uploads/'.$newfilename;

   // file extension
   $file_extension = pathinfo($location, PATHINFO_EXTENSION);
   $file_extension = strtolower($file_extension);

   // Valid extensions
   $valid_ext = array("apk","aab","ipa");

   $response = 0;
   $filenamenew = 0;
   if(in_array($file_extension,$valid_ext)){
      // Upload file
      if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
         $response = 1;
         $filenamenew = $filenamenew;
      }
   }

   echo $response;
   exit;
   echo "<p>$filenamenew<p>";
   exit;
}
?>
</code>```

In this code it says in p tag is undefined

Body:
Here is js and html

I want to get filename in p tag. How to do this?

I tried with above code but still not working.

  <input type="file" name="file" id="file">
  <input type="button" id="btn_uploadfile"
     value="Upload"
     onclick="uploadFile();" >

Php code here

<?php

if(isset($_FILES['file']['name'])){
   // file name
   $filename = $_FILES["file"]["name"];
   $newfilename = round(microtime(true)) . '_original_' . $filename ;

   // Location
   $location = '../uploads/'.$newfilename;

   // file extension
   $file_extension = pathinfo($location, PATHINFO_EXTENSION);
   $file_extension = strtolower($file_extension);

   // Valid extensions
   $valid_ext = array("apk","aab","ipa");

   $response = 0;
   $filenamenew = 0;
   if(in_array($file_extension,$valid_ext)){
      // Upload file
      if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
         $response = 1;
         $filenamenew = $filenamenew;
      }
   }

   echo $response;
   exit;
   echo "
$filenamenew
";
   exit;
}
?>

In this code it says in p tag is undefined


问:
BASH variables in xmlstarlet commands
I am trying to use BASH variables in the xmlstarlet commands as below

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

OLD_PASSWD='old_passwd'
echo "Enter the new app password:"
read NEW_PASSWD

find . -name "*.xml" -print0 | while read -d $'\0' file
do
    xmlstarlet ed --inplace --var old_passwd "'$OLD_PASSWD'" -u '//Call[Arg="jdbc/MySQL"]//Call[@name="addDataSourceProperty"][Arg="password"]/Arg[text()=$old_passwd]' -v $NEW_PASSWD $file
    #xmlstarlet ed --inplace -u '//Call[Arg="jdbc/MySQL"]//Set[@name="password"]' -v $NEW_PASSWD $file
done
</code>```

I am following examples here but it does not work. I get the error:

```<code>failed to load external entity "old_passwd"
</code>```

Title: BASH variables in xmlstarlet commands

Body:
I am trying to use BASH variables in the xmlstarlet commands as below

#!/bin/bash

OLD_PASSWD='old_passwd'
echo "Enter the new app password:"
read NEW_PASSWD

find . -name "*.xml" -print0 | while read -d $'\0' file
do
    xmlstarlet ed --inplace --var old_passwd "'$OLD_PASSWD'" -u '//Call[Arg="jdbc/MySQL"]//Call[@name="addDataSourceProperty"][Arg="password"]/Arg[text()=$old_passwd]' -v $NEW_PASSWD $file
    #xmlstarlet ed --inplace -u '//Call[Arg="jdbc/MySQL"]//Set[@name="password"]' -v $NEW_PASSWD $file
done

I am following examples here but it does not work. I get the error:

failed to load external entity "old_passwd"


问:
Unable to asynchronously make requests uing aiohttp and asyncio
I have written a script where draft orders are created in shopify and then used the id of the first request for the url of the second request which involves completing the order. Below is just a portion of the script that I wrote. However, there are delays that are happening when response is being fetched. And , because of this the draft order only sometimes get completed:

```<code> url=f"https://{shop_url}/admin/api/{api_version}/draft_orders.json"
    headers = {"X-Shopify-Access-Token": private_app_password}
    counter = count(start=1)

    for _ in range(number_of_orders):

        order = get_order(
            line_items_list, locale="en_US", country="United States"
        )
        response = requests.post(url, json=order, headers=headers)
        data = response.json()

        # complete order
        url2 = f"https://{shop_url}/admin/api/{api_version}/draft_orders/{data['draft_order']['id']}/complete.json"
        requests.put(url2,headers=headers)
</code>```

The problem seems to have to do with the delay that happens when the first response is fetched. Hence why I tried to wrap my API calls in asycn to fetch but the same thing is still occuring. The portion of the script is given below:

```<code>async def fetch(session, url,order,headers):
    async with session.post(url,headers=headers,json=order) as response:
        return await response.json()

async def get_draft_order(url,order,headers):
    async with aiohttp.ClientSession() as session:
        data = await fetch(session,url,order,headers)
        url2 = f"https://{shop_url}/admin/api/{api_version}/draft_orders/{data['draft_order']['id']}/complete.json"
        await session.put(url2,headers=headers,json=data)

def create_orders():

    # POST request
    url = f"https://{shop_url}/admin/api/{api_version}/draft_orders.json"
    headers = {"X-Shopify-Access-Token": private_app_password}
    counter = count(start=1)

    for _ in range(number_of_orders):

        order = get_order(
            line_items_list, locale="en_US", country="United States"
        )

        asyncio.run(get_draft_order(url,order,headers))
</code>```

Could someone help me understand what is wrong with the way I have implemented it. The second request depends on the id of the first request.

Body:
I have written a script where draft orders are created in shopify and then used the id of the first request for the url of the second request which involves completing the order. Below is just a portion of the script that I wrote. However, there are delays that are happening when response is being fetched. And , because of this the draft order only sometimes get completed:

 url=f"https://{shop_url}/admin/api/{api_version}/draft_orders.json"
    headers = {"X-Shopify-Access-Token": private_app_password}
    counter = count(start=1)

    for _ in range(number_of_orders):

        order = get_order(
            line_items_list, locale="en_US", country="United States"
        )
        response = requests.post(url, json=order, headers=headers)
        data = response.json()

        # complete order
        url2 = f"https://{shop_url}/admin/api/{api_version}/draft_orders/{data['draft_order']['id']}/complete.json"
        requests.put(url2,headers=headers)

The problem seems to have to do with the delay that happens when the first response is fetched. Hence why I tried to wrap my API calls in asycn to fetch but the same thing is still occuring. The portion of the script is given below:

async def fetch(session, url,order,headers):
    async with session.post(url,headers=headers,json=order) as response:
        return await response.json()

async def get_draft_order(url,order,headers):
    async with aiohttp.ClientSession() as session:
        data = await fetch(session,url,order,headers)
        url2 = f"https://{shop_url}/admin/api/{api_version}/draft_orders/{data['draft_order']['id']}/complete.json"
        await session.put(url2,headers=headers,json=data)

def create_orders():

    # POST request
    url = f"https://{shop_url}/admin/api/{api_version}/draft_orders.json"
    headers = {"X-Shopify-Access-Token": private_app_password}
    counter = count(start=1)

    for _ in range(number_of_orders):

        order = get_order(
            line_items_list, locale="en_US", country="United States"
        )

        asyncio.run(get_draft_order(url,order,headers))

Could someone help me understand what is wrong with the way I have implemented it. The second request depends on the id of the first request.


问:
Telegraf Starlark - How to pass configuration file?
My telegraf receives messages from eventhub where the tag has "A". Now i want to transform from "A" to "B", "C", "D" using a loopup configuration file which i have. I see Processor.Enum can apply only update at a time also it doesn't take configuration file as parameters. How to Achive this?

Eg:

Input: test,"Name":"A3"
My Custom Config:
[{"Name":"A1", "City":"C1", "Branch":"B1"},{"Name":"A2", "City":"C2", "Branch":"B2"},{"Name":"A3", "City":"C3", "Branch":"B3"}]
Expected Output: test,"Name":"A3","City":"C3","Branch":"B3"


问:
Return the wrong response if type of is number in the graphql
I tried to run the basic query in the graphql. But the below query is always return the no data if the typeof id is number. incase typeof id is string it returns the correct respone.

```<code>{
  movie(id: 1) {
    id
    name
  }
}
</code>```

respone

```<code>{
  "data": {
    "movie": null
  }
}
</code>```

attached my code below

```<code>const graphql = require("graphql");
    const _ = require("lodash");
    const {
      GraphQLObjectType,
      GraphQLString,
      GraphQLSchema,
      GraphQLID,
      GraphQLInt,
      GraphQLList,
    } = graphql;

    const movies = [
      { name: "book1", genre: "Thriller", id: 1, directorId: 1 },
      { name: "book2", genre: "Horror", id: 2, directorId: 1 },
      { name: "book3", genre: "Historical", id: 3, directorId: 2 },
      { name: "book4", genre: "Thriller", id: 4, directorId: 1 },
      { name: "book5", genre: "Science Fiction", id: 5, directorId: 2 },
      { name: "book6", genre: "Horror", id: 6, directorId: 3 },
      { name: "book7", genre: "Romance", id: 7, directorId: 1 },
    ];

    const directors = [
      { name: "directors1", age: "26", id: 1 },
      { name: "directors2", age: "36", id: 2 },
      { name: "directors3", age: "46", id: 3 },
    ];

    const MovieType = new GraphQLObjectType({
      name: "Movie",
      fields: () => ({
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        genre: { type: GraphQLString },
        director: {
          type: DirectorType,
          resolve: (parent, args) => {
            return _.find(directors, { id: parent.directorId });
          },
        },
      }),
    });

    const DirectorType = new GraphQLObjectType({
      name: "Director",
      fields: () => ({
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        age: { type: GraphQLInt },
        movies: {
            type: MovieType,
            resolve: (parent, args) => {
              return _.find(movies, { directorId: parent.id });
            },
          },
      }),
    });

    const RootQuery = new GraphQLObjectType({
      name: "RootQueryType",
      fields: {
        movie: {
          type: MovieType,
          args: { id: { type: GraphQLID } },
          resolve(parent, args) {
            console.log(args)
            return _.find(movies, { id: args.id });
          },
        },
        director: {
            type: DirectorType,
            args: {id: {type: GraphQLID}},
            resolve(parent, args) {
                return _.find(directors, {id: args.id})
            }
        },
        movies: {
          type: new GraphQLList(MovieType),
          resolve() {
            return movies;
          },
        },
        directors: {
          type: new GraphQLList(DirectorType),
          resolve() {
            return directors;
          },
        },
      },
    });

    module.exports = new GraphQLSchema({
      query: RootQuery,
    });
</code>```

not sure what I have missed.

Body:
I tried to run the basic query in the graphql. But the below query is always return the no data if the typeof id is number. incase typeof id is string it returns the correct respone.

{
  movie(id: 1) {
    id
    name
  }
}

respone

{
  "data": {
    "movie": null
  }
}

attached my code below

const graphql = require("graphql");
    const _ = require("lodash");
    const {
      GraphQLObjectType,
      GraphQLString,
      GraphQLSchema,
      GraphQLID,
      GraphQLInt,
      GraphQLList,
    } = graphql;

    const movies = [
      { name: "book1", genre: "Thriller", id: 1, directorId: 1 },
      { name: "book2", genre: "Horror", id: 2, directorId: 1 },
      { name: "book3", genre: "Historical", id: 3, directorId: 2 },
      { name: "book4", genre: "Thriller", id: 4, directorId: 1 },
      { name: "book5", genre: "Science Fiction", id: 5, directorId: 2 },
      { name: "book6", genre: "Horror", id: 6, directorId: 3 },
      { name: "book7", genre: "Romance", id: 7, directorId: 1 },
    ];

    const directors = [
      { name: "directors1", age: "26", id: 1 },
      { name: "directors2", age: "36", id: 2 },
      { name: "directors3", age: "46", id: 3 },
    ];

    const MovieType = new GraphQLObjectType({
      name: "Movie",
      fields: () => ({
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        genre: { type: GraphQLString },
        director: {
          type: DirectorType,
          resolve: (parent, args) => {
            return _.find(directors, { id: parent.directorId });
          },
        },
      }),
    });

    const DirectorType = new GraphQLObjectType({
      name: "Director",
      fields: () => ({
        id: { type: GraphQLID },
        name: { type: GraphQLString },
        age: { type: GraphQLInt },
        movies: {
            type: MovieType,
            resolve: (parent, args) => {
              return _.find(movies, { directorId: parent.id });
            },
          },
      }),
    });

    const RootQuery = new GraphQLObjectType({
      name: "RootQueryType",
      fields: {
        movie: {
          type: MovieType,
          args: { id: { type: GraphQLID } },
          resolve(parent, args) {
            console.log(args)
            return _.find(movies, { id: args.id });
          },
        },
        director: {
            type: DirectorType,
            args: {id: {type: GraphQLID}},
            resolve(parent, args) {
                return _.find(directors, {id: args.id})
            }
        },
        movies: {
          type: new GraphQLList(MovieType),
          resolve() {
            return movies;
          },
        },
        directors: {
          type: new GraphQLList(DirectorType),
          resolve() {
            return directors;
          },
        },
      },
    });

    module.exports = new GraphQLSchema({
      query: RootQuery,
    });

not sure what I have missed.


问:
Webpack dev server Failed to load resource
The problem is that I get this very error Failed to load resource: the server responded with a status of 404 (Not Found) when I use webpack-dev-server.
But if I just build the project then I can run my index.html and get the expected result.
My project structure is:

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./src/css/style.css">
</head>
<body>
    <div class="container">
        <button id="displayNumber">Show/Change Number</button>

        <span id="number">15</span>
    </div>

    <script src="./dist/bundle.js"></script>
</body>
</html>
</code>```

And here're webpack config file

webpack.config.js

```<code>var path = require('path');

module.exports = {
    mode: 'development',
    entry: path.resolve(__dirname,'src/js/script.js'),
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
        publicPath: 'dist'
    },
    devServer: {
        static: {
            directory: path.resolve(__dirname,'dist'),
            publicPath: '/dist/',
        },
        open: true,
        hot: true,
    }
}
</code>```

So when I run webpack-dev-server --open --config webpack.dev.js CLI command then I get the error.
And when I run webpack --config webpack.prod.js and then open index.html everything works just fine.
My question is why does webpack-dev-server behaves that oddly? What am I missing?

Body:
The problem is that I get this very error Failed to load resource: the server responded with a status of 404 (Not Found) when I use webpack-dev-server.
But if I just build the project then I can run my index.html and get the expected result.
My project structure is:

index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./src/css/style.css">

        <button id="displayNumber">Show/Change Number</button>

        15

And here're webpack config file

webpack.config.js

var path = require('path');

module.exports = {
    mode: 'development',
    entry: path.resolve(__dirname,'src/js/script.js'),
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
        publicPath: 'dist'
    },
    devServer: {
        static: {
            directory: path.resolve(__dirname,'dist'),
            publicPath: '/dist/',
        },
        open: true,
        hot: true,
    }
}

So when I run webpack-dev-server --open --config webpack.dev.js CLI command then I get the error.
And when I run webpack --config webpack.prod.js and then open index.html everything works just fine.
My question is why does webpack-dev-server behaves that oddly? What am I missing?


问:
How to extract specific table from word or PDF using python
I am working on a project where I have about a thousand word files or PDFs. In these documents there's a specific table I want to extract. In the heading or the text of the document I should have the word results and I want to extract the table after that. I looked at libraries both for PDFs and docx but I failed to figure out a way to first read the word then extract the table. I already found a library called camelot for PDFs that extract tables but it extracts all of them. Is there a way I can only extract my choosen table as there is no way for me to distinguish my choosen table if I extract all tables. Anyone can help me with finding an appropriate library/s or method to only read the one table.</p>


问:
How to load and set an images inside table dynamically to Stimulsoft web report?
I have a problem, In my case, I have a table in the database name attachment content( FileURL, FileName) this table has a relationship with operation table one to many one row in operation has multi images in attach table, I want to create a table inside report to fetch all images for specific operation from table attach and divide table to 3 columns and X rows. I'm using Stimulsoft web report with ASP.NET Core, attached is an image to explain

sample


问:
How can we apply Filters in particular Coordinates or area with CameraX + Media-pipe Android AAR
I’m trying to create a iris filter app. I created aar from the help of thier docs and i can able to get the coordinates of iris

I’m using CameraX + Mediapipe AAR file.

How or what are the possibilities to show some color filters on only the iris part (typically adding filter in that coordinates)


问:
Trouble downloading GHCup on Windows
I am trying to download Haskell using GHCup on a Windows 10 laptop. I copy and pasted this command in a Windows PowerShell window:

```<code>Set-ExecutionPolicy Bypass -Scope Process -Force;[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; try { Invoke-Command -ScriptBlock ([ScriptBlock]::Create((Invoke-WebRequest https://www.haskell.org/ghcup/sh/bootstrap-haskell.ps1 -UseBasicParsing))) -ArgumentList $true } catch { Write-Error $_ }
</code>```

I am receiving this error message when installing GHCup:

curl: (35) schannel: next InitializeSecurityContext failed: Unknown error (0x80092012) - The revocation function was unable to check revocation for the certificate.
```

I have used google to search for this error message but had no luck finding any info to troubleshoot the Haskell stack installation.

I put the command script in the powershell with only my C:\>

Title: Trouble downloading GHCup on Windows

Body:
I am trying to download Haskell using GHCup on a Windows 10 laptop. I copy and pasted this command in a Windows PowerShell window:

Set-ExecutionPolicy Bypass -Scope Process -Force;[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; try { Invoke-Command -ScriptBlock ([ScriptBlock]::Create((Invoke-WebRequest https://www.haskell.org/ghcup/sh/bootstrap-haskell.ps1 -UseBasicParsing))) -ArgumentList $true } catch { Write-Error $_ }

I am receiving this error message when installing GHCup:

curl: (35) schannel: next InitializeSecurityContext failed: Unknown error (0x80092012) - The revocation function was unable to check revocation for the certificate.

I have used google to search for this error message but had no luck finding any info to troubleshoot the Haskell stack installation.

I put the command script in the powershell with only my C:\>


问:
Why is my image not loading using the Suspense tag
This is my App.js,

```<code>import React, { Suspense } from 'react';
import './App.css';
import SyncLoader  from "react-spinners/SyncLoader";
const Newhome  = React.lazy(() => import('./COMPONENTS/Newhome'));
function App() {
  return (
    <div>
      <Suspense className='App' fallback={
        <div className='align'>
          <SyncLoader  size={'20px'} color='#FF5757' className='loader App'/>
        </div>
      }>
        <Newhome />
      </Suspense>
    </div>
  );
}
export default App;
</code>```

The problem with this is the image is taking some more time after the loader disappears, I also tried to reduce the image size.

But nothing is happening, can anyone suggest to me what should I change in this code?

The image is in the Newhome.jsx which is imported at the top.

Body:
This is my App.js,

import React, { Suspense } from 'react';
import './App.css';
import SyncLoader  from "react-spinners/SyncLoader";
const Newhome  = React.lazy(() => import('./COMPONENTS/Newhome'));
function App() {
  return (

      <Suspense className='App' fallback={

          <SyncLoader  size={'20px'} color='#FF5757' className='loader App'/>

      }>
        <Newhome />
      </Suspense>

  );
}
export default App;

The problem with this is the image is taking some more time after the loader disappears, I also tried to reduce the image size.

But nothing is happening, can anyone suggest to me what should I change in this code?

The image is in the Newhome.jsx which is imported at the top.


问:
How to hide extent report logo for the extent report version 7
This is the Extent report

Have used the below code in extent-config.xml to hide logo. But, its not working for extent report version 7.

```<code>`<scripts>
        <![CDATA[
        $(document).ready(function() {
        $(".logo-content").hide();
                });
        ]]>
    </scripts>`
</code>```


问:
api for java or dart to get mikrotik command line output?
I can connect to the router with java via  jsch library and I can't get some Mikrotik command line (tool torch ether1 src-address=0.0.0.0/0 , /interface monitor-traffic ether1 ) output</p>
```<code>public static void listFolderStructure(String username, String password,
  String host, int port, String command) throws Exception {

    Session session = null;
    ChannelExec channel = null;

    try {
        session = new JSch().getSession(username, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();

        channel = (ChannelExec) session.openChannel("exec");
        channel.setCommand(command);
        ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
        channel.setOutputStream(responseStream);
        channel.connect();

        while (channel.isConnected()) {
            Thread.sleep(100);
        }

        String responseString = new String(responseStream.toByteArray());
        System.out.println(responseString);
    } finally {
        if (session != null) {
            session.disconnect();
        }
        if (channel != null) {
            channel.disconnect();
        }
    }
}
</code>```

Body:
I can connect to the router with java via  jsch library and I can't get some Mikrotik command line (tool torch ether1 src-address=0.0.0.0/0 , /interface monitor-traffic ether1 ) output

public static void listFolderStructure(String username, String password,
  String host, int port, String command) throws Exception {

    Session session = null;
    ChannelExec channel = null;

    try {
        session = new JSch().getSession(username, host, port);
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();

        channel = (ChannelExec) session.openChannel("exec");
        channel.setCommand(command);
        ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
        channel.setOutputStream(responseStream);
        channel.connect();

        while (channel.isConnected()) {
            Thread.sleep(100);
        }

        String responseString = new String(responseStream.toByteArray());
        System.out.println(responseString);
    } finally {
        if (session != null) {
            session.disconnect();
        }
        if (channel != null) {
            channel.disconnect();
        }
    }
}


问:
How to use the 'reset picture & size' button in a Macro in Word?
I'm dealing with many documents created by formal Word.

There are many equations converted into inline shapes with a fixed size.

I've found that using the 'reset picture & size' button can recover them to normal.

the 'reset picture & size' button

But because of the inline shapes property, I can't select all of them at the same time and use the button. So I want to use a Macro to do it.

I've known there is a reset method defined -- InlineShape.Reset method (Word).

https://learn.microsoft.com/en-us/office/vba/api/word.inlineshape.reset

But it only presents the 'reset picture' button, so how can I achieve the latter 'reset size'?

I've found the property scale for InlineShape Objects too.

https://learn.microsoft.com/en-us/office/vba/api/word.inlineshape.scaleheight

https://learn.microsoft.com/en-us/office/vba/api/word.inlineshape.scalewidth

But changing them to 100 is useless.

the following is my Macro Code.

```<code>Sub reset_all_picture_size()
Dim n
    For n = 1 To ActiveDocument.InlineShapes.Count
        ActiveDocument.InlineShapes(n).reset
        With ActiveDocument.InlineShapes(n)
             .ScaleHeight = 100
             .ScaleWidth = 100
        End With
    Next n
End Sub
</code>```

I'm a student from China so may cause some Chinese English, plz excuse me.

Body:
I'm dealing with many documents created by formal Word.

There are many equations converted into inline shapes with a fixed size.

I've found that using the 'reset picture & size' button can recover them to normal.

the 'reset picture & size' button

But because of the inline shapes property, I can't select all of them at the same time and use the button. So I want to use a Macro to do it.

I've known there is a reset method defined -- InlineShape.Reset method (Word).

https://learn.microsoft.com/en-us/office/vba/api/word.inlineshape.reset

But it only presents the 'reset picture' button, so how can I achieve the latter 'reset size'?

I've found the property scale for InlineShape Objects too.

https://learn.microsoft.com/en-us/office/vba/api/word.inlineshape.scaleheight

https://learn.microsoft.com/en-us/office/vba/api/word.inlineshape.scalewidth

But changing them to 100 is useless.

the following is my Macro Code.

Sub reset_all_picture_size()
Dim n
    For n = 1 To ActiveDocument.InlineShapes.Count
        ActiveDocument.InlineShapes(n).reset
        With ActiveDocument.InlineShapes(n)
             .ScaleHeight = 100
             .ScaleWidth = 100
        End With
    Next n
End Sub

I'm a student from China so may cause some Chinese English, plz excuse me.


问:
org.xml.sax.SAXParseException error while integrating XML for generating PDF
While Running the following code in order to read an XML file and generating a corresponding PDF. I am facing the errors mentioned below the code.

```<code>
package com.test.pdf;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

import java.util.List;

import org.apache.log4j.Logger;

import com.google.zxing.WriterException;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfDocument;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import com.itextpdf.xmp.impl.Base64;
//import com.itextpdf.text.pdf.codec.Base64;

import org.apache.log4j.Logger;

public class PDFGenerator {

    final static Logger logger = Logger.getLogger(PDFGenerator.class);
    private static final String TITLE = "TestReport";
    public static final String PDF_EXTENSION = ".pdf";
    public static  String arg1 = "";
    public static  String arg2 = "";
    public static  String arg3 = "";

    public static String createPDFBase64(String arg1 , String arg2 , String arg3)  throws IOException, URISyntaxException, com.lowagie.text.DocumentException, WriterException {

        byte[] encoded = null;
        String out= null;
        Document document = new Document();

        try {

            //arg1 = args[0];
            //Document is not auto-closable hence need to close it separately
            document = new Document(PageSize.LETTER);
            System.out.println("Here i amn777");

            File temp = File.createTempFile(TITLE ,PDF_EXTENSION);
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(
                    temp)); // new File

            HeaderFooter event = new HeaderFooter(arg2);

            event.setHeader("Test Report");

            writer.setPageEvent(event);

            document.open();
            PDFCreator pdfCreator = new PDFCreator();
            pdfCreator.addMetaData(document,  arg1 , arg2 );

            pdfCreator.addTitlePage(document, arg2 );

            //PDFCreator.addContent(document, dataObjList);
            //String base64String = Base64.encodeFromFile("C:\\Users\\2000554\\Downloads\\HTMLToPDF\\TestReport.pdf");
            //System.out.println("===============>>>" + base64String);
            document.close();

            byte[] inFileBytes = Files.readAllBytes(temp.toPath());
            //PdfReader pReader = new PdfReader(inFileBytes);
            //System.out.println("pReader.getFileLength()===============>>>" + pReader.getFileLength());
            //System.out.println("pReader.getFileLength()===============>>>" + PdfTextExtractor.getTextFromPage(pReader, 1));
            out = new String(Base64.encode(inFileBytes), "UTF-8");
            System.out.println("Clear cache..");
            pdfCreator.xmlData.clear();
            pdfCreator.dataObjMRCList.clear();
            pdfCreator.dataObjNRCList.clear();
            pdfCreator.dataObjVASList.clear();
            pdfCreator.dataObjDEVList.clear();
            pdfCreator.stcPhoneNumDispList.clear();
            pdfCreator.stcSvcMap.clear();
            pdfCreator.stcSvcBandWthMap.clear();
            pdfCreator.invoiceTaxDvcMap.clear();
            //byte[] decoded = java.util.Base64.getDecoder().decode(out.getBytes());
            /* byte[] decoded = Base64.decode(out.getBytes());
             FileOutputStream fos = new FileOutputStream("C:\\Users\\2000554\\Downloads\\HTMLToPDF\\TestBaseReport.pdf");
            fos.write(decoded);
            fos.flush();
            fos.close();*/

        }catch ( FileNotFoundException e) {
           System.out.println("FileNotFoundException occurs.." + e.getMessage());
            e.printStackTrace();
        }catch (DocumentException  e) {
           System.out.println("DocumentException occurs.." + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("Exception occurs.." + e.getMessage());
            e.printStackTrace();
            return null;
        }
        finally{
            if(null != document){
               // document.close();
            }
        }
        return out;
    }

    public static void main(String args[]) {

        try {
            if(args != null && args.length>1) {
                FileReader fReader = new FileReader(new File("C:\\Users\\2004807\\Downloads\\XML\\Amendment.xml"));
                BufferedReader bdr = new BufferedReader(fReader);
                String line = null;
                String xmlString = "";
                while ((line=bdr.readLine())!=null){
                    xmlString += line;
                }
                createPDFBase64(xmlString,args[1],args[2]);
            }else {
                createPDFBase64("","","");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (com.lowagie.text.DocumentException e) {
            e.printStackTrace();
        } catch (WriterException e) {
            e.printStackTrace();
        }

    }

}
</code>```

I rechecked the path and the XML format since the error mentioned is due to wrong formatting of XML in some cases. I still am getting the following error.

```<code>Here i amn777
1getting resourcesfile:/C:/Users/2004807/Desktop/B2B%20Java/HtmlToPdf/target/classes/new.PNG
Inside getXMLData
XML==>
[Fatal Error] :1:1: Premature end of file.
Error is :org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.
xmlData size is :0
</code>```

Body:
While Running the following code in order to read an XML file and generating a corresponding PDF. I am facing the errors mentioned below the code.

package com.test.pdf;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

import java.util.List;

import org.apache.log4j.Logger;

import com.google.zxing.WriterException;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfDocument;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import com.itextpdf.xmp.impl.Base64;
//import com.itextpdf.text.pdf.codec.Base64;

import org.apache.log4j.Logger;

public class PDFGenerator {

    final static Logger logger = Logger.getLogger(PDFGenerator.class);
    private static final String TITLE = "TestReport";
    public static final String PDF_EXTENSION = ".pdf";
    public static  String arg1 = "";
    public static  String arg2 = "";
    public static  String arg3 = "";

    public static String createPDFBase64(String arg1 , String arg2 , String arg3)  throws IOException, URISyntaxException, com.lowagie.text.DocumentException, WriterException {

        byte[] encoded = null;
        String out= null;
        Document document = new Document();

        try {

            //arg1 = args[0];
            //Document is not auto-closable hence need to close it separately
            document = new Document(PageSize.LETTER);
            System.out.println("Here i amn777");

            File temp = File.createTempFile(TITLE ,PDF_EXTENSION);
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(
                    temp)); // new File

            HeaderFooter event = new HeaderFooter(arg2);

            event.setHeader("Test Report");

            writer.setPageEvent(event);

            document.open();
            PDFCreator pdfCreator = new PDFCreator();
            pdfCreator.addMetaData(document,  arg1 , arg2 );

            pdfCreator.addTitlePage(document, arg2 );

            //PDFCreator.addContent(document, dataObjList);
            //String base64String = Base64.encodeFromFile("C:\\Users\\2000554\\Downloads\\HTMLToPDF\\TestReport.pdf");
            //System.out.println("===============>>>" + base64String);
            document.close();

            byte[] inFileBytes = Files.readAllBytes(temp.toPath());
            //PdfReader pReader = new PdfReader(inFileBytes);
            //System.out.println("pReader.getFileLength()===============>>>" + pReader.getFileLength());
            //System.out.println("pReader.getFileLength()===============>>>" + PdfTextExtractor.getTextFromPage(pReader, 1));
            out = new String(Base64.encode(inFileBytes), "UTF-8");
            System.out.println("Clear cache..");
            pdfCreator.xmlData.clear();
            pdfCreator.dataObjMRCList.clear();
            pdfCreator.dataObjNRCList.clear();
            pdfCreator.dataObjVASList.clear();
            pdfCreator.dataObjDEVList.clear();
            pdfCreator.stcPhoneNumDispList.clear();
            pdfCreator.stcSvcMap.clear();
            pdfCreator.stcSvcBandWthMap.clear();
            pdfCreator.invoiceTaxDvcMap.clear();
            //byte[] decoded = java.util.Base64.getDecoder().decode(out.getBytes());
            /* byte[] decoded = Base64.decode(out.getBytes());
             FileOutputStream fos = new FileOutputStream("C:\\Users\\2000554\\Downloads\\HTMLToPDF\\TestBaseReport.pdf");
            fos.write(decoded);
            fos.flush();
            fos.close();*/

        }catch ( FileNotFoundException e) {
           System.out.println("FileNotFoundException occurs.." + e.getMessage());
            e.printStackTrace();
        }catch (DocumentException  e) {
           System.out.println("DocumentException occurs.." + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.out.println("Exception occurs.." + e.getMessage());
            e.printStackTrace();
            return null;
        }
        finally{
            if(null != document){
               // document.close();
            }
        }
        return out;
    }

    public static void main(String args[]) {

        try {
            if(args != null && args.length>1) {
                FileReader fReader = new FileReader(new File("C:\\Users\\2004807\\Downloads\\XML\\Amendment.xml"));
                BufferedReader bdr = new BufferedReader(fReader);
                String line = null;
                String xmlString = "";
                while ((line=bdr.readLine())!=null){
                    xmlString += line;
                }
                createPDFBase64(xmlString,args[1],args[2]);
            }else {
                createPDFBase64("","","");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (com.lowagie.text.DocumentException e) {
            e.printStackTrace();
        } catch (WriterException e) {
            e.printStackTrace();
        }

    }

}

I rechecked the path and the XML format since the error mentioned is due to wrong formatting of XML in some cases. I still am getting the following error.

Here i amn777
1getting resourcesfile:/C:/Users/2004807/Desktop/B2B%20Java/HtmlToPdf/target/classes/new.PNG
Inside getXMLData
XML==>
[Fatal Error] :1:1: Premature end of file.
Error is :org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.
xmlData size is :0