问:
How to Change Viewer Model Dynamically
I have a react project and am trying to use the Autodesk Forge viewer.  I have it sort of working but am getting a lot of errors and weird behavior that I don't understand.  I'm pretty new to both Forge viewer and React so I'm sure I'm missing something simple but I don't know what it is.

The general idea of this page is that the user gets a list of locations from the DB (outside Forge) that they can click on.  If they click on one to select it the system checks if there is a dwg file associated with it.  If not it displays a generic div that says there is no file associated but if so it displays the dwg in the forge viewer.  So the viewer itself is sometimes hidden but should always be there but will need to change the file that it's displaying sometimes.

Right now I have it so that when I click the first one it comes up and displays it correctly.  However, when I click another and then back to the first one it blanks out and gives me an error in the console.  Here is my forge component:

```<code>import React, { useEffect, useRef } from "react";
import styled from "styled-components";
import { BorderedZoneOuter } from "./Generic/CommonStyledComponents";
import { ForgeBackgroundService } from "../services/ForgeBackgroundService";
import { valueIsNullOrUndefined } from "../Utility";

const viewerLibraryURL =
  "https://developer.api.autodesk.com/modelderivative/v2/viewers/viewer3D.min.js?v=v7.*";
const viewerStylesheetURL =
  "https://developer.api.autodesk.com/modelderivative/v2/viewers/style.min.css?v=v7.*";

let viewerLibraryLoaded = false;
let viewerStyleLoaded = false;
let viewerLoading = false;

const ForgeContainer = styled(BorderedZoneOuter)`
  position: relative;
  flex: 1;
`;

const _backgroundService = new ForgeBackgroundService();
let viewer: Autodesk.Viewing.GuiViewer3D | undefined;

const ForgeViewer = (props: {
  urn: string;
  viewerReady?: (viewer: Autodesk.Viewing.GuiViewer3D) => void;
}) => {
  const container: any = useRef();

  useEffect(() => {
    const handleStyleLoad = () => {
      console.log("style loaded");
      viewerStyleLoaded = true;
      viewerLibraryLoaded && loadViewer();
    };

    const handleScriptLoad = () => {
      console.log("script loaded");
      viewerLibraryLoaded = true;
      viewerStyleLoaded && loadViewer();
    };

    const loadViewer = () => {
      console.log("loading viewer");
      if (!viewerLoading) {
        viewerLoading = true;
        Autodesk.Viewing.Initializer(
          {
            env: "AutodeskProduction2",
            api: "streamingV2",
            getAccessToken: (onTokenReady) => {
              if (onTokenReady) {
                _backgroundService.GetToken().then((t) => {
                  if (valueIsNullOrUndefined(t)) {
                    return;
                  }
                  onTokenReady(t!.token, t!.expiresIn);
                });
              }
            },
          },
          () => {
            viewer = new Autodesk.Viewing.GuiViewer3D(container.current);
            viewer.start();
            loadModel(props.urn);
            viewerLoading = false;
          }
        );
      }
    };

    const loadStyleSheet = (href: string) => {
      const styles = document.createElement("link");
      styles.rel = "stylesheet";
      styles.type = "text/css";
      styles.href = href;
      styles.onload = handleStyleLoad;
      document.getElementsByTagName("head")[0].appendChild(styles);
    };

    const loadViewerScript = (href: string) => {
      const script = document.createElement("script");
      script.src = href;
      script.async = true;
      script.onload = handleScriptLoad;
      document.getElementsByTagName("head")[0].appendChild(script);
    };

    function loadModel(urn: string): void {
      console.log(urn);
      console.log(viewer);
      Autodesk.Viewing.Document.load(
        urn,
        (doc) => {
          console.log(doc);
          const defaultModel = doc.getRoot().getDefaultGeometry();
          console.log(defaultModel);
          viewer?.loadDocumentNode(doc, defaultModel)
            .then((m: Autodesk.Viewing.Model) => {
              console.log(m);
              if (props.viewerReady) {
                props.viewerReady(viewer!);
              }
            });
        },
        () => {
          console.error("failed to load document");
        }
      );
    }

    if (!valueIsNullOrUndefined(viewer)) {
      console.log("have viewer, loading model");
      loadModel(props.urn);
    } else {
      console.log("no viewer, loading scripts");
      loadStyleSheet(viewerStylesheetURL);
      loadViewerScript(viewerLibraryURL);
    }

    return () => {
      viewer?.finish();
    };
  }, [props]);

  return <ForgeContainer ref={container} />;
};

export default ForgeViewer;
</code>```

In the parent component that uses the viewer, here is the relevant portion of the tsx:

```<code>  <MainCanvas>
    <PageTitle>Create Spaces</PageTitle>
    <button onClick={select}>select</button>
    {valueIsNullOrUndefined(state.selectedFloor) && (
      <NoBackgroundZone>
        <div>You have not selected a floor</div>
        <div>
          Please select a floor to view the background and create spaces
        </div>
      </NoBackgroundZone>
    )}

    {!valueIsNullOrUndefined(state.selectedFloor) &&
      valueIsNullOrUndefined(state.backgroundUrn) && (
        <NoBackgroundZone>
          <div>There is no background added for this floor</div>
          <LinkButton>Add a background</LinkButton>
        </NoBackgroundZone>
      )}

    {!valueIsNullOrUndefined(state.selectedFloor) &&
      !valueIsNullOrUndefined(state.backgroundUrn) && (
        <ForgeViewer urn={state.backgroundUrn!} viewerReady={viewerReady} />
      )}
  </MainCanvas>
</code>```

The error I get is:

```<code>Uncaught TypeError: Cannot read properties of null (reading 'hasModels') Viewer3D.js:1799
  at C.he.loadDocumentNode (Viewer3D.js:1799:53)
  at ForgeViewer.tsx:98:1
  ...
</code>```

The line number that it's referring to in the error is the one that starts with viewer?.loadDocumnentNode(...  If it's using the conditional access how can it be null and still throwing the error?  I also have logged all three variables on that line (doc, defaultModel, and viewer) right before that call and they never show up as null...

Can anyone tell me what I'm doing wrong here?  I've looked at a lot of different samples but all of them seem to deal with just getting something displayed and I can't find anything about changing the display.

答:
Ok so after doing a lot more logging and investigating I think I have this solved with a few changes described below for anyone that finds themselves in the same situation I was.

First, it turns out the issue was mostly centered around the viewer being 'finished' in the destructor function of useEffect here:

```<code>return () => {
  viewer?.finish();
};
</code>```

After this happens the viewer in effect is dead, but I didn't set my value to undefined so the next time it found the viewer as non-null and tried to use it but it had already been finished.  First simple change:

```<code>return () => {
  viewer?.finish();
  viewer = undefined;
};
</code>```

This makes sure that the viewer is recreated if it's been finished.

Secondly was actually in my consumer that is using this module. The props for this component has a viewer ready callback that tells the consuming module when the viewer is ready for use.  My calling component then does other things with the viewer (finds layers and blocks, etc.).  However, I was storing this in a standard variable:

```<code>const SpaceCreator = () => {
  let viewer: Autodesk.Viewing.GuiViewer3D | undefined;

  ...

  function viewerReady(v: Autodesk.Viewing.GuiViewer3D): void {
    viewer = v;
  }

  ...
}
</code>```

Instead I needed to make this part of the state and use the reducer to set the current viewer like so:

```<code>const SpaceCreator = () => {
  const [state, dispatch] = useReducer(reducer, new SpaceCreatorState());

  ...

  function viewerReady(v: Autodesk.Viewing.GuiViewer3D): void {
    dispatch({ type: SpaceCreatorActions.viewer, payload: v });
  }

  ...
}
</code>```

This was almost it, except that it kept reloading on me constantly.  I updated the dependencies in the useEffect to be only props.urn so that it would only re-run when the urn changed. This stopped the constant reloading, but React (linting anyway) complained about the dependency array not including the viewerReady event since it was used in the useEffect method.  After some more research, basically the viewerReady event was being redone on every render causing the value to change which is causing the constant re-renders.  Instead I needed to use useCallback to create the method which makes it not change unless one of it's dependencies changes (and since I have no dependencies it just creates on the first render).  Here is the final method:

```<code>const viewerReady = useCallback((v: Autodesk.Viewing.GuiViewer3D) => {
    dispatch({ type: SpaceCreatorActions.viewer, payload: v });
  }, []);
</code>```

After all of this it seems to be stable, working correctly, and React is happy.  Hope this helps someone else having this issue.

Title: How to Change Viewer Model Dynamically

Body:
I have a react project and am trying to use the Autodesk Forge viewer.  I have it sort of working but am getting a lot of errors and weird behavior that I don't understand.  I'm pretty new to both Forge viewer and React so I'm sure I'm missing something simple but I don't know what it is.

The general idea of this page is that the user gets a list of locations from the DB (outside Forge) that they can click on.  If they click on one to select it the system checks if there is a dwg file associated with it.  If not it displays a generic div that says there is no file associated but if so it displays the dwg in the forge viewer.  So the viewer itself is sometimes hidden but should always be there but will need to change the file that it's displaying sometimes.

Right now I have it so that when I click the first one it comes up and displays it correctly.  However, when I click another and then back to the first one it blanks out and gives me an error in the console.  Here is my forge component:

import React, { useEffect, useRef } from "react";
import styled from "styled-components";
import { BorderedZoneOuter } from "./Generic/CommonStyledComponents";
import { ForgeBackgroundService } from "../services/ForgeBackgroundService";
import { valueIsNullOrUndefined } from "../Utility";

const viewerLibraryURL =
  "https://developer.api.autodesk.com/modelderivative/v2/viewers/viewer3D.min.js?v=v7.*";
const viewerStylesheetURL =
  "https://developer.api.autodesk.com/modelderivative/v2/viewers/style.min.css?v=v7.*";

let viewerLibraryLoaded = false;
let viewerStyleLoaded = false;
let viewerLoading = false;

const ForgeContainer = styled(BorderedZoneOuter)`
  position: relative;
  flex: 1;
`;

const _backgroundService = new ForgeBackgroundService();
let viewer: Autodesk.Viewing.GuiViewer3D | undefined;

const ForgeViewer = (props: {
  urn: string;
  viewerReady?: (viewer: Autodesk.Viewing.GuiViewer3D) => void;
}) => {
  const container: any = useRef();

  useEffect(() => {
    const handleStyleLoad = () => {
      console.log("style loaded");
      viewerStyleLoaded = true;
      viewerLibraryLoaded && loadViewer();
    };

    const handleScriptLoad = () => {
      console.log("script loaded");
      viewerLibraryLoaded = true;
      viewerStyleLoaded && loadViewer();
    };

    const loadViewer = () => {
      console.log("loading viewer");
      if (!viewerLoading) {
        viewerLoading = true;
        Autodesk.Viewing.Initializer(
          {
            env: "AutodeskProduction2",
            api: "streamingV2",
            getAccessToken: (onTokenReady) => {
              if (onTokenReady) {
                _backgroundService.GetToken().then((t) => {
                  if (valueIsNullOrUndefined(t)) {
                    return;
                  }
                  onTokenReady(t!.token, t!.expiresIn);
                });
              }
            },
          },
          () => {
            viewer = new Autodesk.Viewing.GuiViewer3D(container.current);
            viewer.start();
            loadModel(props.urn);
            viewerLoading = false;
          }
        );
      }
    };

    const loadStyleSheet = (href: string) => {
      const styles = document.createElement("link");
      styles.rel = "stylesheet";
      styles.type = "text/css";
      styles.href = href;
      styles.onload = handleStyleLoad;
      document.getElementsByTagName("head")[0].appendChild(styles);
    };

    const loadViewerScript = (href: string) => {
      const script = document.createElement("script");
      script.src = href;
      script.async = true;
      script.onload = handleScriptLoad;
      document.getElementsByTagName("head")[0].appendChild(script);
    };

    function loadModel(urn: string): void {
      console.log(urn);
      console.log(viewer);
      Autodesk.Viewing.Document.load(
        urn,
        (doc) => {
          console.log(doc);
          const defaultModel = doc.getRoot().getDefaultGeometry();
          console.log(defaultModel);
          viewer?.loadDocumentNode(doc, defaultModel)
            .then((m: Autodesk.Viewing.Model) => {
              console.log(m);
              if (props.viewerReady) {
                props.viewerReady(viewer!);
              }
            });
        },
        () => {
          console.error("failed to load document");
        }
      );
    }

    if (!valueIsNullOrUndefined(viewer)) {
      console.log("have viewer, loading model");
      loadModel(props.urn);
    } else {
      console.log("no viewer, loading scripts");
      loadStyleSheet(viewerStylesheetURL);
      loadViewerScript(viewerLibraryURL);
    }

    return () => {
      viewer?.finish();
    };
  }, [props]);

  return <ForgeContainer ref={container} />;
};

export default ForgeViewer;

In the parent component that uses the viewer, here is the relevant portion of the tsx:

  <MainCanvas>
    <PageTitle>Create Spaces</PageTitle>
    <button onClick={select}>select</button>
    {valueIsNullOrUndefined(state.selectedFloor) && (
      <NoBackgroundZone>

You have not selected a floor

          Please select a floor to view the background and create spaces

      </NoBackgroundZone>
    )}

    {!valueIsNullOrUndefined(state.selectedFloor) &&
      valueIsNullOrUndefined(state.backgroundUrn) && (
        <NoBackgroundZone>

There is no background added for this floor

          <LinkButton>Add a background</LinkButton>
        </NoBackgroundZone>
      )}

    {!valueIsNullOrUndefined(state.selectedFloor) &&
      !valueIsNullOrUndefined(state.backgroundUrn) && (
        <ForgeViewer urn={state.backgroundUrn!} viewerReady={viewerReady} />
      )}
  </MainCanvas>

The error I get is:

Uncaught TypeError: Cannot read properties of null (reading 'hasModels') Viewer3D.js:1799
  at C.he.loadDocumentNode (Viewer3D.js:1799:53)
  at ForgeViewer.tsx:98:1
  ...

The line number that it's referring to in the error is the one that starts with viewer?.loadDocumnentNode(...  If it's using the conditional access how can it be null and still throwing the error?  I also have logged all three variables on that line (doc, defaultModel, and viewer) right before that call and they never show up as null...

Can anyone tell me what I'm doing wrong here?  I've looked at a lot of different samples but all of them seem to deal with just getting something displayed and I can't find anything about changing the display.

Body:
Ok so after doing a lot more logging and investigating I think I have this solved with a few changes described below for anyone that finds themselves in the same situation I was.

First, it turns out the issue was mostly centered around the viewer being 'finished' in the destructor function of useEffect here:

return () => {
  viewer?.finish();
};

After this happens the viewer in effect is dead, but I didn't set my value to undefined so the next time it found the viewer as non-null and tried to use it but it had already been finished.  First simple change:

return () => {
  viewer?.finish();
  viewer = undefined;
};

This makes sure that the viewer is recreated if it's been finished.

Secondly was actually in my consumer that is using this module. The props for this component has a viewer ready callback that tells the consuming module when the viewer is ready for use.  My calling component then does other things with the viewer (finds layers and blocks, etc.).  However, I was storing this in a standard variable:

const SpaceCreator = () => {
  let viewer: Autodesk.Viewing.GuiViewer3D | undefined;

  ...

  function viewerReady(v: Autodesk.Viewing.GuiViewer3D): void {
    viewer = v;
  }

  ...
}

Instead I needed to make this part of the state and use the reducer to set the current viewer like so:

const SpaceCreator = () => {
  const [state, dispatch] = useReducer(reducer, new SpaceCreatorState());

  ...

  function viewerReady(v: Autodesk.Viewing.GuiViewer3D): void {
    dispatch({ type: SpaceCreatorActions.viewer, payload: v });
  }

  ...
}

This was almost it, except that it kept reloading on me constantly.  I updated the dependencies in the useEffect to be only props.urn so that it would only re-run when the urn changed. This stopped the constant reloading, but React (linting anyway) complained about the dependency array not including the viewerReady event since it was used in the useEffect method.  After some more research, basically the viewerReady event was being redone on every render causing the value to change which is causing the constant re-renders.  Instead I needed to use useCallback to create the method which makes it not change unless one of it's dependencies changes (and since I have no dependencies it just creates on the first render).  Here is the final method:

const viewerReady = useCallback((v: Autodesk.Viewing.GuiViewer3D) => {
    dispatch({ type: SpaceCreatorActions.viewer, payload: v });
  }, []);

After all of this it seems to be stable, working correctly, and React is happy.  Hope this helps someone else having this issue.


来源: stackexchange

问:
Can't read JSON file in Angular
I want to read a JSON file from the file system but I can't make it work.

I've found this solution that seems to be what I need: Is it possible to upload a JSON file though file upload and read the contents in Angular 6 without talking to an API?

But i get two errors:

Parameter 'event' implicitly has an 'any' type on  uploadFile(event) {

and

Object is possibly 'null' on console.log(reader.result.toString());

This is my code:

component.html:

```<code> <form name="JSONform" (ngSubmit)="fJSON.form.valid && decryptJSON()" #fJSON="ngForm" novalidate>
        <input type="file" name="files" (change)="uploadFile($event)" />
        <div class="buttons">
            <div class="decrypt">
                <button class="btn btn-primary" type="submit">Decrypt</button>
            </div>
        </div>
    </form>
</code>```

component.ts:

```<code> uploadFile(event) {
    if (event.target.files.length !== 1) {
      console.error('No file selected');
    } else {
      const reader = new FileReader();
      reader.onloadend = (e) => {
        console.log(reader.result.toString());
        // handle data processing
      };
      reader.readAsText(event.target.files[0]);
    }
  }
</code>```

I don't know what I'm missing.
Thank you in advance.

答:
You're not missing anything. These errors are TSLINT or TypeScript errors. Just got to check for them:</p>
```<code>// Tell TS that you mean it as any (or you can find the actual event d.ts
// Use the ? operator to check for nulls (or do an if( reader.result != null)
// before calling toString()
uploadFile(event: any) {
    if (event.target.files.length !== 1) {
      console.error('No file selected');
    } else {
      const reader = new FileReader();
      reader.onloadend = (e) => {
        console.log(reader.result?.toString());
        // handle data processing
      };
      reader.readAsText(event.target.files[0]);
    }
  }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Can't read JSON file in Angular

Body:
I want to read a JSON file from the file system but I can't make it work.

I've found this solution that seems to be what I need: Is it possible to upload a JSON file though file upload and read the contents in Angular 6 without talking to an API?

But i get two errors:

Parameter 'event' implicitly has an 'any' type on  uploadFile(event) {

and

Object is possibly 'null' on console.log(reader.result.toString());

This is my code:

component.html:

 <form name="JSONform" (ngSubmit)="fJSON.form.valid && decryptJSON()" #fJSON="ngForm" novalidate>
        <input type="file" name="files" (change)="uploadFile($event)" />

                <button class="btn btn-primary" type="submit">Decrypt</button>

    </form>

component.ts:

 uploadFile(event) {
    if (event.target.files.length !== 1) {
      console.error('No file selected');
    } else {
      const reader = new FileReader();
      reader.onloadend = (e) => {
        console.log(reader.result.toString());
        // handle data processing
      };
      reader.readAsText(event.target.files[0]);
    }
  }

I don't know what I'm missing.
Thank you in advance.

Body:
You're not missing anything. These errors are TSLINT or TypeScript errors. Just got to check for them:

// Tell TS that you mean it as any (or you can find the actual event d.ts
// Use the ? operator to check for nulls (or do an if( reader.result != null)
// before calling toString()
uploadFile(event: any) {
    if (event.target.files.length !== 1) {
      console.error('No file selected');
    } else {
      const reader = new FileReader();
      reader.onloadend = (e) => {
        console.log(reader.result?.toString());
        // handle data processing
      };
      reader.readAsText(event.target.files[0]);
    }
  }


问:
Slick Slider: Mark custom nav link as active when navigate with arrows
I'm using some custom navigation links for my slick slider to navigate to certain slides.

It works fine but I've a problem if I add the built in arrows from the slider.
When I navigate with these, the custom links don't get the .active class.

Is there any way to add this class? I know, that I could use the slider syncing option to do that. But in my case I have to use custom links and couldn't use the asNavFor option.

Here's my current code (working example here: https://codepen.io/cray_code/pen/JjObOPa):

```<code>$('.product-gallery').slick({
dots: false,
    arrows: true,
    speed: 300,
    slidesToShow: 1,
    slidesToScroll: 1,
    fade: true,
});

// Custom links
$('a[data-slide]').click(function(e) {
    e.preventDefault();
    var slideno = $(this).data('slide');
    $('.product-gallery').slick('slickGoTo', slideno - 1);
    $('a[data-slide]').removeClass('active');
    this.classList.add('active');
});
</code>```

Thanks to this answer.

答:
You can use the method afterChange to perform this task. Here is the live demo https://codepen.io/sifat009/pen/bGYgBvP

Here is the javascript code to achieve this.

$('.product-gallery').slick({
    dots: false,
    arrows: true,
    speed: 300,
    slidesToShow: 1,
    slidesToScroll: 1,
    fade: true,
});

$('.product-gallery').on('afterChange', function(event, slick, currentSlide, nextSlide){
  const link = document.querySelector(`.action a[data-slide="${currentSlide+1}"]`);
    $('a[data-slide]').removeClass('active');
    link?.classList?.add('active');
});

$('a[data-slide]').click(function(e) {
    e.preventDefault();
    var slideno = $(this).data('slide');
    $('.product-gallery').slick('slickGoTo', slideno - 1);
    $('a[data-slide]').removeClass('active');
    this.classList.add('active');
});
```

Body:
I'm using some custom navigation links for my slick slider to navigate to certain slides.

It works fine but I've a problem if I add the built in arrows from the slider.
When I navigate with these, the custom links don't get the .active class.

Is there any way to add this class? I know, that I could use the slider syncing option to do that. But in my case I have to use custom links and couldn't use the asNavFor option.

Here's my current code (working example here: https://codepen.io/cray_code/pen/JjObOPa):

$('.product-gallery').slick({
dots: false,
    arrows: true,
    speed: 300,
    slidesToShow: 1,
    slidesToScroll: 1,
    fade: true,
});

// Custom links
$('a[data-slide]').click(function(e) {
    e.preventDefault();
    var slideno = $(this).data('slide');
    $('.product-gallery').slick('slickGoTo', slideno - 1);
    $('a[data-slide]').removeClass('active');
    this.classList.add('active');
});

Thanks to this answer.


问:
Windows service does not recognize network path. Whats the workaround?
We have a Buffalo NAS drive as a backup drive.

And when we map this drive as B:\ , our backup application seems to understand this and run as an application.

But when run as a service, it does not recognize the mapping and crashes.

I tried giving the path as \\\192.168.x.x\Backups\ as the backup path, the service runs but then a lot of submodules fail because it sees the \\\ as a escape character.

What is the workaround so that the windows service can see the mapped drive.

I am trying to run zip.exe via a CreateProcess();

""C:\Users\jvenkatraj\Documents\SQLite\Debug\zip.exe" -9 -q -g -u "\\\192.168.123.60\Backup\store\location1\50\f2\25\43\d8\88\b9\68\49\8d\2b\d0\08\9e\7e\df\z.zip" "\\\192.168.123.60\Backup\store\temp\SPD405.tmp\file_contents""

The backslashes are messing with the quotes. And it is a WCHAR type, and I can't change it to any other type, else I will have to redefine this elsewhere as well. How many backslashes should I use?

答: Try running your service under a user that "sees" the network, such as the "Network Service" user or even as the "human" user that mapped the network drive.</p>

ContentLicense: CC BY-SA 3.0


问:
Validate columns in a csv file are present in another csv file JAVA
I have two arrays ArrayList<String> csv1 and ArrayList<String> csv2

csv2 has more columns than csv1 but the goal is to check that all columns in csv1 are present in csv2, regardless of the extra files.

I esstenially want the code to only look at the columns in csv1 and check if they are in csv2 and nothing else.

Currently its giving me a 'false' output because there are extra columns in csv2 so its saying that they do not match.

I have a class called ReadCsvFile that reads csv files from a path

```<code>Public static void main(String[] args) {
ReadCsvFile readFile - new ReadCsvFile();
ArrayList<String> csv1 = (ArrayList<String>) readFile.readcsv1(some parameters here);
ArrayList<String> csv2 = (ArrayList<String>) readFile.readcsv2(some parameters here);
Collections.sort(csv1);
Collections.sort(csv2);
System.out.println(csv1.equals(csv2)); ```

```

答:
The line csv1.equals(csv2) would mean that both file contents are strictly identical.

What you want is :

check only header line : use List.get(0) and split on the good separator

check if columns of 1 are all in 2 : use List.containsAll

```<code>// use your separator if not comma
List<String> header1 = Arrays.asList(csv1.get(0).split(","));
List<String> header2 = Arrays.asList(csv2.get(0).split(","));

boolean ok = header2.containsAll(header1);
System.out.println(ok);
</code>```

Body:
I have two arrays ArrayList<String> csv1 and ArrayList<String> csv2

csv2 has more columns than csv1 but the goal is to check that all columns in csv1 are present in csv2, regardless of the extra files.

I esstenially want the code to only look at the columns in csv1 and check if they are in csv2 and nothing else.

Currently its giving me a 'false' output because there are extra columns in csv2 so its saying that they do not match.

I have a class called ReadCsvFile that reads csv files from a path

Public static void main(String[] args) {
ReadCsvFile readFile - new ReadCsvFile();
ArrayList<String> csv1 = (ArrayList<String>) readFile.readcsv1(some parameters here);
ArrayList<String> csv2 = (ArrayList<String>) readFile.readcsv2(some parameters here);
Collections.sort(csv1);
Collections.sort(csv2);
System.out.println(csv1.equals(csv2)); ```

Body:
The line csv1.equals(csv2) would mean that both file contents are strictly identical.

What you want is :

check only header line : use List.get(0) and split on the good separator

check if columns of 1 are all in 2 : use List.containsAll

// use your separator if not comma
List<String> header1 = Arrays.asList(csv1.get(0).split(","));
List<String> header2 = Arrays.asList(csv2.get(0).split(","));

boolean ok = header2.containsAll(header1);
System.out.println(ok);


问:
"MountVolume.SetUp failed for volume" with EKS and EFS
I'm trying to set up EFS with EKS, but when I deploy my pod, I get errors like MountVolume.SetUp failed for volume "efs-pv3" : rpc error: code = DeadlineExceeded desc = context deadline exceeded
in my events.

What is the cause of this?

答:
Here is an automated way to use Phyxx's answer.

At first, I was using the private subnets of my cluster, this led to the error mentioned by this thread. After seeing the answered mentioned, I noticed all my nodes were in the public subnet. Therefore I only had to switch "Private" to "Public" to make it work.

Here is script that worked for me :

CLUSTER_REGION=<YOUR_CLUSTER_REGION>
CLUSTER_NAME=<YOUR_CLUSTER_NAME>
EFS_SECURITY_GROUP_NAME=<YOUR_EFS_SECURITY_GROUP_NAME>
EFS_FILE_SYSTEM_NAME<YOUR_EFS_FILE_SYSTEM_NAME>

create_efs_mount_targets() {
    file_system_id=$(aws efs describe-file-systems \
                            --region $CLUSTER_REGION \
                            --query "FileSystems[?Name=='$EFS_FILE_SYSTEM_NAME'].FileSystemId" \
                            --output text) \
    && security_group_id=$(aws ec2 describe-security-groups \
    --region $CLUSTER_REGION \
    --query 'SecurityGroups[*]' \
    --output json \
    | jq -r 'map(select(.GroupName=="'$EFS_SECURITY_GROUP_NAME'")) | .[].GroupId') \
    && public_cluster_subnets=$(aws ec2 describe-subnets \
                --region $CLUSTER_REGION \
                --output json \
                --filters Name=tag:alpha.eksctl.io/cluster-name,Values=$CLUSTER_NAME Name=tag:aws:cloudformation:logical-id,Values=SubnetPublic* \
                | jq -r '.Subnets[].SubnetId')
    if [[ $? != 0 ]]; then
        exit 1
    fi
    for subnet in ${public_cluster_subnets[@]}
    do
        echo "Attempting to create mount target in "$subnet"..."

        aws efs create-mount-target \
            --file-system-id $file_system_id \
            --subnet-id $subnet \
            --security-groups $security_group_id \
        &> /dev/null \
        && echo "Mount target created!"
    done
}

create_efs_mount_targets
```


问:
export a variable inside a function to be used in other modules
I'm quite new to programming. I have spend last 3 days trying to figure this out. So any help really appreciate it.

I have access to clientID inside a for loop. (Please look at the last line in the code below). There is only one ClientID which I'm successfully able to print.

I want this client ID to be exported from this module so that I can use it in other modules.

```<code>import { Configurations } from './models';

type MethodNames = 'init' | 'event';

export const DEFAULT_NAME = '_hw';

interface LoaderObject {
    q: Array<[MethodNames, {}]>;
}

export default (
    win: Window,
    defaultConfig: Configurations,
    scriptElement: Element | null,
    render: (element: HTMLElement, config: Configurations) => void
) => {

    const instanceName =
        scriptElement?.attributes.getNamedItem('id')?.value ?? DEFAULT_NAME;
    const loaderObject: LoaderObject = win[instanceName];
    if (!loaderObject || !loaderObject.q) {
        throw new Error(
            `Widget didn't find LoaderObject`);
    }

    if (win[`loaded-${instanceName}`]) {
        throw new Error(
            `Widget already loaded`)
        );
    }

    let targetElement: HTMLElement;

    for (let i = 0; i < loaderObject.q.length; i++) {
        const item = loaderObject.q[i];
        const methodName = item[0];
        console.log(methodName);
        if (i === 0 && methodName !== 'init') {
            throw new Error(
                `Failed to start Widget`);
        } else if (i !== 0 && methodName === 'init') {
            continue;
        }

        const valueObject = Object.assign(defaultConfig, item[1]);
        const clientID = valueObject.clientID
        console.log("ClientID", clientID)
    }

//rest of the code....

</code>```

I have also tried this. defined a variable clientID outside the for loop and then storing value from inside the for loop. But on printing, I'm getting undefined

```<code>var clientID;
console.log("....last Client ID", clientID)
</code>```
```<code>   const valueObject = Object.assign(defaultConfig, item[1]);
    clientID = valueObject.clientID

</code>```

答: I guess the way you can access the variable is by creating a let variable outside the loop then assign it a value in the loop, or create an array outside the loop and push values into it inside the loop, that way you can have access to the variable outside the loop's scope.</p>

Body:
I'm quite new to programming. I have spend last 3 days trying to figure this out. So any help really appreciate it.

I have access to clientID inside a for loop. (Please look at the last line in the code below). There is only one ClientID which I'm successfully able to print.

I want this client ID to be exported from this module so that I can use it in other modules.

import { Configurations } from './models';

type MethodNames = 'init' | 'event';

export const DEFAULT_NAME = '_hw';

interface LoaderObject {
    q: Array<[MethodNames, {}]>;
}

export default (
    win: Window,
    defaultConfig: Configurations,
    scriptElement: Element | null,
    render: (element: HTMLElement, config: Configurations) => void
) => {

    const instanceName =
        scriptElement?.attributes.getNamedItem('id')?.value ?? DEFAULT_NAME;
    const loaderObject: LoaderObject = win[instanceName];
    if (!loaderObject || !loaderObject.q) {
        throw new Error(
            `Widget didn't find LoaderObject`);
    }

    if (win[`loaded-${instanceName}`]) {
        throw new Error(
            `Widget already loaded`)
        );
    }

    let targetElement: HTMLElement;

    for (let i = 0; i < loaderObject.q.length; i++) {
        const item = loaderObject.q[i];
        const methodName = item[0];
        console.log(methodName);
        if (i === 0 && methodName !== 'init') {
            throw new Error(
                `Failed to start Widget`);
        } else if (i !== 0 && methodName === 'init') {
            continue;
        }

        const valueObject = Object.assign(defaultConfig, item[1]);
        const clientID = valueObject.clientID
        console.log("ClientID", clientID)
    }

//rest of the code....

I have also tried this. defined a variable clientID outside the for loop and then storing value from inside the for loop. But on printing, I'm getting undefined

var clientID;
console.log("....last Client ID", clientID)

   const valueObject = Object.assign(defaultConfig, item[1]);
    clientID = valueObject.clientID


问:
How can I balance "Pythonic" and "convenient" in this case?
I have an "interface" that will be implemented by client code:

```<code>class Runner:
    def run(self):
        pass
</code>```

run should in general return a docutils node but because the far far most
common case is plain text, the caller allows run to return a string, which will be
checked using type() and turned into a node.

However, the way I understand "Pythonic", this is not "Pythonic" because
checking the type() of something doesn't let it "be" a type by "acting" like
one -- ie "Pythonic" code should use duck typing.

I considered

```<code>def run_str(self):
    pass

def run_node(self):
    return make_node(self.run_str())
</code>```

but I don't care for this because it puts the not-so-interesting return type
right there in the name; it's distracting.

Are there any ideas I've missed? Also, are there problems I might encounter
down the road with my "bad" system (it seems more or less safe to me)?

答:
Check out Errors and Exceptions. You could do something like this:

```<code>def run(self,arg):
    try:
        return make_node(arg)
    except AlreadyNodeError:
        pass
</code>```

Inside your make_node function, have it raise a AlreadyNodeError if the argument is already a node.

Body:
I have an "interface" that will be implemented by client code:

class Runner:
    def run(self):
        pass

run should in general return a docutils node but because the far far most
common case is plain text, the caller allows run to return a string, which will be
checked using type() and turned into a node.

However, the way I understand "Pythonic", this is not "Pythonic" because
checking the type() of something doesn't let it "be" a type by "acting" like
one -- ie "Pythonic" code should use duck typing.

I considered

def run_str(self):
    pass

def run_node(self):
    return make_node(self.run_str())

but I don't care for this because it puts the not-so-interesting return type
right there in the name; it's distracting.

Are there any ideas I've missed? Also, are there problems I might encounter
down the road with my "bad" system (it seems more or less safe to me)?

Body:
Check out Errors and Exceptions. You could do something like this:

def run(self,arg):
    try:
        return make_node(arg)
    except AlreadyNodeError:
        pass

Inside your make_node function, have it raise a AlreadyNodeError if the argument is already a node.


问:
Async/Await ReferenceError: Can't find variable: regeneratorRuntime
I've been searching a lot on this error and found that is related to babel that cannot generate the code related to my async/await calls.

As I don't want to remove them, I would like to solve this issue. I've tried many things found on the web but can't get rid of it. Here is my code:

.babelrc

```<code>{
  "presets": [
    ["@babel/preset-env", { "useBuiltIns": "usage", "corejs": 3 }],
    "@babel/preset-react",
    "@babel/preset-typescript"
  ],
  "plugins": [
    "@babel/plugin-transform-async-to-generator",
    "@babel/plugin-proposal-class-properties",
    [
      "@babel/plugin-transform-runtime",
      {
        "regenerator": true
      }
    ],
    "@babel/plugin-transform-regenerator"
  ]
}
</code>```

webpack.config.js

```<code>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = (env, { mode = 'development' }) => {
  const config = {
    mode,
    entry: ['./src/index.tsx'],
    devtool: '',
    resolve: {
      modules: ['src', 'node_modules'],
      extensions: ['.js', '.jsx', '.ts', '.tsx'],
    },
    module: {
      rules: [
        {
          test: /\.(js|jsx|tsx|ts)$/,
          enforce: 'pre',
          loader: 'eslint-loader',
          exclude: /node_modules/,
          options: {
            emitError: true,
            configFile: './.eslintrc.js',
          },
        },
        {
          test: /\.(png|svg|jpg|gif)$/,
          use: [
            {
              loader: 'file-loader',
            },
          ],
        },
        {
          test: /\.scss$/,
          use: [
            { loader: 'style-loader' },
            { loader: 'css-loader' },
            { loader: 'sass-loader' },
          ],
        },
        {
          test: /\.less$/,
          use: [
            { loader: 'style-loader' },
            { loader: 'css-loader' },
            { loader: 'less-loader' },
          ],
        },
        {
          test: /\.css$/,
          use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],
        },
        {
          test: /\.(js|jsx|tsx|ts)$/,
          exclude: /node_modules/,
          // use: {
          //   loader: 'babel-loader',
          //   options: {
          //     presets: [
          //       ['@babel/preset-env', { useBuiltIns: false }],
          //       '@babel/preset-react',
          //       '@babel/preset-typescript',
          //     ],
          //     plugins: [
          //       '@babel/plugin-transform-async-to-generator',
          //       '@babel/plugin-proposal-class-properties',
          //       [
          //         '@babel/plugin-transform-runtime',
          //         {
          //           helpers: true,
          //           regenerator: true,
          //         },
          //       ],
          //       '@babel/plugin-transform-regenerator',
          //     ],
          //   },
          // },
          use: 'babel-loader',
        },
      ],
    },
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'bundle.js',
      libraryTarget: 'umd',
      publicPath: '/dist/',
      umdNamedDefine: true,
    },
    optimization: {
      mangleWasmImports: true,
      mergeDuplicateChunks: true,
      minimize: true,
      nodeEnv: 'production',
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"production"',
      }),
      new HtmlWebpackPlugin({
        filename: path.resolve(__dirname, 'dist/index.html'),
        template: path.resolve(__dirname, 'src', 'index.html'),
      }),
    ],
  };

  /**
   * If in development mode adjust the config accordingly
   */
  if (mode === 'development') {
    config.devtool = 'source-map';
    config.output = {
      filename: '[name]/index.js',
    };
    config.module.rules.push({
      loader: 'source-map-loader',
      test: /\.js$/,
      exclude: /node_modules/,
      enforce: 'pre',
    });
    config.plugins = [
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"development"',
      }),
      new HtmlWebpackPlugin({
        filename: path.resolve(__dirname, 'dist/index.html'),
        template: path.resolve(__dirname, 'src', 'index.html'),
      }),
      new webpack.HotModuleReplacementPlugin(),
    ];
    config.devServer = {
      contentBase: path.resolve(__dirname, 'dist'),
      publicPath: '/',
      stats: {
        colors: true,
        hash: false,
        version: false,
        timings: true,
        assets: true,
        chunks: false,
        modules: false,
        reasons: false,
        children: false,
        source: false,
        errors: true,
        errorDetails: true,
        warnings: false,
        publicPath: false,
      },
    };
    config.optimization = {
      mangleWasmImports: true,
      mergeDuplicateChunks: true,
      minimize: false,
      nodeEnv: 'development',
    };
  }
  return config;
};
</code>```

I imported these in my root index file:

import 'core-js/stable';
import 'regenerator-runtime/runtime';
```

I read a lot about babel-polyfill but according to the official documentation, it's deprecated since babel 7 so I'm trying to solve this without it.

答:
Just add this babel plugin to your .babelrc file, so it look like this:</p>
```<code>  "plugins": [
    ...other plugins,
    "@babel/plugin-transform-runtime"
  ]
</code>```

Body:
I've been searching a lot on this error and found that is related to babel that cannot generate the code related to my async/await calls.

As I don't want to remove them, I would like to solve this issue. I've tried many things found on the web but can't get rid of it. Here is my code:

.babelrc

{
  "presets": [
    ["@babel/preset-env", { "useBuiltIns": "usage", "corejs": 3 }],
    "@babel/preset-react",
    "@babel/preset-typescript"
  ],
  "plugins": [
    "@babel/plugin-transform-async-to-generator",
    "@babel/plugin-proposal-class-properties",
    [
      "@babel/plugin-transform-runtime",
      {
        "regenerator": true
      }
    ],
    "@babel/plugin-transform-regenerator"
  ]
}

webpack.config.js

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = (env, { mode = 'development' }) => {
  const config = {
    mode,
    entry: ['./src/index.tsx'],
    devtool: '',
    resolve: {
      modules: ['src', 'node_modules'],
      extensions: ['.js', '.jsx', '.ts', '.tsx'],
    },
    module: {
      rules: [
        {
          test: /\.(js|jsx|tsx|ts)$/,
          enforce: 'pre',
          loader: 'eslint-loader',
          exclude: /node_modules/,
          options: {
            emitError: true,
            configFile: './.eslintrc.js',
          },
        },
        {
          test: /\.(png|svg|jpg|gif)$/,
          use: [
            {
              loader: 'file-loader',
            },
          ],
        },
        {
          test: /\.scss$/,
          use: [
            { loader: 'style-loader' },
            { loader: 'css-loader' },
            { loader: 'sass-loader' },
          ],
        },
        {
          test: /\.less$/,
          use: [
            { loader: 'style-loader' },
            { loader: 'css-loader' },
            { loader: 'less-loader' },
          ],
        },
        {
          test: /\.css$/,
          use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],
        },
        {
          test: /\.(js|jsx|tsx|ts)$/,
          exclude: /node_modules/,
          // use: {
          //   loader: 'babel-loader',
          //   options: {
          //     presets: [
          //       ['@babel/preset-env', { useBuiltIns: false }],
          //       '@babel/preset-react',
          //       '@babel/preset-typescript',
          //     ],
          //     plugins: [
          //       '@babel/plugin-transform-async-to-generator',
          //       '@babel/plugin-proposal-class-properties',
          //       [
          //         '@babel/plugin-transform-runtime',
          //         {
          //           helpers: true,
          //           regenerator: true,
          //         },
          //       ],
          //       '@babel/plugin-transform-regenerator',
          //     ],
          //   },
          // },
          use: 'babel-loader',
        },
      ],
    },
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'bundle.js',
      libraryTarget: 'umd',
      publicPath: '/dist/',
      umdNamedDefine: true,
    },
    optimization: {
      mangleWasmImports: true,
      mergeDuplicateChunks: true,
      minimize: true,
      nodeEnv: 'production',
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"production"',
      }),
      new HtmlWebpackPlugin({
        filename: path.resolve(__dirname, 'dist/index.html'),
        template: path.resolve(__dirname, 'src', 'index.html'),
      }),
    ],
  };

  /**
   * If in development mode adjust the config accordingly
   */
  if (mode === 'development') {
    config.devtool = 'source-map';
    config.output = {
      filename: '[name]/index.js',
    };
    config.module.rules.push({
      loader: 'source-map-loader',
      test: /\.js$/,
      exclude: /node_modules/,
      enforce: 'pre',
    });
    config.plugins = [
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': '"development"',
      }),
      new HtmlWebpackPlugin({
        filename: path.resolve(__dirname, 'dist/index.html'),
        template: path.resolve(__dirname, 'src', 'index.html'),
      }),
      new webpack.HotModuleReplacementPlugin(),
    ];
    config.devServer = {
      contentBase: path.resolve(__dirname, 'dist'),
      publicPath: '/',
      stats: {
        colors: true,
        hash: false,
        version: false,
        timings: true,
        assets: true,
        chunks: false,
        modules: false,
        reasons: false,
        children: false,
        source: false,
        errors: true,
        errorDetails: true,
        warnings: false,
        publicPath: false,
      },
    };
    config.optimization = {
      mangleWasmImports: true,
      mergeDuplicateChunks: true,
      minimize: false,
      nodeEnv: 'development',
    };
  }
  return config;
};

I imported these in my root index file:

import 'core-js/stable';
import 'regenerator-runtime/runtime';

I read a lot about babel-polyfill but according to the official documentation, it's deprecated since babel 7 so I'm trying to solve this without it.

Body:
Just add this babel plugin to your .babelrc file, so it look like this:

  "plugins": [
    ...other plugins,
    "@babel/plugin-transform-runtime"
  ]


问:
How to create my own command handler for library shell app in Python
I want to create a shell application for a litte digital library and I want to be able to get some commands for importing books in library from users like this:

```<code>ADD { book_title } TO { library_id } WITH { COUNT } RECORDS
</code>```

It is like sql queries but in my own way.
So, I want to create this system to get my data from queries that the user wrote.

If any one can help me I will be appreciative.

答:
For a Command Line Interface (CLI) you could use click for the CLI.

For a Read-Evaluate-Print-Loop (REPL) which is more like an interactive shell (like known by IPython or most SQL clients) you could use cmd from the Python standard library or cmd2.

Example of CLI using Click

In your case you would use Multi Command Chaining and Contexts.

Example: script.py

import click

# ADD { book_title } TO { library_id } WITH { COUNT } RECORDS

@click.group(chain=True)
@click.pass_context
def cli(ctx):
    if ctx.invoked_subcommand is None:
        click.echo('I was invoked without subcommand')
    else:
        click.echo(f"I am about to invoke {ctx.invoked_subcommand}")

@cli.command(name='ADD')
@click.argument('book_title')
@click.pass_context
def add(ctx, book_title):
    """ADD {book_title}"""
    click.echo(f"add book {book_title}")
    ctx.ensure_object(dict)
    ctx.obj['book'] = book_title

@cli.command(name='TO')
@click.argument('library_id')
@click.pass_context
def to(ctx, library_id):
    """TO {library_id}"""
    click.echo(f"to {library_id}")
    click.echo(f"Book is {ctx.obj['book']}")
    ctx.ensure_object(dict)
    ctx.obj['library'] = library_id

@cli.command(name='WITH')
@click.argument('count')
@click.pass_context
def withRecords(ctx, count):
    """WITH {count} records"""
    click.echo(f"with {count} records")
    click.echo(f"Book is {ctx.obj['book']}")
    click.echo(f"Library is {ctx.obj['library']}")

if __name__ == '__main__':
    cli(obj={})
```
<p>When invoked like <code>python3 script.py ADD title TO library WITH 3</code> it prints:</p>
```I am about to invoke *
add book title
to library
Book is title
with 3 records
Book is title
Library is library
```

Body:
I want to create a shell application for a litte digital library and I want to be able to get some commands for importing books in library from users like this:

ADD { book_title } TO { library_id } WITH { COUNT } RECORDS

It is like sql queries but in my own way.
So, I want to create this system to get my data from queries that the user wrote.

If any one can help me I will be appreciative.

Body:
For a Command Line Interface (CLI) you could use click for the CLI.

For a Read-Evaluate-Print-Loop (REPL) which is more like an interactive shell (like known by IPython or most SQL clients) you could use cmd from the Python standard library or cmd2.

Example of CLI using Click

In your case you would use Multi Command Chaining and Contexts.

Example: script.py

import click

# ADD { book_title } TO { library_id } WITH { COUNT } RECORDS

@click.group(chain=True)
@click.pass_context
def cli(ctx):
    if ctx.invoked_subcommand is None:
        click.echo('I was invoked without subcommand')
    else:
        click.echo(f"I am about to invoke {ctx.invoked_subcommand}")

@cli.command(name='ADD')
@click.argument('book_title')
@click.pass_context
def add(ctx, book_title):
    """ADD {book_title}"""
    click.echo(f"add book {book_title}")
    ctx.ensure_object(dict)
    ctx.obj['book'] = book_title

@cli.command(name='TO')
@click.argument('library_id')
@click.pass_context
def to(ctx, library_id):
    """TO {library_id}"""
    click.echo(f"to {library_id}")
    click.echo(f"Book is {ctx.obj['book']}")
    ctx.ensure_object(dict)
    ctx.obj['library'] = library_id

@cli.command(name='WITH')
@click.argument('count')
@click.pass_context
def withRecords(ctx, count):
    """WITH {count} records"""
    click.echo(f"with {count} records")
    click.echo(f"Book is {ctx.obj['book']}")
    click.echo(f"Library is {ctx.obj['library']}")

if __name__ == '__main__':
    cli(obj={})

When invoked like python3 script.py ADD title TO library WITH 3 it prints:

I am about to invoke *
add book title
to library
Book is title
with 3 records
Book is title
Library is library


问:
Ag Grid's flush update problem when changing browser tab
I'm using ag-grid v23 for stock board and updating data at high frequency about ~100 ms/message.
I'm using batchUpdateRowData to update multiple row.
The board updates normally when I focus on its tab, but when I change to others tab and after a while back to board tab, It starts to flush all updated data which receives from the moment I'm not on board tab until when I come back, It makes a very terrible performance. Any idea how this happens and how to resolve this? I tried to upgrade to ag-grid v25 but the problem still there.

答: I believe that's the Browser's behavior. You might want to disable browser's throttling when you switch tab or catch the tab switch event and stop your updates until reactivate.</p>


问:
Must contain a non-null value and possible null reference
I'm trying to switch to .Net 6.0 from .Net 3.1 and I encounter a few issues.

Apparently, in .Net 6.0 models need to have non-nullable property, for example:

```<code>public string Email { get; set; } = String.Empty;
</code>```

The problem for the DbSet I fixed like:

```<code>public DbSet<User>? Users { get; set; }
</code>```

However, now I'm getting warnings of possible null reference argument/return as the image below:

答:
As the docs show  you can use Set method with expression bodied property:

public DbSet<User> Users => Set<User>();
```

Body:
I'm trying to switch to .Net 6.0 from .Net 3.1 and I encounter a few issues.

Apparently, in .Net 6.0 models need to have non-nullable property, for example:

public string Email { get; set; } = String.Empty;

The problem for the DbSet I fixed like:

public DbSet<User>? Users { get; set; }

However, now I'm getting warnings of possible null reference argument/return as the image below:


问:
How to control file generation using Freemarker template process
I am using freemarker template to generate a file. The ftl template has java API call and when there is an any exception from java API, i want to avoid writing the file in between template processing. See below code</p>
```<code>templateFileName --> freemarker template file name (.ftl file)
templateFilePath --> freemarker template file path (.ftl file)
outputFilePath --> output file path

FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(new File(templateFilePath));

MultiTemplateLoader tmpltLoader = new MultiTemplateLoader(
    new TemplateLoader[] { fileTemplateLoader});

// Set to Configuration
freemarkerConfig.setTemplateLoader(tmpltLoader);
freemarkerConfig.setLogTemplateExceptions(false);
freemarkerConfig.setWrapUncheckedExceptions(true);
freemarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
freemarkerConfig.setFallbackOnNullLoopVariable(false);

Template template =
    freemarkerConfig.getTemplate(templateFileName.substring(templateFileName.lastIndexOf('/') + 1, templateFileName.length()),
        StandardCharsets.ISO_8859_1.name());

// write output into a file:
try (FileWriter fileWriter = new FileWriter(new File(outputFilePath))) {
  template.process(input, fileWriter);
}
catch (TemplateException e) {
  new FileOutputStream(outputFilePath).close(); //This causes only the file empty. But i dont want to write the output file
}
</code>```

答: You could pass a StringWriter to Template.process, and then if there was no exception, write the resulting String into the file. However, be sure that the output is small enough to fit into the memory. Otherwise write into a temporary file, and move it to the final place if there was no exception.

Body:
I am using freemarker template to generate a file. The ftl template has java API call and when there is an any exception from java API, i want to avoid writing the file in between template processing. See below code

templateFileName --> freemarker template file name (.ftl file)
templateFilePath --> freemarker template file path (.ftl file)
outputFilePath --> output file path

FileTemplateLoader fileTemplateLoader = new FileTemplateLoader(new File(templateFilePath));

MultiTemplateLoader tmpltLoader = new MultiTemplateLoader(
    new TemplateLoader[] { fileTemplateLoader});

// Set to Configuration
freemarkerConfig.setTemplateLoader(tmpltLoader);
freemarkerConfig.setLogTemplateExceptions(false);
freemarkerConfig.setWrapUncheckedExceptions(true);
freemarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
freemarkerConfig.setFallbackOnNullLoopVariable(false);

Template template =
    freemarkerConfig.getTemplate(templateFileName.substring(templateFileName.lastIndexOf('/') + 1, templateFileName.length()),
        StandardCharsets.ISO_8859_1.name());

// write output into a file:
try (FileWriter fileWriter = new FileWriter(new File(outputFilePath))) {
  template.process(input, fileWriter);
}
catch (TemplateException e) {
  new FileOutputStream(outputFilePath).close(); //This causes only the file empty. But i dont want to write the output file
}


问:
Pyinstaller Hidden imports and user defined modules error

Basically I made a GUI app and it has a lot of user defined modules stored in different py files. All of these py files have been imported as modules in the main file but whenever i run the executable this exception is generated in the command prompt. I have no idea how to solve this problem

答:
If you are using virtualenv you should use the "-p" or "--path='D:...'" option. Like this:

```<code>pyinstaller.exe --onefile --paths=D:\env\Lib\site-packages  .\foo.py
</code>```

What this does is generates foo.spec file with this pathex path

Body:
If you are using virtualenv you should use the "-p" or "--path='D:...'" option. Like this:

pyinstaller.exe --onefile --paths=D:\env\Lib\site-packages  .\foo.py

What this does is generates foo.spec file with this pathex path


问:
Pulling EventLogs using powershell from a certain time period
I am trying to run a powershell script that will pull application event logs from between 2 certain times. I have the following code:

```<code>$Begin = Get-Date -Date '2/04/2022 14:36:00'
$End = Get-Date -Date '2/04/2022 14:40:00'
Get-EventLog –LogName Application -After $Begin -Before $End
</code>```

I keep receiving the following error.

```<code>Get-Date : Cannot bind parameter because parameter 'Date' is specified more
than once. To provide multiple values to parameters that can accept multiple
values, use the array syntax. For example, "-parameter value1,value2,value3".
</code>```

Does anyone know what I am doing wrong?

答:
An example with get-winevent's filterhashtable.  Any string that can be converted to a datetime would work.  Searching every log would require a foreach-object loop.</p>
```<code>get-winevent -filterhashtable @{logname = 'application'; starttime = '12:45 pm';
  endtime = '12:50 pm' }

   ProviderName: gupdate

TimeCreated                      Id LevelDisplayName Message
-----------                      -- ---------------- -------
2/7/2022 12:45:19 PM              0

</code>```

Body:
I am trying to run a powershell script that will pull application event logs from between 2 certain times. I have the following code:

$Begin = Get-Date -Date '2/04/2022 14:36:00'
$End = Get-Date -Date '2/04/2022 14:40:00'
Get-EventLog –LogName Application -After $Begin -Before $End

I keep receiving the following error.

Get-Date : Cannot bind parameter because parameter 'Date' is specified more
than once. To provide multiple values to parameters that can accept multiple
values, use the array syntax. For example, "-parameter value1,value2,value3".

Does anyone know what I am doing wrong?

Body:
An example with get-winevent's filterhashtable.  Any string that can be converted to a datetime would work.  Searching every log would require a foreach-object loop.

get-winevent -filterhashtable @{logname = 'application'; starttime = '12:45 pm';
  endtime = '12:50 pm' }

   ProviderName: gupdate

TimeCreated                      Id LevelDisplayName Message
-----------                      -- ---------------- -------
2/7/2022 12:45:19 PM              0


问:
How to add data to a ManyToMany field model?
I have model Department:

```<code>class Department(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=30)
    subsidiary = models.ManyToManyField('self',null=True,blank=True, symmetrical=False, related_name='subsidiary_name')
    superior = models.ForeignKey('self',null=True,blank=True, related_name='superior_name', on_delete = models.DO_NOTHING)
    manager = models.ForeignKey(Manager, on_delete = models.DO_NOTHING)
    history = HistoricalRecords()

def get_subsidiary(self):
        return "\n".join([p.title for p in self.subsidiary.all()])

def __str__(self):
    return self.title
</code>```

In Department model I have 2 instance of the same model: subsidiary and superior departments. The rules are simple: one department can have only one superior department, and many subsidiary.
I want to implement next logic:

I am creating new department SLF, and f.e. I choose SID department as superior department for SLF. Finally, when I save SLF object I want to add this department as subsidiary for SID automatically.

I am trying to override save method like:

```<code>def save(self, *args, **kwargs):
    print('Department.objects.filter(title=self.superior): ', Department.objects.filter(title=self.superior))
    if self.superior__in == Department.objects.filter(title=self.superior.title):
        tmp = Department.objects.filter(title=self.superior.title)
        tmp.create(subsidiary = self.superior)
        tmp.save()

    super(Department, self).save(*args, **kwargs)
</code>```

But it doesn't work. How can implement something like this?

答:
Finally,

```<code>def save(self, *args, **kwargs):
        super(Department, self).save(*args, **kwargs)
        if self.superior == Department.objects.get(title=self.superior.title):
            tmp = Department.objects.get(title=self.superior.title)
            tmp.subsidiary.add(self)
</code>```

Thank you for your advices.

Body:
I have model Department:

class Department(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=30)
    subsidiary = models.ManyToManyField('self',null=True,blank=True, symmetrical=False, related_name='subsidiary_name')
    superior = models.ForeignKey('self',null=True,blank=True, related_name='superior_name', on_delete = models.DO_NOTHING)
    manager = models.ForeignKey(Manager, on_delete = models.DO_NOTHING)
    history = HistoricalRecords()

def get_subsidiary(self):
        return "\n".join([p.title for p in self.subsidiary.all()])

def __str__(self):
    return self.title

In Department model I have 2 instance of the same model: subsidiary and superior departments. The rules are simple: one department can have only one superior department, and many subsidiary.
I want to implement next logic:

I am creating new department SLF, and f.e. I choose SID department as superior department for SLF. Finally, when I save SLF object I want to add this department as subsidiary for SID automatically.

I am trying to override save method like:

def save(self, *args, **kwargs):
    print('Department.objects.filter(title=self.superior): ', Department.objects.filter(title=self.superior))
    if self.superior__in == Department.objects.filter(title=self.superior.title):
        tmp = Department.objects.filter(title=self.superior.title)
        tmp.create(subsidiary = self.superior)
        tmp.save()

    super(Department, self).save(*args, **kwargs)

But it doesn't work. How can implement something like this?

Body:
Finally,

def save(self, *args, **kwargs):
        super(Department, self).save(*args, **kwargs)
        if self.superior == Department.objects.get(title=self.superior.title):
            tmp = Department.objects.get(title=self.superior.title)
            tmp.subsidiary.add(self)

Thank you for your advices.


问:
(p) element doesn't display when it should
Hi I'm trying to make a website editor with drag and drop feature
I added an input field when you press a button and the text you type in becomes the inner text for a "p" element but the "p" element doesn't display
Here's the code
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">

  <title>HTML</title>

  <!-- HTML -->

  <!-- Custom Styles -->
  <link rel="stylesheet" href="style.css">
</head>

<body>
   <nav>
   <button class="button" id="h1">Header</button>
   <button class="button" id="h2">Header2</button>
   <button class="button" id="p">Text</button>
   <button class="button" id="img">Image</button>
   </nav>
   <input type="text" placeholder="type your text here" id="text-field">
<!-- Linking scripts -->
   <script type="module" src="main.js"></script>
   <script type="module" src="mouse.js"></script>
   <script type="module" src="header_button.js"></script>
   <script type="module" src="header2_button.js"></script>
   <script type="module" src="image_button.js"></script>
   <script src="text_button.js"></script>
</code>```

JavaScript:

```<code>let text_button = document.getElementById('p')
let text_data_holder = document.getElementById('text-field')
let paragraph = document.createElement('p')
let text_data = ''
//Creating text
text_button.addEventListener('click', function() {
  text_data_holder.style.display = 'block'
})
text_data_holder.addEventListener('change', function(e) {
   e.preventDefault()
   text_data += e.target.value
    if(text_data == e.target.value){
     paragraph.innerText = text_data
     console.log(text_data)
    }
})
</code>```

答:
as mentioned, you have to add p somewhere to the DOM. e.g. with .after()

```<code>let paragraph = document.createElement('p')
text_data_holder.after(paragraph)
let text_data = ''
</code>```

Body:
Hi I'm trying to make a website editor with drag and drop feature
I added an input field when you press a button and the text you type in becomes the inner text for a "p" element but the "p" element doesn't display
Here's the code
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">

  <title>HTML</title>

  <link rel="stylesheet" href="style.css">

   <button class="button" id="h1">Header</button>
   <button class="button" id="h2">Header2</button>
   <button class="button" id="p">Text</button>
   <button class="button" id="img">Image</button>

   <input type="text" placeholder="type your text here" id="text-field">

JavaScript:

let text_button = document.getElementById('p')
let text_data_holder = document.getElementById('text-field')
let paragraph = document.createElement('p')
let text_data = ''
//Creating text
text_button.addEventListener('click', function() {
  text_data_holder.style.display = 'block'
})
text_data_holder.addEventListener('change', function(e) {
   e.preventDefault()
   text_data += e.target.value
    if(text_data == e.target.value){
     paragraph.innerText = text_data
     console.log(text_data)
    }
})

Body:
as mentioned, you have to add p somewhere to the DOM. e.g. with .after()

let paragraph = document.createElement('p')
text_data_holder.after(paragraph)
let text_data = ''


答:
You don't necessarily need to have methods to handle each type, especially if a simple operation is all that will occur. A common Pythonic approach would be to do something like:

```<code>def run(self):
    try:
        ...assume it's a str
    except TypeError:
        ...oops, not a str, we'll address that
</code>```

This follows the Easier to ask for forgiveness than permission (EAFP) style of coding, which is generally faster and simpler.

Title: How can I balance "Pythonic" and "convenient" in this case?

Body:
You don't necessarily need to have methods to handle each type, especially if a simple operation is all that will occur. A common Pythonic approach would be to do something like:

def run(self):
    try:
        ...assume it's a str
    except TypeError:
        ...oops, not a str, we'll address that

This follows the Easier to ask for forgiveness than permission (EAFP) style of coding, which is generally faster and simpler.


问:
Scrabble Score Count
I have been trying to make a scrabble score counter but I end up falling in an infinite loop, I attach my code in case anyone can give me a hand, it personally makes sense, but for some reason Python does not like my code :((</p>
```<code>def letterScore(let):
    """Argument let: one character string
    Return Value: the scrabble value of the letter"""
    if let in 'qz':
        return 10
    elif let in 'aelnorstu':
        return 1
    elif let in 'd':
        return 2
    elif let in 'bcmp':
        return 3
    elif let in 'vwy':
        return 4
    elif let in 'k':
        return 5
    elif let in 'x':
        return 8
    else:
        return 0

def scrabbleScore (S):
    """"Argument S: String argument S
    Return Value: the total Scrabble score :))"""

    if "s[0]" == '':
        return 0
    else:
        return letterScore(S[0]) + scrabbleScore (S[1:])

#
# Tests
#
print( "scrabbleScore('quetzal')           should be  25 :",  scrabbleScore('quetzal') )
</code>```

答:
As the comments suggested, you should check for the string to be empty with S == ''. The string comparison you had before made no sense, as it was always false.</p>
```<code>def scrabbleScore(S):
    """"Argument S: String argument S
    Return Value: the total Scrabble score :))"""
    if S == '':
        return 0
    else:
        return letterScore(S[0]) + scrabbleScore(S[1:])
</code>```

Title: Scrabble Score Count

Body:
I have been trying to make a scrabble score counter but I end up falling in an infinite loop, I attach my code in case anyone can give me a hand, it personally makes sense, but for some reason Python does not like my code :((

def letterScore(let):
    """Argument let: one character string
    Return Value: the scrabble value of the letter"""
    if let in 'qz':
        return 10
    elif let in 'aelnorstu':
        return 1
    elif let in 'd':
        return 2
    elif let in 'bcmp':
        return 3
    elif let in 'vwy':
        return 4
    elif let in 'k':
        return 5
    elif let in 'x':
        return 8
    else:
        return 0

def scrabbleScore (S):
    """"Argument S: String argument S
    Return Value: the total Scrabble score :))"""

    if "s[0]" == '':
        return 0
    else:
        return letterScore(S[0]) + scrabbleScore (S[1:])

#
# Tests
#
print( "scrabbleScore('quetzal')           should be  25 :",  scrabbleScore('quetzal') )

Body:
As the comments suggested, you should check for the string to be empty with S == ''. The string comparison you had before made no sense, as it was always false.

def scrabbleScore(S):
    """"Argument S: String argument S
    Return Value: the total Scrabble score :))"""
    if S == '':
        return 0
    else:
        return letterScore(S[0]) + scrabbleScore(S[1:])


问:
Failed to evaluate transaction: Error: You've asked to invoke a function that does not exist: getLastPatientId
I want to do inheritance in Hyperledger Fabric Chaincode using NodeJs.
I have created two classes CommonContract and AdminContract. CommonContract is the base class and AdminContract child class. But I got error when I invoke getLastPatiendId function from AdminContract. Error is as follows.

```<code>Failed to evaluate transaction: Error: You've asked to invoke a function that does not exist: getLastPatientId
[nodemon] app crashed - waiting for file changes before starting...
</code>```

Even though getLastPatientId function is written in contract it is giving error function does not exists.

Below are the code of AdminContract, CommonContract, index.js file for chaincode and the server API  which invoke transaction

CommonContract.js

This is CommonContract smart contract which is a base class.

```<code>'use strict';

const { Contract } = require('fabric-contract-api');

class CommonContract extends Contract {

    async initLedger(ctx) {
        console.info('============= START : Initialize Ledger ===========');
        const initData = [
            {
                "firstName": "ABC",
                "middleName": "D",
                "lastName": "BCA",
                "password": "d74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1",
                "age": "16",
                "phoneNumber": "1234567890",
                "address": "India",
                "bloodGroup": "O+ve",
                "updatedBy": "initLedger",
                "symptoms": "fever",
                "diagnosis": "Covid",
                "treatment": "dolo 2 times",
                "other": "no",
            },
            {
                "firstName": "Five",
                "middleName": ".H.",
                "lastName": "CDA",
                "password": "d74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1",
                "age": "16",
                "phoneNumber": "1234567890",
                "address": "India",
                "bloodGroup": "O+ve",
                "updatedBy": "initLedger",
                "symptoms": "fever",
                "diagnosis": "Covid",
                "treatment": "dolo 2 times",
                "other": "no",
            }
        ]

        for (let i = 0; i < initData.length; i++) {
            initData[i].docType = 'patient';
            await ctx.stub.putState('PID' + i, Buffer.from(JSON.stringify(initData[i])));
            console.log('Data Added:---', initData[i]);
        }
    }

    async getPatient(ctx, patientId){
        const patient = await ctx.stub.getState(patientId);
        if(patient.length || patient.length > 0)
        console.log(patient);
        let data = JSON.parse(patient.toString());
        return data;
    }

    async getAllPatient(ctx){
        const startKey = '';
        const endKey = '';
        const allResults = [];
        for await (const {key, value} of ctx.stub.getStateByRange(startKey, endKey)){
            const strValue = Buffer.from(value).toString('utf8');
            let record;
            try {
                record = JSON.parse(strValue);
            } catch (err) {
                console.log(err);
                record = strValue;
            }
            allResults.push({ Key: key, Record: record });
        }
        console.info(allResults);
        return JSON.stringify(allResults);
    }
}

module.exports = CommonContract;
</code>```

AdminContract.js

This is an AdminContract smart contract that inherits CommonContract and has a single function getLastPatientId() it generally returns the patient id of the last patient created in the ledger.

```<code>
'use strict';

let Patient = require('./PatientAssets.js');
const CommonContract = require('./CommonContract.js');

class AdminContract extends CommonContract {

    async getLastPatientId(ctx) {
        let result = await getAllPatient(ctx);
        console.log(result);
        return result[result.length - 1].patiendId;
    }
}

module.exports = AdminContract;
</code>```

index.js

This file is main entry point all smart contract.

```<code>'use strict';

const CommonContract = require('./lib/CommonContract.js');
const AdminContract = require('./lib/AdminContract.js');

module.exports.contracts = [CommonContract, AdminContract];
</code>```

admin.js

This is server side route file which invoke the getLastPatientId function which is in AdminContract.js smart contract file.

```<code>router.get('/getAllPatient', async (req, res) => {
    try {
        // load the network configuration
        const ccpPath = path.resolve(__dirname, '..', '..', 'network-config', 'organizations', 'peerOrganizations', 'doctor.hospital_network.com', 'connection-doctor.json');
        const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));

        // Create a new file system based wallet for managing identities.
        const walletPath = path.join(process.cwd(), 'wallet');
        const wallet = await Wallets.newFileSystemWallet(walletPath);
        console.log(`Wallet path: ${walletPath}`);

        // Check to see if we've already enrolled the user.
        const identity = await wallet.get('appUser1');
        if (!identity) {
            console.log('An identity for the user "appUser" does not exist in the wallet');
            console.log('Run the registerUser.js application before retrying');
            return;
        }

        // Create a new gateway for connecting to our peer node.
        const gateway = new Gateway();
        await gateway.connect(ccp, { wallet, identity: 'appUser1', discovery: { enabled: true, asLocalhost: true } });

        // Get the network (channel) our contract is deployed to.
        const network = await gateway.getNetwork('hospital');

        // Get the contract from the network.
        const contract = network.getContract('basic');

        const result = await contract.evaluateTransaction('getLastPatientId');
        const data = JSON.parse(result);
        console.log(`Transaction has been evaluated, result is: ${result}`);

        // Disconnect from the gateway.
        await gateway.disconnect();
        return data;

    } catch (error) {
        console.error(`Failed to evaluate transaction: ${error}`);
        process.exit(1);
    }
});
</code>```

I found out that evalutateTransaction() invokes the function in CommonContract but was not able to invoke AdminContract functions. Please help me out. What is the error in my code ?

答:
This is because you need to specify the contract name when calling transactions, except for the first contract which is treated as a default. For example, you should be able to successfully call initLedger, CommonContract:initLedger, and AdminContract:getLastPatientId but getLastPatientId will fail because there is no such transaction on the default contract.

You can see what transactions are available, and which contract is the default, by getting the metadata for the contract. You can get the metadata using the org.hyperledger.fabric:GetMetadata transaction, where org.hyperledger.fabric is the system contract and GetMetadata is the transaction. The ccmetadata utility will call that get metadata transaction if that helps.

You can also customise the contract names using a constructor. For example, to call an Admin:getLastPatientId transaction, add the following constructor:

```<code>class AdminContract extends Contract {
    constructor() {
        super('Admin');
    }

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

Note: I don't think it's related to your current problem but I'm not sure why you want to use inheritance in this case. It might cause other problems so I would stick to extending Contract as shown above.

Body:
I want to do inheritance in Hyperledger Fabric Chaincode using NodeJs.
I have created two classes CommonContract and AdminContract. CommonContract is the base class and AdminContract child class. But I got error when I invoke getLastPatiendId function from AdminContract. Error is as follows.

Failed to evaluate transaction: Error: You've asked to invoke a function that does not exist: getLastPatientId
[nodemon] app crashed - waiting for file changes before starting...

Even though getLastPatientId function is written in contract it is giving error function does not exists.

Below are the code of AdminContract, CommonContract, index.js file for chaincode and the server API  which invoke transaction

CommonContract.js

This is CommonContract smart contract which is a base class.

'use strict';

const { Contract } = require('fabric-contract-api');

class CommonContract extends Contract {

    async initLedger(ctx) {
        console.info('============= START : Initialize Ledger ===========');
        const initData = [
            {
                "firstName": "ABC",
                "middleName": "D",
                "lastName": "BCA",
                "password": "d74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1",
                "age": "16",
                "phoneNumber": "1234567890",
                "address": "India",
                "bloodGroup": "O+ve",
                "updatedBy": "initLedger",
                "symptoms": "fever",
                "diagnosis": "Covid",
                "treatment": "dolo 2 times",
                "other": "no",
            },
            {
                "firstName": "Five",
                "middleName": ".H.",
                "lastName": "CDA",
                "password": "d74ff0ee8da3b9806b18c877dbf29bbde50b5bd8e4dad7a3a725000feb82e8f1",
                "age": "16",
                "phoneNumber": "1234567890",
                "address": "India",
                "bloodGroup": "O+ve",
                "updatedBy": "initLedger",
                "symptoms": "fever",
                "diagnosis": "Covid",
                "treatment": "dolo 2 times",
                "other": "no",
            }
        ]

        for (let i = 0; i < initData.length; i++) {
            initData[i].docType = 'patient';
            await ctx.stub.putState('PID' + i, Buffer.from(JSON.stringify(initData[i])));
            console.log('Data Added:---', initData[i]);
        }
    }

    async getPatient(ctx, patientId){
        const patient = await ctx.stub.getState(patientId);
        if(patient.length || patient.length > 0)
        console.log(patient);
        let data = JSON.parse(patient.toString());
        return data;
    }

    async getAllPatient(ctx){
        const startKey = '';
        const endKey = '';
        const allResults = [];
        for await (const {key, value} of ctx.stub.getStateByRange(startKey, endKey)){
            const strValue = Buffer.from(value).toString('utf8');
            let record;
            try {
                record = JSON.parse(strValue);
            } catch (err) {
                console.log(err);
                record = strValue;
            }
            allResults.push({ Key: key, Record: record });
        }
        console.info(allResults);
        return JSON.stringify(allResults);
    }
}

module.exports = CommonContract;

AdminContract.js

This is an AdminContract smart contract that inherits CommonContract and has a single function getLastPatientId() it generally returns the patient id of the last patient created in the ledger.

'use strict';

let Patient = require('./PatientAssets.js');
const CommonContract = require('./CommonContract.js');

class AdminContract extends CommonContract {

    async getLastPatientId(ctx) {
        let result = await getAllPatient(ctx);
        console.log(result);
        return result[result.length - 1].patiendId;
    }
}

module.exports = AdminContract;

index.js

This file is main entry point all smart contract.

'use strict';

const CommonContract = require('./lib/CommonContract.js');
const AdminContract = require('./lib/AdminContract.js');

module.exports.contracts = [CommonContract, AdminContract];

admin.js

This is server side route file which invoke the getLastPatientId function which is in AdminContract.js smart contract file.

router.get('/getAllPatient', async (req, res) => {
    try {
        // load the network configuration
        const ccpPath = path.resolve(__dirname, '..', '..', 'network-config', 'organizations', 'peerOrganizations', 'doctor.hospital_network.com', 'connection-doctor.json');
        const ccp = JSON.parse(fs.readFileSync(ccpPath, 'utf8'));

        // Create a new file system based wallet for managing identities.
        const walletPath = path.join(process.cwd(), 'wallet');
        const wallet = await Wallets.newFileSystemWallet(walletPath);
        console.log(`Wallet path: ${walletPath}`);

        // Check to see if we've already enrolled the user.
        const identity = await wallet.get('appUser1');
        if (!identity) {
            console.log('An identity for the user "appUser" does not exist in the wallet');
            console.log('Run the registerUser.js application before retrying');
            return;
        }

        // Create a new gateway for connecting to our peer node.
        const gateway = new Gateway();
        await gateway.connect(ccp, { wallet, identity: 'appUser1', discovery: { enabled: true, asLocalhost: true } });

        // Get the network (channel) our contract is deployed to.
        const network = await gateway.getNetwork('hospital');

        // Get the contract from the network.
        const contract = network.getContract('basic');

        const result = await contract.evaluateTransaction('getLastPatientId');
        const data = JSON.parse(result);
        console.log(`Transaction has been evaluated, result is: ${result}`);

        // Disconnect from the gateway.
        await gateway.disconnect();
        return data;

    } catch (error) {
        console.error(`Failed to evaluate transaction: ${error}`);
        process.exit(1);
    }
});

I found out that evalutateTransaction() invokes the function in CommonContract but was not able to invoke AdminContract functions. Please help me out. What is the error in my code ?

Body:
This is because you need to specify the contract name when calling transactions, except for the first contract which is treated as a default. For example, you should be able to successfully call initLedger, CommonContract:initLedger, and AdminContract:getLastPatientId but getLastPatientId will fail because there is no such transaction on the default contract.

You can see what transactions are available, and which contract is the default, by getting the metadata for the contract. You can get the metadata using the org.hyperledger.fabric:GetMetadata transaction, where org.hyperledger.fabric is the system contract and GetMetadata is the transaction. The ccmetadata utility will call that get metadata transaction if that helps.

You can also customise the contract names using a constructor. For example, to call an Admin:getLastPatientId transaction, add the following constructor:

class AdminContract extends Contract {
    constructor() {
        super('Admin');
    }

    //...
}

Note: I don't think it's related to your current problem but I'm not sure why you want to use inheritance in this case. It might cause other problems so I would stick to extending Contract as shown above.


问:
How to visit pre-defined URLs from file
If I have 30 pages to check, for example, EN has a disclaimer, but other 29 language don't, what would be the best way to do this? For example, right now I have it like this:

const urls = ['http://google.com/en',
  'http://google.com/bg'
]

describe('Disclaimer check', () => {
  urls.forEach((url) => {
    it(`Checks disclaimer text ${url}`, () => {
      cy.visit(url)
      cy.get('.Disclaimer').should('be.visible')
        .and('contain', 'This is disclaimer.')
    })
  })
})```

For 2 sites it's fine to define them in the same code but other file that checks that Disclaimer isn't there would be 29 different URL-s. What would be the best practice here? One idea is to separate all the test but that would mean 30 tests for each feature which doesn't sound too great.

As url I'm working with uses many different values in it, making it short with baseurl doesn't seem to fit also.

Thank you in advance!

答:
Adding all of your data to a data object, import that data object, and then using Cypress Lodash to iterate a number of times should achieve your goal.

// data.js
// defining data
export const data =[{
  "url": "www.google.com",
  "hasDisclaimer": true
}, {
  "url": "www.other-url.com",
  "hasDisclaimer": false
}...
]
```
<p>You can then wrap the returned array and use it in a Cypress chain.</p>
<pre class="lang-js prettyprint-override"><code>import { data } from './path/to/data'

describe('Tests', () => {
  Cypress._.times(data.length, (index) => {
    const curr = data[index];
    it(`Checks disclaimer text ${curr.url}`, () => {
      cy.visit(curr.url).then(() => {
        if (curr.hasDisclaimer) {
          cy.get('.Disclaimer').should('be.visible')
          .and('contain', 'This is disclaimer.');
        } else {
          // code for checking disclaimer does not exist
        }
      });
    });
  });
});

</code>```

Title: How to visit pre-defined URLs from file

Body:
If I have 30 pages to check, for example, EN has a disclaimer, but other 29 language don't, what would be the best way to do this? For example, right now I have it like this:

const urls = ['http://google.com/en',
  'http://google.com/bg'
]

describe('Disclaimer check', () => {
  urls.forEach((url) => {
    it(`Checks disclaimer text ${url}`, () => {
      cy.visit(url)
      cy.get('.Disclaimer').should('be.visible')
        .and('contain', 'This is disclaimer.')
    })
  })
})

For 2 sites it's fine to define them in the same code but other file that checks that Disclaimer isn't there would be 29 different URL-s. What would be the best practice here? One idea is to separate all the test but that would mean 30 tests for each feature which doesn't sound too great.

As url I'm working with uses many different values in it, making it short with baseurl doesn't seem to fit also.

Thank you in advance!

Body:
Adding all of your data to a data object, import that data object, and then using Cypress Lodash to iterate a number of times should achieve your goal.

// data.js
// defining data
export const data =[{
  "url": "www.google.com",
  "hasDisclaimer": true
}, {
  "url": "www.other-url.com",
  "hasDisclaimer": false
}...
]

You can then wrap the returned array and use it in a Cypress chain.

import { data } from './path/to/data'

describe('Tests', () => {
  Cypress._.times(data.length, (index) => {
    const curr = data[index];
    it(`Checks disclaimer text ${curr.url}`, () => {
      cy.visit(curr.url).then(() => {
        if (curr.hasDisclaimer) {
          cy.get('.Disclaimer').should('be.visible')
          .and('contain', 'This is disclaimer.');
        } else {
          // code for checking disclaimer does not exist
        }
      });
    });
  });
});


问:
Custom FragmentDialog with round corners and not 100% screen width
I am creating a custom fragment dialog with round corners and with layout that would not fill the screen width (I would prefer if it just wrapped its content).

this is my rounded_dialog.xml in drawable folder, which is called by my Custom ThemeWithCorners as a background for the dialog. I also tried to set it as background to the linear layout which creates its content but nothing works.

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid android:color="@android:color/white"/>
<corners android:radius="20dp"
/>
</shape>
</code>```

and this is how i call the dialog:

```<code>final String FTAG = "TAG_FRAGMENT_DIALOG_CALENDAR";
    dialog = (CalendarDialog) fm.findFragmentByTag(FTAG);
    ft = fm.beginTransaction();
    if (dialog != null)
    {
        ft.remove(dialog);
    }
    dialog = CalendarDialog.newInstance(this);
    dialog.setCancelable(true);

    ft.add(dialog, FTAG);
    ft.show(dialog);
    ft.commit();
</code>```

In onCreate method of the dialog I set the style and theme:

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(DialogFragment.STYLE_NO_TITLE, R.style.ThemeWithCorners);
}
</code>```

This is the onCreateView method:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
getDialog().setCanceledOnTouchOutside(true);
v = (MyCalendar)inflater.inflate(R.layout.calendar_dialog, container, true)
    return v;
}
</code>```

I also tried to add this to onCreateDialog method as other answers on SO suggested but did not work either:

```<code>@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    Dialog d =  super.onCreateDialog(savedInstanceState);
    LayoutParams lp=d.getWindow().getAttributes();
    d.getWindow().setBackgroundDrawable(new ColorDrawable(0));
    lp.width=-2;lp.height=-2;lp.gravity=Gravity.CENTER;
    lp.dimAmount=0;
    lp.flags=LayoutParams.FLAG_LAYOUT_NO_LIMITS | LayoutParams.FLAG_NOT_TOUCH_MODAL;

    return d;
}
</code>```

So to sum it up, I want round corners, not 100% width of the screen, it preferably should wrap its content. Please, please, I need some help, I am really desperate about this, I´v ebeen trying it for days!

答:
There is a quick fix for DialogFragment. For example, in the method onCreateDialog() add style in AlertDialog.Builder(context, style):

```<code>@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    View view = LayoutInflater.from(getActivity()).inflate(R.layout.custom_dialog_lauout, null);
    return new AlertDialog.Builder(getActivity(), R.style.custom_alert_dialog)
            .setView(view)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int i) {
                    // do something
                }
            })
            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            })
            .create();
}
</code>```

In styles folder custom_alert_dialog

```<code><style name="custom_alert_dialog" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:windowBackground">@drawable/corner_background</item>
</style>
</code>```

In drawable folder corner_background.xml

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<corners android:radius="8dp" />
</code>```

It's tested for API >= 21

Body:
I am creating a custom fragment dialog with round corners and with layout that would not fill the screen width (I would prefer if it just wrapped its content).

this is my rounded_dialog.xml in drawable folder, which is called by my Custom ThemeWithCorners as a background for the dialog. I also tried to set it as background to the linear layout which creates its content but nothing works.

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid android:color="@android:color/white"/>
<corners android:radius="20dp"
/>
</shape>

and this is how i call the dialog:

final String FTAG = "TAG_FRAGMENT_DIALOG_CALENDAR";
    dialog = (CalendarDialog) fm.findFragmentByTag(FTAG);
    ft = fm.beginTransaction();
    if (dialog != null)
    {
        ft.remove(dialog);
    }
    dialog = CalendarDialog.newInstance(this);
    dialog.setCancelable(true);

    ft.add(dialog, FTAG);
    ft.show(dialog);
    ft.commit();

In onCreate method of the dialog I set the style and theme:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(DialogFragment.STYLE_NO_TITLE, R.style.ThemeWithCorners);
}

This is the onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
getDialog().setCanceledOnTouchOutside(true);
v = (MyCalendar)inflater.inflate(R.layout.calendar_dialog, container, true)
    return v;
}

I also tried to add this to onCreateDialog method as other answers on SO suggested but did not work either:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    Dialog d =  super.onCreateDialog(savedInstanceState);
    LayoutParams lp=d.getWindow().getAttributes();
    d.getWindow().setBackgroundDrawable(new ColorDrawable(0));
    lp.width=-2;lp.height=-2;lp.gravity=Gravity.CENTER;
    lp.dimAmount=0;
    lp.flags=LayoutParams.FLAG_LAYOUT_NO_LIMITS | LayoutParams.FLAG_NOT_TOUCH_MODAL;

    return d;
}

So to sum it up, I want round corners, not 100% width of the screen, it preferably should wrap its content. Please, please, I need some help, I am really desperate about this, I´v ebeen trying it for days!

Body:
There is a quick fix for DialogFragment. For example, in the method onCreateDialog() add style in AlertDialog.Builder(context, style):

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    View view = LayoutInflater.from(getActivity()).inflate(R.layout.custom_dialog_lauout, null);
    return new AlertDialog.Builder(getActivity(), R.style.custom_alert_dialog)
            .setView(view)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int i) {
                    // do something
                }
            })
            .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            })
            .create();
}

In styles folder custom_alert_dialog

<style name="custom_alert_dialog" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:windowBackground">@drawable/corner_background</item>
</style>

In drawable folder corner_background.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF" />
<corners android:radius="8dp" />

It's tested for API >= 21