问:
How to correctly configure git submodule
I am trying to add a repository as a submodule in another git module.
After adding the submodule I tried to clone the parent project:

```<code>git clone https://...
cd <parent_path>/<submodule_path>
git submodule init
git submodule update
</code>```

Now if I git status in the submodule the HEAD is detached:

```<code>cd <submodule_path>
git status
HEAD detached at a4709b3
nothing to commit, working tree clean
</code>```

After reading this answer I tried to checkout to submodule's master:

```<code>git checkout master
git status

On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean
</code>```

But now, if I git status on parent directory it shows that there are new commits in the submodule (which is definitely not the case)

```<code>cd <parent_dir_path>
git status

On branch test_submodule
Your branch is up to date with 'origin/test_submodule'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   submodule_name (new commits)

no changes added to commit (use "git add" and/or "git commit -a")
</code>```

Can someone shed some light on this?

EDIT:
Here's the output of cd <submodule_path> && git show master:

```<code>commit 42309e0e2f48aba11902633173053e2423d4ba62 (HEAD -> master, origin/master, origin/HEAD)
Merge: a4709b3 1c1ae85
Author: Abc
Date:   Fri May 31 16:27:52 2019 +0100

    Merge pull request #6 in test/testing_submodule from test_integration_with_repos to master

    * commit '1c1ae8515716d9c2d5135e86dc9c024c81e4320b':
      test
</code>```

答:
TL;DR

git status compares the HEAD commit (current commit) and the index.  Whatever is different is staged for commit.  Then it compares the index and the work-tree.  Whatever is different is not staged for commit.  In this case, Git is comparing the index gitlink to the actual commit hash ID in the submodule.  When it says:

```<code>modified:   submodule_name (new commits)
</code>```

it just means the gitlink in the index does not match the HEAD commit hash in the submodule.  This does not mean there are new commits in the submodule, nor that there aren't new commits there; it just means that the existing index gitlink hash ID doesn't match the existing submodule checkout.

Long

There's always a lot of confusion around submodules.  The question you linked to—Why is my GIT Submodule HEAD detached from master?—has, as its accepted answer, an answer that doesn't really get to the heart of the problem, which I think can be summarized by the following conversation:

PERSON: Hey, Git, I'd like to use this other Git repository as a subdirectory of my Git repository.

GIT: OK, done.

PERSON: Cool.  [Later:] Oh hey, why, when I make a new clone, is my submodule in detached HEAD state?

GIT: That's how it works.

PERSON: But I want it to be on branch master.

GIT: OK.

PERSON: It's still detached!

GIT: Yeah.

PERSON: I want it on a branch!

GIT: Yeah, no.  Sorry.

In short, that's just how it works.  Now, a submodule is a Git repository, so you can get the submodule onto a branch.  But the superproject Git is going to yank it right back off the branch, because that's how submodules work.  It takes one more bit of mind-set to understand why this is the case.

Why submodules are detached

First, let's note again that a submodule is a Git repository.  The only thing that makes it a submodule is the fact that some other Git repository controls it now and then.  We call the other Git repository the superproject.  The superproject is doing control commands, and the submodule is obeying them.  Other than this, they're two independent Git repositories: if the submodule has master and develop and whatever else branches, these are independent of the superproject's master and develop and whatever else, and the submodule and superproject don't have to have the same set of branch names at all.

Note, too, that a submodule can be a superproject to yet another submodule.  This situation gets especially confusing since now saying "the" submodule or "the" superproject is ambiguous.  There are now two superprojects, two submodules, and three Git repositories, and the middle Git repository is both submodule (of the top Git) and superproject (of the bottom one).

The design makes one huge assumption, which is a completely safe assumption, but can be annoying.  This assumptions is:  The submodule is cloned from a repository that you don't control.  This other repository may be updated very frequently, or hardly ever, but their branches, which get copied to your clone as your submodule's origin/* remote-tracking names, change in a way that you don't necessarily control.  When you first clone that submodule repository, git clone would create new branch named master, or some other name if they say so, and the commit you'd get by checking out whichever name this is, is under their control, not yours.

For this reason, the superproject itself does not need—and hardly ever uses—any of the branch names of the submodule.  Instead, the superproject records something about the submodule repository that cannot change.  The fact that it can't change means that no matter what whoever controls your clone-source does to the submodule, they cannot wreck your dependency on that submodule.

(That's not 100% true of course.  For instance, they can completely delete the source repository.  Or they can discard a commit or tag that you depend on, but in general, people don't delete repositories.  Discarding commits is rare-ish, and discarding a published tag and its corresponding commit is especially rare.)

The thing that cannot change, that your superproject records, is the raw hash ID of the commit that the superproject will tell the submodule to git checkout hash.  This recorded information goes into every commit in your superproejct!  (Well, every commit that uses the submodule.)

A detached HEAD occurs when you run git checkout hash

If you've been using Git long enough, you're familiar with this.  Check out any historic commit by its hash ID, and Git goes into detached HEAD mode.

The superproject checks out a historic commit by its unchangeable hash ID.  So the submodule ends up in detached HEAD mode.  That's both how and why it all works.  The superproject records the hash ID, and commands the submodule: check that one out, and now you're in detached HEAD mode.

This works great for read-only historic commits.  Every commit in your superproject records the correct submodule hash ID, for that superproject commit.  When you check out that commit, you tell Git to synchronize your submodules, and you get the right submodule commit too, so that you can build and use your project.

This gets in the way of new work

First, we all need to agree on a definition: Existing commits are not about new work.  Commits are read-only, frozen for all time.  You cannot change anything about any existing commit.  (That's why the submodule's commit's hash ID is useful to the superproject: it's frozen in time, and presumably good forevermore.)  Each commit contains a snapshot of all of your files, plus some metadata such as who made it, when, and why—the log message.

Commits are frozen like this, but new work is, we presume, a desirable thing.  So any Git repository—well, except a --bare one—provides a place in which you can do that.  That place is the work-tree (or working tree or any number of similar spellings).  Git copies the compressed, read-only, Git-only-format files out of some commit, into the work-tree, where they take on their ordinary everyday form and you can therefore see and work on/with your files.

A commit that refers to a submodule does so through what Git calls a gitlink.  The gitlink is, in effect, a committed file of mode 160000 (normal files are mode 100644 or mode 100755), where the file's "contents" are just the hash ID that the superproject should command the submodule Git to git checkout.

Hence, a submodule entry—a gitlink—in a commit tells git checkout: You are acting as as a superproject.  When you get to this place in the work-tree, instead of extracting just one file here, the submodule should be on this commit, as a detached HEAD.  If you use git checkout --recurse-submodules, Git does exactly that.  If you use git checkout --no-recurse-submodules, Git holds off on doing that—it leaves the submodule, which is after all a separate Git repository, alone.

Now, Git makes new commits not from what's in the work-tree, but rather what's in the index.  The index contains a copy of every file ... and when a commit has a gitlink, the index contains a copy of that gitlink.  It's the gitlink entry in the index that determines what goes into the next commit you make.  So the next superproject commit uses whatever is in the superproject's index.

Sometimes you want the submodule to be on another commit.  Since the submodule is a Git repository, you can just go into it and git checkout whatever you like.  If you use a branch name, the submodule's HEAD will now be attached.  As far as the superproject Git is concerned, this doesn't matter: what matters to the superproject is the actual hash ID.  If the submodule's git rev-parse HEAD still produces the same hash ID that's in the superproject's index's gitlink, everything still matches up.  If it produces some other hash ID, it's up to you to resolve that.  Since you want a different commit, you should now update the superproject's index's gitlink.

PERSON: But, hey Git: I told you to remember a branch name in the superproject, for this specific submodule.  How about you, Git, command the Git that's controlling the submodule to git checkout that branch name?

You can do that.  But the assumption here is that you had your Git clone your submodule Git from an upstream repository that you don't control and that you don't git push to.  So this isn't sufficient and what Git provides instead is the command:

```<code>git submodule update --remote
</code>```

In this case, the superproject Git will:

enter the submodule

command the submodule Git to run git fetch

wait for origin/master, or whatever it is, to get updated in the submodule, as a result of that git fetch

find the new hash ID of the submodule's origin/master (or whatever) based on the upstream (that you don't control, but that you just fetched-from)

and then have the submodule Git git checkout that hash ID ... as a detached HEAD, again!

If you do control the submodule, and want to make new commits in it, you need to cd into the submodule and just git checkout whatever branch name you want, and then do your work there.  This submodule is, after all, a regular old Git repository.  You can do whatever work you like and then run git add to copy any updated work-tree files into the index—git commit is going to use what's in the index—and run git commit to make the new commit.

Then, having done all of this, you can either push the commit upstream right now, or wait and cd back into the superproject.  Either way you can now do whatever work is required in the superproject, and git add any modified files and the name of the submodule.  You're not just updating the files in the superproject index, you also need to update the gitlink in the superproject.  And now that you've done all of that, you can run git commit in the superproject, to make a new commit that stores the updated files and the updated gitlink.

Now that you have a new superproject commit, you can git push the new superproject commit somewhere.  If you already used git push in the submodule, that's all you need to do.  But if not, you should git push the submodule first.  The reason is pretty obvious, once you think about it: the new superproject commit says: When you get to this submodule, read this gitlink and extract commit a987654... (or whatever hash ID it is).  For someone else to do that, they'll need to git fetch the upstream submodule that you have to already have git pushed to, so as to get commit a987654... into their submodule Git!

Note that this matches the git submodule update --remote action: they will go to their submodule's upstream, git fetch the updated branch, and then git checkout the appropriate origin/branch hash ID, in this case a987654..., as the detached HEAD for their submodule.

This is not the smoothest process ever, but it's as simple as Git itself can make it.  There are several more things that git submodule update can do, but they all start with this frame of mind: the submodule repository is cloned from somewhere else, and it is primarily the somewhere else that supplies new commits for the submodule.

Body:
I am trying to add a repository as a submodule in another git module.
After adding the submodule I tried to clone the parent project:

git clone https://...
cd <parent_path>/<submodule_path>
git submodule init
git submodule update

Now if I git status in the submodule the HEAD is detached:

cd <submodule_path>
git status
HEAD detached at a4709b3
nothing to commit, working tree clean

After reading this answer I tried to checkout to submodule's master:

git checkout master
git status

On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

But now, if I git status on parent directory it shows that there are new commits in the submodule (which is definitely not the case)

cd <parent_dir_path>
git status

On branch test_submodule
Your branch is up to date with 'origin/test_submodule'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   submodule_name (new commits)

no changes added to commit (use "git add" and/or "git commit -a")

Can someone shed some light on this?

EDIT:
Here's the output of cd <submodule_path> && git show master:

commit 42309e0e2f48aba11902633173053e2423d4ba62 (HEAD -> master, origin/master, origin/HEAD)
Merge: a4709b3 1c1ae85
Author: Abc
Date:   Fri May 31 16:27:52 2019 +0100

    Merge pull request #6 in test/testing_submodule from test_integration_with_repos to master

    * commit '1c1ae8515716d9c2d5135e86dc9c024c81e4320b':
      test

Body:
TL;DR

git status compares the HEAD commit (current commit) and the index.  Whatever is different is staged for commit.  Then it compares the index and the work-tree.  Whatever is different is not staged for commit.  In this case, Git is comparing the index gitlink to the actual commit hash ID in the submodule.  When it says:

modified:   submodule_name (new commits)

it just means the gitlink in the index does not match the HEAD commit hash in the submodule.  This does not mean there are new commits in the submodule, nor that there aren't new commits there; it just means that the existing index gitlink hash ID doesn't match the existing submodule checkout.

Long

There's always a lot of confusion around submodules.  The question you linked to—Why is my GIT Submodule HEAD detached from master?—has, as its accepted answer, an answer that doesn't really get to the heart of the problem, which I think can be summarized by the following conversation:

PERSON: Hey, Git, I'd like to use this other Git repository as a subdirectory of my Git repository.

GIT: OK, done.

PERSON: Cool.  [Later:] Oh hey, why, when I make a new clone, is my submodule in detached HEAD state?

GIT: That's how it works.

PERSON: But I want it to be on branch master.

GIT: OK.

PERSON: It's still detached!

GIT: Yeah.

PERSON: I want it on a branch!

GIT: Yeah, no.  Sorry.

In short, that's just how it works.  Now, a submodule is a Git repository, so you can get the submodule onto a branch.  But the superproject Git is going to yank it right back off the branch, because that's how submodules work.  It takes one more bit of mind-set to understand why this is the case.

Why submodules are detached

First, let's note again that a submodule is a Git repository.  The only thing that makes it a submodule is the fact that some other Git repository controls it now and then.  We call the other Git repository the superproject.  The superproject is doing control commands, and the submodule is obeying them.  Other than this, they're two independent Git repositories: if the submodule has master and develop and whatever else branches, these are independent of the superproject's master and develop and whatever else, and the submodule and superproject don't have to have the same set of branch names at all.

Note, too, that a submodule can be a superproject to yet another submodule.  This situation gets especially confusing since now saying "the" submodule or "the" superproject is ambiguous.  There are now two superprojects, two submodules, and three Git repositories, and the middle Git repository is both submodule (of the top Git) and superproject (of the bottom one).

The design makes one huge assumption, which is a completely safe assumption, but can be annoying.  This assumptions is:  The submodule is cloned from a repository that you don't control.  This other repository may be updated very frequently, or hardly ever, but their branches, which get copied to your clone as your submodule's origin/* remote-tracking names, change in a way that you don't necessarily control.  When you first clone that submodule repository, git clone would create new branch named master, or some other name if they say so, and the commit you'd get by checking out whichever name this is, is under their control, not yours.

For this reason, the superproject itself does not need—and hardly ever uses—any of the branch names of the submodule.  Instead, the superproject records something about the submodule repository that cannot change.  The fact that it can't change means that no matter what whoever controls your clone-source does to the submodule, they cannot wreck your dependency on that submodule.

(That's not 100% true of course.  For instance, they can completely delete the source repository.  Or they can discard a commit or tag that you depend on, but in general, people don't delete repositories.  Discarding commits is rare-ish, and discarding a published tag and its corresponding commit is especially rare.)

The thing that cannot change, that your superproject records, is the raw hash ID of the commit that the superproject will tell the submodule to git checkout hash.  This recorded information goes into every commit in your superproejct!  (Well, every commit that uses the submodule.)

A detached HEAD occurs when you run git checkout hash

If you've been using Git long enough, you're familiar with this.  Check out any historic commit by its hash ID, and Git goes into detached HEAD mode.

The superproject checks out a historic commit by its unchangeable hash ID.  So the submodule ends up in detached HEAD mode.  That's both how and why it all works.  The superproject records the hash ID, and commands the submodule: check that one out, and now you're in detached HEAD mode.

This works great for read-only historic commits.  Every commit in your superproject records the correct submodule hash ID, for that superproject commit.  When you check out that commit, you tell Git to synchronize your submodules, and you get the right submodule commit too, so that you can build and use your project.

This gets in the way of new work

First, we all need to agree on a definition: Existing commits are not about new work.  Commits are read-only, frozen for all time.  You cannot change anything about any existing commit.  (That's why the submodule's commit's hash ID is useful to the superproject: it's frozen in time, and presumably good forevermore.)  Each commit contains a snapshot of all of your files, plus some metadata such as who made it, when, and why—the log message.

Commits are frozen like this, but new work is, we presume, a desirable thing.  So any Git repository—well, except a --bare one—provides a place in which you can do that.  That place is the work-tree (or working tree or any number of similar spellings).  Git copies the compressed, read-only, Git-only-format files out of some commit, into the work-tree, where they take on their ordinary everyday form and you can therefore see and work on/with your files.

A commit that refers to a submodule does so through what Git calls a gitlink.  The gitlink is, in effect, a committed file of mode 160000 (normal files are mode 100644 or mode 100755), where the file's "contents" are just the hash ID that the superproject should command the submodule Git to git checkout.

Hence, a submodule entry—a gitlink—in a commit tells git checkout: You are acting as as a superproject.  When you get to this place in the work-tree, instead of extracting just one file here, the submodule should be on this commit, as a detached HEAD.  If you use git checkout --recurse-submodules, Git does exactly that.  If you use git checkout --no-recurse-submodules, Git holds off on doing that—it leaves the submodule, which is after all a separate Git repository, alone.

Now, Git makes new commits not from what's in the work-tree, but rather what's in the index.  The index contains a copy of every file ... and when a commit has a gitlink, the index contains a copy of that gitlink.  It's the gitlink entry in the index that determines what goes into the next commit you make.  So the next superproject commit uses whatever is in the superproject's index.

Sometimes you want the submodule to be on another commit.  Since the submodule is a Git repository, you can just go into it and git checkout whatever you like.  If you use a branch name, the submodule's HEAD will now be attached.  As far as the superproject Git is concerned, this doesn't matter: what matters to the superproject is the actual hash ID.  If the submodule's git rev-parse HEAD still produces the same hash ID that's in the superproject's index's gitlink, everything still matches up.  If it produces some other hash ID, it's up to you to resolve that.  Since you want a different commit, you should now update the superproject's index's gitlink.

PERSON: But, hey Git: I told you to remember a branch name in the superproject, for this specific submodule.  How about you, Git, command the Git that's controlling the submodule to git checkout that branch name?

You can do that.  But the assumption here is that you had your Git clone your submodule Git from an upstream repository that you don't control and that you don't git push to.  So this isn't sufficient and what Git provides instead is the command:

git submodule update --remote

In this case, the superproject Git will:

enter the submodule

command the submodule Git to run git fetch

wait for origin/master, or whatever it is, to get updated in the submodule, as a result of that git fetch

find the new hash ID of the submodule's origin/master (or whatever) based on the upstream (that you don't control, but that you just fetched-from)

and then have the submodule Git git checkout that hash ID ... as a detached HEAD, again!

If you do control the submodule, and want to make new commits in it, you need to cd into the submodule and just git checkout whatever branch name you want, and then do your work there.  This submodule is, after all, a regular old Git repository.  You can do whatever work you like and then run git add to copy any updated work-tree files into the index—git commit is going to use what's in the index—and run git commit to make the new commit.

Then, having done all of this, you can either push the commit upstream right now, or wait and cd back into the superproject.  Either way you can now do whatever work is required in the superproject, and git add any modified files and the name of the submodule.  You're not just updating the files in the superproject index, you also need to update the gitlink in the superproject.  And now that you've done all of that, you can run git commit in the superproject, to make a new commit that stores the updated files and the updated gitlink.

Now that you have a new superproject commit, you can git push the new superproject commit somewhere.  If you already used git push in the submodule, that's all you need to do.  But if not, you should git push the submodule first.  The reason is pretty obvious, once you think about it: the new superproject commit says: When you get to this submodule, read this gitlink and extract commit a987654... (or whatever hash ID it is).  For someone else to do that, they'll need to git fetch the upstream submodule that you have to already have git pushed to, so as to get commit a987654... into their submodule Git!

Note that this matches the git submodule update --remote action: they will go to their submodule's upstream, git fetch the updated branch, and then git checkout the appropriate origin/branch hash ID, in this case a987654..., as the detached HEAD for their submodule.

This is not the smoothest process ever, but it's as simple as Git itself can make it.  There are several more things that git submodule update can do, but they all start with this frame of mind: the submodule repository is cloned from somewhere else, and it is primarily the somewhere else that supplies new commits for the submodule.


来源: stackexchange

问:
Ranking different combinations in SQL
I'm working with pharmacy data and I'm trying to rank the use of three specific medications (A, B, C) amongst a large group of patients. In short, I want to figure out the top 12 combinations of these meds that people are using. So for instance, patient 1 might take meds A + B,

patient 2 takes A + C, patient 3 takes B + C, patient 4 takes A + B, and so forth. I did some digging and there are 25 possible combinations to rank. I want my output to look something like this:

The tables I'm working with look like this:

Currently I'm breaking the drugs up into different combination groups by doing something like this:

```<code>select distinct concat(substance_name, dosage, unit) as Drug_Dose_Combo,
count(distinct user_id) as Patients
from pharmacy_data a join drug_reference_table b
on a.drug_code=b.drug_code
group by 1
order by 2 desc
</code>```

However, this seems very inefficient so I'm looking for a better way of building this out. I don't necessarily need to use a rank() here, I just want the output to look similar to what I've outlined above.

答:
Alright it's not too clear what you are looking for, but you did indicate that you want to perform some sort of frequency analysis based on combinations of up to three pharmaceutical products.

The first step in an analysis like this is to take the pharmacy data and for each user_id determine the sets of 1, 2, and 3 drug_dose combinations that they participate in, however, since you may want to do the same analysis on the substance_name, drug_name, and/or drug_code I'm going to throw the kitchen sink at it and do all four.  Not knowing what sort of DB you have on the back end, I'm going to use SQL Server 2017 for this example, though the concepts used are applicable to DBs such as Oracle, MySQL, PostgreSQL and others though the syntax may differ.

To create the drug_code and other combinations I'll first join the pharmacy_data table to the drug_reference table and then use a recursive query on the composite data:

```<code>with usage_info as (
  select pd.user_id
       , dr.drug_code
       , dr.drug_name
       , dr.substance_name
       , concat(dr.substance_name,dr.dosage,dr.unit) drug_dose
    from pharmacy_data pd
    join drug_reference dr
      on dr.drug_code = pd.drug_code
), recur(user_id, combo_id, dc_combo, dc_combo_size, dn_combo, sn_combo, dd_combo, last_dc) as (
  -- Anchor part
  select user_id
       , cast(cast(drug_code as binary(4)) as varbinary(max))
       , cast(drug_code as varchar(max))
       , 1
       , cast(drug_name as varchar(max))
       , cast(substance_name as varchar(max))
       , cast(drug_dose as varchar(max))
       , drug_code
    from usage_info

  union all
  -- Recursive Part
  select prev.user_id
       , prev.combo_id+cast(curr.drug_code as binary(4))
       , prev.dc_combo+','+cast(curr.drug_code as varchar(max))
       , prev.dc_combo_size+1
       , prev.dn_combo+','+curr.drug_name
       , prev.sn_combo+','+curr.substance_name
       , prev.dd_combo+','+curr.drug_dose
       , curr.drug_code
    from recur prev
    join usage_info curr
      on prev.user_id = curr.user_id
     and prev.last_dc < curr.drug_code
     and prev.dc_combo_size < 3 -- Maximum combination size
)
</code>```

Selecting from the above common table expressions for the data provided in your question:

```<code>select * from recur;
</code>```

shows that some irregularities in the groupings for dn_combo, sn_combo, and possibly the dd_combo columns for example there exists dn_combos for both 'CAZERTA,BEXERA' and 'BEXERA,CAZERTA' which really should be equivalent

To rectify this I'll normalize the combinations by splitting them up and recombining them in sorted order.  In the process I'll also deduplicate any instance where a user_id may have two or more equivalent but not identical products e.g. two different doses of the same medication:

```<code>, combos as (
select user_id
     , combo_id
     , dc_combo
     , dc_combo_size
     , -- Normalize and deduplicate Drug_Name combos
       (select string_agg(value,',') within group (order by value)
          from (select distinct value from string_split(dn_combo,',')) dn
       ) dn_combo
     , (select count(distinct value) from string_split(dn_combo,',')) dn_combo_size
     , -- Normalize and deduplicate Substance_Name combos
       (select string_agg(value,',') within group (order by value)
          from (select distinct value from string_split(sn_combo,',')) sn
       ) sn_combo
     , (select count(distinct value) from string_split(sn_combo,',')) sn_combo_size
     , -- Normalize and deduplicate Drug_Dose combos
       (select string_agg(value,',') within group (order by value)
          from (select distinct value from string_split(dd_combo,',')) ddc
       ) dd_combo
     , (select count(distinct value) from string_split(dd_combo,',')) dd_combo_size
  from recur
)
</code>```

Now while you could just select the count(user_id) over (partition by <grouping_column>) to get the occurrence frequency of each drug combination those numbers could be inflated.  Take for example if your data had an additional user_id of 999 with drug_codes 50, 100, 200, and 350 (that's two different doses of BEXERA along with AXIOM and CAZERTA), then user_id 999 would show up multiple times for every combination that includes BEXERA.  Depending on your database flavor you could just select the count(DISTINCT user_id) over (partition by <grouping_column>) but as of SQL Server 2017 it doesn't allow the distinct operator in analytic functions. </shrug> We can still do it just takes another step to identify the unique values per group.  Enter Common Table combo2 where we compute row numbers across various partitions:

```<code>, combo2 as (
select user_id
     , combo_id
     , dc_combo
     , dc_combo_size
     , row_number() over (partition by dc_combo, user_id order by dc_combo) dc_uid_rn
     , dn_combo
     , dn_combo_size
     , row_number() over (partition by dn_combo, user_id order by dc_combo) dn_uid_rn
     , row_number() over (partition by dn_combo, dc_combo order by user_id) dn_combo_rn
     , sn_combo
     , sn_combo_size
     , row_number() over (partition by sn_combo, user_id order by dc_combo) sn_uid_rn
     , row_number() over (partition by sn_combo, dc_combo order by user_id) sn_combo_rn
     , dd_combo
     , dd_combo_size
     , row_number() over (partition by dd_combo, user_id order by dc_combo) dd_uid_rn
     , row_number() over (partition by dd_combo, dc_combo order by user_id) dd_combo_rn
  from combos
)
</code>```

And then finally calculate our counts of which we have two types.  The uid_cnt columns are counts of distinct user_ids for each combination, and the combo_cnt columns indicate the number of distinct drug_code combinations that make up the less granular groupings:

```<code>select user_id
     , combo_id
     , dc_combo
     , dc_combo_size
     , count(case dc_uid_rn when 1 then 1 end) over (partition by dc_combo) dc_uid_cnt
     , dn_combo
     , dn_combo_size
     , count(case dn_uid_rn when 1 then 1 end) over (partition by dn_combo) dn_uid_cnt
     , count(case dn_combo_rn when 1 then 1 end) over (partition by dn_combo) dn_combo_cnt
     , sn_combo
     , sn_combo_size
     , count(case sn_uid_rn when 1 then 1 end) over (partition by sn_combo) sn_uid_cnt
     , count(case sn_combo_rn when 1 then 1 end) over (partition by sn_combo) sn_combo_cnt
     , dd_combo
     , dd_combo_size
     , count(case dd_uid_rn when 1 then 1 end) over (partition by dd_combo) dd_uid_cnt
     , count(case dd_combo_rn when 1 then 1 end) over (partition by dd_combo) dd_combo_cnt
  from combo2
  order by dn_combo, dd_combo
</code>```

All together with my additional sample data the above code results in the following table.  To see it in action please see the SQL Fiddle:

```<code>| user_id |    dc_combo | dc_combo_size | dc_uid_cnt |             dn_combo | dn_combo_size | dn_uid_cnt | dn_combo_cnt |                        sn_combo | sn_combo_size | sn_uid_cnt | sn_combo_cnt |                                        dd_combo | dd_combo_size | dd_uid_cnt | dd_combo_cnt |
|---------|-------------|---------------|------------|----------------------|---------------|------------|--------------|---------------------------------|---------------|------------|--------------|-------------------------------------------------|---------------|------------|--------------|
|       3 |         200 |             1 |          2 |                AXIOM |             1 |          4 |            3 |                           nsaid |             1 |          4 |            3 |                                       nsaid10mg |             1 |          2 |            1 |
|     999 |         200 |             1 |          2 |                AXIOM |             1 |          4 |            3 |                           nsaid |             1 |          4 |            3 |                                       nsaid10mg |             1 |          2 |            1 |
|     175 |         300 |             1 |          1 |                AXIOM |             1 |          4 |            3 |                           nsaid |             1 |          4 |            3 |                                       nsaid25mg |             1 |          1 |            1 |
|       1 |          25 |             1 |          1 |                AXIOM |             1 |          4 |            3 |                           nsaid |             1 |          4 |            3 |                                        nsaid5mg |             1 |          1 |            1 |
|     999 |     200,350 |             2 |          1 |         AXIOM,BEXERA |             2 |          3 |            5 |                 nsaid,potassium |             2 |          3 |            5 |                         nsaid10mg,potassium12mg |             2 |          1 |            1 |
|     999 |  50,200,350 |             3 |          1 |         AXIOM,BEXERA |             2 |          3 |            5 |                 nsaid,potassium |             2 |          3 |            5 |           nsaid10mg,potassium12mg,potassium20mg |             3 |          1 |            1 |
|     999 |      50,200 |             2 |          1 |         AXIOM,BEXERA |             2 |          3 |            5 |                 nsaid,potassium |             2 |          3 |            5 |                         nsaid10mg,potassium20mg |             2 |          1 |            1 |
|     175 |      50,300 |             2 |          1 |         AXIOM,BEXERA |             2 |          3 |            5 |                 nsaid,potassium |             2 |          3 |            5 |                         nsaid25mg,potassium20mg |             2 |          1 |            1 |
|       1 |       25,50 |             2 |          1 |         AXIOM,BEXERA |             2 |          3 |            5 |                 nsaid,potassium |             2 |          3 |            5 |                          nsaid5mg,potassium20mg |             2 |          1 |            1 |
|     999 | 100,200,350 |             3 |          1 | AXIOM,BEXERA,CAZERTA |             3 |          2 |            3 | nsaid,potassium,sodium chloride |             3 |          2 |            3 |     nsaid10mg,potassium12mg,sodium chloride10mg |             3 |          1 |            1 |
|     999 |  50,100,200 |             3 |          1 | AXIOM,BEXERA,CAZERTA |             3 |          2 |            3 | nsaid,potassium,sodium chloride |             3 |          2 |            3 |     nsaid10mg,potassium20mg,sodium chloride10mg |             3 |          1 |            1 |
|       1 |   25,50,100 |             3 |          1 | AXIOM,BEXERA,CAZERTA |             3 |          2 |            3 | nsaid,potassium,sodium chloride |             3 |          2 |            3 |      nsaid5mg,potassium20mg,sodium chloride10mg |             3 |          1 |            1 |
|     999 |     100,200 |             2 |          1 |        AXIOM,CAZERTA |             2 |          2 |            2 |           nsaid,sodium chloride |             2 |          2 |            2 |                   nsaid10mg,sodium chloride10mg |             2 |          1 |            1 |
|       1 |      25,100 |             2 |          1 |        AXIOM,CAZERTA |             2 |          2 |            2 |           nsaid,sodium chloride |             2 |          2 |            2 |                    nsaid5mg,sodium chloride10mg |             2 |          1 |            1 |
|     201 |         350 |             1 |          2 |               BEXERA |             1 |          5 |            4 |                       potassium |             1 |          5 |            4 |                                   potassium12mg |             1 |          2 |            1 |
|     999 |         350 |             1 |          2 |               BEXERA |             1 |          5 |            4 |                       potassium |             1 |          5 |            4 |                                   potassium12mg |             1 |          2 |            1 |
|     999 |      50,350 |             2 |          1 |               BEXERA |             1 |          5 |            4 |                       potassium |             1 |          5 |            4 |                     potassium12mg,potassium20mg |             2 |          1 |            1 |
|     378 |         400 |             1 |          1 |               BEXERA |             1 |          5 |            4 |                       potassium |             1 |          5 |            4 |                                   potassium15mg |             1 |          1 |            1 |
|       1 |          50 |             1 |          3 |               BEXERA |             1 |          5 |            4 |                       potassium |             1 |          5 |            4 |                                   potassium20mg |             1 |          3 |            1 |
|     175 |          50 |             1 |          3 |               BEXERA |             1 |          5 |            4 |                       potassium |             1 |          5 |            4 |                                   potassium20mg |             1 |          3 |            1 |
|     999 |          50 |             1 |          3 |               BEXERA |             1 |          5 |            4 |                       potassium |             1 |          5 |            4 |                                   potassium20mg |             1 |          3 |            1 |
|     999 |  50,100,350 |             3 |          1 |       BEXERA,CAZERTA |             2 |          4 |            5 |       potassium,sodium chloride |             2 |          4 |            5 | potassium12mg,potassium20mg,sodium chloride10mg |             3 |          1 |            1 |
|     999 |     100,350 |             2 |          1 |       BEXERA,CAZERTA |             2 |          4 |            5 |       potassium,sodium chloride |             2 |          4 |            5 |               potassium12mg,sodium chloride10mg |             2 |          1 |            1 |
|     201 |     350,450 |             2 |          1 |       BEXERA,CAZERTA |             2 |          4 |            5 |       potassium,sodium chloride |             2 |          4 |            5 |               potassium12mg,sodium chloride30mg |             2 |          1 |            1 |
|     378 |     100,400 |             2 |          1 |       BEXERA,CAZERTA |             2 |          4 |            5 |       potassium,sodium chloride |             2 |          4 |            5 |               potassium15mg,sodium chloride10mg |             2 |          1 |            1 |
|       1 |      50,100 |             2 |          2 |       BEXERA,CAZERTA |             2 |          4 |            5 |       potassium,sodium chloride |             2 |          4 |            5 |               potassium20mg,sodium chloride10mg |             2 |          2 |            1 |
|     999 |      50,100 |             2 |          2 |       BEXERA,CAZERTA |             2 |          4 |            5 |       potassium,sodium chloride |             2 |          4 |            5 |               potassium20mg,sodium chloride10mg |             2 |          2 |            1 |
|       1 |         100 |             1 |          3 |              CAZERTA |             1 |          4 |            2 |                 sodium chloride |             1 |          4 |            2 |                             sodium chloride10mg |             1 |          3 |            1 |
|     378 |         100 |             1 |          3 |              CAZERTA |             1 |          4 |            2 |                 sodium chloride |             1 |          4 |            2 |                             sodium chloride10mg |             1 |          3 |            1 |
|     999 |         100 |             1 |          3 |              CAZERTA |             1 |          4 |            2 |                 sodium chloride |             1 |          4 |            2 |                             sodium chloride10mg |             1 |          3 |            1 |
|     201 |         450 |             1 |          1 |              CAZERTA |             1 |          4 |            2 |                 sodium chloride |             1 |          4 |            2 |                             sodium chloride30mg |             1 |          1 |            1 |
</code>```

ContentLicense: CC BY-SA 4.0

Title: Ranking different combinations in SQL

Body:
I'm working with pharmacy data and I'm trying to rank the use of three specific medications (A, B, C) amongst a large group of patients. In short, I want to figure out the top 12 combinations of these meds that people are using. So for instance, patient 1 might take meds A + B,

patient 2 takes A + C, patient 3 takes B + C, patient 4 takes A + B, and so forth. I did some digging and there are 25 possible combinations to rank. I want my output to look something like this:

The tables I'm working with look like this:

Currently I'm breaking the drugs up into different combination groups by doing something like this:

select distinct concat(substance_name, dosage, unit) as Drug_Dose_Combo,
count(distinct user_id) as Patients
from pharmacy_data a join drug_reference_table b
on a.drug_code=b.drug_code
group by 1
order by 2 desc

However, this seems very inefficient so I'm looking for a better way of building this out. I don't necessarily need to use a rank() here, I just want the output to look similar to what I've outlined above.

Body:
Alright it's not too clear what you are looking for, but you did indicate that you want to perform some sort of frequency analysis based on combinations of up to three pharmaceutical products.

The first step in an analysis like this is to take the pharmacy data and for each user_id determine the sets of 1, 2, and 3 drug_dose combinations that they participate in, however, since you may want to do the same analysis on the substance_name, drug_name, and/or drug_code I'm going to throw the kitchen sink at it and do all four.  Not knowing what sort of DB you have on the back end, I'm going to use SQL Server 2017 for this example, though the concepts used are applicable to DBs such as Oracle, MySQL, PostgreSQL and others though the syntax may differ.

To create the drug_code and other combinations I'll first join the pharmacy_data table to the drug_reference table and then use a recursive query on the composite data:

with usage_info as (
  select pd.user_id
       , dr.drug_code
       , dr.drug_name
       , dr.substance_name
       , concat(dr.substance_name,dr.dosage,dr.unit) drug_dose
    from pharmacy_data pd
    join drug_reference dr
      on dr.drug_code = pd.drug_code
), recur(user_id, combo_id, dc_combo, dc_combo_size, dn_combo, sn_combo, dd_combo, last_dc) as (
  -- Anchor part
  select user_id
       , cast(cast(drug_code as binary(4)) as varbinary(max))
       , cast(drug_code as varchar(max))
       , 1
       , cast(drug_name as varchar(max))
       , cast(substance_name as varchar(max))
       , cast(drug_dose as varchar(max))
       , drug_code
    from usage_info

  union all
  -- Recursive Part
  select prev.user_id
       , prev.combo_id+cast(curr.drug_code as binary(4))
       , prev.dc_combo+','+cast(curr.drug_code as varchar(max))
       , prev.dc_combo_size+1
       , prev.dn_combo+','+curr.drug_name
       , prev.sn_combo+','+curr.substance_name
       , prev.dd_combo+','+curr.drug_dose
       , curr.drug_code
    from recur prev
    join usage_info curr
      on prev.user_id = curr.user_id
     and prev.last_dc < curr.drug_code
     and prev.dc_combo_size < 3 -- Maximum combination size
)

Selecting from the above common table expressions for the data provided in your question:

select * from recur;

shows that some irregularities in the groupings for dn_combo, sn_combo, and possibly the dd_combo columns for example there exists dn_combos for both 'CAZERTA,BEXERA' and 'BEXERA,CAZERTA' which really should be equivalent

To rectify this I'll normalize the combinations by splitting them up and recombining them in sorted order.  In the process I'll also deduplicate any instance where a user_id may have two or more equivalent but not identical products e.g. two different doses of the same medication:

, combos as (
select user_id
     , combo_id
     , dc_combo
     , dc_combo_size
     , -- Normalize and deduplicate Drug_Name combos
       (select string_agg(value,',') within group (order by value)
          from (select distinct value from string_split(dn_combo,',')) dn
       ) dn_combo
     , (select count(distinct value) from string_split(dn_combo,',')) dn_combo_size
     , -- Normalize and deduplicate Substance_Name combos
       (select string_agg(value,',') within group (order by value)
          from (select distinct value from string_split(sn_combo,',')) sn
       ) sn_combo
     , (select count(distinct value) from string_split(sn_combo,',')) sn_combo_size
     , -- Normalize and deduplicate Drug_Dose combos
       (select string_agg(value,',') within group (order by value)
          from (select distinct value from string_split(dd_combo,',')) ddc
       ) dd_combo
     , (select count(distinct value) from string_split(dd_combo,',')) dd_combo_size
  from recur
)

Now while you could just select the count(user_id) over (partition by <grouping_column>) to get the occurrence frequency of each drug combination those numbers could be inflated.  Take for example if your data had an additional user_id of 999 with drug_codes 50, 100, 200, and 350 (that's two different doses of BEXERA along with AXIOM and CAZERTA), then user_id 999 would show up multiple times for every combination that includes BEXERA.  Depending on your database flavor you could just select the count(DISTINCT user_id) over (partition by <grouping_column>) but as of SQL Server 2017 it doesn't allow the distinct operator in analytic functions. </shrug> We can still do it just takes another step to identify the unique values per group.  Enter Common Table combo2 where we compute row numbers across various partitions:

, combo2 as (
select user_id
     , combo_id
     , dc_combo
     , dc_combo_size
     , row_number() over (partition by dc_combo, user_id order by dc_combo) dc_uid_rn
     , dn_combo
     , dn_combo_size
     , row_number() over (partition by dn_combo, user_id order by dc_combo) dn_uid_rn
     , row_number() over (partition by dn_combo, dc_combo order by user_id) dn_combo_rn
     , sn_combo
     , sn_combo_size
     , row_number() over (partition by sn_combo, user_id order by dc_combo) sn_uid_rn
     , row_number() over (partition by sn_combo, dc_combo order by user_id) sn_combo_rn
     , dd_combo
     , dd_combo_size
     , row_number() over (partition by dd_combo, user_id order by dc_combo) dd_uid_rn
     , row_number() over (partition by dd_combo, dc_combo order by user_id) dd_combo_rn
  from combos
)

And then finally calculate our counts of which we have two types.  The uid_cnt columns are counts of distinct user_ids for each combination, and the combo_cnt columns indicate the number of distinct drug_code combinations that make up the less granular groupings:

select user_id
     , combo_id
     , dc_combo
     , dc_combo_size
     , count(case dc_uid_rn when 1 then 1 end) over (partition by dc_combo) dc_uid_cnt
     , dn_combo
     , dn_combo_size
     , count(case dn_uid_rn when 1 then 1 end) over (partition by dn_combo) dn_uid_cnt
     , count(case dn_combo_rn when 1 then 1 end) over (partition by dn_combo) dn_combo_cnt
     , sn_combo
     , sn_combo_size
     , count(case sn_uid_rn when 1 then 1 end) over (partition by sn_combo) sn_uid_cnt
     , count(case sn_combo_rn when 1 then 1 end) over (partition by sn_combo) sn_combo_cnt
     , dd_combo
     , dd_combo_size
     , count(case dd_uid_rn when 1 then 1 end) over (partition by dd_combo) dd_uid_cnt
     , count(case dd_combo_rn when 1 then 1 end) over (partition by dd_combo) dd_combo_cnt
  from combo2
  order by dn_combo, dd_combo

All together with my additional sample data the above code results in the following table.  To see it in action please see the SQL Fiddle:

| user_id |    dc_combo | dc_combo_size | dc_uid_cnt |             dn_combo | dn_combo_size | dn_uid_cnt | dn_combo_cnt |                        sn_combo | sn_combo_size | sn_uid_cnt | sn_combo_cnt |                                        dd_combo | dd_combo_size | dd_uid_cnt | dd_combo_cnt |
|---------|-------------|---------------|------------|----------------------|---------------|------------|--------------|---------------------------------|---------------|------------|--------------|-------------------------------------------------|---------------|------------|--------------|
|       3 |         200 |             1 |          2 |                AXIOM |             1 |          4 |            3 |                           nsaid |             1 |          4 |            3 |                                       nsaid10mg |             1 |          2 |            1 |
|     999 |         200 |             1 |          2 |                AXIOM |             1 |          4 |            3 |                           nsaid |             1 |          4 |            3 |                                       nsaid10mg |             1 |          2 |            1 |
|     175 |         300 |             1 |          1 |                AXIOM |             1 |          4 |            3 |                           nsaid |             1 |          4 |            3 |                                       nsaid25mg |             1 |          1 |            1 |
|       1 |          25 |             1 |          1 |                AXIOM |             1 |          4 |            3 |                           nsaid |             1 |          4 |            3 |                                        nsaid5mg |             1 |          1 |            1 |
|     999 |     200,350 |             2 |          1 |         AXIOM,BEXERA |             2 |          3 |            5 |                 nsaid,potassium |             2 |          3 |            5 |                         nsaid10mg,potassium12mg |             2 |          1 |            1 |
|     999 |  50,200,350 |             3 |          1 |         AXIOM,BEXERA |             2 |          3 |            5 |                 nsaid,potassium |             2 |          3 |            5 |           nsaid10mg,potassium12mg,potassium20mg |             3 |          1 |            1 |
|     999 |      50,200 |             2 |          1 |         AXIOM,BEXERA |             2 |          3 |            5 |                 nsaid,potassium |             2 |          3 |            5 |                         nsaid10mg,potassium20mg |             2 |          1 |            1 |
|     175 |      50,300 |             2 |          1 |         AXIOM,BEXERA |             2 |          3 |            5 |                 nsaid,potassium |             2 |          3 |            5 |                         nsaid25mg,potassium20mg |             2 |          1 |            1 |
|       1 |       25,50 |             2 |          1 |         AXIOM,BEXERA |             2 |          3 |            5 |                 nsaid,potassium |             2 |          3 |            5 |                          nsaid5mg,potassium20mg |             2 |          1 |            1 |
|     999 | 100,200,350 |             3 |          1 | AXIOM,BEXERA,CAZERTA |             3 |          2 |            3 | nsaid,potassium,sodium chloride |             3 |          2 |            3 |     nsaid10mg,potassium12mg,sodium chloride10mg |             3 |          1 |            1 |
|     999 |  50,100,200 |             3 |          1 | AXIOM,BEXERA,CAZERTA |             3 |          2 |            3 | nsaid,potassium,sodium chloride |             3 |          2 |            3 |     nsaid10mg,potassium20mg,sodium chloride10mg |             3 |          1 |            1 |
|       1 |   25,50,100 |             3 |          1 | AXIOM,BEXERA,CAZERTA |             3 |          2 |            3 | nsaid,potassium,sodium chloride |             3 |          2 |            3 |      nsaid5mg,potassium20mg,sodium chloride10mg |             3 |          1 |            1 |
|     999 |     100,200 |             2 |          1 |        AXIOM,CAZERTA |             2 |          2 |            2 |           nsaid,sodium chloride |             2 |          2 |            2 |                   nsaid10mg,sodium chloride10mg |             2 |          1 |            1 |
|       1 |      25,100 |             2 |          1 |        AXIOM,CAZERTA |             2 |          2 |            2 |           nsaid,sodium chloride |             2 |          2 |            2 |                    nsaid5mg,sodium chloride10mg |             2 |          1 |            1 |
|     201 |         350 |             1 |          2 |               BEXERA |             1 |          5 |            4 |                       potassium |             1 |          5 |            4 |                                   potassium12mg |             1 |          2 |            1 |
|     999 |         350 |             1 |          2 |               BEXERA |             1 |          5 |            4 |                       potassium |             1 |          5 |            4 |                                   potassium12mg |             1 |          2 |            1 |
|     999 |      50,350 |             2 |          1 |               BEXERA |             1 |          5 |            4 |                       potassium |             1 |          5 |            4 |                     potassium12mg,potassium20mg |             2 |          1 |            1 |
|     378 |         400 |             1 |          1 |               BEXERA |             1 |          5 |            4 |                       potassium |             1 |          5 |            4 |                                   potassium15mg |             1 |          1 |            1 |
|       1 |          50 |             1 |          3 |               BEXERA |             1 |          5 |            4 |                       potassium |             1 |          5 |            4 |                                   potassium20mg |             1 |          3 |            1 |
|     175 |          50 |             1 |          3 |               BEXERA |             1 |          5 |            4 |                       potassium |             1 |          5 |            4 |                                   potassium20mg |             1 |          3 |            1 |
|     999 |          50 |             1 |          3 |               BEXERA |             1 |          5 |            4 |                       potassium |             1 |          5 |            4 |                                   potassium20mg |             1 |          3 |            1 |
|     999 |  50,100,350 |             3 |          1 |       BEXERA,CAZERTA |             2 |          4 |            5 |       potassium,sodium chloride |             2 |          4 |            5 | potassium12mg,potassium20mg,sodium chloride10mg |             3 |          1 |            1 |
|     999 |     100,350 |             2 |          1 |       BEXERA,CAZERTA |             2 |          4 |            5 |       potassium,sodium chloride |             2 |          4 |            5 |               potassium12mg,sodium chloride10mg |             2 |          1 |            1 |
|     201 |     350,450 |             2 |          1 |       BEXERA,CAZERTA |             2 |          4 |            5 |       potassium,sodium chloride |             2 |          4 |            5 |               potassium12mg,sodium chloride30mg |             2 |          1 |            1 |
|     378 |     100,400 |             2 |          1 |       BEXERA,CAZERTA |             2 |          4 |            5 |       potassium,sodium chloride |             2 |          4 |            5 |               potassium15mg,sodium chloride10mg |             2 |          1 |            1 |
|       1 |      50,100 |             2 |          2 |       BEXERA,CAZERTA |             2 |          4 |            5 |       potassium,sodium chloride |             2 |          4 |            5 |               potassium20mg,sodium chloride10mg |             2 |          2 |            1 |
|     999 |      50,100 |             2 |          2 |       BEXERA,CAZERTA |             2 |          4 |            5 |       potassium,sodium chloride |             2 |          4 |            5 |               potassium20mg,sodium chloride10mg |             2 |          2 |            1 |
|       1 |         100 |             1 |          3 |              CAZERTA |             1 |          4 |            2 |                 sodium chloride |             1 |          4 |            2 |                             sodium chloride10mg |             1 |          3 |            1 |
|     378 |         100 |             1 |          3 |              CAZERTA |             1 |          4 |            2 |                 sodium chloride |             1 |          4 |            2 |                             sodium chloride10mg |             1 |          3 |            1 |
|     999 |         100 |             1 |          3 |              CAZERTA |             1 |          4 |            2 |                 sodium chloride |             1 |          4 |            2 |                             sodium chloride10mg |             1 |          3 |            1 |
|     201 |         450 |             1 |          1 |              CAZERTA |             1 |          4 |            2 |                 sodium chloride |             1 |          4 |            2 |                             sodium chloride30mg |             1 |          1 |            1 |


问:
How to avoid com.thoughtworks.xstream.io.StreamException: Cannot create XmlPullParser while deseriliazation?
I am getting a exception"Exception in thread "main" com.thoughtworks.xstream.io.StreamException: Cannot create XmlPullParser" while deserializing the xml . I have added  following dependency

```<code>xmlpull_1_0_5.jar
xpp3_min-1.1.4.jar
xstream-1.4.8.jar
</code>```

Test code:

```<code>import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class Test {

  public static void main(String[] args) {

    Map<String, String> map = new HashMap<String, String>();
    map.put("name", "chris");
    map.put("island", "faranga");

    XStream magicApi = new XStream();
    magicApi.registerConverter(new MapEntryConverter());
    magicApi.alias("root", Map.class);

    String xml = magicApi.toXML(map);
    System.out.println("Result of tweaked XStream toXml()");
    System.out.println(xml);

    magicApi.fromXML(xml);
    // assert extractedMap.get("name").equals("chris");
    // assert extractedMap.get("island").equals("faranga");

  }

  public static class MapEntryConverter implements Converter {

    public boolean canConvert(Class clazz) {
      return AbstractMap.class.isAssignableFrom(clazz);
    }

    public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {

      AbstractMap map = (AbstractMap) value;
      for (Object obj : map.entrySet()) {
        Map.Entry entry = (Map.Entry) obj;
        writer.startNode(entry.getKey().toString());
        Object val = entry.getValue();
        if (null != val) {
          writer.setValue(val.toString());
        }
        writer.endNode();
      }

    }

    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

      Map<String, String> map = new HashMap<String, String>();

      while (reader.hasMoreChildren()) {
        reader.moveDown();

        String key = reader.getNodeName(); // nodeName aka element's name
        String value = reader.getValue();
        map.put(key, value);

        reader.moveUp();
      }

      return map;
    }

  }

}
</code>```

Am i misiing some dependency .Any help On this will be appreciated.

答:
This problem gave me so much headache. I've solved using:

```<code>XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library
XStream xstream = new XStream(new StaxDriver()); // does not require XPP3 library starting with Java 6
</code>```

If still problem continues try import these

```<code><dependency>
        <groupId>com.thoughtworks.xstream</groupId>
        <artifactId>xstream</artifactId>
        <version>1.4</version>
</dependency>

<dependency>
       <groupId>xmlpull</groupId>
       <artifactId>xmlpull</artifactId>
       <version>1.1.3.1</version>
</dependency>
<dependency>
       <groupId>xpp3</groupId>
       <artifactId>xpp3_min</ artifactId>
       <version>1.1.4c</version>
</dependency>
</code>```

Refs:

https://x-stream.github.io/tutorial.html

https://my.oschina.net/u/3067322/blog/821900

ContentLicense: CC BY-SA 3.0

Body:
I am getting a exception"Exception in thread "main" com.thoughtworks.xstream.io.StreamException: Cannot create XmlPullParser" while deserializing the xml . I have added  following dependency

xmlpull_1_0_5.jar
xpp3_min-1.1.4.jar
xstream-1.4.8.jar

Test code:

import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Map;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class Test {

  public static void main(String[] args) {

    Map<String, String> map = new HashMap<String, String>();
    map.put("name", "chris");
    map.put("island", "faranga");

    XStream magicApi = new XStream();
    magicApi.registerConverter(new MapEntryConverter());
    magicApi.alias("root", Map.class);

    String xml = magicApi.toXML(map);
    System.out.println("Result of tweaked XStream toXml()");
    System.out.println(xml);

    magicApi.fromXML(xml);
    // assert extractedMap.get("name").equals("chris");
    // assert extractedMap.get("island").equals("faranga");

  }

  public static class MapEntryConverter implements Converter {

    public boolean canConvert(Class clazz) {
      return AbstractMap.class.isAssignableFrom(clazz);
    }

    public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {

      AbstractMap map = (AbstractMap) value;
      for (Object obj : map.entrySet()) {
        Map.Entry entry = (Map.Entry) obj;
        writer.startNode(entry.getKey().toString());
        Object val = entry.getValue();
        if (null != val) {
          writer.setValue(val.toString());
        }
        writer.endNode();
      }

    }

    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

      Map<String, String> map = new HashMap<String, String>();

      while (reader.hasMoreChildren()) {
        reader.moveDown();

        String key = reader.getNodeName(); // nodeName aka element's name
        String value = reader.getValue();
        map.put(key, value);

        reader.moveUp();
      }

      return map;
    }

  }

}

Am i misiing some dependency .Any help On this will be appreciated.

Body:
This problem gave me so much headache. I've solved using:

XStream xstream = new XStream(new DomDriver()); // does not require XPP3 library
XStream xstream = new XStream(new StaxDriver()); // does not require XPP3 library starting with Java 6

If still problem continues try import these

<dependency>
        <groupId>com.thoughtworks.xstream</groupId>
        <artifactId>xstream</artifactId>
        <version>1.4</version>
</dependency>

<dependency>
       <groupId>xmlpull</groupId>
       <artifactId>xmlpull</artifactId>
       <version>1.1.3.1</version>
</dependency>
<dependency>
       <groupId>xpp3</groupId>
       <artifactId>xpp3_min</ artifactId>
       <version>1.1.4c</version>
</dependency>

Refs:

https://x-stream.github.io/tutorial.html

https://my.oschina.net/u/3067322/blog/821900


问:
Best way to upload dataset from my PC to Virtual Machine instance on Google Cloud Platform
I have a big dataset (around 50 GB) for a deep learning experiment. I will train my net on a Virtual Machine instance provided from The Google Cloud Platform. So I need to upload my dataset into the virtual machine.
I've tried to use the gcloud console with the command:

```<code>gcloud compute scp --recurse C:\Users\Lenovo\Desktop\dataset root@instance-1:/home/Lenovo/dataset
</code>```

It works, but it needs around 50 hours to end.

Is there any way to make this process faster?

I also have a Google Drive repository in which I stored my dataset. It is possible to directly download into my virtual machine from Google Drive?
My virtual machine has Ubuntu 18.04 LTS version of operating system.

答:
The time taken will primarily be governed by the slowest link on the network.  Let us assume that the network hosting your GCP Virtual Machine (Compute Engine) isn't going to that.  It is also likely that your Google Drive is also not the slowest.  Chances are high that the path from your local machine where you are running gcloud is going to be the bottleneck.  What I would suggest is to login to your VM on GCP and run a download from your data which I understand is on Drive.

There appears to be a number of ways to achieve that.

Run VNC on your GCP machine
This would give you a GUI environment accessed from your local PC but presented from GCP.  From there you could install Chrome (on GCP) and access your Drive and initiate a download.

Download a Drive access tool
An alternative is to install a Drive data access tool.  Here is an example I found with a Google search but others may work:

https://www.howtoforge.com/tutorial/how-to-access-google-drive-from-linux-gdrive/

Follow the recipes there and download the Drive files onto your GCP.

If you have need for further big data work, consider placing your data on Google Cloud Storage and then additional options will apply.

See transferring big data sets.

Body:
I have a big dataset (around 50 GB) for a deep learning experiment. I will train my net on a Virtual Machine instance provided from The Google Cloud Platform. So I need to upload my dataset into the virtual machine.
I've tried to use the gcloud console with the command:

gcloud compute scp --recurse C:\Users\Lenovo\Desktop\dataset root@instance-1:/home/Lenovo/dataset

It works, but it needs around 50 hours to end.

Is there any way to make this process faster?

I also have a Google Drive repository in which I stored my dataset. It is possible to directly download into my virtual machine from Google Drive?
My virtual machine has Ubuntu 18.04 LTS version of operating system.


问:
Passing additional vs one argument into the function
I am implementing compose function using reduceRight menthod as follows

const compose = fns => (...args) =>
  fns.reduceRight((acc, fn) => fn(acc, ...[args.slice(1)]), args[0]);

const func3 = (x, y) => (y > 0 ? x + 3 : x - 3);

const func2 = x => x ** 2;

const func1 = x => x - 8;

const fnOne = compose([func1, func2, func3])('3', 1);
console.log(fnOne); // should be 1081

const fnTwo = compose([func1, func2, func3])('3', -1);
console.log(fnTwo); //should be -8```

the first function is supposed to receive two arguments and return the result to the next function as the only one argument. The problem is that the first function is passing two arguments to the next function instead of one. Let me know if you have any ideas how to fix it. Any help is very much appreciated.

答:
The problem here is that you're not modifying the args variable.

Let's look at what happens in detail:

At the first call of your reductor, acc becomes func3(args[0], ...[args.shift(1)]) === func3(args[0], args[1], args[2], ...).

At the second call, acc becomes func2(acc, [args.shift(1)]), which is func2(func3(args[0], args[1], args[2], ...), args[1], args[2], ...).

You can already see where the problem lies: args1 is never dropped from the array, because Array.slice() creates a copy and does not modify the actual array.

To solve your problem you should instead use:

const compose = fns => (...args) =>
  fns.reduceRight((acc, fn) => fn(acc, ...args.splice(0, fn.length - 1)), args[0]);```

Body:
I am implementing compose function using reduceRight menthod as follows

const compose = fns => (...args) =>
  fns.reduceRight((acc, fn) => fn(acc, ...[args.slice(1)]), args[0]);

const func3 = (x, y) => (y > 0 ? x + 3 : x - 3);

const func2 = x => x ** 2;

const func1 = x => x - 8;

const fnOne = compose([func1, func2, func3])('3', 1);
console.log(fnOne); // should be 1081

const fnTwo = compose([func1, func2, func3])('3', -1);
console.log(fnTwo); //should be -8

the first function is supposed to receive two arguments and return the result to the next function as the only one argument. The problem is that the first function is passing two arguments to the next function instead of one. Let me know if you have any ideas how to fix it. Any help is very much appreciated.


问:
Google pub/sub push subscriber error "The supplied HTTP URL is not registered in the subscription's parent project"
I am trying to write a push based subscriber for Google Cloud pub/sub

My code looks like this

```<code>try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create(subscriptionAdminSettings)) {
  ProjectSubscriptionName name = ProjectSubscriptionName.of(PROJECT, SUBSCRIPTION_NAME);
  ProjectTopicName topic = ProjectTopicName.of(PROJECT, TOPIC_NAME);
  PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(PUSH_ENDPOINT).build();
  int ackDeadlineSeconds = 5;
  Subscription subscription = subscriptionAdminClient.createSubscription(name, topic, pushConfig, ackDeadlineSeconds);
}
</code>```

However, I get this error at runtime

```<code>The supplied HTTP URL is not registered in the subscription's parent project
(url="https://...", project_id="8xxxxxxxxx5").
</code>```

Where do I need to register this url? Somewhere in project, or with topic?

Found some discussion here but seems slightly dated as some of those links are redirecting to other docs now.

答: To prevent unwelcome traffic, Cloud Pub/Sub requires you to verify your ownership of the push endpoint. Please follow the steps at https://cloud.google.com/pubsub/docs/push#domain_ownership_validation to verify ownership of your push endpoint.</p>

Body:
I am trying to write a push based subscriber for Google Cloud pub/sub

My code looks like this

try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create(subscriptionAdminSettings)) {
  ProjectSubscriptionName name = ProjectSubscriptionName.of(PROJECT, SUBSCRIPTION_NAME);
  ProjectTopicName topic = ProjectTopicName.of(PROJECT, TOPIC_NAME);
  PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(PUSH_ENDPOINT).build();
  int ackDeadlineSeconds = 5;
  Subscription subscription = subscriptionAdminClient.createSubscription(name, topic, pushConfig, ackDeadlineSeconds);
}

However, I get this error at runtime

The supplied HTTP URL is not registered in the subscription's parent project
(url="https://...", project_id="8xxxxxxxxx5").

Where do I need to register this url? Somewhere in project, or with topic?

Found some discussion here but seems slightly dated as some of those links are redirecting to other docs now.


问:
Need help matching a string if it ONLY contains approved substrings
I am having a hard time writing this regular expression.

Basically I need to block email delivery if the message recipient envelope contains an unapproved domain.  My internet mail gateway (Brightmail) allows to create rules where I can specify a condition using Match/DoesNotMatch a regular expression.

For example I need only allow mail to yahoo.com, hotmail.com, and gmail.com.

If someone sends a message to some other domain, the message should be blocked.

If someone sends a message to yahoo.com AND some other domain, the message should be blocked

If someone sends a message to yahoo.com, the message should be allowed.

Is this possible?

If someone sends a message to yahoo.com and hotmail.com, the message should be allowed.

I am not a total noob with regular expression, but this one has me stumped.

答:
That sounds like its possible.  It would be a token find where you have a series of OR operators between tokens.

I don't know if you have ever used this site, but it is a GODSEND when I am developing regex queries.

http://regexpal.com/


问:
can i pass function as attribute to web component?
I'm trying to create a native web component for input element. I wanted the component to have custom validation functionality, similar to polymer's paper-input custom validator function. I'm not sure if I can pass a custom validator function as attribute to an instance of (web component) input element. Any suggestions would be appreciated. </p>

答:
Just pass it to the constructor.
Your custom element statement:

class CustomInput extends HTMLElement {
  constructor(validator) {
    super()
    this.validate = validator
  }

  /* Your Custom Input Methods */
}
```

<p>And then instantiate your component via the <code>new</code> operator instead of the <code>document.createElement</code>.</p>

<p><strong>Instantiation:</strong></p>

<pre class="lang-js prettyprint-override"><code>const customInputEl = new CustomInput((inputString) => {
  // your validation code
})
</code>```

If you want to pass a function to the component, it must mean that you instantiate it via javascript anyway.

Body:
Just pass it to the constructor.
Your custom element statement:

class CustomInput extends HTMLElement {
  constructor(validator) {
    super()
    this.validate = validator
  }

  /* Your Custom Input Methods */
}

And then instantiate your component via the new operator instead of the document.createElement.

Instantiation:

const customInputEl = new CustomInput((inputString) => {
  // your validation code
})

If you want to pass a function to the component, it must mean that you instantiate it via javascript anyway.


问:
Do I remove webpack-dev-server and hot-module middleware code during production build, or when I get ready for production?
As the title suggests, when I'm ready to host the code for production, should I remove all usages of webpack-dev-middleware and webpack-hot-middleware from my server code as they are dev-dependencies? What's the best way to set this up so maybe I don't have to worry about this?

This is a snapshot of my server code:

```<code>// webpack -> HMR
const webpack = require("webpack");
const webpackConfig = require("../webpack.config");
const compiler = webpack(webpackConfig);

// webpack HMR init
app.use(
    require("webpack-dev-middleware")(compiler, {
        noInfo: false,
        publicPath: webpackConfig.output.publicPath,
    })
);
app.use(require("webpack-hot-middleware")(compiler));

...

app.get("/", async (req, res) => {
    const initialContent = await serverRender();
    res.render("index", {
        ...initialContent,
    });
});

app.listen(port, () => {
    console.log(`Express application listening on port ${port}`);
});
</code>```

答:
You should wrap your HMR code (or really, any development/environment specific setting) into it's own area. I wouldn't recommend taking it out of your code as you may come back to the application and want to update something. Having HMR is a pretty nice luxery, so I would just have you code sniff out the environment, and if it's development, run the associated code. Otherwise, don't run it.

How do you detect the environment in an express.js app?

Body:
As the title suggests, when I'm ready to host the code for production, should I remove all usages of webpack-dev-middleware and webpack-hot-middleware from my server code as they are dev-dependencies? What's the best way to set this up so maybe I don't have to worry about this?

This is a snapshot of my server code:

// webpack -> HMR
const webpack = require("webpack");
const webpackConfig = require("../webpack.config");
const compiler = webpack(webpackConfig);

// webpack HMR init
app.use(
    require("webpack-dev-middleware")(compiler, {
        noInfo: false,
        publicPath: webpackConfig.output.publicPath,
    })
);
app.use(require("webpack-hot-middleware")(compiler));

...

app.get("/", async (req, res) => {
    const initialContent = await serverRender();
    res.render("index", {
        ...initialContent,
    });
});

app.listen(port, () => {
    console.log(`Express application listening on port ${port}`);
});


问:
Is it possible to include a C# variable in a string variable without using a concatenator?
Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In the pseudo, I'm using a $ symbol to specify the variable):

```<code>DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);
</code>```

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

```<code>string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>
    <html>
    <head>
        <title>$title</title>
    </head>
    <body>
    <div>Hello StackO</div>
    <div>The date is $date</div>
    </body>
    </html>
    ";

}
</code>```

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.

答:
```<code>string.Format("The date is {0}", DateTime.Now.ToString())
</code>```

Body:
Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In the pseudo, I'm using a $ symbol to specify the variable):

DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>

        <title>$title</title>

Hello StackO

The date is $date

    ";

}

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.


问:
Cleaning up rails migrations & persisting production data
We maintain a large project with many migrations dating back about 4 years.

Ideally we would like to delete all the old migrations and copy the schema contents into an initial_migration.rb file.

My question then, consists of three things:

Will this wipe out our clients databases?

If so, how do we persist the data?

Generally speaking what is the best way to go about this

Thanks in advance.

答:
I think first of all you should backup your databases.

For your current environments, I think there's no need to run your new migration, so, it should have timestamp less than your current schema version.

If you want to run that new migration file on other environments, I think you can. From my opinion, you will have another database with the same structure. Or, you can just make copy of current one for those environments.


问:
How do I return an InternalErrorResult?
I am using Swagger with a .Net Core API.
When there is a bug in the API I want to receive an InternalServerError
However there is no NotOK method to do this.

Currently I have the following in my base controller

```<code>using System;
using Microsoft.AspNetCore.Mvc;

namespace MyApi.Controllers
{
    public class BaseController : Controller
    {
        public IActionResult RouteInterfaceMethod<TResponse>(Func<TResponse> function)
        {
        //    try
        //    {
                IActionResult res = null;
                TResponse ret = function();
                res = Ok(ret);
                return res;
        //    }
        //    catch (Exception e)
        //    {
        //       var msg = MakeErrorMessage(e);
        //       return base.NotFound( msg);
        //    }
        }
    }
}
</code>```

And am about to  un-comment the code ,is there an alternative to using NotFound()

答:
You can return InternalServerError in this way

```<code>catch (Exception e)
{
   var msg = MakeErrorMessage(e);
   return StatusCode(HttpStatusCode.InternalServerError, msg);
}
</code>```

or just re-throw an exception

```<code> catch (Exception e)
 {
       var msg = MakeErrorMessage(e);
       throw;
 }
</code>```

Title: How do I return an InternalErrorResult?

Body:
I am using Swagger with a .Net Core API.
When there is a bug in the API I want to receive an InternalServerError
However there is no NotOK method to do this.

Currently I have the following in my base controller

using System;
using Microsoft.AspNetCore.Mvc;

namespace MyApi.Controllers
{
    public class BaseController : Controller
    {
        public IActionResult RouteInterfaceMethod<TResponse>(Func<TResponse> function)
        {
        //    try
        //    {
                IActionResult res = null;
                TResponse ret = function();
                res = Ok(ret);
                return res;
        //    }
        //    catch (Exception e)
        //    {
        //       var msg = MakeErrorMessage(e);
        //       return base.NotFound( msg);
        //    }
        }
    }
}

And am about to  un-comment the code ,is there an alternative to using NotFound()

Body:
You can return InternalServerError in this way

catch (Exception e)
{
   var msg = MakeErrorMessage(e);
   return StatusCode(HttpStatusCode.InternalServerError, msg);
}

or just re-throw an exception

 catch (Exception e)
 {
       var msg = MakeErrorMessage(e);
       throw;
 }


问:
How to make the planehelper rotate at a point that is not the origin
I have set a clip plane in the scene that is not at the origin. I want the clip plane to rotate around its axis at its current position. I found that the existing planehelper class could not do this. What is the method? If I need to implement a new class myself, what good ideas are there? Thank you.</p>

答:
Place the planeHelper in a new Group().

Change the position of planeHelper in the opposite direction of the new pivot point you want. If you want it to pivot around (1, 0, 2), move it to (-1, 0, -2)

Add the group to the scene.

Rotate the parent group.


答:
No, it doesn't. There are ways around this, but they defeat the purpose. Easiest thing for your example is</p>

```<code>Console.WriteLine("The date is {0}", DateTime.Now);
</code>```

Title: Is it possible to include a C# variable in a string variable without using a concatenator?

Body:
No, it doesn't. There are ways around this, but they defeat the purpose. Easiest thing for your example is

Console.WriteLine("The date is {0}", DateTime.Now);


问:
How to change the bootstrap primary color?
Is it possible to change the bootstrap primary color to match to the brand color? I am using bootswatch's paper theme in my case.  </p>

答:
I've created this tool: https://lingtalfi.com/bootstrap4-color-generator,
you simply put primary in the first field, then choose your color, and click generate.

Then copy the generated scss or css code, and paste it in a file named my-colors.scss or my-colors.css (or whatever name you want).

Once you compile the scss into css, you can include that css file AFTER the bootstrap CSS and you'll be good to go.

The whole process takes about 10 seconds if you get the gist of it, provided that the my-colors.scss file is already created and included in your head tag.

Note: this tool can be used to override bootstrap's default colors (primary, secondary, danger, ...), but you can also create custom colors if you want (blue, green, ternary, ...).

Note2: this tool was made to work with bootstrap 4 (i.e. not any subsequent version for now).


问:
How to use azure-cli node package in Node js application
I am developing a Node js application. I want to use the azure-cli package in my application to create HDI cluster and VM.

```<code>npm install azure-cli -g --save
</code>```

Above command install the azure-cli v1.0 only.

How and where should I use the azure commands in my application.

Should I need write azure cli commands in shell script file and call that script file from node js application or any other way like calling azure cli commands in the node js application without a script file?

Note: Why azure-cli doesn't install azure cli V2.0

Update 1:-

If I install winston package application, I can use like the following

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

  winston.log('info', 'Hello distributed log files!');
  winston.info('Hello again distributed logs');
</code>```

Like that, Is there a way to use if I install azure-cli? (i.e inside my node js application)

答:
To answer your specific question around creating a VM or HDI (Hadoop cluster) in your Node.js app, the best approach would be to use the Azure SDK for Node.

For VMs, use npm install azure-arm-compute and follow instructions in VM Modules for NodeJS

For Hadoop, use npm install azure-arm-hdinsight and follow reference for azure-arm-hdinsight package

The older version of the Azure CLI was Node.js based, while the current version of the Azure CLI (v2) is Python based. You can install the latest version via the multiple mechanisms provided in http://aka.ms/cli.

Body:
I am developing a Node js application. I want to use the azure-cli package in my application to create HDI cluster and VM.

npm install azure-cli -g --save

Above command install the azure-cli v1.0 only.

How and where should I use the azure commands in my application.

Should I need write azure cli commands in shell script file and call that script file from node js application or any other way like calling azure cli commands in the node js application without a script file?

Note: Why azure-cli doesn't install azure cli V2.0

Update 1:-

If I install winston package application, I can use like the following

 var winston = require('winston');

  winston.log('info', 'Hello distributed log files!');
  winston.info('Hello again distributed logs');

Like that, Is there a way to use if I install azure-cli? (i.e inside my node js application)


问:
How do you explicitly set a new property on `window` in TypeScript?
I setup global namespaces for my objects by explicitly setting a property on window.

```<code>window.MyNamespace = window.MyNamespace || {};
</code>```

TypeScript underlines MyNamespace and complains that:

The property 'MyNamespace' does not exist on value of type 'window'
  any"

I can make the code work by declaring MyNamespace as an ambient variable and dropping the window explicitness but I don't want to do that.

```<code>declare var MyNamespace: any;

MyNamespace = MyNamespace || {};
</code>```

How can I keep window in there and make TypeScript happy?

As a side note I find it especially funny that TypeScript complains since it tells me that window is of type any which by definitely can contain anything.

答:
First you need to declare the window object in the current
scope. Because TypeScript would like to know the type of the
object. Since the window object is defined somewhere else, you can not redefine it.

But you can declare it as follows:

```<code>declare var window: any;
</code>```

This will not redefine the window object nor will it create another variable with name window. This means window is defined somewhere else and you are just referencing it in the current scope.

Then you can refer to your MyNamespace object simply by:

```<code>window.MyNamespace
</code>```

Or you can set the new property on the window object simply by:

```<code>window.MyNamespace = MyObject
</code>```

And now the TypeScript won’t complain.

Body:
I setup global namespaces for my objects by explicitly setting a property on window.

window.MyNamespace = window.MyNamespace || {};

TypeScript underlines MyNamespace and complains that:

The property 'MyNamespace' does not exist on value of type 'window'
  any"

I can make the code work by declaring MyNamespace as an ambient variable and dropping the window explicitness but I don't want to do that.

declare var MyNamespace: any;

MyNamespace = MyNamespace || {};

How can I keep window in there and make TypeScript happy?

As a side note I find it especially funny that TypeScript complains since it tells me that window is of type any which by definitely can contain anything.

Body:
First you need to declare the window object in the current
scope. Because TypeScript would like to know the type of the
object. Since the window object is defined somewhere else, you can not redefine it.

But you can declare it as follows:

declare var window: any;

This will not redefine the window object nor will it create another variable with name window. This means window is defined somewhere else and you are just referencing it in the current scope.

Then you can refer to your MyNamespace object simply by:

window.MyNamespace

Or you can set the new property on the window object simply by:

window.MyNamespace = MyObject

And now the TypeScript won’t complain.


问:
How to separate each elements of a nested list and convert the list to the list of tuples?
I have a nested list like below:

```<code>Zeros = [[1], [2], [3, 4], [5, 6]]

</code>```

How can I separate each element and make a list of tuples, like below:

```<code>Modified_zeros = [(1), (2), (3), (4), (5), (6)]

</code>```

Thanks

答:
You can try iterating each element in the nested list and finally adding the single element in brackets with ,. There are other similar answers to create tuples.

```<code>results = [(j,) for i in Zeros for j in i]
</code>```

Output:

```<code>[(1,), (2,), (3,), (4,), (5,), (6,)]
</code>```

Body:
I have a nested list like below:

Zeros = [[1], [2], [3, 4], [5, 6]]

How can I separate each element and make a list of tuples, like below:

Modified_zeros = [(1), (2), (3), (4), (5), (6)]

Thanks

Body:
You can try iterating each element in the nested list and finally adding the single element in brackets with ,. There are other similar answers to create tuples.

results = [(j,) for i in Zeros for j in i]

Output:

[(1,), (2,), (3,), (4,), (5,), (6,)]


问:
Selecting data from sql database doesn't work. how do I fix it?
I am trying to select data from a database. I do have a successful connection, but it seems like the query doesn't work even though I know for sure that the query is right. What am I doing wrong?

If I execute the code below, the result I get is: "Connected successfullyBad query". The 'Bad query' should mean that the query is wrong, but I checked it and it isn't wrong...

```<code><?php
$servername = "localhost";
$username = "root";
$password = "usbw";
// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql ="SELECT * FROM  `producten`";
$result = mysqli_query($conn, $sql) or die("Bad query");

$conn->close();

?>
</code>```

I expect to only see "connected successfully"

答:
You are missing your database name. You can do it two ways, or in the connect statement:

```<code>$conn = new mysqli($servername, $username, $password,$database);
</code>```

Or you can do it in your select statement:

```<code>$sql ="SELECT * FROM  `yourdatabase`.`producten`";
</code>```

If you don´t set your database your query is wrong

Body:
I am trying to select data from a database. I do have a successful connection, but it seems like the query doesn't work even though I know for sure that the query is right. What am I doing wrong?

If I execute the code below, the result I get is: "Connected successfullyBad query". The 'Bad query' should mean that the query is wrong, but I checked it and it isn't wrong...

<?php
$servername = "localhost";
$username = "root";
$password = "usbw";
// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql ="SELECT * FROM  `producten`";
$result = mysqli_query($conn, $sql) or die("Bad query");

$conn->close();

?>

I expect to only see "connected successfully"

Body:
You are missing your database name. You can do it two ways, or in the connect statement:

$conn = new mysqli($servername, $username, $password,$database);

Or you can do it in your select statement:

$sql ="SELECT * FROM  `yourdatabase`.`producten`";

If you don´t set your database your query is wrong