问:
CSSRuleList traversing, Error not iterable
```<code>for(var ss of document.styleSheets){
  for(var cssrule of ss.cssRules){continue;}}
</code>```

document.styleSheets is of type StyleSheetList, it has a [Symbol.iterator] so it is iterable. It is populated by a number of CSSStyleSheet objects that have a cssRules property pointing to a CSSRuleList which has a [Symbol.iterator] so it should be iterable too.

In theory the code should work but it throws an error ( "ss.cssRules not iterable" ), is this behaviour intended?

答:
In typescript due to this bug (sadly yet not fixed) I was forced to use following solution

for(let ssIdx=0; ssIdx < document.styleSheets.length; ssIdx++) {
  let ss = document.styleSheets[ssIdx];

  for(let cssrule of [...ss.cssRules] ) {
    continue;
  }
}
```

Body:
for(var ss of document.styleSheets){
  for(var cssrule of ss.cssRules){continue;}}

document.styleSheets is of type StyleSheetList, it has a [Symbol.iterator] so it is iterable. It is populated by a number of CSSStyleSheet objects that have a cssRules property pointing to a CSSRuleList which has a [Symbol.iterator] so it should be iterable too.

In theory the code should work but it throws an error ( "ss.cssRules not iterable" ), is this behaviour intended?


来源: stackexchange

问:
Save a numpy ndarray (1, 160, 160) into a grayscale image
I have a (5200, 1, 160, 160) array that I could iterate.
How can I save (1, 160, 160) array into grayscale image?</p>

答:
Suppose gray has shape (1, 160, 160) which you want to save in grayscale, then you can do this:

```<code>cv2.imwrite('gray_image.png', gray[0])
</code>```

I suppose you know how to iterate thrpugh the main array. If this does not solve your question let me know.

ContentLicense: CC BY-SA 4.0

Body:
Suppose gray has shape (1, 160, 160) which you want to save in grayscale, then you can do this:

cv2.imwrite('gray_image.png', gray[0])

I suppose you know how to iterate thrpugh the main array. If this does not solve your question let me know.


问:
How to have multiple instances of jQuery plugin on single page?
I'm writing a simple jQuery plugin, but I'm having trouble being able to use multiple instances on a page.

For instance, here is a sample plugin to illustrate my point:

```<code>(function($) {
  $.fn.samplePlugin = function(options) {
    if (typeof foo != 'undefined')
    {
      alert('Already defined!');
    } else {
      var foo = 'bar';
    }
  };
})(jQuery);
</code>```

And then if I do this:

```<code>$(document).ready(function(){
  $('#myDiv').samplePlugin({}); // does nothing
  $('#myDiv2').samplePlugion({}); // alerts "Already defined!"
});
</code>```

This is obviously an over-simplified example to get across the point. So my question is, how do I have two separate instances of the plugin? I'd like to be able to use it across multiple instances on the same page.

I'm guessing that part of the problem might be with defining the variables in a global scope. How can I define them unique to that instance of the plugin then?

Thank you for your guidance!

答:
instead of writing this

```<code>$("#divid1").samplePlugin();
$("#divid2").samplePlugin();
</code>```

you can do this way

```<code>$.plugin('samplePlugin1', samplePlugin);
$("#divid1").samplePlugin1();

$.plugin('samplePlugin2', samplePlugin);
$("#divid2").samplePlugin2();
</code>```

You can have much details from here
http://alexsexton.com/?p=51

ContentLicense: CC BY-SA 2.5

Body:
I'm writing a simple jQuery plugin, but I'm having trouble being able to use multiple instances on a page.

For instance, here is a sample plugin to illustrate my point:

(function($) {
  $.fn.samplePlugin = function(options) {
    if (typeof foo != 'undefined')
    {
      alert('Already defined!');
    } else {
      var foo = 'bar';
    }
  };
})(jQuery);

And then if I do this:

$(document).ready(function(){
  $('#myDiv').samplePlugin({}); // does nothing
  $('#myDiv2').samplePlugion({}); // alerts "Already defined!"
});

This is obviously an over-simplified example to get across the point. So my question is, how do I have two separate instances of the plugin? I'd like to be able to use it across multiple instances on the same page.

I'm guessing that part of the problem might be with defining the variables in a global scope. How can I define them unique to that instance of the plugin then?

Thank you for your guidance!

Body:
instead of writing this

$("#divid1").samplePlugin();
$("#divid2").samplePlugin();

you can do this way

$.plugin('samplePlugin1', samplePlugin);
$("#divid1").samplePlugin1();

$.plugin('samplePlugin2', samplePlugin);
$("#divid2").samplePlugin2();

You can have much details from here
http://alexsexton.com/?p=51

ContentLicense: CC BY-SA 3.0


问:
How to show Valid or Invalid Snackbar when user enters the credential in Flutter?
When the user enter wrong credentials the snackbar should show Login Failed and when right page should show successfully logged in snackbar.
I have used firebase to authentication.

```<code>  final _formKey = GlobalKey<FormState>();
  TextEditingController _emailLoginFormTextEditingController = new TextEditingController();
  TextEditingController _passwordLoginFormTextEditingController = new TextEditingController();

  void initState() {
    super.initState();
  }

  _signInUsingFirebase(String email, String password) {
    FirebaseAuth firebaseAuth = FirebaseAuth.instance;
    firebaseAuth.signInWithEmailAndPassword(email: email, password: password)
        .then((AuthResult authResult) {
      FirebaseUser user = authResult.user;
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => HomePage(email: email, userid: user.uid,),
      ));
    }).catchError((error) {
      debugPrint(error);
    });
  }

  Widget _loginPageSaffoldBody(BuildContext context) {
    return Form(
      key: _formKey,
      child: ListView(
        padding: EdgeInsets.all(32),
        children: <Widget>[
          TextFormField(
            controller: _emailLoginFormTextEditingController,
          ),
          TextFormField(
            controller: _passwordLoginFormTextEditingController,
          ),
          RaisedButton(
            onPressed: () {
              // If statement is validating the input fields.
              if (_formKey.currentState.validate()) {
                _signInUsingFirebase(_emailLoginFormTextEditingController.text,
                    _passwordLoginFormTextEditingController.text);
                Scaffold.of(context).showSnackBar(                          //Snackbar for Succesfull
                  SnackBar(
                    content: Text(
                      "Succesfull",
                    ),
                  ),
                );
              }
              else{
                Scaffold.of(context).showSnackBar(                        //Snackbar for unsuccesfull
                  SnackBar(
                    content: Text(
                      "Unsuccesfull",
                    ),
                  ),
                );
              }
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Icon(
                  Icons.lock_open,
                ),
                SizedBox(width: 4),
                Text(
                  "Submit",
                ),
              ],
            ),
          ), // Submit Button
        ],
      ),
    );
  }
</code>```

A little out of context question I also want to keep user logged in once they enter the credentials till they login in i want to use shared preference but unable to understand how if u can provide any link might help
Thank You !

答:
Declare a Key:- key:_scaffoldKey, in scaffold

Declare final _scaffoldKey = GlobalKey<ScaffoldState>();

Then simply initialize it in .catchError((error) and .then((AuthResult authResult)

```<code>final snackBar = SnackBar(content: Text("Succesfully LoggedIn"));
      _scaffoldKey.currentState.showSnackBar(snackBar);
</code>```

Body:
When the user enter wrong credentials the snackbar should show Login Failed and when right page should show successfully logged in snackbar.
I have used firebase to authentication.

  final _formKey = GlobalKey<FormState>();
  TextEditingController _emailLoginFormTextEditingController = new TextEditingController();
  TextEditingController _passwordLoginFormTextEditingController = new TextEditingController();

  void initState() {
    super.initState();
  }

  _signInUsingFirebase(String email, String password) {
    FirebaseAuth firebaseAuth = FirebaseAuth.instance;
    firebaseAuth.signInWithEmailAndPassword(email: email, password: password)
        .then((AuthResult authResult) {
      FirebaseUser user = authResult.user;
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) => HomePage(email: email, userid: user.uid,),
      ));
    }).catchError((error) {
      debugPrint(error);
    });
  }

  Widget _loginPageSaffoldBody(BuildContext context) {
    return Form(
      key: _formKey,
      child: ListView(
        padding: EdgeInsets.all(32),
        children: <Widget>[
          TextFormField(
            controller: _emailLoginFormTextEditingController,
          ),
          TextFormField(
            controller: _passwordLoginFormTextEditingController,
          ),
          RaisedButton(
            onPressed: () {
              // If statement is validating the input fields.
              if (_formKey.currentState.validate()) {
                _signInUsingFirebase(_emailLoginFormTextEditingController.text,
                    _passwordLoginFormTextEditingController.text);
                Scaffold.of(context).showSnackBar(                          //Snackbar for Succesfull
                  SnackBar(
                    content: Text(
                      "Succesfull",
                    ),
                  ),
                );
              }
              else{
                Scaffold.of(context).showSnackBar(                        //Snackbar for unsuccesfull
                  SnackBar(
                    content: Text(
                      "Unsuccesfull",
                    ),
                  ),
                );
              }
            },
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Icon(
                  Icons.lock_open,
                ),
                SizedBox(width: 4),
                Text(
                  "Submit",
                ),
              ],
            ),
          ), // Submit Button
        ],
      ),
    );
  }

A little out of context question I also want to keep user logged in once they enter the credentials till they login in i want to use shared preference but unable to understand how if u can provide any link might help
Thank You !

Body:
Declare a Key:- key:_scaffoldKey, in scaffold

Declare final _scaffoldKey = GlobalKey<ScaffoldState>();

Then simply initialize it in .catchError((error) and .then((AuthResult authResult)

final snackBar = SnackBar(content: Text("Succesfully LoggedIn"));
      _scaffoldKey.currentState.showSnackBar(snackBar);


问:
Need understand "ulimit"'s nofile setting in host and container
As I know if we need adjust "open files" nofile (soft and hard) in linux system, we need run command ulimit or set in related configuraiton file to get the setting permanently. But I am little bit confused about the setting for containers running in a host

For example, If a Linux OS has ulimit nofile set to 1024 (soft) and Hard (4096) , and I run docker with --ulimit nofile=10240:40960, could the container use more nofiles than its host?

Update

In my environment, current setting with dockers running,

On host (Debian)-  65535 (soft) 65535 (hard)

Docker Daemon setting Max - 1048576 (soft) 1048576 (hard)

default docker run - 1024 (soft) 4096 (hard)

customized docker run - 10240 (soft) 40960 (hard)

I found the application can run with about 100K open files, then crash. How to understand this?

What's the real limits?

答:
For example, If a Linux OS has ulimit nofile set to 1024 (soft) and Hard (4096) , and I run docker with ----ulimit nofile=10240:40960, could the container use more nofiles than its host?

Docker has the CAP_SYS_RESOURCE capability set on it's permissions.
This means that Docker is able to set an ulimit different from the host. according to man 2 prlimit:

A privileged process (under Linux: one with the CAP_SYS_RESOURCE capability in the initial user namespace) may make arbitrary changes to either limit value.

So, for containers, the limits to be considered are the ones set by the docker daemon.
You can check the docker daemon limits with this command:

```<code>$ cat /proc/$(ps -A | grep dockerd | awk '{print $1}')/limits | grep "files"
Max open files            1048576              1048576              files
</code>```

As you can see, the docker 19 has a pretty high limit of 1048576 so your 40960 will work like a charm.

And if you run a docker container with --ulimit set to be higher than the node but lower than the daemon itself, you won't find any problem, and won't need to give additional permissions like in the example bellow:

```<code>$ cat /proc/$(ps -A | grep dockerd | awk '{print $1}')/limits | grep "files"
Max open files            1048576              1048576              files

$ docker run -d -it --rm --ulimit nofile=99999:99999 python python;
354de39a75533c7c6e31a1773a85a76e393ba328bfb623069d57c38b42937d03

$ cat /proc/$(ps -A | grep python | awk '{print $1}')/limits | grep "files"
Max open files            99999                99999                files
</code>```

You can set a new limit for dockerd on the file /etc/init.d/docker:

```<code>$ cat /etc/init.d/docker | grep ulimit
                ulimit -n 1048576
</code>```

As for the container itself having a ulimit higher than the docker daemon, it's a bit more tricky, but doable, refer here.

I saw you have tagged the Kubernetes tag, but didn't mention it in your question, but in order to make it work on Kubernetes, the container will need securityContext.priviledged: true, this way you can run the command ulimit as root inside the container, here an example:

```<code>image: image-name
  command: ["sh", "-c", "ulimit -n 65536"]
  securityContext:
    privileged: true
</code>```

Body:
For example, If a Linux OS has ulimit nofile set to 1024 (soft) and Hard (4096) , and I run docker with ----ulimit nofile=10240:40960, could the container use more nofiles than its host?

Docker has the CAP_SYS_RESOURCE capability set on it's permissions.
This means that Docker is able to set an ulimit different from the host. according to man 2 prlimit:

A privileged process (under Linux: one with the CAP_SYS_RESOURCE capability in the initial user namespace) may make arbitrary changes to either limit value.

So, for containers, the limits to be considered are the ones set by the docker daemon.
You can check the docker daemon limits with this command:

$ cat /proc/$(ps -A | grep dockerd | awk '{print $1}')/limits | grep "files"
Max open files            1048576              1048576              files

As you can see, the docker 19 has a pretty high limit of 1048576 so your 40960 will work like a charm.

And if you run a docker container with --ulimit set to be higher than the node but lower than the daemon itself, you won't find any problem, and won't need to give additional permissions like in the example bellow:

$ cat /proc/$(ps -A | grep dockerd | awk '{print $1}')/limits | grep "files"
Max open files            1048576              1048576              files

$ docker run -d -it --rm --ulimit nofile=99999:99999 python python;
354de39a75533c7c6e31a1773a85a76e393ba328bfb623069d57c38b42937d03

$ cat /proc/$(ps -A | grep python | awk '{print $1}')/limits | grep "files"
Max open files            99999                99999                files

You can set a new limit for dockerd on the file /etc/init.d/docker:

$ cat /etc/init.d/docker | grep ulimit
                ulimit -n 1048576

As for the container itself having a ulimit higher than the docker daemon, it's a bit more tricky, but doable, refer here.

I saw you have tagged the Kubernetes tag, but didn't mention it in your question, but in order to make it work on Kubernetes, the container will need securityContext.priviledged: true, this way you can run the command ulimit as root inside the container, here an example:

image: image-name
  command: ["sh", "-c", "ulimit -n 65536"]
  securityContext:
    privileged: true


问:
Search static data from array based on route variable?
I'm trying to search for a specific object in an array that has a unique slug that matches a variable in an array.
I am receiving an error when trying to use the switchmap without .valueChanges at the end of the return statement below, but I receive an error when using the valuechanges as well saying that it doesn't exist on "type 'void'".

Component

```<code>post$;
  constructor(private nrs: NewsroomService, private route: ActivatedRoute) { }

  ngOnInit() {
    this.post$ = this.route.paramMap.pipe(
      switchMap(params => {
        const post = params.get('slug');
        return this.nrs.postSearch(post).valueChanges();
      })
    );
  }
</code>```

Here's the function from in the service:

```<code>postSearch(slug: string) {
    var __FOUND = -1;
        for(var i=0; i<this.posts.length; i++) {
            if(this.posts[i].postURL == slug) {
                // __FOUND is set to the index of the element
                __FOUND = i;
                break;
            }
        }
  }
</code>```

I wasn't quite sure where to go from here in trying to resolve this.

答:
I fixed the issue by updating the post component to this:

```<code>post$: any;
  constructor(private nrs: NewsroomService, private route: ActivatedRoute) { }
  ngOnInit() {
    this.post$ = this.route.paramMap.pipe(
        map(params => {
          const post = params.get('slug');
          return this.nrs.postSearch(post);
        })
      );
    }
</code>```

and changing the service function to this:

```<code>postSearch(slug: string) {
    var __FOUND = -1;
        for(var i=0; i<this.posts.length; i++) {
            if(this.posts[i].postURL == slug) {
                // __FOUND is set to the index of the element
                __FOUND = i;
                return this.posts[__FOUND];
            }
        }
  }
</code>```

Body:
I'm trying to search for a specific object in an array that has a unique slug that matches a variable in an array.
I am receiving an error when trying to use the switchmap without .valueChanges at the end of the return statement below, but I receive an error when using the valuechanges as well saying that it doesn't exist on "type 'void'".

Component

post$;
  constructor(private nrs: NewsroomService, private route: ActivatedRoute) { }

  ngOnInit() {
    this.post$ = this.route.paramMap.pipe(
      switchMap(params => {
        const post = params.get('slug');
        return this.nrs.postSearch(post).valueChanges();
      })
    );
  }

Here's the function from in the service:

postSearch(slug: string) {
    var __FOUND = -1;
        for(var i=0; i<this.posts.length; i++) {
            if(this.posts[i].postURL == slug) {
                // __FOUND is set to the index of the element
                __FOUND = i;
                break;
            }
        }
  }

I wasn't quite sure where to go from here in trying to resolve this.

Body:
I fixed the issue by updating the post component to this:

post$: any;
  constructor(private nrs: NewsroomService, private route: ActivatedRoute) { }
  ngOnInit() {
    this.post$ = this.route.paramMap.pipe(
        map(params => {
          const post = params.get('slug');
          return this.nrs.postSearch(post);
        })
      );
    }

and changing the service function to this:

postSearch(slug: string) {
    var __FOUND = -1;
        for(var i=0; i<this.posts.length; i++) {
            if(this.posts[i].postURL == slug) {
                // __FOUND is set to the index of the element
                __FOUND = i;
                return this.posts[__FOUND];
            }
        }
  }


问:
How to color one of a 100 boxes with a button in a modal using javascript
Just to make it easier Im explaining what I wish to do in a simplified example.

I have 100 boxes on my site using simple html/css. (styling not shown)

I have written a bit of JS to open a modal that opens when clicking on one of the 100 boxes carrying the same class: class="boxes":

The modal has an Id of "modal":

```<code>var modal = document.getElementById("modal");
var boxes = document.getElementsByClassName("box");
var boxesLength = boxes.length;
</code>```

When any box is clicked the modal appears:

```<code>    for (var i = 0; i < boxesLength; i++) {
    boxes[i].onclick = function () {
    modal.style.display = "block";
    };
    }
</code>```

Now I wish to color the box  that was clicked using a button in the modal that was opened. The code that doesn't work but is my closest guess looks like this:

```<code>//get the coloring button in the modal which has Id of "green".

var coloring = document.getElementById("green");

coloring.onclick = function () {
boxes[i].style.backgroundColor = "#90EE90";
//closing the modal after clicking which works
modal.style.display = "none";
};
</code>```

Writing "boxes[0]" will color the first box, but that is of course not what I wish. I wish to color the box that was clicked.

Thank you for any input. Good day!

on request ive added som simple html

```<code>    //The modal
    <div id="modal">
            <button id="green">Completed</button>
    </div>

    //just some boxes
    <div class="boxes"></div>
    <div class="boxes"></div>
    <div class="boxes"></div>
    <div class="boxes"></div>
    .... 96 more boxes
</code>```

答:
I figured it out using "this":</p>

```<code>    for (var i = 0; i < boxesLength; i++) {
      boxes[i].onclick = function () {
        modal.style.display = "block";
        var koko = this;
        green.onclick = function () {
          koko.style.backgroundColor = "#90EE90";
          modal.style.display = "none";
        };
      };
</code>```

Body:
Just to make it easier Im explaining what I wish to do in a simplified example.

I have 100 boxes on my site using simple html/css. (styling not shown)

I have written a bit of JS to open a modal that opens when clicking on one of the 100 boxes carrying the same class: class="boxes":

The modal has an Id of "modal":

var modal = document.getElementById("modal");
var boxes = document.getElementsByClassName("box");
var boxesLength = boxes.length;

When any box is clicked the modal appears:

    for (var i = 0; i < boxesLength; i++) {
    boxes[i].onclick = function () {
    modal.style.display = "block";
    };
    }

Now I wish to color the box  that was clicked using a button in the modal that was opened. The code that doesn't work but is my closest guess looks like this:

//get the coloring button in the modal which has Id of "green".

var coloring = document.getElementById("green");

coloring.onclick = function () {
boxes[i].style.backgroundColor = "#90EE90";
//closing the modal after clicking which works
modal.style.display = "none";
};

Writing "boxes[0]" will color the first box, but that is of course not what I wish. I wish to color the box that was clicked.

Thank you for any input. Good day!

on request ive added som simple html

    //The modal

            <button id="green">Completed</button>

    //just some boxes

    .... 96 more boxes

Body:
I figured it out using "this":

    for (var i = 0; i < boxesLength; i++) {
      boxes[i].onclick = function () {
        modal.style.display = "block";
        var koko = this;
        green.onclick = function () {
          koko.style.backgroundColor = "#90EE90";
          modal.style.display = "none";
        };
      };


问:
Catching OutOfMemoryError
Is there any point catching an out of memory error (java.lang.OutOfMemoryError) in Java?

答:
As some other answers have pointed out, it is a bad idea to catch OutOfMemoryError and attempt to recover1.  Rather than just repeating that the javadoc says you Error exceptions are not recoverable, I'll try to explain why.

In fact there are at least two solid reasons why OOME recovery is unwise:

The First Reason is that OOME's are typically the result of undiagnosed memory leaks.  If your application catches and attempts to recover, the chances are that the leaked memory will still be reachable and hence still won't be reclaimed.  So when your application starts doing things it is likely to leak more memory ... and run into another OOME.  Sooner or later, the application grinds to a halt.

Since there is no way you can be absolutely sure that your application doesn't leak, OOME recovery is never going to be a solid, reliable answer.

The Second Reason is that when an OOME occurs, there is a chance that it will do damage to the execution state.  It might cause threads to terminate, leaving other threads waiting for notifications that will never arrive, etc.  It might occur in the middle of updating a critical application data structure or (possibly worse) a JVM data structure.  If your application then attempts to recover, it might lock up, or (worse) it might manage to keep going with corrupted data, and produce unpredictable results.

Unless you perform a forensic analysis of your codebase, you can never be entirely sure that this kind of thing won't happen.

I won't say you should NEVER attempt to recover from an OOME, but in general it is a risky thing to do.  And the more complex your application is, the harder it is to evaluate the risk.

1 - Here I am talking about catching OOME in an attempt to allow the application to continue running as before; i.e. to recover the application.  Catching an OOME in order to perform (or trigger) an orderly shutdown is a different matter.

Title: Catching OutOfMemoryError


问:
Typescript : SyntaxError: Unexpected token 'export'
IN my React project I have need to share models(typescript interfaces in my case) between 3 typescript projects. So I opted for bit.env and imported all my models to https://bit.dev/model/index/~code and its all good.

Then I had a need to verify fields in my model so I added utility functions to https://bit.dev/model/index/~code#util.ts and deployed the same to bit.env

I started facing following error when I tried to use this helper function in my project #2 (place where I keep firebase cloud functions).

```<code>/Users/vinoth.gopu/Documents/mine/oss/Cloud/functions/node_modules/@bit/model.index/dist/index.js:1
export * from './admin';
^^^^^^

SyntaxError: Unexpected token 'export'
    at wrapSafe (internal/modules/cjs/loader.js:1101:16)
    at Module._compile (internal/modules/cjs/loader.js:1149:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1205:10)

</code>```

My code in project #2

```<code>export const placeOrder = functions
    .runWith({
        memory:'256MB'
    })
    .region(cloudConfig.firebase.region)
    .firestore
    .document('Orders/{OrderId}')
    .onCreate((snap, context) => {
        const orderDetails = snap.data() as UserOrders;

        try {
            //check if all fields of interface implemented
            if(isOrder(orderDetails)) { // PROBLEM HERE
                 //do something
            }

</code>```

As pointed out in the code above I can use all interfaces from that model project but helper function throwing error message.

I referred to these articles and links

Getting Unexpected Token Export

https://medium.com/the-node-js-collection/an-update-on-es6-modules-in-node-js-42c958b890c

But none of them seems to work(also I was bit confused which project needs transpilation shared model or Project #2 in my case?). I can understand that this is some problem with node where it cant recognise ES6 module and requires some sort of intermediate transpilation. But I am wondering how all interfaces with similar export statement are working very fine. I would like to understand what am I missing here.

答:
It seems answer lies within bit.dev </p>

```<code>"bit": {
    "env": {
      "compiler": {
        "bit.envs/compilers/react-typescript@3.1.52": {
          "rawConfig": {
            "tsconfig": {
              "compilerOptions": {
                "target": "ES5",
                "module": "CommonJS"
              }
            }
          }
        }
      }
    },
    "componentsDefaultDirectory": "src/{name}",
    "packageManager": "npm"
  },
</code>```

<p>Solved my issue by taking care of transpilation. </p>

Body:
IN my React project I have need to share models(typescript interfaces in my case) between 3 typescript projects. So I opted for bit.env and imported all my models to https://bit.dev/model/index/~code and its all good.

Then I had a need to verify fields in my model so I added utility functions to https://bit.dev/model/index/~code#util.ts and deployed the same to bit.env

I started facing following error when I tried to use this helper function in my project #2 (place where I keep firebase cloud functions).

/Users/vinoth.gopu/Documents/mine/oss/Cloud/functions/node_modules/@bit/model.index/dist/index.js:1
export * from './admin';
^^^^^^

SyntaxError: Unexpected token 'export'
    at wrapSafe (internal/modules/cjs/loader.js:1101:16)
    at Module._compile (internal/modules/cjs/loader.js:1149:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1205:10)

My code in project #2

export const placeOrder = functions
    .runWith({
        memory:'256MB'
    })
    .region(cloudConfig.firebase.region)
    .firestore
    .document('Orders/{OrderId}')
    .onCreate((snap, context) => {
        const orderDetails = snap.data() as UserOrders;

        try {
            //check if all fields of interface implemented
            if(isOrder(orderDetails)) { // PROBLEM HERE
                 //do something
            }

As pointed out in the code above I can use all interfaces from that model project but helper function throwing error message.

I referred to these articles and links

Getting Unexpected Token Export

https://medium.com/the-node-js-collection/an-update-on-es6-modules-in-node-js-42c958b890c

But none of them seems to work(also I was bit confused which project needs transpilation shared model or Project #2 in my case?). I can understand that this is some problem with node where it cant recognise ES6 module and requires some sort of intermediate transpilation. But I am wondering how all interfaces with similar export statement are working very fine. I would like to understand what am I missing here.

Body:
It seems answer lies within bit.dev

"bit": {
    "env": {
      "compiler": {
        "bit.envs/compilers/react-typescript@3.1.52": {
          "rawConfig": {
            "tsconfig": {
              "compilerOptions": {
                "target": "ES5",
                "module": "CommonJS"
              }
            }
          }
        }
      }
    },
    "componentsDefaultDirectory": "src/{name}",
    "packageManager": "npm"
  },

Solved my issue by taking care of transpilation.


问:
C++, = operator different options
I Wrote the following function for = operator:

```<code>Set& Set::operator=(const Set& s)
{
    delete[] data;
    data=new int [s.size];
    size=s.size;
    maxSize=s.size;
    for (int i=0;i<size;i++)
    {
        data[i]=s.data[i];
    }
    return *this;
}
</code>```

But, I wanted the following code to work as expected (without deleting current data):

```<code>Set s1,s2;
s1=s1;
</code>```

So I made the following changes:

```<code>Set& Set::operator=(const Set& s)
{
    if (this == &s)
    {
        return *this;
    }
    delete[] data;
    data=new int [s.size];
    size=s.size;
    maxSize=s.size;
    for (int i=0;i<size;i++)
    {
        data[i]=s.data[i];
    }
    return *this;
}
</code>```

my question is:

1. Why this is correct:

```<code>    if (this == &s)
    {
        return *this;
    }
</code>```

while this is not:

```<code>    if (this == s)
    {
        return *this;
    }
</code>```

s is a reference so it's a location on memory and there is no need to use &operator with it

2. Can we write the following instead of what is shown above:

```<code>    if (*this == s)
    {
        return *this;
    }
</code>```

答:
s is a reference to an object. Think of it as an alias. It is not a pointer, So you cannot compare it to this which is a pointer.

As for comparing *this to s. That doesn't quite do what you want. It compares the two objects for equality and many objects of the type may contain the same values and thus compare equal. But, what you want is not whether the objects compare equal, you want to know if they are the same object.

Comparing &s with this tells you if the two objects are located at the same memory address or not. If they are at the same location then they are the same object, if not then they are just two instances (possibly equal) of the same type. So this is what you want.

Title: C++, = operator different options

Body:
I Wrote the following function for = operator:

Set& Set::operator=(const Set& s)
{
    delete[] data;
    data=new int [s.size];
    size=s.size;
    maxSize=s.size;
    for (int i=0;i<size;i++)
    {
        data[i]=s.data[i];
    }
    return *this;
}

But, I wanted the following code to work as expected (without deleting current data):

Set s1,s2;
s1=s1;

So I made the following changes:

Set& Set::operator=(const Set& s)
{
    if (this == &s)
    {
        return *this;
    }
    delete[] data;
    data=new int [s.size];
    size=s.size;
    maxSize=s.size;
    for (int i=0;i<size;i++)
    {
        data[i]=s.data[i];
    }
    return *this;
}

my question is:

1. Why this is correct:

    if (this == &s)
    {
        return *this;
    }

while this is not:

    if (this == s)
    {
        return *this;
    }

s is a reference so it's a location on memory and there is no need to use &operator with it

2. Can we write the following instead of what is shown above:

    if (*this == s)
    {
        return *this;
    }


问:
Migrating Azure Service Bus Queue to Topic and Subscription
We have created Azure service bus queue and have a azure function - servicebus queue trigger subscribed to it. We now want this queue to convert to Topic as we will need multiple subscription to it. is there a way that we can convert queue to Topic without deleting queue and re creating this as a Topic. I understand that Azure function code which is in c# needs to be changed so it points to service bus topic.

Thanks,
Punit Singhi

答: Use the ForwardTo feature for forwarding a message to the topic entity.


问:
How to list all json key from LogEntry in azure KQL
I'm using azure log analytics workspace for crating azure monitoring workbooks.

Here is one parameter I have to create which will present All json key from LogEntry.

e.g. screenshot

LogEntry has details of @metadata, @timestamp and other keys.

Which operator I should use for getting all Json key under LogEntry.

I try below steps but there is no such a sub module it's showing.

ContainerLog | project LogEntry | evaluate bag_unpack(LogEntry)

I was reffering link but this parameters is not working in log analytics.

答:
Although not mentioned in the blog you referenced, the bag_unpack plugin can be used in Azure Application Insights Workbooks as well.

However, I'm afraid it won't work on the table in question, the reason being, bag_unpack(column) expects the column argument to be a reference to a dynamic column, whereas the LogEntry column in ContainerLog table is of type string.

References:

https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/bag-unpackplugin

https://learn.microsoft.com/en-us/azure/azure-monitor/reference/tables/containerlog


问:
Can't create handler inside thread that has not called Looper.prepare()
I get this error "Can't create handler inside thread that has not called Looper.prepare()"

Can you tell me how to fix it?

```<code>public class PaymentActivity extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.payment);

    final Button buttonBank = (Button) findViewById(R.id.buttonBank);

    buttonBank.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            progressDialog = ProgressDialog.show(PaymentActivity.this, "",
                    "Redirecting to payment gateway...", true, true);

            new Thread() {
                public void run() {
                    try {
                        startPayment("Bank");
                    } catch (Exception e) {
                        alertDialog.setMessage(e.getMessage());
                        handler.sendEmptyMessage(1);
                        progressDialog.cancel();
                    }
                }
            }.start();
        }

    });
</code>```

StartPayment Method:

```<code>    private void startPayment(String id) {
    Bundle b = getIntent().getExtras();
    final Sail sail = b.getParcelable(Constant.SAIL);

    final Intent bankIntent = new Intent(this, BankActivity.class);

    try {
        Reservation reservation = RestService.createReservation(
                sail.getId(),
                getSharedPreferences(Constant.PREF_NAME_CONTACT, 0));
        bankIntent.putExtra(Constant.RESERVATION, reservation);

        // <workingWithDB> Storing Reservation info in Database
        DBAdapter db = new DBAdapter(this);
        db.open();
        @SuppressWarnings("unused")
        long rowid;
        rowid = db.insertRow(sail.getId(), sail.getFrom(),
                sail.getTo(), sail.getShip(), sail.getDateFrom().getTime(),
                sail.getPrice().toString(), reservation.getId().floatValue());
        db.close();
        // </workingWithDB>

        String html = PaymentService.getRedirectHTML(id, reservation);

        bankIntent.putExtra(Constant.BANK, html);
    } catch (Exception e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog alertDialog = builder.create();
        alertDialog.setMessage(e.getMessage());
        alertDialog.show();
    }

    startActivity(bankIntent);
}
</code>```

答:
You should know that when you try to modify your UI , the only thread who can do that is the UiThread.

So if you want to modify your UI in another thread, try to use the method: Activity.runOnUiThread(new Runnable);

Your code should be like this :

```<code> new Thread() {
    public void run() {
        YourActivity.this.runOnUiThread(new Runnable(){

             @Override
             public void run(){
                 try {
                      startPayment("Bank");//Edit,integrate this on the runOnUiThread
                 } catch (Exception e) {
                     alertDialog.setMessage(e.getMessage());
                     handler.sendEmptyMessage(1);
                     progressDialog.cancel();
                 }
            });
           }
      }
  }.start();
</code>```

Body:
I get this error "Can't create handler inside thread that has not called Looper.prepare()"

Can you tell me how to fix it?

public class PaymentActivity extends BaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.payment);

    final Button buttonBank = (Button) findViewById(R.id.buttonBank);

    buttonBank.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            progressDialog = ProgressDialog.show(PaymentActivity.this, "",
                    "Redirecting to payment gateway...", true, true);

            new Thread() {
                public void run() {
                    try {
                        startPayment("Bank");
                    } catch (Exception e) {
                        alertDialog.setMessage(e.getMessage());
                        handler.sendEmptyMessage(1);
                        progressDialog.cancel();
                    }
                }
            }.start();
        }

    });

StartPayment Method:

    private void startPayment(String id) {
    Bundle b = getIntent().getExtras();
    final Sail sail = b.getParcelable(Constant.SAIL);

    final Intent bankIntent = new Intent(this, BankActivity.class);

    try {
        Reservation reservation = RestService.createReservation(
                sail.getId(),
                getSharedPreferences(Constant.PREF_NAME_CONTACT, 0));
        bankIntent.putExtra(Constant.RESERVATION, reservation);

        // <workingWithDB> Storing Reservation info in Database
        DBAdapter db = new DBAdapter(this);
        db.open();
        @SuppressWarnings("unused")
        long rowid;
        rowid = db.insertRow(sail.getId(), sail.getFrom(),
                sail.getTo(), sail.getShip(), sail.getDateFrom().getTime(),
                sail.getPrice().toString(), reservation.getId().floatValue());
        db.close();
        // </workingWithDB>

        String html = PaymentService.getRedirectHTML(id, reservation);

        bankIntent.putExtra(Constant.BANK, html);
    } catch (Exception e) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        AlertDialog alertDialog = builder.create();
        alertDialog.setMessage(e.getMessage());
        alertDialog.show();
    }

    startActivity(bankIntent);
}

Body:
You should know that when you try to modify your UI , the only thread who can do that is the UiThread.

So if you want to modify your UI in another thread, try to use the method: Activity.runOnUiThread(new Runnable);

Your code should be like this :

 new Thread() {
    public void run() {
        YourActivity.this.runOnUiThread(new Runnable(){

             @Override
             public void run(){
                 try {
                      startPayment("Bank");//Edit,integrate this on the runOnUiThread
                 } catch (Exception e) {
                     alertDialog.setMessage(e.getMessage());
                     handler.sendEmptyMessage(1);
                     progressDialog.cancel();
                 }
            });
           }
      }
  }.start();


问:
XML Tag grouping in RTF template to calculate totals via nested table not giving formatted output. Extra row in the nested table
My XML Tag generated is as follows-

```<code><P_MONTH>01</P_MONTH>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Global Operations</DEPARTMENT>

<DEP_EMPL_COUNT>9</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Laboratory Services</DEPARTMENT>

<DEP_EMPL_COUNT>11</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Corporate</DEPARTMENT>

<DEP_EMPL_COUNT>3</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Administration</DEPARTMENT>
<INTERNAL_ADDRESS_LINE>100-01-000-000-210-99802-000-000000-000000</INTERNAL_ADDRESS_LINE>

<DEP_EMPL_COUNT>6</DEP_EMPL_COUNT>
<SERVICE_LINE>000</SERVICE_LINE>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Technology</DEPARTMENT>

<DEP_EMPL_COUNT>1</DEP_EMPL_COUNT>

</G_1>
</code>```

When I am using these tag like below in the RTF template-

```<code>DIVISION                            DISTRICT                    DEPARTMENT                 COUNT
<?for-each:G_1?> <DIVISION>         <DISTRICT>                   <DEPARTMENT>             <COUNT> <?end for-each?>
</code>```

This is giving an output like -

```<code>DIVISION              DISTRICT                          DEPARTMENT                      COUNT
CA Division           CA District                     Global Operations                  9
CA Division           CA District                     Laboratory Services                11
CA Division           CA District                     Corporate                          3
CA Division           S District                      Corporate Administration           6
CA Division           S District                      Corporate Technology               1
</code>```

But I want the grouping to be done in the output and the total calculated as per the grouping of the district and division.
I have used a nested table for that. somewhat like -

But the RTF template is giving me an extra row in the output even though the RTF template formatting is correct-

 what can i use to remove the extra row and perfect the formatting

答: You probably have a space or new line under the nested table. Use backspace to remove it. Once you move the curser from the cell, you should see the extra space go away. Also make sure the line spacing is single spaced. </p>

Body:
My XML Tag generated is as follows-

<P_MONTH>01</P_MONTH>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Global Operations</DEPARTMENT>

<DEP_EMPL_COUNT>9</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Laboratory Services</DEPARTMENT>

<DEP_EMPL_COUNT>11</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>CA District</DISTRICT>

<DEPARTMENT>Corporate</DEPARTMENT>

<DEP_EMPL_COUNT>3</DEP_EMPL_COUNT>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Administration</DEPARTMENT>
<INTERNAL_ADDRESS_LINE>100-01-000-000-210-99802-000-000000-000000</INTERNAL_ADDRESS_LINE>

<DEP_EMPL_COUNT>6</DEP_EMPL_COUNT>
<SERVICE_LINE>000</SERVICE_LINE>

</G_1>

-<G_1>

<DIVISION>CA Division</DIVISION>

<DISTRICT>S District</DISTRICT>

<DEPARTMENT>Corporate Technology</DEPARTMENT>

<DEP_EMPL_COUNT>1</DEP_EMPL_COUNT>

</G_1>

When I am using these tag like below in the RTF template-

DIVISION                            DISTRICT                    DEPARTMENT                 COUNT
<?for-each:G_1?> <DIVISION>         <DISTRICT>                   <DEPARTMENT>             <COUNT> <?end for-each?>

This is giving an output like -

DIVISION              DISTRICT                          DEPARTMENT                      COUNT
CA Division           CA District                     Global Operations                  9
CA Division           CA District                     Laboratory Services                11
CA Division           CA District                     Corporate                          3
CA Division           S District                      Corporate Administration           6
CA Division           S District                      Corporate Technology               1

But I want the grouping to be done in the output and the total calculated as per the grouping of the district and division.
I have used a nested table for that. somewhat like -

But the RTF template is giving me an extra row in the output even though the RTF template formatting is correct-

 what can i use to remove the extra row and perfect the formatting


问:
How to get back missing `Local Changes` tab inside `Version Control/Git` tab in Android Studio 4.1?
I recently installed a new AndroidStudio4.1 IDE but it is missing the Local Changes tab inside the Version Control which is now renamed to Git? tab. I only see the Log tab. Is there any shortcut to get the Local Changes tab back? also I would like to have the Pull Requests and Console tabs in there.

I tried deleting all the AndroidStudio related folders from the library but none of that helped.

```<code>~/Library/Application Support/AndroidStudio*
~/Library/Application Support/Google/AndroidStudio*
~/Library/Caches/AndroidStudio*
~/Library/Logs/AndroidStudio*
~/Library/Preferences/AndroidStudio*
</code>```

答: Just disable the following option under File | Settings | Version Control | Commit:

Body:
I recently installed a new AndroidStudio4.1 IDE but it is missing the Local Changes tab inside the Version Control which is now renamed to Git? tab. I only see the Log tab. Is there any shortcut to get the Local Changes tab back? also I would like to have the Pull Requests and Console tabs in there.

I tried deleting all the AndroidStudio related folders from the library but none of that helped.

~/Library/Application Support/AndroidStudio*
~/Library/Application Support/Google/AndroidStudio*
~/Library/Caches/AndroidStudio*
~/Library/Logs/AndroidStudio*
~/Library/Preferences/AndroidStudio*


问:
Pickle all variables
I"m looking for a way to pickle all the variables with their values in a sorted order. I'm trying the method below:

Expected result: Append value of va to totalList , then vb's value..and so on. And then dump the totalList to a pickle file.

```<code>import pickle
import time
import os
import re

v0 = ["r0", "hello","hello there","hi there","hi", "hey","good to see you"]
v1 = ["r1", "how are you", "how do you do","how are you doing", "how you doing"]
v2 = ["r2", "What's up" , "what is up" , "what's up bro"]
v10 = ['r10', 'who made you', 'who built you', 'who is your creator']

imports = "pickle","time","os","re"
totalList = []
for key in dir():
    if key.startswith("__") == 0 and key not in imports:
        print(globals()[key])
        totalList.append(globals()[key])
# print(totalList) # getting weird values

with open('queryList.pkl', 'wb') as f:
    pickle.dump(totalList, f)
</code>```

I'm getting result like this:

```<code>>> ('pickle', 'time', 'os', 're')
>> []
>> ['r0', 'hello', 'hello there', 'hi there', 'hi', 'hey', 'good to see you']
>> ['r1', 'how are you', 'how do you do', 'how are you doing', 'how you doing']
>> ['r10', 'who made you', 'who built you', 'who is your creator']
>> ['r2', "What's up", 'what is up', "what's up bro"]
</code>```

I want to get rid of the results ('pickle', 'time', 'os', 're') and [] and sort the result before appending to totalList or sort it before iteration.

答:
Here's a way to do what you want. You should ignore some variables you're not interested in - specifically, imports and totalList.

```<code>ignore_list = [ "ignore_list", "totalList"]
totalList = []

for key in dir():
    if not key.startswith("__") and key not in ignore_list and type(globals()[key]) != type(pickle):
        print(key)
        totalList.append(globals()[key])

totalList = sorted(totalList, key=lambda x: int(x[0][1:]) )
</code>```

The result is:

```<code>[['r0', 'hello', 'hello there', 'hi there', 'hi', 'hey', 'good to see you'],
 ['r1', 'how are you', 'how do you do', 'how are you doing', 'how you doing'],
 ['r2', "What's up", 'what is up', "what's up bro"],
 ['r10', 'who made you', 'who built you', 'who is your creator']]
</code>```

Title: Pickle all variables

Body:
I"m looking for a way to pickle all the variables with their values in a sorted order. I'm trying the method below:

Expected result: Append value of va to totalList , then vb's value..and so on. And then dump the totalList to a pickle file.

import pickle
import time
import os
import re

v0 = ["r0", "hello","hello there","hi there","hi", "hey","good to see you"]
v1 = ["r1", "how are you", "how do you do","how are you doing", "how you doing"]
v2 = ["r2", "What's up" , "what is up" , "what's up bro"]
v10 = ['r10', 'who made you', 'who built you', 'who is your creator']

imports = "pickle","time","os","re"
totalList = []
for key in dir():
    if key.startswith("__") == 0 and key not in imports:
        print(globals()[key])
        totalList.append(globals()[key])
# print(totalList) # getting weird values

with open('queryList.pkl', 'wb') as f:
    pickle.dump(totalList, f)

I'm getting result like this:

>> ('pickle', 'time', 'os', 're')
>> []
>> ['r0', 'hello', 'hello there', 'hi there', 'hi', 'hey', 'good to see you']
>> ['r1', 'how are you', 'how do you do', 'how are you doing', 'how you doing']
>> ['r10', 'who made you', 'who built you', 'who is your creator']
>> ['r2', "What's up", 'what is up', "what's up bro"]

I want to get rid of the results ('pickle', 'time', 'os', 're') and [] and sort the result before appending to totalList or sort it before iteration.

Body:
Here's a way to do what you want. You should ignore some variables you're not interested in - specifically, imports and totalList.

ignore_list = [ "ignore_list", "totalList"]
totalList = []

for key in dir():
    if not key.startswith("__") and key not in ignore_list and type(globals()[key]) != type(pickle):
        print(key)
        totalList.append(globals()[key])

totalList = sorted(totalList, key=lambda x: int(x[0][1:]) )

The result is:

[['r0', 'hello', 'hello there', 'hi there', 'hi', 'hey', 'good to see you'],
 ['r1', 'how are you', 'how do you do', 'how are you doing', 'how you doing'],
 ['r2', "What's up", 'what is up', "what's up bro"],
 ['r10', 'who made you', 'who built you', 'who is your creator']]


问:
What cause the "Poly object has no attribute 'expand' " error?
I have a 4x4 sympy matrix of polynomials:

```<code>S = Matrix([[Poly(alpha**4 + alpha**3, alpha, modulus=2), Poly(alpha**4 + alpha**3 + alpha + 1, alpha, modulus=2),Poly(alpha**3 + alpha**2 + alpha, alpha, modulus=2), Poly(alpha**4 + alpha**3 + alpha**2 + alpha, alpha, modulus=2)],
       [Poly(alpha**4 + alpha**3 + alpha + 1, alpha, modulus=2), Poly(alpha**3 + alpha**2 + alpha, alpha, modulus=2), Poly(alpha**4 + alpha**3 + alpha**2 + alpha, alpha, modulus=2),Poly(alpha**3 + alpha**2, alpha, modulus=2)],
       [Poly(alpha**3 + alpha**2 + alpha, alpha, modulus=2), Poly(alpha**4 + alpha**3 + alpha**2 + alpha, alpha, modulus=2), Poly(alpha**3 + alpha**2, alpha, modulus=2), Poly(alpha**4 + alpha + 1, alpha, modulus=2)],
       [Poly(alpha**4 + alpha**3 + alpha**2 + alpha, alpha, modulus=2), Poly(alpha**3 + alpha**2, alpha, modulus=2), Poly(alpha**4 + alpha + 1, alpha, modulus=2),Poly(alpha**2 + alpha + 1, alpha, modulus=2)]])
</code>```

The goal is to get S.det() and set the domain:

```<code>S_det = (S.det()).set_domain(GF(self.q))
</code>```

Debugger output:

```<code> File "/home/gamergod77/work/Staircase codes/Product Codes/bchcoder.py", line 52, in decode
    S_det = (S.det()).set_domain(GF(self.q))

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/matrices/matrices.py", line 123, in det
    return _det(self, method=method, iszerofunc=iszerofunc)

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/matrices/determinant.py", line 596, in _det
    return M._eval_det_bareiss(iszerofunc=iszerofunc)

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/matrices/matrices.py", line 99, in _eval_det_bareiss
    return _det_bareiss(self, iszerofunc=iszerofunc)

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/matrices/determinant.py", line 669, in _det_bareiss
    return bareiss(M)

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/matrices/determinant.py", line 637, in bareiss
    pivot_pos, pivot_val, _, _ = _find_reasonable_pivot(mat[:, 0], iszerofunc=iszerofunc)

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/matrices/determinant.py", line 56, in _find_reasonable_pivot
    is_zero = iszerofunc(x)

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/matrices/utilities.py", line 84, in _is_zero_after_expand_mul
    return expand_mul(x) == 0

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/core/function.py", line 2799, in expand_mul
    return sympify(expr).expand(deep=deep, mul=True, power_exp=False,

AttributeError: 'Poly' object has no attribute 'expand'
</code>```

Noteble that something like

```<code>S[:3, :3].det().set_domain(GF(2))
</code>```

with the same S passes perfectly fine

答:
You should either use Expr in the matrix or you should use PolyMatrix instead. It looks like using Expr will be best for your example:

```<code>In [5]: S = S.applyfunc(lambda p: p.as_expr())

In [6]: S
Out[6]:
⎡     4    3        4    3              3    2          4    3    2    ⎤
⎢    α  + α        α  + α  + α + 1     α  + α  + α     α  + α  + α  + α⎥
⎢                                                                      ⎥
⎢ 4    3              3    2          4    3    2           3    2     ⎥
⎢α  + α  + α + 1     α  + α  + α     α  + α  + α  + α      α  + α      ⎥
⎢                                                                      ⎥
⎢   3    2          4    3    2           3    2           4           ⎥
⎢  α  + α  + α     α  + α  + α  + α      α  + α           α  + α + 1   ⎥
⎢                                                                      ⎥
⎢ 4    3    2           3    2           4                 2           ⎥
⎣α  + α  + α  + α      α  + α           α  + α + 1        α  + α + 1   ⎦

In [7]: S.det()
Out[7]:
 15      14      13      12      11      10      9      8    7      5      4    3      2
α   + 3⋅α   + 4⋅α   + 4⋅α   - 2⋅α   - 3⋅α   + 6⋅α  + 9⋅α  + α  + 5⋅α  + 2⋅α  + α  + 5⋅α  + 4⋅α + 1

In [8]: d = S.det()

In [9]: d
Out[9]:
 15      14      13      12      11      10      9      8    7      5      4    3      2
α   + 3⋅α   + 4⋅α   + 4⋅α   - 2⋅α   - 3⋅α   + 6⋅α  + 9⋅α  + α  + 5⋅α  + 2⋅α  + α  + 5⋅α  + 4⋅α + 1

In [10]: Poly(d, alpha).set_domain(GF(2))
Out[10]: Poly(alpha**15 + alpha**14 + alpha**10 + alpha**8 + alpha**7 + alpha**5 + alpha**3 + alpha**2 + 1, alpha, modulus=2)

</code>```

Body:
I have a 4x4 sympy matrix of polynomials:

S = Matrix([[Poly(alpha**4 + alpha**3, alpha, modulus=2), Poly(alpha**4 + alpha**3 + alpha + 1, alpha, modulus=2),Poly(alpha**3 + alpha**2 + alpha, alpha, modulus=2), Poly(alpha**4 + alpha**3 + alpha**2 + alpha, alpha, modulus=2)],
       [Poly(alpha**4 + alpha**3 + alpha + 1, alpha, modulus=2), Poly(alpha**3 + alpha**2 + alpha, alpha, modulus=2), Poly(alpha**4 + alpha**3 + alpha**2 + alpha, alpha, modulus=2),Poly(alpha**3 + alpha**2, alpha, modulus=2)],
       [Poly(alpha**3 + alpha**2 + alpha, alpha, modulus=2), Poly(alpha**4 + alpha**3 + alpha**2 + alpha, alpha, modulus=2), Poly(alpha**3 + alpha**2, alpha, modulus=2), Poly(alpha**4 + alpha + 1, alpha, modulus=2)],
       [Poly(alpha**4 + alpha**3 + alpha**2 + alpha, alpha, modulus=2), Poly(alpha**3 + alpha**2, alpha, modulus=2), Poly(alpha**4 + alpha + 1, alpha, modulus=2),Poly(alpha**2 + alpha + 1, alpha, modulus=2)]])

The goal is to get S.det() and set the domain:

S_det = (S.det()).set_domain(GF(self.q))

Debugger output:

 File "/home/gamergod77/work/Staircase codes/Product Codes/bchcoder.py", line 52, in decode
    S_det = (S.det()).set_domain(GF(self.q))

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/matrices/matrices.py", line 123, in det
    return _det(self, method=method, iszerofunc=iszerofunc)

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/matrices/determinant.py", line 596, in _det
    return M._eval_det_bareiss(iszerofunc=iszerofunc)

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/matrices/matrices.py", line 99, in _eval_det_bareiss
    return _det_bareiss(self, iszerofunc=iszerofunc)

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/matrices/determinant.py", line 669, in _det_bareiss
    return bareiss(M)

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/matrices/determinant.py", line 637, in bareiss
    pivot_pos, pivot_val, _, _ = _find_reasonable_pivot(mat[:, 0], iszerofunc=iszerofunc)

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/matrices/determinant.py", line 56, in _find_reasonable_pivot
    is_zero = iszerofunc(x)

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/matrices/utilities.py", line 84, in _is_zero_after_expand_mul
    return expand_mul(x) == 0

  File "/home/gamergod77/.local/lib/python3.8/site-packages/sympy/core/function.py", line 2799, in expand_mul
    return sympify(expr).expand(deep=deep, mul=True, power_exp=False,

AttributeError: 'Poly' object has no attribute 'expand'

Noteble that something like

S[:3, :3].det().set_domain(GF(2))

with the same S passes perfectly fine

Body:
You should either use Expr in the matrix or you should use PolyMatrix instead. It looks like using Expr will be best for your example:

In [5]: S = S.applyfunc(lambda p: p.as_expr())

In [6]: S
Out[6]:
⎡     4    3        4    3              3    2          4    3    2    ⎤
⎢    α  + α        α  + α  + α + 1     α  + α  + α     α  + α  + α  + α⎥
⎢                                                                      ⎥
⎢ 4    3              3    2          4    3    2           3    2     ⎥
⎢α  + α  + α + 1     α  + α  + α     α  + α  + α  + α      α  + α      ⎥
⎢                                                                      ⎥
⎢   3    2          4    3    2           3    2           4           ⎥
⎢  α  + α  + α     α  + α  + α  + α      α  + α           α  + α + 1   ⎥
⎢                                                                      ⎥
⎢ 4    3    2           3    2           4                 2           ⎥
⎣α  + α  + α  + α      α  + α           α  + α + 1        α  + α + 1   ⎦

In [7]: S.det()
Out[7]:
 15      14      13      12      11      10      9      8    7      5      4    3      2
α   + 3⋅α   + 4⋅α   + 4⋅α   - 2⋅α   - 3⋅α   + 6⋅α  + 9⋅α  + α  + 5⋅α  + 2⋅α  + α  + 5⋅α  + 4⋅α + 1

In [8]: d = S.det()

In [9]: d
Out[9]:
 15      14      13      12      11      10      9      8    7      5      4    3      2
α   + 3⋅α   + 4⋅α   + 4⋅α   - 2⋅α   - 3⋅α   + 6⋅α  + 9⋅α  + α  + 5⋅α  + 2⋅α  + α  + 5⋅α  + 4⋅α + 1

In [10]: Poly(d, alpha).set_domain(GF(2))
Out[10]: Poly(alpha**15 + alpha**14 + alpha**10 + alpha**8 + alpha**7 + alpha**5 + alpha**3 + alpha**2 + 1, alpha, modulus=2)


问:
Get current frame on Microsoft Maps MapTileSource.Play()
I have a MapTileSource which I .Play() on Microsoft Maps. This works well, but I'm wondering how I can get the current frame. I'm not able to find an event or anything.

Basically, there is 10 layers. I would like to display the date for each layer as it's played. For example: Layer 1: Monday XX/XX/XXXX. Layer 2: Tuesday XX/XX/XXXX.

Does anyone have any recommendations how I can fire an event each time a new frame is Played on the map?

答: I don't think there's any way to do this. The best workaround I can suggest is to estimate the right label to show based on the frame timing you requested, and then periodically stop and restart the animation to remove any drift.</p>


问:
GRPC - nodejs DNS resolution failed
I'm working with a GRPC service hosted with HTTPS and self-signed cert. When I connect using syntax like:

```<code>const client = new productService('https://grpc-server-xxx.com:9090',
grpc.credentials.createInsecure())
</code>```

I am getting the error like this

```<code>{ Error: 14 UNAVAILABLE: DNS resolution failed
at Object.exports.createStatusError (C:\grpc\node_modules\grpc\src\common.js:91:15)
at Object.onReceiveStatus (C:\grpc\node_modules\grpc\src\client_interceptors.js:1209:28)
at InterceptingListener._callNext (C:\grpc\node_modules\grpc\src\client_interceptors.js:568:42)
at InterceptingListener.onReceiveStatus (C:\grpc\node_modules\grpc\src\client_interceptors.js:618:8) at callback (C:\grpc\node_modules\grpc\src\client_interceptors.js:847:24)code: 14,metadata: Metadata { _internal_repr: {}, flags: 0 },details: 'DNS resolution failed'
</code>```

Anyone help me how can I resolve the issue.

Note:
My OS is Windows 10,
nodejs -- v10.16.0,
GRPC

答: The gRPC library does not recognize the https:// scheme for addresses, so that target name will cause it to try to resolve the wrong name. You should instead use grpc-server-xxx.com:9090 or dns:grpc-server-xxx.com:9090 or dns:///grpc-server-xxx.com:9090. More detailed information about how gRPC interprets channel target names can be found in this documentation page.

Title: GRPC - nodejs DNS resolution failed

Body:
I'm working with a GRPC service hosted with HTTPS and self-signed cert. When I connect using syntax like:

const client = new productService('https://grpc-server-xxx.com:9090',
grpc.credentials.createInsecure())

I am getting the error like this

{ Error: 14 UNAVAILABLE: DNS resolution failed
at Object.exports.createStatusError (C:\grpc\node_modules\grpc\src\common.js:91:15)
at Object.onReceiveStatus (C:\grpc\node_modules\grpc\src\client_interceptors.js:1209:28)
at InterceptingListener._callNext (C:\grpc\node_modules\grpc\src\client_interceptors.js:568:42)
at InterceptingListener.onReceiveStatus (C:\grpc\node_modules\grpc\src\client_interceptors.js:618:8) at callback (C:\grpc\node_modules\grpc\src\client_interceptors.js:847:24)code: 14,metadata: Metadata { _internal_repr: {}, flags: 0 },details: 'DNS resolution failed'

Anyone help me how can I resolve the issue.

Note:
My OS is Windows 10,
nodejs -- v10.16.0,
GRPC


问:
Python Database that stays with the program
So mysql works great when you log into  your mysql database program on that device but what if you want to move the program to another device, the connected databases wont work...

Is there anyway to have the database somehow within the python file, so that when I move it to other devices it will act the same...Thank you!

答: Yes, use a database external to the host.  You can then use DNS or an ip address to access the mysql database as long as the new device has connectivity to the database.  For mobile apps and mobile devices, build out an API on top of the data that you'd like to be able to access and then secure the API with appropriate credentials.  </p>


问:
How do I install a package that enable Jupyter load it?
I already have imageio installed:

```<code>$ pip install imageio
Requirement already satisfied: imageio in /Library/Python/2.7/site-packages
Requirement already satisfied: numpy in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from imageio)
Requirement already satisfied: pillow in /Library/Python/2.7/site-packages (from imageio)
</code>```

Now I load a .ipynb file with Jupyter:

```<code>$ jupyter notebook 1_notmnist.ipynb
</code>```

got error:

```<code>ImportError: No module named imageio
</code>```

I thought it has something to do with Can't load Python modules installed via pip from site-packages directory, and follow exactly as the answer suggest to reinstall imageio:

$ python -m pip install imageio

and still no help.

How do I install imageio that enable Jupyter load it?

update:

Terminal: $ which python

/usr/bin/python

Jupyter:

```<code>$ import sys
print sys.executable
</code>```

/usr/local/opt/python/bin/python2.7

答:
When I got a similar error with Jupyter Notebook and Mac OS, I ran the following in Terminal:

sudo conda install imageio

Body:
I already have imageio installed:

$ pip install imageio
Requirement already satisfied: imageio in /Library/Python/2.7/site-packages
Requirement already satisfied: numpy in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from imageio)
Requirement already satisfied: pillow in /Library/Python/2.7/site-packages (from imageio)

Now I load a .ipynb file with Jupyter:

$ jupyter notebook 1_notmnist.ipynb

got error:

ImportError: No module named imageio

I thought it has something to do with Can't load Python modules installed via pip from site-packages directory, and follow exactly as the answer suggest to reinstall imageio:

$ python -m pip install imageio

and still no help.

How do I install imageio that enable Jupyter load it?

update:

Terminal: $ which python

/usr/bin/python

Jupyter:

$ import sys
print sys.executable

/usr/local/opt/python/bin/python2.7


问:
How to select rows which are evenly distributed on some column?
I have a table tbl with 3 columns imp_col, data1, data2 where imp_col's type is enum('imp1', 'imp2, 'imp3', 'imp4'). Now if I want to select 10 rows randomly I can do like this.
```<code>select imp_col, data1, data2 from tbl where imp_col in ('imp1', 'imp2', 'imp3') limit 10 order by rand();```But in this case all the 10 resulting rows may have imp_col as imp1.
Is there an SQL query which can return 10 rows with imp_col distributed evenly among imp1, imp2, imp3?
Thanks.

答:
Are you able to use limit and rand() in an inline view in mySQL?

```<code>      select Y.c1, Y.c2, Y.c3
      from
      (
      select c1, c2, c3.... from X limit 500 order by rand()
      ) as Y
      where Y.c2 in ( 'imp1', 'imp2', 'imp3')
      limit 10
</code>```

That would give you a better chance of getting a variety of 'imp' values, if it's legal.

Body:
I have a table tbl with 3 columns imp_col, data1, data2 where imp_col's type is enum('imp1', 'imp2, 'imp3', 'imp4'). Now if I want to select 10 rows randomly I can do like this.

select imp_col, data1, data2 from tbl where imp_col in ('imp1', 'imp2', 'imp3') limit 10 order by rand();
But in this case all the 10 resulting rows may have imp_col as imp1.
Is there an SQL query which can return 10 rows with imp_col distributed evenly among imp1, imp2, imp3?
Thanks.

Body:
Are you able to use limit and rand() in an inline view in mySQL?

      select Y.c1, Y.c2, Y.c3
      from
      (
      select c1, c2, c3.... from X limit 500 order by rand()
      ) as Y
      where Y.c2 in ( 'imp1', 'imp2', 'imp3')
      limit 10

That would give you a better chance of getting a variety of 'imp' values, if it's legal.


问:
Heroku rails console automatically exits
I'm running a simple rails active query command on 300,000 records.

Why does the heroku console automatically exit?

```<code>def is_number? string
  true if Float(string) rescue false
end
documents = []
DocumentText.all.each do |t|
  if is_number?(t.src)
    documents << t
  end
end
</code>```

答:
It is probably easier to filter on the database side e.g.

```<code>DocumentText
  .pluck('src::float as src')
  .where("src ~ '^([0-9]+[.]?[0-9]*|[.][0-9]+)$'");nil
</code>```

Here we cast src to a float where src meets the given pattern. The casting may or may not be important to you but the where clause will filter your results in the database rather than loading them all then filtering them.

Body:
I'm running a simple rails active query command on 300,000 records.

Why does the heroku console automatically exit?

def is_number? string
  true if Float(string) rescue false
end
documents = []
DocumentText.all.each do |t|
  if is_number?(t.src)
    documents << t
  end
end

Body:
It is probably easier to filter on the database side e.g.

DocumentText
  .pluck('src::float as src')
  .where("src ~ '^([0-9]+[.]?[0-9]*|[.][0-9]+)$'");nil

Here we cast src to a float where src meets the given pattern. The casting may or may not be important to you but the where clause will filter your results in the database rather than loading them all then filtering them.


问:
What's the fastest way to get the word out of the middle of a sentence of three? / manipulating strings
I have several strings that I have to modify in different ways

```<code>const string1 = 'PACK Nº1 compressed :';
const string2 = 'PACK Nº2 compressed :';
const string3 = 'PACK Nº3 compressed :';
const string4 = 'PACK Nº4 compressed :';
const string5 = 'PACK Nº5 compressed :';

</code>```

I must transform them all so that they look like this

```<code>', Pack Nº1 compressed'
</code>```

For this I have been getting the first and last word and transforming them and also eliminating the elements that I do not want

```<code>    const phrase = 'PACK N°1 comprenant :';
    const result = phrase.replace(' :', ''); //to eliminate : and blank space

    const firstWord = result.replace(/ .*/,'');
    const lastWOrd = result.split(" ").pop(); // to get first and last word

    const lastWordCapitalized = lastWOrd.charAt(0).toUpperCase() + lastWOrd.slice(1); // to capitalize the first letter of the last word

    const lowerFirstWord = firstWord.toLowerCase();
    const firstWordCapitalize = lowerFirstWord.charAt(0).toUpperCase() + lowerFirstWord.slice(1); //to capitalize the first letter of the first word

</code>```

now that I have them separately I wonder what would be the quickest way to get the second word of the original sentence to put them all together... or if there is a more efficient way to perform the desired conversion

thank you in advance for your help

答:
I have commented each part in the snippet below, all you need to do is loop over your strings.

I have assumed you meant to capitalise each word as that was what your code was showing, even though your example desired output did not show this.

Also it wasn't clear if you wanted to keep the "º" or replace it with a "°" as you used both within your question. I went with the former, if you need help with changing that let me know.

var phrase = 'PACK Nº1 compressed :';
phrase = phrase.replace(" :",""); // get rid of the unwanted characters at the end
phrase = phrase.toLowerCase() //split by words and capitalise the first letter of each
    .split(' ')
    .map((s) => s.charAt(0).toUpperCase() + s.substring(1))
    .join(' ');

phrase = ", " + phrase; //add the leading comma

console.log(phrase);```

Body:
I have several strings that I have to modify in different ways

const string1 = 'PACK Nº1 compressed :';
const string2 = 'PACK Nº2 compressed :';
const string3 = 'PACK Nº3 compressed :';
const string4 = 'PACK Nº4 compressed :';
const string5 = 'PACK Nº5 compressed :';

I must transform them all so that they look like this

', Pack Nº1 compressed'

For this I have been getting the first and last word and transforming them and also eliminating the elements that I do not want

    const phrase = 'PACK N°1 comprenant :';
    const result = phrase.replace(' :', ''); //to eliminate : and blank space

    const firstWord = result.replace(/ .*/,'');
    const lastWOrd = result.split(" ").pop(); // to get first and last word

    const lastWordCapitalized = lastWOrd.charAt(0).toUpperCase() + lastWOrd.slice(1); // to capitalize the first letter of the last word

    const lowerFirstWord = firstWord.toLowerCase();
    const firstWordCapitalize = lowerFirstWord.charAt(0).toUpperCase() + lowerFirstWord.slice(1); //to capitalize the first letter of the first word

now that I have them separately I wonder what would be the quickest way to get the second word of the original sentence to put them all together... or if there is a more efficient way to perform the desired conversion

thank you in advance for your help


问:
Terminate nodejs aws lambda function in a .then or .catch function
Consider the following AWS lambda function written in nodejs.

```<code>export const handler: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
  var file;

  await getFile()
    .then((filedata): void => {
      file = filedata;
    }).catch((e): void => {
      < Return error response and stop execution >
    });

  await saveFile(file)
    .then((result): void => {

    }).catch((e): void => {
      < Return error response and stop execution >
    });
  return {statusCode: 200};
};
</code>```

If getFile fails I want the lambda function to just return an error and stop executing.

I can't return a response from the .catch statement because it's in the wrong scope.

I can surround the whole handler with try/catch and throw an error from the .catch statement like this:

```<code>try {
  await getFile()
    .then((filedata): void => {
      file = filedata;
    }).catch((e): void => {
      throw new Error("Error getFile");
    });

  await saveFile(file)
    .catch((e): void => {
      throw new Error("Error saveFile");
    });
  return {statusCode: 200, body: "success"};
} catch (error) {
  return {statusCode: 500, body: error.message};
}
</code>```

...but I assume that there is a better way?

How would you do it?

Thank you for your help!

答:
If you can use await, you have the option to not use then(), so you could  rewrite the getFile part to something along the lines of this:

```<code>try {
  file = await getFile():
} catch(e) {
  < Return error response and stop execution >
};
</code>```

Body:
Consider the following AWS lambda function written in nodejs.

export const handler: APIGatewayProxyHandler = async (event: APIGatewayProxyEvent): Promise<APIGatewayProxyResult> => {
  var file;

  await getFile()
    .then((filedata): void => {
      file = filedata;
    }).catch((e): void => {
      < Return error response and stop execution >
    });

  await saveFile(file)
    .then((result): void => {

    }).catch((e): void => {
      < Return error response and stop execution >
    });
  return {statusCode: 200};
};

If getFile fails I want the lambda function to just return an error and stop executing.

I can't return a response from the .catch statement because it's in the wrong scope.

I can surround the whole handler with try/catch and throw an error from the .catch statement like this:

try {
  await getFile()
    .then((filedata): void => {
      file = filedata;
    }).catch((e): void => {
      throw new Error("Error getFile");
    });

  await saveFile(file)
    .catch((e): void => {
      throw new Error("Error saveFile");
    });
  return {statusCode: 200, body: "success"};
} catch (error) {
  return {statusCode: 500, body: error.message};
}

...but I assume that there is a better way?

How would you do it?

Thank you for your help!

Body:
If you can use await, you have the option to not use then(), so you could  rewrite the getFile part to something along the lines of this:

try {
  file = await getFile():
} catch(e) {
  < Return error response and stop execution >
};


问:
Breakpoints in vscode debugger often fail for a React application
My React application is written in Typescript and I debug it using Chrome. After a fresh start of the application everything works fine. I can set breakpoints and the debugger stops at them.

The problems appear when I change source code. Existing breakpoints are moved to a wrong line and when I try to set new breakpoints they cannot be resolved. I have to close Chrome and re-open it to make things work again. My launch config is:

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Shell GUI",
            "url": "https://localhost:3001",
            "webRoot": "${workspaceFolder}/src",
            "userDataDir": "${workspaceRoot}/.vscode/chrome",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                "webpack:///build/*": "${webRoot}/*"
            }
        }
    ]
}
</code>```

I tried to fix the issue by specifying source map overrides, but that has not improved the situation at all. And if I haven't created a production build yet then there's no build folder at all. To me it looks as if Chrome doesn't get code changes (assuming here that breakpoints are evaluated by Chrome).

What do I have to change to make debugging working correctly, even after source code changes?

答:
Unfortunately this is a known issue with create-react-app at the moment:

There's a link to track the issue here: https://github.com/facebook/create-react-app/issues/6074

Body:
My React application is written in Typescript and I debug it using Chrome. After a fresh start of the application everything works fine. I can set breakpoints and the debugger stops at them.

The problems appear when I change source code. Existing breakpoints are moved to a wrong line and when I try to set new breakpoints they cannot be resolved. I have to close Chrome and re-open it to make things work again. My launch config is:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Shell GUI",
            "url": "https://localhost:3001",
            "webRoot": "${workspaceFolder}/src",
            "userDataDir": "${workspaceRoot}/.vscode/chrome",
            "sourceMaps": true,
            "sourceMapPathOverrides": {
                "webpack:///build/*": "${webRoot}/*"
            }
        }
    ]
}

I tried to fix the issue by specifying source map overrides, but that has not improved the situation at all. And if I haven't created a production build yet then there's no build folder at all. To me it looks as if Chrome doesn't get code changes (assuming here that breakpoints are evaluated by Chrome).

What do I have to change to make debugging working correctly, even after source code changes?


问:
How to get latex in edge labels using dot2tex?
The following example does not  work. The edge label doesn't show up properly.

```<code>DiGraph {
X [texlbl="$X$"]
Y [texlbl="$Y_s$"]
X -> YY [texlbl="$\int f(x) dx$"]
}
</code>```

Looking for a way to get edge labels to work.

答:
Ugh just saw this deep in the pdf after I posted:

If you use texlbl for edges, you have to provide a dummy label
  attribute. Otherwise Graphviz will not generate the necessary code for
  placing edge labels

So do this:

```<code>X -> YY [label="      ", texlbl="$asdf$"]
</code>```

Body:
The following example does not  work. The edge label doesn't show up properly.

DiGraph {
X [texlbl="$X$"]
Y [texlbl="$Y_s$"]
X -> YY [texlbl="$\int f(x) dx$"]
}

Looking for a way to get edge labels to work.

Body:
Ugh just saw this deep in the pdf after I posted:

If you use texlbl for edges, you have to provide a dummy label
  attribute. Otherwise Graphviz will not generate the necessary code for
  placing edge labels

So do this:

X -> YY [label="      ", texlbl="$asdf$"]


问:
How do I programmatically update OCX references in vb6 projects?
I periodically break binary compatibility and need to recompile an entire vb6 application composed of several dozen ActiveX DLLs and OCXs in total. I've written a script to automate this process, but I have encountered a problem.

When an OCX is recompiled with project compatibility its version is incremented, and projects referencing the OCX will not recompile until their reference is updated to the new version. This is checked automatically when the project is opened normally, and the user is prompted to update the reference, but I need to do it in a script.

How do I do it?

答:
My project, maintained over a decade, consists of a hierarchy of two dozen ActiveX DLLs and a half dozen controls. Compiled with a script system as well.

I don't recommend doing what you are doing.

What we do is as follows

Make our changes including additions
and test in the IDE.

We compile from the bottom of the
hierarchy to the top

we copy the newly complied files to
a revision directory for example
601,then 602 etc etc

we create the setup.exe

when the setup is finalized we copy
over the revision directory into our
compatibility director. Note we
never point to the compiled binary
in the project directory. Always to
a compability directory that has all
the DLLs.

The reason this works is that if you look at the IDL source using the OLE View tool you will find that any referenced control or dlls is added to the interface via a #include. If you point to the binary in your project directory then the include is picked up from the registry which can lead to a lot of strangness and compatibility.

However if the referenced DLL is present in the directory that binary exists while being used for binary compatibility, VB6 will use that instead of whatever in the registry.

Now there is one problem that you will get on an infrequent basis. Consider this heirarchy

MyUtilityDLL

MyObjectDLL

MyUIDLL

MyEXE

If you ADD a property or method to a class in MyUtilityDLL MyUIDLL may not compile giving a binary incompatibility error if you are lucky or a strange error like [inref]. In any case the solution is to compile MyUtilityDLL and then immediately copy MyUtilityDLL into the compatibility directory. Then the rest of the automated compile will work fine.

You may want to include this step in the automated build.

Note that in many cases the projects will work fine in the IDE. To if you are now aware of this you could be pulling your hair out.

OwnerDisplayName: Strilanc

OwnerDisplayName: RS Conley


问:
C pass int array pointer as parameter into a function
I want to pass the B int array pointer into func function and be able to change it from there and then view the changes in main function

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

int func(int *B[10]){

}

int main(void){

    int *B[10];

    func(&B);

    return 0;
}
</code>```

the above code gives me some errors:

```<code>In function 'main':|
warning: passing argument 1 of 'func' from incompatible pointer type [enabled by default]|
note: expected 'int **' but argument is of type 'int * (*)[10]'|
</code>```

EDIT:
new code:

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

int func(int *B){
    *B[0] = 5;
}

int main(void){

    int B[10] = {NULL};
    printf("b[0] = %d\n\n", B[0]);
    func(B);
    printf("b[0] = %d\n\n", B[0]);

    return 0;
}
</code>```

now i get these errors:

```<code>||In function 'func':|
|4|error: invalid type argument of unary '*' (have 'int')|
||In function 'main':|
|9|warning: initialization makes integer from pointer without a cast [enabled by default]|
|9|warning: (near initialization for 'B[0]') [enabled by default]|
||=== Build finished: 1 errors, 2 warnings ===|
</code>```

答:
Make use of *(B) instead of *B[0].
Here,  *(B+i) implies B[i] and *(B) implies B[0], that is
*(B+0)=*(B)=B[0].

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

int func(int *B){
    *B = 5;
    // if you want to modify ith index element in the array just do *(B+i)=<value>
}

int main(void){

    int B[10] = {};
    printf("b[0] = %d\n\n", B[0]);
    func(B);
    printf("b[0] = %d\n\n", B[0]);
    return 0;
}
</code>```

Body:
I want to pass the B int array pointer into func function and be able to change it from there and then view the changes in main function

#include <stdio.h>

int func(int *B[10]){

}

int main(void){

    int *B[10];

    func(&B);

    return 0;
}

the above code gives me some errors:

In function 'main':|
warning: passing argument 1 of 'func' from incompatible pointer type [enabled by default]|
note: expected 'int **' but argument is of type 'int * (*)[10]'|

EDIT:
new code:

#include <stdio.h>

int func(int *B){
    *B[0] = 5;
}

int main(void){

    int B[10] = {NULL};
    printf("b[0] = %d\n\n", B[0]);
    func(B);
    printf("b[0] = %d\n\n", B[0]);

    return 0;
}

now i get these errors:

||In function 'func':|
|4|error: invalid type argument of unary '*' (have 'int')|
||In function 'main':|
|9|warning: initialization makes integer from pointer without a cast [enabled by default]|
|9|warning: (near initialization for 'B[0]') [enabled by default]|
||=== Build finished: 1 errors, 2 warnings ===|

Body:
Make use of *(B) instead of *B[0].
Here,  *(B+i) implies B[i] and *(B) implies B[0], that is
*(B+0)=*(B)=B[0].

#include <stdio.h>

int func(int *B){
    *B = 5;
    // if you want to modify ith index element in the array just do *(B+i)=<value>
}

int main(void){

    int B[10] = {};
    printf("b[0] = %d\n\n", B[0]);
    func(B);
    printf("b[0] = %d\n\n", B[0]);
    return 0;
}


问:
Install needed libraries for Weasyprint on pipenv (Windows environment)
In order to start generating documents with Weasyprint I installed it on my Windows machine following these instructions:

https://weasyprint.readthedocs.io/en/stable/install.html#step-5-run-weasyprint

On my computer it works but I have a Django project where I want to integrate this library and I use pipenv.
How to install the necessary libraries even in the virtual environment?

I tried setting the path for the pycairo package into the Pipfile like

```<code>pycairo= {path= "C:/Program Files/GTK3-Runtime Win64/bin/"}
</code>```

but still it throws the error:

```<code>OSError: dlopen() failed to load a library: cairo / cairo-2 / cairo-gobject-2 / cairo.so.2
</code>```

I have 64bit Windows machine and this is the Pipfile:

```<code>[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]
pylint = "*"

[packages]
django = "*"
mysql = "*"
ipython = "*"
django-webpack = "*"
django-webpack-loader = "*"
django-livereload-server = "*"
pylint = "*"
reportlab = "*"
weasyprint = "*"
django-weasyprint = "*"
pycairo= {path= "C:/Program Files/GTK3-Runtime Win64/bin/"}
cairocffi = "*"

[requires]
python_version = "3.7"
</code>```

答:
Please type the following command:

WHERE libcairo-2.dll

you should be getting 'C:\msys2\mingw64\bin\libcairo-2.dll'

then open your cmd and type the following.

SET PROPER_GTK_FOLDER=

SET PATH=%PROPER_GTK_FOLDER%;%PATH%

Please follow the documentation it has everything to run on windows. It worked for me it i hope it will work for youenter link description here

Body:
In order to start generating documents with Weasyprint I installed it on my Windows machine following these instructions:

https://weasyprint.readthedocs.io/en/stable/install.html#step-5-run-weasyprint

On my computer it works but I have a Django project where I want to integrate this library and I use pipenv.
How to install the necessary libraries even in the virtual environment?

I tried setting the path for the pycairo package into the Pipfile like

pycairo= {path= "C:/Program Files/GTK3-Runtime Win64/bin/"}

but still it throws the error:

OSError: dlopen() failed to load a library: cairo / cairo-2 / cairo-gobject-2 / cairo.so.2

I have 64bit Windows machine and this is the Pipfile:

[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]
pylint = "*"

[packages]
django = "*"
mysql = "*"
ipython = "*"
django-webpack = "*"
django-webpack-loader = "*"
django-livereload-server = "*"
pylint = "*"
reportlab = "*"
weasyprint = "*"
django-weasyprint = "*"
pycairo= {path= "C:/Program Files/GTK3-Runtime Win64/bin/"}
cairocffi = "*"

[requires]
python_version = "3.7"


问:
Dynamic Linq - String.Split
It appears that Dynamic Linq doesn't implement the String.Split method.

Is there a way achieve the same results with Dynamic Linq ?

答:
Dynamic Linq does support String.Split and also calling other .net type methods as shown below

```<code>var query =
                db.Customers.Where("City.Split(\"abc\".ToCharArray()).Length == 1 and Orders.Count >= @1", "London", 10).
                OrderBy("CompanyName").
                Select("New(CompanyName as Name, Phone)");
</code>```

It was able to convert the string to expression tree but as SQL doesn't have any string split operation it throws error if you run it on SQL

Title: Dynamic Linq - String.Split

Body:
Dynamic Linq does support String.Split and also calling other .net type methods as shown below

var query =
                db.Customers.Where("City.Split(\"abc\".ToCharArray()).Length == 1 and Orders.Count >= @1", "London", 10).
                OrderBy("CompanyName").
                Select("New(CompanyName as Name, Phone)");

It was able to convert the string to expression tree but as SQL doesn't have any string split operation it throws error if you run it on SQL


问:
Define a value in JSR223 Assertion and Access it from User Defined Variables in a Different Thread
Simply this is what I want help with,

Using Jmeter -

Set a variable in the JSR223 Assertion in the 1st thread

Access that value in a different threads User Defined Variables

Thanks in advance

答:
JMeter Variables are local to the current thread only therefore you won't be able to access the value outside the current thread (virtual user) context.

As per JMeter Documentation:

Properties are not the same as variables. Variables are local to a thread; properties are common to all threads

So if you need to make some variable "global" you can convert it into a property like:

```<code>props.put('foo', 'bar')
</code>```

in the JSR223 Assertion

Once done you should be able to access the value using __P() function as ${__P(foo,)} where required

You can also use __setProperty() function instead of setting the value in the JSR223 Assertion.

More information on JMeter Functions concept: Apache JMeter Functions - An Introduction

Body:
JMeter Variables are local to the current thread only therefore you won't be able to access the value outside the current thread (virtual user) context.

As per JMeter Documentation:

Properties are not the same as variables. Variables are local to a thread; properties are common to all threads

So if you need to make some variable "global" you can convert it into a property like:

props.put('foo', 'bar')

in the JSR223 Assertion

Once done you should be able to access the value using __P() function as ${__P(foo,)} where required

You can also use __setProperty() function instead of setting the value in the JSR223 Assertion.

More information on JMeter Functions concept: Apache JMeter Functions - An Introduction


问:
Azure Form Recognizer error Atribute error when making the request
I'm trying to follow this document for the form recognizer API,
specifically the example for Recognize receipts:

```<code>https://learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/quickstarts/client-library?pivots=programming-language-python&tabs=windows
</code>```

I'm trying the following code:

```<code>import sys
import logging
from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential
import os
import azure.ai.formrecognizer

endpoint = r"https://form-recognizer-XXXXX-test.cognitiveservices.azure.com/"
form_recognizer_client = FormRecognizerClient(endpoint=endpoint, credential="XXXXXXXXX")
receiptUrl = "https://raw.githubusercontent.com/Azure/azure-sdk-for-python/master/sdk/formrecognizer/azure-ai-formrecognizer/tests/sample_forms/receipt/contoso-receipt.png"

poller = form_recognizer_client.begin_recognize_receipts_from_url(receiptUrl)
receipts = poller.result()
</code>```

And getting this error:

```<code>    request.http_request.headers[self._name] = self._credential.key

AttributeError: 'str' object has no attribute 'key'
</code>```

The difference I see is that in the example the endpoint and key are called as attributes of a class:

```<code>form_recognizer_client = FormRecognizerClient(endpoint=self.endpoint, credential=AzureKeyCredential(self.key))
</code>```

But I do not see where does the "self." comes from and how is that the value is not a string.

答:
I agree that it is a bit unclear in the quickstart where that key is coming from. In the example, the API key is getting set as a class variable (where the self is coming from), but you do not need to do this to get your code working. </p>

<p>For successful authentication, the string API key "XXXXXXXXX" must be wrapped in the credential class AzureKeyCredential. I've updated your code below to do this, please let me know if it works for you: </p>

```<code>import sys
import logging
from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential
import os
import azure.ai.formrecognizer

endpoint = r"https://form-recognizer-XXXXX-test.cognitiveservices.azure.com/"
form_recognizer_client = FormRecognizerClient(endpoint=endpoint,
    credential=AzureKeyCredential("XXXXXXXXX"))
receiptUrl = "https://raw.githubusercontent.com/Azure/azure-sdk-for-
    python/master/sdk/formrecognizer/azure-ai-
    formrecognizer/tests/sample_forms/receipt/contoso-receipt.png"

poller = form_recognizer_client.begin_recognize_receipts_from_url(receiptUrl)
receipts = poller.result()
</code>```

Body:
I'm trying to follow this document for the form recognizer API,
specifically the example for Recognize receipts:

https://learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/quickstarts/client-library?pivots=programming-language-python&tabs=windows

I'm trying the following code:

import sys
import logging
from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential
import os
import azure.ai.formrecognizer

endpoint = r"https://form-recognizer-XXXXX-test.cognitiveservices.azure.com/"
form_recognizer_client = FormRecognizerClient(endpoint=endpoint, credential="XXXXXXXXX")
receiptUrl = "https://raw.githubusercontent.com/Azure/azure-sdk-for-python/master/sdk/formrecognizer/azure-ai-formrecognizer/tests/sample_forms/receipt/contoso-receipt.png"

poller = form_recognizer_client.begin_recognize_receipts_from_url(receiptUrl)
receipts = poller.result()

And getting this error:

    request.http_request.headers[self._name] = self._credential.key

AttributeError: 'str' object has no attribute 'key'

The difference I see is that in the example the endpoint and key are called as attributes of a class:

form_recognizer_client = FormRecognizerClient(endpoint=self.endpoint, credential=AzureKeyCredential(self.key))

But I do not see where does the "self." comes from and how is that the value is not a string.

Body:
I agree that it is a bit unclear in the quickstart where that key is coming from. In the example, the API key is getting set as a class variable (where the self is coming from), but you do not need to do this to get your code working.

For successful authentication, the string API key "XXXXXXXXX" must be wrapped in the credential class AzureKeyCredential. I've updated your code below to do this, please let me know if it works for you:

import sys
import logging
from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential
import os
import azure.ai.formrecognizer

endpoint = r"https://form-recognizer-XXXXX-test.cognitiveservices.azure.com/"
form_recognizer_client = FormRecognizerClient(endpoint=endpoint,
    credential=AzureKeyCredential("XXXXXXXXX"))
receiptUrl = "https://raw.githubusercontent.com/Azure/azure-sdk-for-
    python/master/sdk/formrecognizer/azure-ai-
    formrecognizer/tests/sample_forms/receipt/contoso-receipt.png"

poller = form_recognizer_client.begin_recognize_receipts_from_url(receiptUrl)
receipts = poller.result()