问:
Can Flutter Router Navigator and Provider at top level work together?
I have a big problem using state management with Providers and the navigator.

Things that we must know:

1) My RESTFUL API gives a token that expires on 12h.

2) My home: parameter is conditioned if the user is authenticated or nor.. if not, based in other parameters I must decide what screen must be the home.

3) If I'm on one screen and the token gets expired on ANY request that the app is doing to the API I:

Call a function inside my auth provider that do logout procedures, (i clean the localStorage with the token). This auth provider sets a property called isAuth to false.

When isAuth is false, if you look the main.dart file at home: you will see that will show the LoginPage().

Everything here is good. The problem is when i must do a redirect using the Navigator.of..... If, for example, in case of error of token expired I do: Navigator.popUntil(context, ModalRoute.withName('/login')); the app goes to the LoginPage() without problem, but... when I try to use the login (using the login function of auth provider) it's stay on the login page! If I use in any place the Navigator to go to any other place, it's appears to override the 'state management way' that I use to control which page shows as home.

Can you help me please?

My main.dart code:

```<code>// Providers
import 'package:provider/provider.dart';
import 'package:cadsanjuan_movil/providers/auth.dart';

// Pages
import './pages/login_page.dart';
import './pages/initial_loading_page.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  final storage = new FlutterSecureStorage();
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          ChangeNotifierProvider<Auth>(create: (context) => Auth()),
          ChangeNotifierProvider<TurnActive>(create: (context) => TurnActive()),
          ChangeNotifierProxyProvider<TurnActive, Checkup>(
              create: (context) => Checkup(),
              update: (_, turnActive, checkup) {
                checkup.turnData = turnActive.turnData;
                return checkup;
              }),
          ChangeNotifierProxyProvider<Auth, ErrorProvider>(
              create: (context) => ErrorProvider(),
              update: (_, auth, errorProvider) {
                errorProvider.logoff = auth.logoff;
                return errorProvider;
              }),
        ],
        child: Consumer3<Auth, TurnActive, Checkup>(
          builder: (context, auth, turnActive, checkup, _) {
            return MaterialApp(
              title: 'CAD App',
              theme: ThemeData(
                primarySwatch: Colors.blue,
              ),
              home: auth.isAuth
                  ? (turnActive.turnData != null &&
                          turnActive.turnData['turn']['checkUpStartId'] != null)
                      ? CheckupPage() // Si el cotejo está en proceso
                      : InitialLoadingPage() // Si no hay cotejo iniciado
                  : FutureBuilder(
                      // Si estamos no hay autenticación en el estado, se chequea en el localStorage
                      future: auth.tryAutoLogin(),
                      builder: (ctx, authResultSnapshot) =>
                          authResultSnapshot.connectionState ==
                                  ConnectionState.waiting
                              ? LoadingData()
                              : LoginPage(),
                    ),
              routes: {
                LoginPage.routeName: (context) => LoginPage(),
                InitialLoadingPage.routeName: (context) => InitialLoadingPage(),
                CheckupPage.routeName: (context) => CheckupPage(),
                CheckupGroupsPage.routeName: (context) => CheckupGroupsPage(),
              },
            );
          },
        ));
  }
}
</code>```

答:
The problem was in this:

```<code>Navigator.popUntil(context, ModalRoute.withName('/login'))
</code>```

If we push the "/login" this override the home parameter in MaterialApp, loads the login page but the page will don't pop because the route. The correct way to do it is:

```<code>Navigator.of(context)
          .pushNamedAndRemoveUntil('/', (Route<dynamic> route) => false);
</code>```

With this one we redirect to '/' and then the state management using home parameter will work.

Body:
I have a big problem using state management with Providers and the navigator.

Things that we must know:

1) My RESTFUL API gives a token that expires on 12h.

2) My home: parameter is conditioned if the user is authenticated or nor.. if not, based in other parameters I must decide what screen must be the home.

3) If I'm on one screen and the token gets expired on ANY request that the app is doing to the API I:

Call a function inside my auth provider that do logout procedures, (i clean the localStorage with the token). This auth provider sets a property called isAuth to false.

When isAuth is false, if you look the main.dart file at home: you will see that will show the LoginPage().

Everything here is good. The problem is when i must do a redirect using the Navigator.of..... If, for example, in case of error of token expired I do: Navigator.popUntil(context, ModalRoute.withName('/login')); the app goes to the LoginPage() without problem, but... when I try to use the login (using the login function of auth provider) it's stay on the login page! If I use in any place the Navigator to go to any other place, it's appears to override the 'state management way' that I use to control which page shows as home.

Can you help me please?

My main.dart code:

// Providers
import 'package:provider/provider.dart';
import 'package:cadsanjuan_movil/providers/auth.dart';

// Pages
import './pages/login_page.dart';
import './pages/initial_loading_page.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  final storage = new FlutterSecureStorage();
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          ChangeNotifierProvider<Auth>(create: (context) => Auth()),
          ChangeNotifierProvider<TurnActive>(create: (context) => TurnActive()),
          ChangeNotifierProxyProvider<TurnActive, Checkup>(
              create: (context) => Checkup(),
              update: (_, turnActive, checkup) {
                checkup.turnData = turnActive.turnData;
                return checkup;
              }),
          ChangeNotifierProxyProvider<Auth, ErrorProvider>(
              create: (context) => ErrorProvider(),
              update: (_, auth, errorProvider) {
                errorProvider.logoff = auth.logoff;
                return errorProvider;
              }),
        ],
        child: Consumer3<Auth, TurnActive, Checkup>(
          builder: (context, auth, turnActive, checkup, _) {
            return MaterialApp(
              title: 'CAD App',
              theme: ThemeData(
                primarySwatch: Colors.blue,
              ),
              home: auth.isAuth
                  ? (turnActive.turnData != null &&
                          turnActive.turnData['turn']['checkUpStartId'] != null)
                      ? CheckupPage() // Si el cotejo está en proceso
                      : InitialLoadingPage() // Si no hay cotejo iniciado
                  : FutureBuilder(
                      // Si estamos no hay autenticación en el estado, se chequea en el localStorage
                      future: auth.tryAutoLogin(),
                      builder: (ctx, authResultSnapshot) =>
                          authResultSnapshot.connectionState ==
                                  ConnectionState.waiting
                              ? LoadingData()
                              : LoginPage(),
                    ),
              routes: {
                LoginPage.routeName: (context) => LoginPage(),
                InitialLoadingPage.routeName: (context) => InitialLoadingPage(),
                CheckupPage.routeName: (context) => CheckupPage(),
                CheckupGroupsPage.routeName: (context) => CheckupGroupsPage(),
              },
            );
          },
        ));
  }
}

Body:
The problem was in this:

Navigator.popUntil(context, ModalRoute.withName('/login'))

If we push the "/login" this override the home parameter in MaterialApp, loads the login page but the page will don't pop because the route. The correct way to do it is:

Navigator.of(context)
          .pushNamedAndRemoveUntil('/', (Route<dynamic> route) => false);

With this one we redirect to '/' and then the state management using home parameter will work.


来源: stackexchange

问:
UITextField textContentType doesn't return suggestion
I am experiencing this rather simple problem and it is confusing me because my Contact Card is filled with email addresses of all (home, work, iCloud, other) where as the First Name, Last Name, Telephone Number are all being presented as suggestions. Please let me know what I am doing wrong. Here is my code:

```<code>    emailTxtField.delegate = self
    emailTxtField.textContentType =.emailAddress
    phoneNumTxtField.delegate = self
    phoneNumTxtField.textContentType =.telephoneNumber
    firstNameTxtField.delegate = self
    firstNameTxtField.textContentType =.givenName
    lastNameTxtField.delegate = self
    lastNameTxtField.textContentType =.familyName
</code>```

Every other fields are getting suggestions but not the email address. Please help?

UPDATE

Some snapshots:

and another
.
.
.

答:
Did you try

```<code>emailTxtField.textContentType = .username
emailTxtField.keyboardType = .emailAddress
</code>```

Refer: Apple's article: Enabling Password AutoFill on a Text Input View

ContentLicense: CC BY-SA 4.0

Body:
I am experiencing this rather simple problem and it is confusing me because my Contact Card is filled with email addresses of all (home, work, iCloud, other) where as the First Name, Last Name, Telephone Number are all being presented as suggestions. Please let me know what I am doing wrong. Here is my code:

    emailTxtField.delegate = self
    emailTxtField.textContentType =.emailAddress
    phoneNumTxtField.delegate = self
    phoneNumTxtField.textContentType =.telephoneNumber
    firstNameTxtField.delegate = self
    firstNameTxtField.textContentType =.givenName
    lastNameTxtField.delegate = self
    lastNameTxtField.textContentType =.familyName

Every other fields are getting suggestions but not the email address. Please help?

UPDATE

Some snapshots:

and another
.
.
.

Body:
Did you try

emailTxtField.textContentType = .username
emailTxtField.keyboardType = .emailAddress

Refer: Apple's article: Enabling Password AutoFill on a Text Input View


问:
Define a maximum number of line in a div
I create a  with a text inside but the text is too large for the div :

How can I stop the text when the div is stopping ?

答:
Set a specific height to the div and then use overflow : auto; to resolve your issue.

<!DOCTYPE html>

    Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet
    dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy
    nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer
    adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem
    ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet
    dolore magna aliquam erat volutpat.

```

Body:
Set a specific height to the div and then use overflow : auto; to resolve your issue.

<!DOCTYPE html>
<html>

<head>
  <style>
    div.ex3 {
      background-color: lightblue;
      width: 100%;
      height: 110px;
      overflow: auto;
    }
  </style>
</head>

<body>
  <div class="ex3">
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet
    dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy
    nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer
    adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem
    ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet
    dolore magna aliquam erat volutpat.</div>

</body>

</html>


问:
Add background image and border image to form
I have a simple form based on jquery -

```<code><center>
    <form id="form1">
    <div id="registerDiv" data-role="fieldcontain" >
     <input type="button" value="Register" id="registerButton" data-inline="true"/>
    </div>
    </form>
  </center>
</code>```

Id like to modify the form so that it has two background images, one background covers the button (number 1 in attachment - layout.png), the second is a background image that act as a border(number 2 in attachment - layout.png). What is the best method of achieving this ?

Thanks

答:
I think all you're looking for is this:</p>

```<code>#form1 {
    background: url( /images/background1.jpg ) no-repeat;
}

#registerDiv {
    margin: 40px;
    background: url( /images/background2.jpg ) no-repeat;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a simple form based on jquery -

    <form id="form1">

     <input type="button" value="Register" id="registerButton" data-inline="true"/>

    </form>

Id like to modify the form so that it has two background images, one background covers the button (number 1 in attachment - layout.png), the second is a background image that act as a border(number 2 in attachment - layout.png). What is the best method of achieving this ?

Thanks

Body:
I think all you're looking for is this:

#form1 {
    background: url( /images/background1.jpg ) no-repeat;
}

#registerDiv {
    margin: 40px;
    background: url( /images/background2.jpg ) no-repeat;
}


问:
How can I add an icon to the Gmail side-bar?
What method do I use in a Google-apps script for Gmail to add an icon to the side-panel?

I can't seem to find any reference to it in the docs. Thanks.

答: You can only add a side panel icon by setting the "logoUrl" property in the manifest for GSuite Add-ons. See reference documentation.</p>


问:
How can I print multidimensional arrays in C?
```<code>#include <stdio.h>

int main(){

  int number[3][4] = {
    {10,20,30,40},
    {15,25,35,45},
    {47,48,49,50},
  };
      printf("%s",number[]);
  return 0;
}
</code>```

Ok, here's my code and what I wonder is how can I print out those arrays that I created. Do I have to use for loop or is there another way?

P.S: Im a newbie.

答:
So there are several problems with your code.

You're missing an array index in printf("%s",number[]);

You're using the wrong format specifier.  It should be %d, not%s.  The %d doesn't just act as a placeholder; it also tells C how to properly convert your number into a displayable form.

To print the array, you need a nested for loop.  Your program should look something like this:

```<code>int main(){

  int number[3][4] = {
    {10,20,30,40},
    {15,25,35,45},
    {47,48,49,50},
  };

  for (int i=0; i<3; i++) {
    for (int j=0; j<4; j++) {
      printf("%d ",number[i][j]);
    }
    printf("\n");
  }

  return 0;
}
</code>```

https://repl.it/@robertwharvey/AffectionateWorseHashmaps

Body:
#include <stdio.h>

int main(){

  int number[3][4] = {
    {10,20,30,40},
    {15,25,35,45},
    {47,48,49,50},
  };
      printf("%s",number[]);
  return 0;
}

Ok, here's my code and what I wonder is how can I print out those arrays that I created. Do I have to use for loop or is there another way?

P.S: Im a newbie.

Body:
So there are several problems with your code.

You're missing an array index in printf("%s",number[]);

You're using the wrong format specifier.  It should be %d, not%s.  The %d doesn't just act as a placeholder; it also tells C how to properly convert your number into a displayable form.

To print the array, you need a nested for loop.  Your program should look something like this:

int main(){

  int number[3][4] = {
    {10,20,30,40},
    {15,25,35,45},
    {47,48,49,50},
  };

  for (int i=0; i<3; i++) {
    for (int j=0; j<4; j++) {
      printf("%d ",number[i][j]);
    }
    printf("\n");
  }

  return 0;
}

https://repl.it/@robertwharvey/AffectionateWorseHashmaps


问:
Why does the command "git fetch -p" brings the same branch as deleted and new branch at the same time?
I have a weird "issue" (is not affecting me at all because the branch does exists locally and remote) and I am curious about it. I am not sure if this is a configuration I am missing or I do have but as I said is really weird.

Each time I do git fetch -p I got the branch [deleted] and [new branch] and the only difference is a capital letter in front of the branch name as shown in the example below:

```<code>λ git checkout development && git pull origin development && git fetch -p
Switched to branch 'development'
Your branch is up to date with 'origin/development'.
From github.com:ers/case
 * branch              development -> FETCH_HEAD
Already up to date.
From github.com:ers/case
 - [deleted]           (none)     -> origin/hotfix/DISPUTELAB-4991
 * [new branch]        Hotfix/DISPUTELAB-4991 -> origin/Hotfix/DISPUTELAB-4991
</code>```

Here is the result of the command git config --list:

```<code>λ git config --list
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
http.sslbackend=openssl
diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
credential.helper=manager
core.editor=nano.exe
core.autocrlf=true
core.fscache=true
core.symlinks=false
core.autocrlf=true
winupdater.recentlyseenversion=2.23.0.windows.1
user.name=reypm
user.email=<********>
alias.l=log --pretty=format:%C(yellow)%h\ %ad%Cred%d\ %Creset%s%Cblue\ [%cn] --decorate --date=short
alias.lg='git log --graph --oneline --decorate --all'
alias.a=add
alias.ap=add -p
alias.aa=add .
alias.ac=!git add -A && git commit -m
alias.c=commit --verbose
alias.ca=commit -a --verbose
alias.cm=commit -m
alias.cam=commit -a -m
alias.m=commit --amend --verbose
alias.d=diff
alias.ds=diff --stat
alias.dc=diff --cached
alias.a=add
alias.ap=add -p
alias.aa=add .
alias.c=commit --verbose
alias.ca=commit -a --verbose
alias.cm=commit -m
alias.cam=commit -a -m
alias.m=commit --amend --verbose
alias.d=diff
alias.ds=diff --stat
alias.dc=diff --cached
alias.s=status -s
alias.co=checkout
alias.cob=checkout -b
alias.b=!git for-each-ref --sort='-authordate' --format='%(authordate)%09%(objectname:short)%09%(refname)' refs/heads | sed -e 's-refs/heads/--'
alias.la=!git config -l | grep alias | cut -c 7-
commit.gpgsign=false
gui.pruneduringfetch=true
smartgit.submodule.fetchalways=true
smartgit.submodule.update=true
smartgit.submodule.initializenew=true
push.recursesubmodules=check
core.repositoryformatversion=0
core.filemode=false
core.bare=false
core.logallrefupdates=true
core.symlinks=false
core.ignorecase=true
remote.origin.url=git@github.com:ers/case.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
user.name=reypm
user.email=<******>
branch.development.remote=origin
branch.development.merge=refs/heads/development
branch.master.remote=origin
branch.master.merge=refs/heads/master
gitflow.branch.master=master
gitflow.branch.develop=development
gitflow.prefix.feature=feature/
gitflow.prefix.bugfix=bugfix/
gitflow.prefix.release=release/
gitflow.prefix.hotfix=hotfix/
gitflow.prefix.support=support/
gitflow.prefix.versiontag=
gitflow.path.hooks=D:/dev/docker/case/.git/hooks
</code>```

In addition to what I have said before I must say I am using Git from Windows.

I also notice core.ignorecase=true but I am not sure what would do if I change that to false or if I should keep it as true since I am in Windows and it's know to be problematic with file names and so on.

As a fun fact remote branches with capital letter does not exists in the origin:

```<code>λ git fetch -p
From github.com:ers/case
 - [deleted]             (none)     -> origin/Hotfix/DISPUTELAB-4991
 * [new branch]          hotfix/DISPUTELAB-4991  -> origin/hotfix/DISPUTELAB-4991

λ git branch -r | grep DISPUTELAB-4991
  origin/hotfix/DISPUTELAB-4991
</code>```

Does any see anything there leading to that "issue"? I am completely lost on this one.

答:
origin/hotfix/DISPUTELAB-4991 is clearly totally different from origin/Hotfix/DISPUTELAB-4991, in the same way that Polish and polish are two completely different words.1

Git understands this fact and handles it correctly.  Your OS, on the other hand, insists that hotfix and Hotfix are the same.  So you get weirdness around this case.

Git sometimes stores these names in a text file, where they are different, the way Linus Torvalds and Git intend them to be.  But sometimes Git stores these names in folder-and-file-names on disk, and then they become the same.  The core.ignorecase setting will not help, for two reasons:

It is purely informative: it tells Git about your system, but does not actually change anything Git does with file names.  (It probably should, but doesn't.)

It's only used for files extracted from commits into your work-tree, not for branch names, tag names, remote-tracking names, and other such references.

Git needs—and is gradually growing2—some better handling of file names inside repositories for these cases.  It also badly needs, but is not getting, better handling of branch and other reference names.  Because of this second issue, it's best to just use all lowercase letters for all branch, tag, and other names.  Just pretend uppercase does not exist: avoid it and you'll never find Git behaving weirdly on case-folding systems.

1The sentence "the Polish man applied shoe polish" makes sense; the variant with "the polish man applied shoe Polish" veers off into the weeds at the last moment. :-)

2This is linked to the ongoing sparse-checkout work.  That's one way to handle the problem, and it generalizes to other problems we encounter when using Git on both Linux and MacOS, for instance, with MacOS's insistence on normalizing file names like schön, although I think it's still not really quite right.

Body:
I have a weird "issue" (is not affecting me at all because the branch does exists locally and remote) and I am curious about it. I am not sure if this is a configuration I am missing or I do have but as I said is really weird.

Each time I do git fetch -p I got the branch [deleted] and [new branch] and the only difference is a capital letter in front of the branch name as shown in the example below:

λ git checkout development && git pull origin development && git fetch -p
Switched to branch 'development'
Your branch is up to date with 'origin/development'.
From github.com:ers/case
 * branch              development -> FETCH_HEAD
Already up to date.
From github.com:ers/case
 - [deleted]           (none)     -> origin/hotfix/DISPUTELAB-4991
 * [new branch]        Hotfix/DISPUTELAB-4991 -> origin/Hotfix/DISPUTELAB-4991

Here is the result of the command git config --list:

λ git config --list
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
http.sslbackend=openssl
diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.process=git-lfs filter-process
filter.lfs.required=true
credential.helper=manager
core.editor=nano.exe
core.autocrlf=true
core.fscache=true
core.symlinks=false
core.autocrlf=true
winupdater.recentlyseenversion=2.23.0.windows.1
user.name=reypm
user.email=<********>
alias.l=log --pretty=format:%C(yellow)%h\ %ad%Cred%d\ %Creset%s%Cblue\ [%cn] --decorate --date=short
alias.lg='git log --graph --oneline --decorate --all'
alias.a=add
alias.ap=add -p
alias.aa=add .
alias.ac=!git add -A && git commit -m
alias.c=commit --verbose
alias.ca=commit -a --verbose
alias.cm=commit -m
alias.cam=commit -a -m
alias.m=commit --amend --verbose
alias.d=diff
alias.ds=diff --stat
alias.dc=diff --cached
alias.a=add
alias.ap=add -p
alias.aa=add .
alias.c=commit --verbose
alias.ca=commit -a --verbose
alias.cm=commit -m
alias.cam=commit -a -m
alias.m=commit --amend --verbose
alias.d=diff
alias.ds=diff --stat
alias.dc=diff --cached
alias.s=status -s
alias.co=checkout
alias.cob=checkout -b
alias.b=!git for-each-ref --sort='-authordate' --format='%(authordate)%09%(objectname:short)%09%(refname)' refs/heads | sed -e 's-refs/heads/--'
alias.la=!git config -l | grep alias | cut -c 7-
commit.gpgsign=false
gui.pruneduringfetch=true
smartgit.submodule.fetchalways=true
smartgit.submodule.update=true
smartgit.submodule.initializenew=true
push.recursesubmodules=check
core.repositoryformatversion=0
core.filemode=false
core.bare=false
core.logallrefupdates=true
core.symlinks=false
core.ignorecase=true
remote.origin.url=git@github.com:ers/case.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
user.name=reypm
user.email=<******>
branch.development.remote=origin
branch.development.merge=refs/heads/development
branch.master.remote=origin
branch.master.merge=refs/heads/master
gitflow.branch.master=master
gitflow.branch.develop=development
gitflow.prefix.feature=feature/
gitflow.prefix.bugfix=bugfix/
gitflow.prefix.release=release/
gitflow.prefix.hotfix=hotfix/
gitflow.prefix.support=support/
gitflow.prefix.versiontag=
gitflow.path.hooks=D:/dev/docker/case/.git/hooks

In addition to what I have said before I must say I am using Git from Windows.

I also notice core.ignorecase=true but I am not sure what would do if I change that to false or if I should keep it as true since I am in Windows and it's know to be problematic with file names and so on.

As a fun fact remote branches with capital letter does not exists in the origin:

λ git fetch -p
From github.com:ers/case
 - [deleted]             (none)     -> origin/Hotfix/DISPUTELAB-4991
 * [new branch]          hotfix/DISPUTELAB-4991  -> origin/hotfix/DISPUTELAB-4991

λ git branch -r | grep DISPUTELAB-4991
  origin/hotfix/DISPUTELAB-4991

Does any see anything there leading to that "issue"? I am completely lost on this one.


问:
JSP editor for eclipse, does it exist?
I noticed that my Eclipse does not include JSP Editor. Does standard JSP editor exist for Eclipse and if so, where can one download it from?

答:
To install from within IDE for newer Eclipse clients:

Help->Eclipse Marketplace

Search for "Eclipse Java EE Developer Tools".  Install.

Title: JSP editor for eclipse, does it exist?


问:
Plotting choropleth map with discrete colorbar/legend using Geopandas
I am trying to make a choropleth map using Geopandas. However I'm having trouble with the colourbar formatting, it seems to be very limited.

Here is the map I have:

But I would like the colorbar(legend?) to be discrete breaks, or a colour key, I'm not really sure what to call it. Something like this:

Is this even possible with Geopandas? I'm finding nothing in their documentation. Maybe something with legend_kwds?

Here is my plotting code

```<code>fig, ax = plt.subplots(1, figsize = (20, 12) )

ax.axis('off')

merged.plot(ax = ax, column = '2019-12', color = 'grey', label = 'No Data') #Plots 'No Data' layer
merged.dropna().plot(ax = ax, column = '2019-12', cmap = 'Reds', alpha = 1, legend = True) #Plots data layer

ax.legend()
</code>```

In an ideal world, I'd also be able to manually set the numbers and limits of the intervals as well.

答: This answer helped a lot. I was able to use classification_kwds and define my own bins using using the User_Defined scheme argument when calling gpd.plot(). Although I would like more functionality, this is good enough for now.

Body:
I am trying to make a choropleth map using Geopandas. However I'm having trouble with the colourbar formatting, it seems to be very limited.

Here is the map I have:

But I would like the colorbar(legend?) to be discrete breaks, or a colour key, I'm not really sure what to call it. Something like this:

Is this even possible with Geopandas? I'm finding nothing in their documentation. Maybe something with legend_kwds?

Here is my plotting code

fig, ax = plt.subplots(1, figsize = (20, 12) )

ax.axis('off')

merged.plot(ax = ax, column = '2019-12', color = 'grey', label = 'No Data') #Plots 'No Data' layer
merged.dropna().plot(ax = ax, column = '2019-12', cmap = 'Reds', alpha = 1, legend = True) #Plots data layer

ax.legend()

In an ideal world, I'd also be able to manually set the numbers and limits of the intervals as well.


Title: grep specific section or number/word, with R, contained in a text file

Body:
I have a text file that contains a lot of different output sections from a research analysis. the text file looks like this...

Zone  1

Dist.   Time         Amb.   Time         Ster.  Time         Vert.  Vert.        Zone       Zone
Tr.(cm) Amb.         Cnts.  Ster.        Cnts.  Rest.        Cnts.  Time         Entries    Time
======= ============ ====== ============ ====== ============ ====== ============ ========== ============
 626.29 000:00:29.90    480 000:00:05.25     52 000:00:24.85     11 000:00:11.75          1 000:01:00.00
 489.99 000:00:23.20    401 000:00:07.30     75 000:00:29.45      5 000:00:11.65          0 000:01:00.00
-----------------------------------------------------------------------------------------------------

Zone Totals

Dist.   Time         Amb.   Time         Ster.  Time         Vert.  Vert.        Zone       Zone
Tr.(cm) Amb.         Cnts.  Ster.        Cnts.  Rest.        Cnts.  Time         Entries    Time
======= ============ ====== ============ ====== ============ ====== ============ ========== ============
5661.08 000:04:39.30   4360 000:00:55.35    572 000:04:25.35     81 000:02:23.85          1 000:10:00.00
======= ============ ====== ============ ====== ============ ====== ============ ==========
-----------------------------------------------------------------------------------------------------

Block Summary
-------------
Dist.      Time         Amb.   Time         Ster.  Time         Vert.  Vert.        Zone
Trav.(cm)  Amb.         Cnts.  Ster.        Cnts.  Rest.        Cnts.  Time         Entries
========== ============ ====== ============ ====== ============ ====== ============ ==========
    626.29 000:00:29.90    480 000:00:05.25     52 000:00:24.85     11 000:00:11.75          1
    489.99 000:00:23.20    401 000:00:07.30     75 000:00:29.45      5 000:00:11.65          0

How can I grep just the zone total section? More specifically, I would like to grep just the "Dist. Tr." number from the "zone totals" section. But I would be happy with just getting the whole section and then cropping the lines where needed.

I was thinking of something like this...

dist_move = apply(data.frame(grep("Totals",dat)+1, grep("Block",dat)-2),1,function(x) (dat[x[1]:x[2]]))

But it was just grabbing all of the lines

Body:
A slightly more generalized method (in case you have multiple rows in Zone Totals) using stringr

library(stringr)

# Split into lines
lines <- unlist(strsplit(myText, "\n"))

# Find bounds of target section
sectStart <- str_which(lines, "Zone Totals")
sectStop <- str_which(lines[seq(sectStart+1, length(lines))],
                      "-----")[1] + sectStart

# subset data rows and extract first entry
dist_move <- str_subset(lines[seq(sectStart, sectStop)], "^[:digit:]") %>%
  str_extract("^[:digit:]+\\.{0,1}[:digit:]*")

NOTE

myText <-
"Zone  1

Dist.   Time         Amb.   Time         Ster.  Time         Vert.  Vert.        Zone       Zone
Tr.(cm) Amb.         Cnts.  Ster.        Cnts.  Rest.        Cnts.  Time         Entries    Time
======= ============ ====== ============ ====== ============ ====== ============ ========== ============
 626.29 000:00:29.90    480 000:00:05.25     52 000:00:24.85     11 000:00:11.75          1 000:01:00.00
 489.99 000:00:23.20    401 000:00:07.30     75 000:00:29.45      5 000:00:11.65          0 000:01:00.00
-----------------------------------------------------------------------------------------------------

Zone Totals

Dist.   Time         Amb.   Time         Ster.  Time         Vert.  Vert.        Zone       Zone
Tr.(cm) Amb.         Cnts.  Ster.        Cnts.  Rest.        Cnts.  Time         Entries    Time
======= ============ ====== ============ ====== ============ ====== ============ ========== ============
5661.08 000:04:39.30   4360 000:00:55.35    572 000:04:25.35     81 000:02:23.85          1 000:10:00.00
======= ============ ====== ============ ====== ============ ====== ============ ==========
-----------------------------------------------------------------------------------------------------

Block Summary
-------------
Dist.      Time         Amb.   Time         Ster.  Time         Vert.  Vert.        Zone
Trav.(cm)  Amb.         Cnts.  Ster.        Cnts.  Rest.        Cnts.  Time         Entries
========== ============ ====== ============ ====== ============ ====== ============ ==========
    626.29 000:00:29.90    480 000:00:05.25     52 000:00:24.85     11 000:00:11.75          1
    489.99 000:00:23.20    401 000:00:07.30     75 000:00:29.45      5 000:00:11.65          0"


问:
Sequential stages inside parallel in Scripted Pipeline syntax
In my Jenkinsfile I execute 2 stages in parallel and one of these stages would consist of few other sequential stages. When I run the script and check the pipeline in BlueOcean, that sequence of stages is represented as one single node.

The (simplified) script is as follows :

```<code>node {
    stage('Stage 1') {...}
    stage('Stage 2') {...}
    stage('Stages 3 & 4 in parallel') {
        parallel(
            'Stage 3': {
                stage('Stage 3') {...}
            },
            'Stage 4': {
                stage('Stage 4a') {...}
                stage('Stage 4b') {...}
            }
        )
    }
}
</code>```

So in BlueOcean this script results in one node for stage 4 while I wish to see two nodes as it is composed of two sequential stages.

答:
I too have faced the same issue with Scripted pipelines. If you are fine with Declarative pipelines, you can use this:

```<code>pipeline {
    agent any
    stages {
        stage('Stage 1') { steps {pwd()}}
        stage('Stage 2') { steps {pwd()}}
        stage('Stages 3 & 4 in parallel') {
            parallel {
                stage('Stage 3') { steps {pwd()}}
                stage('Stage 4') {
                    stages {
                        stage('Stage 4a') { steps {pwd()}}
                        stage('Stage 4b') { steps {pwd()}}
                    }
                }
            }
        }
    }
}
</code>```

Body:
In my Jenkinsfile I execute 2 stages in parallel and one of these stages would consist of few other sequential stages. When I run the script and check the pipeline in BlueOcean, that sequence of stages is represented as one single node.

The (simplified) script is as follows :

node {
    stage('Stage 1') {...}
    stage('Stage 2') {...}
    stage('Stages 3 & 4 in parallel') {
        parallel(
            'Stage 3': {
                stage('Stage 3') {...}
            },
            'Stage 4': {
                stage('Stage 4a') {...}
                stage('Stage 4b') {...}
            }
        )
    }
}

So in BlueOcean this script results in one node for stage 4 while I wish to see two nodes as it is composed of two sequential stages.

Body:
I too have faced the same issue with Scripted pipelines. If you are fine with Declarative pipelines, you can use this:

pipeline {
    agent any
    stages {
        stage('Stage 1') { steps {pwd()}}
        stage('Stage 2') { steps {pwd()}}
        stage('Stages 3 & 4 in parallel') {
            parallel {
                stage('Stage 3') { steps {pwd()}}
                stage('Stage 4') {
                    stages {
                        stage('Stage 4a') { steps {pwd()}}
                        stage('Stage 4b') { steps {pwd()}}
                    }
                }
            }
        }
    }
}


问:
Error creating Security Group: InvalidGroup.Duplicate when defining AWS security group in Terraform
I'm new to Terraform, when I run Terraform apply, I git this error:

```<code>Error: Error creating Security Group: InvalidGroup.Duplicate: The security group 'xxxxxxx' already exists for VPC 'vpc-xxxxxx'
        status code: 400
</code>```

The script for this part looks like this:

```<code>resource "aws_security_group" "xxxxx_security_group" {
  name   = "xxxxx-security-group-xxxx"
  vpc_id = xxxxxxxxxxxxx

  egress {
    from_port   = x
    protocol    = x
    to_port     = x
    cidr_blocks = ["x.x.x.x/x"]
  }
}
</code>```

Can someone give me some hints? Spent like almost an hour now, still no clue....

答:
It looks like you created the security group in the console already (or with the CLI), so trying to create the security group again in terraform is causing an error because the name already exists.

To fix this, go into the AWS console and look for the security group with the name you're trying to make. Find its ID value, which will look like sg-xxxxxxxxxxxx.

Then in your terminal, import that resource into your terraform state by running:

terraform import aws_security_group.xxxxx_security_group sg-xxxxxxxxxxx

After this, you can run terraform plan or terraform apply and everything should work, because terraform's state knows about the existing resource.

Body:
I'm new to Terraform, when I run Terraform apply, I git this error:

Error: Error creating Security Group: InvalidGroup.Duplicate: The security group 'xxxxxxx' already exists for VPC 'vpc-xxxxxx'
        status code: 400

The script for this part looks like this:

resource "aws_security_group" "xxxxx_security_group" {
  name   = "xxxxx-security-group-xxxx"
  vpc_id = xxxxxxxxxxxxx

  egress {
    from_port   = x
    protocol    = x
    to_port     = x
    cidr_blocks = ["x.x.x.x/x"]
  }
}

Can someone give me some hints? Spent like almost an hour now, still no clue....


问:
Round Robin Tournament algorithm in C#
I am having some trouble to achieve this little round robin project. What i try to do is to generate a preview calendar of games

then I want to output;

day 1:
Team 1 vs Team 2;
Team 3 vs Team 4;
Team 5vs Team 6;

day 2
Team 1 vs Team 4;
Team 6 vs Team 3;
Team 2 vs Team 5;

till the end of the championship;

Here is the code i've got so far but i'm having trouble to let the first team fixed while the rest of the array rotates...:

```<code>static void Main(string[] args)
   {
        string[] ListTeam = new string[] {"Equipe1", "Equipe2", "Equipe3", "Equipe4", "Equipe5", "Equipe6"};
        IList<Match> ListMatch = new List<Match>();
        it NumberOfDays = (ListTeam.Count()-1);
        int y = 2;

        for (int i = 1; i <= NumberOfDays; i++)
        {
            Console.WriteLine("\nDay {0} : \n",i);
            Console.WriteLine(ListTeam[0].ToString() + " VS " + ListTeam[i].ToString());

            for (y =ListTeam.Count(); y>0 ; y--)
            {
                Console.WriteLine(ListTeam[y].ToString() + " VS " + ListTeam[y+1].ToString());
                y++;
            }

        }
    }
</code>```

EDIT: I found a code sample in java but i cant translate it...

答:
I've posted my implementation on github RoundRobinTournamentSchedule
You can find corresponding nuget package and use it in your own solution

Cheers

ContentLicense: CC BY-SA 2.5

Title: Round Robin Tournament algorithm in C#

Body:
I am having some trouble to achieve this little round robin project. What i try to do is to generate a preview calendar of games

then I want to output;

day 1:
Team 1 vs Team 2;
Team 3 vs Team 4;
Team 5vs Team 6;

day 2
Team 1 vs Team 4;
Team 6 vs Team 3;
Team 2 vs Team 5;

till the end of the championship;

Here is the code i've got so far but i'm having trouble to let the first team fixed while the rest of the array rotates...:

static void Main(string[] args)
   {
        string[] ListTeam = new string[] {"Equipe1", "Equipe2", "Equipe3", "Equipe4", "Equipe5", "Equipe6"};
        IList<Match> ListMatch = new List<Match>();
        it NumberOfDays = (ListTeam.Count()-1);
        int y = 2;

        for (int i = 1; i <= NumberOfDays; i++)
        {
            Console.WriteLine("\nDay {0} : \n",i);
            Console.WriteLine(ListTeam[0].ToString() + " VS " + ListTeam[i].ToString());

            for (y =ListTeam.Count(); y>0 ; y--)
            {
                Console.WriteLine(ListTeam[y].ToString() + " VS " + ListTeam[y+1].ToString());
                y++;
            }

        }
    }

EDIT: I found a code sample in java but i cant translate it...


问:
Facing issue while link snowboy with google assistant

i facing the problem while running the commands to link snowboy with google assistant, i dont understand what error and how to resolve this please give some solution for this error

```<code>Traceback (most recent call last):
</code>```

File "demo.py", line 1, in
    import snowboydecoder
  File "/home/pi/hestia/snowboy/examples/Python3/snowboydecoder.py", line 7, in
    import snowboydetect
  File "/home/pi/hestia/snowboy/examples/Python3/snowboydetect.py", line 17, in
    _snowboydetect = swig_import_helper()
  File "/home/pi/hestia/snowboy/examples/Python3/snowboydetect.py", line 16, in swig_import_helper
    return importlib.import_module('_snowboydetect')
  File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module
    import(name)
ImportError: dynamic module does not define init function (init_snowboydetect)

答:
i had the same issue. fixed it by running demo.py using python2

python2 demo.py snowboy.umdl

Body:
i facing the problem while running the commands to link snowboy with google assistant, i dont understand what error and how to resolve this please give some solution for this error

Traceback (most recent call last):

File "demo.py", line 1, in
    import snowboydecoder
  File "/home/pi/hestia/snowboy/examples/Python3/snowboydecoder.py", line 7, in
    import snowboydetect
  File "/home/pi/hestia/snowboy/examples/Python3/snowboydetect.py", line 17, in
    _snowboydetect = swig_import_helper()
  File "/home/pi/hestia/snowboy/examples/Python3/snowboydetect.py", line 16, in swig_import_helper
    return importlib.import_module('_snowboydetect')
  File "/usr/lib/python2.7/importlib/init.py", line 37, in import_module
    import(name)
ImportError: dynamic module does not define init function (init_snowboydetect)


问:
Select sibling records until next tag using XSLT 1.0
I have following input XML. The successive E_Records are optional and it should be populated into L_Record. I have written the below XSLT coding. Is there any changes should i have to do?

Input XML

```<code><?xml version="1.0" encoding="UTF-8"?>
  <Record>
     <H_Record>
        <Rec_Type>H</Rec_Type>
     </H_Record>
     <C_Record>
        <Rec_Type>C</Rec_Type>
     </C_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
     </L_Record>
     <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>3</E_Qty>
     </E_Record>
     <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>4</E_Qty>
     </E_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
     </L_Record>
     <R_Record>
        <Rec_Type>R</Rec_Type>
     </R_Record>
  </Record>
  <Record>
     <H_Record>
        <Rec_Type>H</Rec_Type>
     </H_Record>
     <C_Record>
        <Rec_Type>C</Rec_Type>
     </C_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
     </L_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
     </L_Record>
     <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>1</E_Qty>
     </E_Record>
     <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>2</E_Qty>
     </E_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
     </L_Record>
     <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>5</E_Qty>
     </E_Record>
     <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>6</E_Qty>
     </E_Record>
     <R_Record>
        <Rec_Type>R</Rec_Type>
     </R_Record>
  </Record>
</code>```

The Output XML i am expecting is

```<code> <Record>
   <H_Record>
        <Rec_Type>H</Rec_Type>
   </H_Record>
   <C_Record>
        <Rec_Type>C</Rec_Type>
   </C_Record>
   <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
      <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>3</E_Qty>
      </E_Record>
      <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>4</E_Qty>
      </E_Record>
    </L_Record>
    <L_Record>
       <Rec_Type>L</Rec_Type>
       <L_Level>2</L_Level>
    </L_Record>
    <R_Record>
       <Rec_Type>R</Rec_Type>
    </R_Record>
  </Record>
  <Record>
     <H_Record>
        <Rec_Type>H</Rec_Type>
     </H_Record>
     <C_Record>
        <Rec_Type>C</Rec_Type>
     </C_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
     </L_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
       <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>1</E_Qty>
       </E_Record>
       <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>2</E_Qty>
       </E_Record>
     </L_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
        <E_Record>
          <Rec_Type>E</Rec_Type>
          <E_Qty>5</E_Qty>
        </E_Record>
        <E_Record>
          <Rec_Type>E</Rec_Type>
          <E_Qty>6</E_Qty>
        </E_Record>
    </L_Record>
    <R_Record>
        <Rec_Type>R</Rec_Type>
     </R_Record>
  </Record>
</code>```

I have written the XSLT mapping for this as below but i am not getting the required output. Could you please help me on this?

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output omit-xml-declaration="yes" indent="yes"/>
         <xsl:template match="@* | node()">
      <xsl:copy>
         <xsl:apply-templates select="@* | node()"/>
      </xsl:copy>
   </xsl:template>
   <xsl:template match="Record/L_Record">
   <L_Record>
    <xsl:variable name="header" select="."/>
            <xsl:apply-templates/>
            <xsl:if test = "not(following-sibling::L_Record)">
            <xsl:for-each select="following-sibling::E_Record[preceding-sibling::L_Record = $header]">
            <xsl:copy-of select="."/>
            </xsl:for-each>
            </xsl:if>
    </L_Record>
    </xsl:template>
 </xsl:stylesheet>
</code>```

Please help me on this?

When i am executing the above code, Record 1 is working fine, but the record 2 is not working properly. The E-Record segment is not appearing in the L-Record segment.

答:
You should be able to create an xsl:key matching E_Record elements and use the generated id of the first preceding L_Record sibling as the key.

Then you can match L_Record elements and copy the node set with the matching key.

Example...

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:key name="e_recs" match="E_Record" use="generate-id(preceding-sibling::L_Record[1])"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="L_Record">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
      <xsl:copy-of select="key('e_recs',generate-id())"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="E_Record"/>

</xsl:stylesheet>
</code>```

Fiddle: http://xsltfiddle.liberty-development.net/94Acsmd

Body:
I have following input XML. The successive E_Records are optional and it should be populated into L_Record. I have written the below XSLT coding. Is there any changes should i have to do?

Input XML

<?xml version="1.0" encoding="UTF-8"?>
  <Record>
     <H_Record>
        <Rec_Type>H</Rec_Type>
     </H_Record>
     <C_Record>
        <Rec_Type>C</Rec_Type>
     </C_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
     </L_Record>
     <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>3</E_Qty>
     </E_Record>
     <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>4</E_Qty>
     </E_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
     </L_Record>
     <R_Record>
        <Rec_Type>R</Rec_Type>
     </R_Record>
  </Record>
  <Record>
     <H_Record>
        <Rec_Type>H</Rec_Type>
     </H_Record>
     <C_Record>
        <Rec_Type>C</Rec_Type>
     </C_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
     </L_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
     </L_Record>
     <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>1</E_Qty>
     </E_Record>
     <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>2</E_Qty>
     </E_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
     </L_Record>
     <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>5</E_Qty>
     </E_Record>
     <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>6</E_Qty>
     </E_Record>
     <R_Record>
        <Rec_Type>R</Rec_Type>
     </R_Record>
  </Record>

The Output XML i am expecting is

 <Record>
   <H_Record>
        <Rec_Type>H</Rec_Type>
   </H_Record>
   <C_Record>
        <Rec_Type>C</Rec_Type>
   </C_Record>
   <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
      <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>3</E_Qty>
      </E_Record>
      <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>4</E_Qty>
      </E_Record>
    </L_Record>
    <L_Record>
       <Rec_Type>L</Rec_Type>
       <L_Level>2</L_Level>
    </L_Record>
    <R_Record>
       <Rec_Type>R</Rec_Type>
    </R_Record>
  </Record>
  <Record>
     <H_Record>
        <Rec_Type>H</Rec_Type>
     </H_Record>
     <C_Record>
        <Rec_Type>C</Rec_Type>
     </C_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
     </L_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
       <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>1</E_Qty>
       </E_Record>
       <E_Record>
        <Rec_Type>E</Rec_Type>
        <E_Qty>2</E_Qty>
       </E_Record>
     </L_Record>
     <L_Record>
        <Rec_Type>L</Rec_Type>
        <L_Level>2</L_Level>
        <E_Record>
          <Rec_Type>E</Rec_Type>
          <E_Qty>5</E_Qty>
        </E_Record>
        <E_Record>
          <Rec_Type>E</Rec_Type>
          <E_Qty>6</E_Qty>
        </E_Record>
    </L_Record>
    <R_Record>
        <Rec_Type>R</Rec_Type>
     </R_Record>
  </Record>

I have written the XSLT mapping for this as below but i am not getting the required output. Could you please help me on this?

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output omit-xml-declaration="yes" indent="yes"/>
         <xsl:template match="@* | node()">
      <xsl:copy>
         <xsl:apply-templates select="@* | node()"/>
      </xsl:copy>
   </xsl:template>
   <xsl:template match="Record/L_Record">
   <L_Record>
    <xsl:variable name="header" select="."/>
            <xsl:apply-templates/>
            <xsl:if test = "not(following-sibling::L_Record)">
            <xsl:for-each select="following-sibling::E_Record[preceding-sibling::L_Record = $header]">
            <xsl:copy-of select="."/>
            </xsl:for-each>
            </xsl:if>
    </L_Record>
    </xsl:template>
 </xsl:stylesheet>

Please help me on this?

When i am executing the above code, Record 1 is working fine, but the record 2 is not working properly. The E-Record segment is not appearing in the L-Record segment.

Body:
You should be able to create an xsl:key matching E_Record elements and use the generated id of the first preceding L_Record sibling as the key.

Then you can match L_Record elements and copy the node set with the matching key.

Example...

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:key name="e_recs" match="E_Record" use="generate-id(preceding-sibling::L_Record[1])"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="L_Record">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
      <xsl:copy-of select="key('e_recs',generate-id())"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="E_Record"/>

</xsl:stylesheet>

Fiddle: http://xsltfiddle.liberty-development.net/94Acsmd


问:
If statement True is ignored and always executes Else
I want to check column 1 for any matches with a TextBox.

If there is a match, update a few textboxes with worksheet data. If there is no match, then display a MsgBox. Here's a snippet of my code:

Private Sub CheckPCButton_Click()
    Dim totRows As Long, i As Long
    totRows = Worksheets("Sheet4").Range("A1").CurrentRegion.Rows.Count

    For i = 2 To totRows
        If Trim(UCase(Sheet4.Cells(i, 1))) = Trim(UCase(TextBox22.Text)) Then
            TextBox22.Text = Sheet4.Cells(i, 1)
            TextBox25.Text = Sheet4.Cells(i, 2)
            TextBox24.Text = Sheet4.Cells(i, 3)
            TextBox23.Text = "Approved"
        Else
            MsgBox "Not approved"
            Exit For
        End If
    Next i

End Sub
```

答:
Is your code's logic correct? My understanding of your code is:

Start with ROW = 2

Check if Cells(ROW,1) and TextBox22 match.

If they do match, update the userform including updating TextBox22

Now advance to the next ROW and repeat starting at step 2

Steps 2, 3, 4 will repeat until a mismatch is encountered

If there is no match, show a MsgBox

So unless all of the values in Column 1 match what is initially in TextBox22, you're eventually going to get the MsgBox.

Added based on comment from original poster

I think this code does what you're after

```<code>Private Sub CheckPCButton_Click()
    Dim MatchFound as boolean
    Dim totRows As Long, i As Long
    totRows = Worksheets("Sheet4").Range("A1").CurrentRegion.Rows.Count
    MatchFound = False
    For i = 2 To totRows
        If Trim(UCase(Sheet4.Cells(i, 1))) = Trim(UCase(TextBox22.Text)) Then
            TextBox22.Text = Sheet4.Cells(i, 1)
            TextBox25.Text = Sheet4.Cells(i, 2)
            TextBox24.Text = Sheet4.Cells(i, 3)
            TextBox23.Text = "Approved"
            MatchFound = True
            Exit For
        End If
    Next i
    If Not MatchFound Then MsgBox "Not approved"

End Sub
</code>```

Body:
Is your code's logic correct? My understanding of your code is:

Start with ROW = 2

Check if Cells(ROW,1) and TextBox22 match.

If they do match, update the userform including updating TextBox22

Now advance to the next ROW and repeat starting at step 2

Steps 2, 3, 4 will repeat until a mismatch is encountered

If there is no match, show a MsgBox

So unless all of the values in Column 1 match what is initially in TextBox22, you're eventually going to get the MsgBox.

Added based on comment from original poster

I think this code does what you're after

Private Sub CheckPCButton_Click()
    Dim MatchFound as boolean
    Dim totRows As Long, i As Long
    totRows = Worksheets("Sheet4").Range("A1").CurrentRegion.Rows.Count
    MatchFound = False
    For i = 2 To totRows
        If Trim(UCase(Sheet4.Cells(i, 1))) = Trim(UCase(TextBox22.Text)) Then
            TextBox22.Text = Sheet4.Cells(i, 1)
            TextBox25.Text = Sheet4.Cells(i, 2)
            TextBox24.Text = Sheet4.Cells(i, 3)
            TextBox23.Text = "Approved"
            MatchFound = True
            Exit For
        End If
    Next i
    If Not MatchFound Then MsgBox "Not approved"

End Sub


问:
Check that object is not instance of any class in typescript
I have a function which takes objects and proxies them.

I do not want it to proxy classes, and I'd like to assert that with the argument type.

How can I do this?

```<code>type NonClassObject = ???;
export function createObjectProxy(obj: NonClassObject) {
  return new Proxy(obj, {});
}

const foo: NonClassObject = {};
const bar: NonClassObject = {} as HTMLElement; // this should be a type error
</code>```

There doesn't seem to be much to distinguish the two except for the typeof the constructor.  I'm not sure if there's a way to say Exact<tyepof OBJ.constructor, Object>... but I'm looking into Utility types now.

On to something:

Dead end: https://github.com/Microsoft/TypeScript/issues/3841

答:
There's an open issue about making the constructor type more defined (https://github.com/Microsoft/TypeScript/issues/3841) but it's 4 years old and not seeming to get anywhere.

As a stopgap solution, I've just started adding { _noMyProjectProxy: true } to all my classes, and listing out anything I don't have access to.  It looks like this:

```<code>type NonClassObject<TYPE> =
  TYPE extends HTMLElement ? never :
  TYPE extends Event ? never :
  TYPE extends OtherClass ? never :
  TYPE extends { _noMyProjectProxy: any } ? never :
  TYPE;

export function createObjectProxy<TYPE extends object>(obj: NonClassObject<TYPE>) {
  return new Proxy(obj, {});
}
</code>```

It's not pretty or elegant, but it works when nothing else did.

Body:
I have a function which takes objects and proxies them.

I do not want it to proxy classes, and I'd like to assert that with the argument type.

How can I do this?

type NonClassObject = ???;
export function createObjectProxy(obj: NonClassObject) {
  return new Proxy(obj, {});
}

const foo: NonClassObject = {};
const bar: NonClassObject = {} as HTMLElement; // this should be a type error

There doesn't seem to be much to distinguish the two except for the typeof the constructor.  I'm not sure if there's a way to say Exact<tyepof OBJ.constructor, Object>... but I'm looking into Utility types now.

On to something:

Dead end: https://github.com/Microsoft/TypeScript/issues/3841

Body:
There's an open issue about making the constructor type more defined (https://github.com/Microsoft/TypeScript/issues/3841) but it's 4 years old and not seeming to get anywhere.

As a stopgap solution, I've just started adding { _noMyProjectProxy: true } to all my classes, and listing out anything I don't have access to.  It looks like this:

type NonClassObject<TYPE> =
  TYPE extends HTMLElement ? never :
  TYPE extends Event ? never :
  TYPE extends OtherClass ? never :
  TYPE extends { _noMyProjectProxy: any } ? never :
  TYPE;

export function createObjectProxy<TYPE extends object>(obj: NonClassObject<TYPE>) {
  return new Proxy(obj, {});
}

It's not pretty or elegant, but it works when nothing else did.


问:
Need emergency help with dw20.exe process?
recently I have deployed asp.net application to production windows server 2008.

after 10-20 min, starts dw20.exe process (Microsoft.net error reporting shim), which takes almost all CPU available which cause to very slow response of my application.

No error no exception in Event Viewer.

I right clicked on the dw20.exe process and created the dump file to analyze what causing the issue.

Then I opened this file in WidDbg. run command .loadby sos mscorwks and get Unable to find module 'mscorwks'

It looks like I'm missing something or doing it wrong.

How to determine what cause an exception in application? how to analyze DMP file created?

Is it possible to stop this service?

答: When we get hit by rogue CPU, we use Sam Saffron's CPU analyzer to see what it is busy doing. Most times it turns out to be a bad regex (no, seriously; this bites too often for comfort).</p>


问:
WordPress admin-ajax.php 400 error generated by Event Tickets plugin ... database related?
I have a WordPress website for a client that uses a custom theme and a number of plugins in combination to create an events calendar where logged in users can purchase tickets for paid events and register for free RSVP-required events. To accomplish this, I am using the following six plugins in combination:

The Events Calendar

Events Calendar Pro

Event Tickets

Event Tickets Plus

WooCommerce

WooCommerce Stripe Gateway

The website was established in 2015. In the last 4 years, those plugins have seen extensive updates, and as a result, at a certain point the custom site I built around those plugins started experiencing deprecation issues, and attempts to upgrade caused performance failure. After consulting with support, it became necessary to pull a duplicate copy of the site onto a development server so that I could do the work to upgrade the install so all the latest versions of all of these plugins can be running and working properly.

Everything was going well with the upgrade work until I noticed that one of the plugins seems to be generating the following error in the console in Chrome:

```<code>POST https://pcapolar.codewordserver.com/wp-admin/admin-ajax.php 400 (Bad Request)
send @ jquery.js?ver=1.12.4-wp:4
ajax @ jquery.js?ver=1.12.4-wp:4
n.<computed> @ jquery.js?ver=1.12.4-wp:4
r.length.e.checkAvailability @ frontend-ticket-form.min.js?ver=4.11.1:1
r.length.e.init @ frontend-ticket-form.min.js?ver=4.11.1:1
(anonymous) @ frontend-ticket-form.min.js?ver=4.11.1:1
(anonymous) @ frontend-ticket-form.min.js?ver=4.11.1:1
</code>```

Loading the same page in Edge generated the following console error:

```<code>HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax
(XHR)POST - https://pcapolar.codewordserver.com/wp-admin/admin-ajax.php
</code>```

The error occurs only under very specific circumstances -- when a single event page displays the frontend form for a paid ticket. The error doesn't occur when the front end paid ticket form is not output, for example when there is a registered RSVP form with no payment component, when there is no ticket component to the event, or when a user who is not an active member views an affected page such that all information about details of the event and buying tickets is excluded from the output via theme template files. Despite the console error generated, it appears that ajax works fine and all of the functionality works exactly as expected. If you weren't looking at the console, you'd never know there was a problem.

In order to rule out an issue with my custom theme or a conflict with another plugin, I activated the default Twenty Twenty theme and deactivated all other plugins except the 6 I listed that are required to use ticketed event process. The error remained present under these circumstances

After going back and forth with Modern Tribe (the plugin developers) support desk, they report the error cannot be replicated. So I tried myself to install a clean copy of WordPress with a new database, then install only those 6 plugins while running the default Twenty Twenty theme. I did this on the same server under the same cPanel account as the dev site with the error, just at different subdomains. On the clean install, the error was NOT present. But when I then pointed the clean WordPress install to a duplicate copy of the database I'm using for the dev site I'm working on, the error shows up again. From that, I can only conclude there is something going on in my database that is making this error happen, but Modern Tribe support are telling me that since the error can't be reproduced by them, there isn't anything they can do to help.

Starting over with a clean install for this site isn't really an option, there is so much data collected over the last 4 years from ticket purchase and membership transactions that we really can't lose. I need to find the faulty data and clean it, but I feel out of my depth here. Any help or suggestions on how to resolve this are welcome.

Edited to add:

I found this code in the javascript file references by the error message in the console. Am I looking in the right place?

```<code>/**
     * Check tickets availability.
     *
     * @since 4.9
     *
     * @return void
     */
    obj.checkAvailability = function() {
        // We're checking availability for all the tickets at once.
        var params = {
            action  : 'ticket_availability_check',
            tickets : obj.getTickets(),
        };

        $.post(
            TribeTicketOptions.ajaxurl,
            params,
            function( response ) {
                var success = response.success;

                // Bail if we don't get a successful response.
                if ( ! success ) {
                    return;
                }

                // Get the tickets response with availability.
                var tickets = response.data.tickets;

                // Make DOM updates.
                obj.updateAvailability( tickets );

            }
        );

        // Repeat every 60 (filterable via tribe_tickets_availability_check_interval ) seconds
        if ( 0 < TribeTicketOptions.availability_check_interval ) {
            setTimeout( obj.checkAvailability, TribeTicketOptions.availability_check_interval );
        }
    }
</code>```

Edited to add:

Then I ran a string search for ticket_availability and found the following. It looks like it might be related, but I'm a bit over my head in interpreting. Am I on the right track yet?

```<code>public function ticket_availability( $tickets = array() ) {

        $response  = array( 'html' => '' );
        $tickets   = tribe_get_request_var( 'tickets', array() );

        // Bail if we receive no tickets
        if ( empty( $tickets ) ) {
            wp_send_json_error( $response );
        }

        /** @var Tribe__Tickets__Tickets_Handler $tickets_handler */
        $tickets_handler = tribe( 'tickets.handler' );

        /** @var Tribe__Tickets__Editor__Template $tickets_editor */
        $tickets_editor = tribe( 'tickets.editor.template' );

        // Parse the tickets and create the array for the response
        foreach ( $tickets as $ticket_id ) {
            $ticket = Tribe__Tickets__Tickets::load_ticket_object( $ticket_id );

            if (
                ! $ticket instanceof Tribe__Tickets__Ticket_Object
                || empty( $ticket->ID )
            ) {
                continue;
            }

            $available = $tickets_handler->get_ticket_max_purchase( $ticket->ID );

            $response['tickets'][ $ticket_id ]['available'] = $available;

            // If there are no more available we will send the template part HTML to update the DOM
            if ( 0 === $available ) {
                $response['tickets'][ $ticket_id ]['unavailable_html'] = $tickets_editor->template( 'blocks/tickets/quantity-unavailable', $ticket, false );
            }
        }

        wp_send_json_success( $response );
    }
</code>```

The weird thing is that this function is filed to a folder called Blocks, which implied it works with Gutenberg, which I have disabled via the Classic Editor plugin.

答:
I am having the same problem and I think the problem is Tribe__Editor::should_load_blocks when the classic editor plugin is active.

To bypass this error I add this code to my theme functions.php file

```<code>add_action( 'xxx', tribe_callback( 'tickets.editor.blocks.tickets', 'register' ) );
do_action( 'xxx' );

</code>```

I hope this works for you.

Body:
I have a WordPress website for a client that uses a custom theme and a number of plugins in combination to create an events calendar where logged in users can purchase tickets for paid events and register for free RSVP-required events. To accomplish this, I am using the following six plugins in combination:

The Events Calendar

Events Calendar Pro

Event Tickets

Event Tickets Plus

WooCommerce

WooCommerce Stripe Gateway

The website was established in 2015. In the last 4 years, those plugins have seen extensive updates, and as a result, at a certain point the custom site I built around those plugins started experiencing deprecation issues, and attempts to upgrade caused performance failure. After consulting with support, it became necessary to pull a duplicate copy of the site onto a development server so that I could do the work to upgrade the install so all the latest versions of all of these plugins can be running and working properly.

Everything was going well with the upgrade work until I noticed that one of the plugins seems to be generating the following error in the console in Chrome:

POST https://pcapolar.codewordserver.com/wp-admin/admin-ajax.php 400 (Bad Request)
send @ jquery.js?ver=1.12.4-wp:4
ajax @ jquery.js?ver=1.12.4-wp:4
n.<computed> @ jquery.js?ver=1.12.4-wp:4
r.length.e.checkAvailability @ frontend-ticket-form.min.js?ver=4.11.1:1
r.length.e.init @ frontend-ticket-form.min.js?ver=4.11.1:1
(anonymous) @ frontend-ticket-form.min.js?ver=4.11.1:1
(anonymous) @ frontend-ticket-form.min.js?ver=4.11.1:1

Loading the same page in Edge generated the following console error:

HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax
(XHR)POST - https://pcapolar.codewordserver.com/wp-admin/admin-ajax.php

The error occurs only under very specific circumstances -- when a single event page displays the frontend form for a paid ticket. The error doesn't occur when the front end paid ticket form is not output, for example when there is a registered RSVP form with no payment component, when there is no ticket component to the event, or when a user who is not an active member views an affected page such that all information about details of the event and buying tickets is excluded from the output via theme template files. Despite the console error generated, it appears that ajax works fine and all of the functionality works exactly as expected. If you weren't looking at the console, you'd never know there was a problem.

In order to rule out an issue with my custom theme or a conflict with another plugin, I activated the default Twenty Twenty theme and deactivated all other plugins except the 6 I listed that are required to use ticketed event process. The error remained present under these circumstances

After going back and forth with Modern Tribe (the plugin developers) support desk, they report the error cannot be replicated. So I tried myself to install a clean copy of WordPress with a new database, then install only those 6 plugins while running the default Twenty Twenty theme. I did this on the same server under the same cPanel account as the dev site with the error, just at different subdomains. On the clean install, the error was NOT present. But when I then pointed the clean WordPress install to a duplicate copy of the database I'm using for the dev site I'm working on, the error shows up again. From that, I can only conclude there is something going on in my database that is making this error happen, but Modern Tribe support are telling me that since the error can't be reproduced by them, there isn't anything they can do to help.

Starting over with a clean install for this site isn't really an option, there is so much data collected over the last 4 years from ticket purchase and membership transactions that we really can't lose. I need to find the faulty data and clean it, but I feel out of my depth here. Any help or suggestions on how to resolve this are welcome.

Edited to add:

I found this code in the javascript file references by the error message in the console. Am I looking in the right place?

/**
     * Check tickets availability.
     *
     * @since 4.9
     *
     * @return void
     */
    obj.checkAvailability = function() {
        // We're checking availability for all the tickets at once.
        var params = {
            action  : 'ticket_availability_check',
            tickets : obj.getTickets(),
        };

        $.post(
            TribeTicketOptions.ajaxurl,
            params,
            function( response ) {
                var success = response.success;

                // Bail if we don't get a successful response.
                if ( ! success ) {
                    return;
                }

                // Get the tickets response with availability.
                var tickets = response.data.tickets;

                // Make DOM updates.
                obj.updateAvailability( tickets );

            }
        );

        // Repeat every 60 (filterable via tribe_tickets_availability_check_interval ) seconds
        if ( 0 < TribeTicketOptions.availability_check_interval ) {
            setTimeout( obj.checkAvailability, TribeTicketOptions.availability_check_interval );
        }
    }

Edited to add:

Then I ran a string search for ticket_availability and found the following. It looks like it might be related, but I'm a bit over my head in interpreting. Am I on the right track yet?

public function ticket_availability( $tickets = array() ) {

        $response  = array( 'html' => '' );
        $tickets   = tribe_get_request_var( 'tickets', array() );

        // Bail if we receive no tickets
        if ( empty( $tickets ) ) {
            wp_send_json_error( $response );
        }

        /** @var Tribe__Tickets__Tickets_Handler $tickets_handler */
        $tickets_handler = tribe( 'tickets.handler' );

        /** @var Tribe__Tickets__Editor__Template $tickets_editor */
        $tickets_editor = tribe( 'tickets.editor.template' );

        // Parse the tickets and create the array for the response
        foreach ( $tickets as $ticket_id ) {
            $ticket = Tribe__Tickets__Tickets::load_ticket_object( $ticket_id );

            if (
                ! $ticket instanceof Tribe__Tickets__Ticket_Object
                || empty( $ticket->ID )
            ) {
                continue;
            }

            $available = $tickets_handler->get_ticket_max_purchase( $ticket->ID );

            $response['tickets'][ $ticket_id ]['available'] = $available;

            // If there are no more available we will send the template part HTML to update the DOM
            if ( 0 === $available ) {
                $response['tickets'][ $ticket_id ]['unavailable_html'] = $tickets_editor->template( 'blocks/tickets/quantity-unavailable', $ticket, false );
            }
        }

        wp_send_json_success( $response );
    }

The weird thing is that this function is filed to a folder called Blocks, which implied it works with Gutenberg, which I have disabled via the Classic Editor plugin.

Body:
I am having the same problem and I think the problem is Tribe__Editor::should_load_blocks when the classic editor plugin is active.

To bypass this error I add this code to my theme functions.php file

add_action( 'xxx', tribe_callback( 'tickets.editor.blocks.tickets', 'register' ) );
do_action( 'xxx' );

I hope this works for you.


问:
css not loading even though there're no errors and it's linked correctly in ejs
so, I'm trying to link a css file to an ejs file but it's not working, and I think I'm linking them correctly:

```<code><head>
<title>Acres & Karats Calculator</title>
<base href="/">
<link type="text/css" href="css/Acres and Karats Calculator.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Titillium+Web:400,700&display=swap" rel="stylesheet">
</code>```

and i specified the public directory to be used in express:

```<code>let express = require("express"),
    app     = express();

app.use("/public", express.static(__dirname + "/public"));

app.get("/", (req, res) => {
    res.render("Acres and Karats Calculator.ejs")
});

app.listen("3000", () => {
    console.log("Server started!");
});
</code>```

and there are no errors in the console at all and the css is not loaded

file structure:

app.js

views

pubilc

css

Acres and Karats Calculator.css

答:
Taking into account the directory layout of your project:

```<code>app.js
views
-|_pubilc
---|_css
-----|_Acres and Karats Calculator.css
</code>```

and the link to the css file in the ejs template:

```<code><link type="text/css" href="css/Acres and Karats Calculator.css">
</code>```

express static path in your app.js should be updated as follows:

```<code>app.use(express.static(__dirname + "/views/public"));
</code>```

Body:
so, I'm trying to link a css file to an ejs file but it's not working, and I think I'm linking them correctly:

<title>Acres & Karats Calculator</title>
<base href="/">
<link type="text/css" href="css/Acres and Karats Calculator.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Titillium+Web:400,700&display=swap" rel="stylesheet">

and i specified the public directory to be used in express:

let express = require("express"),
    app     = express();

app.use("/public", express.static(__dirname + "/public"));

app.get("/", (req, res) => {
    res.render("Acres and Karats Calculator.ejs")
});

app.listen("3000", () => {
    console.log("Server started!");
});

and there are no errors in the console at all and the css is not loaded

file structure:

app.js

views

pubilc

css

Acres and Karats Calculator.css

Body:
Taking into account the directory layout of your project:

app.js
views
-|_pubilc
---|_css
-----|_Acres and Karats Calculator.css

and the link to the css file in the ejs template:

<link type="text/css" href="css/Acres and Karats Calculator.css">

express static path in your app.js should be updated as follows:

app.use(express.static(__dirname + "/views/public"));


问:
How to display dead-letter messages in Azure CLI
Currently we use Service Bus Explorer to connect to our Service Bus Namespace and manage our dead letters. However as this is a third party tool it's been asked that we do not use this anymore as there is a lot of sensitive data being pulled from the dead letters.

We do not get many dead letter messages in the queues so we thought it would be great if we can view the payload of a dead letter directly in Azure CLI or Powershell. I have looked around online and can't seem to find anything in regards to viewing payloads in CLI. Everything seems to recommend using Service Bus Explorer for viewing payloads.

Any help on this would be greatly appreciated.

答:
Azure CLI for Service Bus is intended to manage service namespace, entities, and control plane (authorization rules, Geo-DR, namespace migration, etc). It is not intended for the data plane. Just as you wouldn't do expect a DB (MariaDB) to provide commands for data manipulation.

You've got two options:

Use a tool

Write custom script/code (which is a way of building a custom tool)

For tooling, you've got a few options: ServiceBus Explorer (free), QueueExplorer (paid), Serverless360 (subscription), etc.

If you choose to write your own code, you could use PowerShell and leverage .NET SDK. Or create your own project/tool to help you inspect and move those dead-lettered messages.

Remember that operating on messages in a dead-letter queue is no different from consuming messages from a regular queue/subscription. It's the path that is slightly different. There's the official documentation on the topic as well as some more extended information on the web. I've posted a few blog posts that could help you work with dead-letter queues more effectively:

Centralized Dead Letter Queue with Azure Service Bus

Monitoring all Dead Letter Queues. Yes, multiple.

If you're using NServiceBus with Azure ServiceBus, you can leverage Service Pulse to achieve monitoring and inspection with a custom plugin. Here's a post.

For a pure code solution, this sample could be a good starting point.


问:
Converting a member function to a static function in C++
I am writing a memory testing framework, in which I replace dynamic memory allocation functions with my own (eg. malloc, realloc, free, etc.). However, the system expects static functions (I can not change this).

I have a MemoryTester class, which logs the memory calls, and I want to bind its member function implementations of the memory allocation functions. Is this possible with C++?

EDIT:

Here is some code highlighting what I'm trying to do:

```<code>typedef void*(allocateFuncPtr) (uint8_t);
typedef void (freeFuncPtr) (void*);

void setAllocateFunction(allocateFuncPtr) {...}
void setFreeFunction(freeFuncPtr) {...}

class MemoryTester
{
    void *malloc(uint8_t size);
    void free(void *ptr);
}

int main()
{
    MemoryTester *tester = new MemoryTester();

    //want to set allocate and free functions to those in tester
    setAllocateFunction( tester->getAllocateFunction() );
    setFreeFunction( tester->getFreeFunction() );

    return 0;
}
</code>```

答:
If I understand correctly what you ask, there is no "binding" to do. Once the memory have been allocated, you can tell the compiler it's type by user a cast, in your case a reinterpret_cast. For example, in you allocation function:

```<code>unsigned char* raw_memory = allocation( std::size_t );
MyFinalType* object = reinterpret_cast<MyFinalType*>(raw_memory); // tells the compiler to take this memory as a MyFinalType.
</code>```

Then you return your final type.

To know wich type to use, you'll certainly want to use templates.

Don't forget that C++ is a statically typed language: you can't bind functions to an object type. Ok you can, but the, you have to use std::function or function pointers, that are not what you want here.

Body:
I am writing a memory testing framework, in which I replace dynamic memory allocation functions with my own (eg. malloc, realloc, free, etc.). However, the system expects static functions (I can not change this).

I have a MemoryTester class, which logs the memory calls, and I want to bind its member function implementations of the memory allocation functions. Is this possible with C++?

EDIT:

Here is some code highlighting what I'm trying to do:

typedef void*(allocateFuncPtr) (uint8_t);
typedef void (freeFuncPtr) (void*);

void setAllocateFunction(allocateFuncPtr) {...}
void setFreeFunction(freeFuncPtr) {...}

class MemoryTester
{
    void *malloc(uint8_t size);
    void free(void *ptr);
}

int main()
{
    MemoryTester *tester = new MemoryTester();

    //want to set allocate and free functions to those in tester
    setAllocateFunction( tester->getAllocateFunction() );
    setFreeFunction( tester->getFreeFunction() );

    return 0;
}

Body:
If I understand correctly what you ask, there is no "binding" to do. Once the memory have been allocated, you can tell the compiler it's type by user a cast, in your case a reinterpret_cast. For example, in you allocation function:

unsigned char* raw_memory = allocation( std::size_t );
MyFinalType* object = reinterpret_cast<MyFinalType*>(raw_memory); // tells the compiler to take this memory as a MyFinalType.

Then you return your final type.

To know wich type to use, you'll certainly want to use templates.

Don't forget that C++ is a statically typed language: you can't bind functions to an object type. Ok you can, but the, you have to use std::function or function pointers, that are not what you want here.


问:
MySQL is blocking GUI with await
I am using an object that should display when a long SQL statement is running; I trigger this using a boolean and a databinding in the XAML;

```<code><window>
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVis" />
    </Window.Resources>
        <Controls:ProgressRing x:Name="PRwaiting" Visibility="{Binding Path=isBusy,Converter={StaticResource BoolToVis}}"/>
</window>
</code>```

In the codebehind;

```<code>public async void DoSomething()
    isBusy = true;
    await LongRunninSQL();
}

private async Task<bool> LongRunninSQL() {
//The isBusy ProgressRing object is visible when I use this delay with a normal SQL statement
//await Task.Delay(3000);

//Yet, the GUI is blocked when this is executed. (and no progressring is displayed)
string SQL = $"select benchmark(9999999, md5('when will it end?')) AS Benchmark";
Collection = await DBC.SelectAsync(SQL);
</code>```

DBC.SelectAsync:

```<code>        public async Task<DataTable> SelectAsync(string query)
        {
            var dataTable = new DataTable();

            if (this.OpenConnection() == true)
            {
                using (MySqlCommand cmd = new MySqlCommand(query, connection))
                {

                    cmd.CommandText = query;

                    using (var dataReader = await cmd.ExecuteReaderAsync())
                    {
                        dataTable.Load(dataReader);

                        //close Data Reader
                        dataReader.Close();

                        //close Connection
                        this.CloseConnection();

                        //return list to be displayed
                        return dataTable;
                    }
                }
            }
            return dataTable;
        }
</code>```

How can I find out why the SQL statement freezes the GUI, even though await and async are being used?

答:
This is a long-standing problem with MySql.Data: they included the asynchronous ADO.NET endpoints, but implemented them synchronously. Unfortunately, it's something you "just have to know", since AFAIK it isn't documented anywhere except a few Stack Overflow questions.

Since you're working on a GUI application, using Task.Run would be an acceptable workaround:

```<code>public async void DoSomething()
{
  isBusy = true;
  await Task.Run(() => LongRunninSQL());
}
</code>```

Alternatively, you can uninstall MySql.Data and replace it with MySqlConnector, which uses true asynchronous implementations.

Title: MySQL is blocking GUI with await

Body:
I am using an object that should display when a long SQL statement is running; I trigger this using a boolean and a databinding in the XAML;

<window>
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVis" />
    </Window.Resources>
        <Controls:ProgressRing x:Name="PRwaiting" Visibility="{Binding Path=isBusy,Converter={StaticResource BoolToVis}}"/>
</window>

In the codebehind;

public async void DoSomething()
    isBusy = true;
    await LongRunninSQL();
}

private async Task<bool> LongRunninSQL() {
//The isBusy ProgressRing object is visible when I use this delay with a normal SQL statement
//await Task.Delay(3000);

//Yet, the GUI is blocked when this is executed. (and no progressring is displayed)
string SQL = $"select benchmark(9999999, md5('when will it end?')) AS Benchmark";
Collection = await DBC.SelectAsync(SQL);

DBC.SelectAsync:

        public async Task<DataTable> SelectAsync(string query)
        {
            var dataTable = new DataTable();

            if (this.OpenConnection() == true)
            {
                using (MySqlCommand cmd = new MySqlCommand(query, connection))
                {

                    cmd.CommandText = query;

                    using (var dataReader = await cmd.ExecuteReaderAsync())
                    {
                        dataTable.Load(dataReader);

                        //close Data Reader
                        dataReader.Close();

                        //close Connection
                        this.CloseConnection();

                        //return list to be displayed
                        return dataTable;
                    }
                }
            }
            return dataTable;
        }

How can I find out why the SQL statement freezes the GUI, even though await and async are being used?

Body:
This is a long-standing problem with MySql.Data: they included the asynchronous ADO.NET endpoints, but implemented them synchronously. Unfortunately, it's something you "just have to know", since AFAIK it isn't documented anywhere except a few Stack Overflow questions.

Since you're working on a GUI application, using Task.Run would be an acceptable workaround:

public async void DoSomething()
{
  isBusy = true;
  await Task.Run(() => LongRunninSQL());
}

Alternatively, you can uninstall MySql.Data and replace it with MySqlConnector, which uses true asynchronous implementations.


问:
How to append in json file at specific position
I'm trying to append JSON objects to a file at specific position but I'm unable to do it as required. I get result but without "," separating the values, so they are separate JSON objects.

I want to loop through JSON objects and append the result to a file and separate it with "," and it is a valid JSON. Here is what I tried

```<code>
auto js_text = R"(
{
  "a": "all_items",
  "b": []
}
        )";
    std::ofstream js_file("test.json");
    js_file << std::setw(4) << js_text << std::endl;
    std::ifstream in("test4.json");
    json js_file = json::parse(in);
    std::ifstream load_url("url_file.json");
    json url_file = json::parse(load_url);
   for (auto& endpoint : url_file["url_list"])
        {
    std::string url = endpoint["url"].get<std::string>();
    auto r = cpr::Get(cpr::Url{ url });
    json j = json::parse(r.text); // r gets a nested json objects from parsed url
    for (auto& td : j["b"])
     {
      json value = j["b"][0];
      json data = js_file;
      data["b"][0] = value;
      std::ofstream output;
      output.open("test.json",std::ios_base::app );
      output << std::setw(4) << data << std::endl;
}

</code>```

Result I want is

```<code>{
  "a": "all_items",
  "b": [
    {
      "c": "xxx",
      "d": "yyy"
    },
    {
      "e": "zzz"
    }
  ]
}

</code>```

Updated Code: after Botje valuable input.

```<code>     auto js_text = R"(
        {
           "a": "abc",
             "b": [ ]
           }
           )";

    json js_file = json::parse(js_text);

     std::ifstream load_url("url_file.json");
    json url_file = json::parse(load_url);

    for (auto& endpoint : url_file["url_list"])
     {
      std::string url = endpoint["url"].get<std::string>();
      auto r = cpr::Get(cpr::Url{ url });
      json j = json::parse(r.text); // j contains results from multiple HTTP requests that has json objects.
       for (auto& elem : j["b"])
            {
              json jd = j["b"];
              js_file["b"].emplace_back(std::move(td));
              std::cout << "jd:" << jd.dump(4) << std::endl;
         }
       }

      std::ofstream output;
      output.open("test.json",std::ios_base::app );
      output << std::setw(4) << js_file << std::endl;
    }

</code>```

Hope this help others.

答:
Let's assume that:

```<code>std::string original_string;  // Original file contents as a string
json original_json; // JSON value parsed from original_string
json updated_json;  // original_json but updated with new values
</code>```

Then you get the string representation like so:

```<code>std::string updated_string = updated_json.dump();
</code>```

Now, compare the two strings character at a time until you get a difference. That is the offset where you can write the new contents of the file.

```<code>size_t update_offset = 0;
for (size_t i = 0; i < original_string.size(); ++i) {
  if (i < updated_string.size()) {
    // Update is shorter than original, something is wrong
  }
  if (original_string[i] != updated_string[i]) {
    update_offset = i;
    break;
  }
}
</code>```

At this point, update_offset will have the number of bytes in common between the two strings; everything after this has changed. Now, we open the original file, seek to this offset and write the rest of the string.

```<code>std::ofstream output{"test.json", std::ofstream::out};
output.seekp(update_offset);
output << updated_string.substr(update_offset);
output.close();
</code>```

The above sequence ensures that the contents of the output file are a syntactically correct representation of your JSON data.

Body:
I'm trying to append JSON objects to a file at specific position but I'm unable to do it as required. I get result but without "," separating the values, so they are separate JSON objects.

I want to loop through JSON objects and append the result to a file and separate it with "," and it is a valid JSON. Here is what I tried

auto js_text = R"(
{
  "a": "all_items",
  "b": []
}
        )";
    std::ofstream js_file("test.json");
    js_file << std::setw(4) << js_text << std::endl;
    std::ifstream in("test4.json");
    json js_file = json::parse(in);
    std::ifstream load_url("url_file.json");
    json url_file = json::parse(load_url);
   for (auto& endpoint : url_file["url_list"])
        {
    std::string url = endpoint["url"].get<std::string>();
    auto r = cpr::Get(cpr::Url{ url });
    json j = json::parse(r.text); // r gets a nested json objects from parsed url
    for (auto& td : j["b"])
     {
      json value = j["b"][0];
      json data = js_file;
      data["b"][0] = value;
      std::ofstream output;
      output.open("test.json",std::ios_base::app );
      output << std::setw(4) << data << std::endl;
}

Result I want is

{
  "a": "all_items",
  "b": [
    {
      "c": "xxx",
      "d": "yyy"
    },
    {
      "e": "zzz"
    }
  ]
}

Updated Code: after Botje valuable input.

     auto js_text = R"(
        {
           "a": "abc",
             "b": [ ]
           }
           )";

    json js_file = json::parse(js_text);

     std::ifstream load_url("url_file.json");
    json url_file = json::parse(load_url);

    for (auto& endpoint : url_file["url_list"])
     {
      std::string url = endpoint["url"].get<std::string>();
      auto r = cpr::Get(cpr::Url{ url });
      json j = json::parse(r.text); // j contains results from multiple HTTP requests that has json objects.
       for (auto& elem : j["b"])
            {
              json jd = j["b"];
              js_file["b"].emplace_back(std::move(td));
              std::cout << "jd:" << jd.dump(4) << std::endl;
         }
       }

      std::ofstream output;
      output.open("test.json",std::ios_base::app );
      output << std::setw(4) << js_file << std::endl;
    }

Hope this help others.

Body:
Let's assume that:

std::string original_string;  // Original file contents as a string
json original_json; // JSON value parsed from original_string
json updated_json;  // original_json but updated with new values

Then you get the string representation like so:

std::string updated_string = updated_json.dump();

Now, compare the two strings character at a time until you get a difference. That is the offset where you can write the new contents of the file.

size_t update_offset = 0;
for (size_t i = 0; i < original_string.size(); ++i) {
  if (i < updated_string.size()) {
    // Update is shorter than original, something is wrong
  }
  if (original_string[i] != updated_string[i]) {
    update_offset = i;
    break;
  }
}

At this point, update_offset will have the number of bytes in common between the two strings; everything after this has changed. Now, we open the original file, seek to this offset and write the rest of the string.

std::ofstream output{"test.json", std::ofstream::out};
output.seekp(update_offset);
output << updated_string.substr(update_offset);
output.close();

The above sequence ensures that the contents of the output file are a syntactically correct representation of your JSON data.