问:
seaborn clustermap: subplots_adjust cancels colour bar relocation
I'm trying to make a heatmap with the colour bar on the side using seaborn. However, in my real application case, I have long column names that I rotate. This requires the use of plt.subplots_adjust, otherwise the labels do not fit in the image:

```<code>plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
plt.subplots_adjust(bottom=0.5)
</code>```

Using the following minimal example, I found out that this last command was cancelling the colour bar relocation:

```<code>#!/usr/bin/env python3

import seaborn as sns
import matplotlib.pyplot as plt

iris = sns.load_dataset("iris")
species = iris.pop("species")
# Make long column names
iris.columns = ["________".join(label.split("_")) for label in iris.columns]

g = sns.clustermap(iris, col_cluster=False, yticklabels=False)
# Relocate colour bar on the side
g.cax.set_position([.15, .2, .03, .45])
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
plt.savefig("/tmp/unadjusted.png")

plt.cla()

g = sns.clustermap(iris, col_cluster=False, yticklabels=False)
g.cax.set_position([.15, .2, .03, .45])
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
# Adjust to have the column labels not cut out
plt.subplots_adjust(bottom=0.5)
plt.savefig("/tmp/adjusted.png")
</code>```

This results in the following images:

Without plt.subplots_adjust:

With plt.subplots_adjust:

Why does this happen?

Is this a bug?

What can I do to have the colour bar where I want and still be sure that my rotated colour labels will not be cut?

答:
Based on a suggestion by @ImportanceOfBeingErnest, I tried to adjust before moving the colour bar. This resulted in the following image:

Since I actually don't want the dendrogram, but just the clustering, I can obtain a more pleasing result by using the dendrogram box to put the colour bar:

```<code>#!/usr/bin/env python3

import seaborn as sns
import matplotlib.pyplot as plt

iris = sns.load_dataset("iris")
species = iris.pop("species")
# Make long column names
iris.columns = ["________".join(label.split("_")) for label in iris.columns]

g = sns.clustermap(iris, col_cluster=False, yticklabels=False)
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
# Adjust to have the column labels not cut out
plt.subplots_adjust(bottom=0.5)
g.cax.set_position([.15, .2, .03, .45])
plt.savefig("/tmp/adjusted_before.png")

plt.cla()

g = sns.clustermap(iris, col_cluster=False, yticklabels=False)
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
# Adjust to have the column labels not cut out
plt.subplots_adjust(bottom=0.5)
# Remove the dendrogram (https://stackoverflow.com/a/42418968/1878788)
g.ax_row_dendrogram.set_visible(False)
# Use the dendrogram box to reposition the colour bar
dendro_box = g.ax_row_dendrogram.get_position()
dendro_box.x0 = (dendro_box.x0 + 2 * dendro_box.x1) / 3
g.cax.set_position(dendro_box)
# Move the ticks to the left (https://stackoverflow.com/a/36939552/1878788)
g.cax.yaxis.set_ticks_position("left")
# If we add a label to the colour bar
# (cbar_kws={"label" : "the_label"} in clustermap arguments)
# we also need to move the label
# g.cax.yaxis.set_label_position("left")
plt.savefig("/tmp/adjusted_before_using_row_dendrogram_box.png")
</code>```

This generates the following image:

Edit: The same issue occurs with plt.tight_layout.

Further developing my heatmap, I wanted to add row colours with legends (using an approach proposed in this answer). In my real application case, the legend takes enough horizontal space to be cut out of the image.

I wanted to use plt.tight_layout to adjust the image. This again interferes with the colour bar relocation (and doesn't even solve the cut legend issue...), as illustrated with the following examples.

```<code>#!/usr/bin/env python3

import seaborn as sns
import matplotlib.pyplot as plt

iris = sns.load_dataset("iris")
species = iris.pop("species")
# Make long column names
iris.columns = ["________".join(label.split("_")) for label in iris.columns]

# Associating colours with species
species_list = species.unique()
label_colours = dict(zip(species_list, sns.color_palette("colorblind", len(species_list))))
row_colours = species.map(label_colours)

g = sns.clustermap(iris, col_cluster=False, yticklabels=False, row_colors=row_colours, cbar_kws={"label" : "measure"})
# Adding row colour legend
# https://stackoverflow.com/a/27992943/1878788
for (label, colour) in label_colours.items():
    # Make long label
    g.ax_col_dendrogram.bar(0, 0, color=colour, label="Iris___________________{}".format(label))
g.ax_col_dendrogram.legend(loc="center", ncol=3)
# Rotating column labels
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
# Adjust to have the column labels not cut out
plt.subplots_adjust(bottom=0.5)
# Remove the dendrogram (https://stackoverflow.com/a/42418968/1878788)
g.ax_row_dendrogram.set_visible(False)
# Use the dendrogram box to reposition the colour bar
dendro_box = g.ax_row_dendrogram.get_position()
dendro_box.x0 = (dendro_box.x0 + 2 * dendro_box.x1) / 3
g.cax.set_position(dendro_box)
# Move the ticks and labels to the left (https://stackoverflow.com/a/36939552/1878788)
g.cax.yaxis.set_ticks_position("left")
g.cax.yaxis.set_label_position("left")
plt.savefig("/tmp/with_row_colour_lengend.png")

plt.cla()

g = sns.clustermap(iris, col_cluster=False, yticklabels=False, row_colors=row_colours, cbar_kws={"label" : "measure"})
# Adding row colour legend
# https://stackoverflow.com/a/27992943/1878788
for (label, colour) in label_colours.items():
    # Make long label
    g.ax_col_dendrogram.bar(0, 0, color=colour, label="Iris___________________{}".format(label))
g.ax_col_dendrogram.legend(loc="center", ncol=3)
# Rotating column labels
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
# Adjust to have the column labels not cut out
plt.subplots_adjust(bottom=0.5)
# Remove the dendrogram (https://stackoverflow.com/a/42418968/1878788)
g.ax_row_dendrogram.set_visible(False)
# Use the dendrogram box to reposition the colour bar
dendro_box = g.ax_row_dendrogram.get_position()
dendro_box.x0 = (dendro_box.x0 + 2 * dendro_box.x1) / 3
g.cax.set_position(dendro_box)
# Move the ticks and labels to the left (https://stackoverflow.com/a/36939552/1878788)
g.cax.yaxis.set_ticks_position("left")
g.cax.yaxis.set_label_position("left")
plt.tight_layout()
plt.savefig("/tmp/tight_after.png")

plt.cla()

g = sns.clustermap(iris, col_cluster=False, yticklabels=False, row_colors=row_colours, cbar_kws={"label" : "measure"})
# Adding row colour legend
# https://stackoverflow.com/a/27992943/1878788
for (label, colour) in label_colours.items():
    # Make long label
    g.ax_col_dendrogram.bar(0, 0, color=colour, label="Iris___________________{}".format(label))
g.ax_col_dendrogram.legend(loc="center", ncol=3)
plt.tight_layout()
# Rotating column labels
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
# Adjust to have the column labels not cut out
plt.subplots_adjust(bottom=0.5)
# Remove the dendrogram (https://stackoverflow.com/a/42418968/1878788)
g.ax_row_dendrogram.set_visible(False)
# Use the dendrogram box to reposition the colour bar
dendro_box = g.ax_row_dendrogram.get_position()
dendro_box.x0 = (dendro_box.x0 + 2 * dendro_box.x1) / 3
g.cax.set_position(dendro_box)
# Move the ticks and labels to the left (https://stackoverflow.com/a/36939552/1878788)
g.cax.yaxis.set_ticks_position("left")
g.cax.yaxis.set_label_position("left")
plt.savefig("/tmp/tight_before.png")
</code>```

This results in the following figures:

Without plt.tight_layout, the right-most label is cut (the species should be "virginica"):

Calling plt.tight_layout after relocating the colour bar:

Calling plt.tight_layout before relocating the colour bar:

Body:
I'm trying to make a heatmap with the colour bar on the side using seaborn. However, in my real application case, I have long column names that I rotate. This requires the use of plt.subplots_adjust, otherwise the labels do not fit in the image:

plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
plt.subplots_adjust(bottom=0.5)

Using the following minimal example, I found out that this last command was cancelling the colour bar relocation:

#!/usr/bin/env python3

import seaborn as sns
import matplotlib.pyplot as plt

iris = sns.load_dataset("iris")
species = iris.pop("species")
# Make long column names
iris.columns = ["________".join(label.split("_")) for label in iris.columns]

g = sns.clustermap(iris, col_cluster=False, yticklabels=False)
# Relocate colour bar on the side
g.cax.set_position([.15, .2, .03, .45])
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
plt.savefig("/tmp/unadjusted.png")

plt.cla()

g = sns.clustermap(iris, col_cluster=False, yticklabels=False)
g.cax.set_position([.15, .2, .03, .45])
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
# Adjust to have the column labels not cut out
plt.subplots_adjust(bottom=0.5)
plt.savefig("/tmp/adjusted.png")

This results in the following images:

Without plt.subplots_adjust:

With plt.subplots_adjust:

Why does this happen?

Is this a bug?

What can I do to have the colour bar where I want and still be sure that my rotated colour labels will not be cut?

Body:
Based on a suggestion by @ImportanceOfBeingErnest, I tried to adjust before moving the colour bar. This resulted in the following image:

Since I actually don't want the dendrogram, but just the clustering, I can obtain a more pleasing result by using the dendrogram box to put the colour bar:

#!/usr/bin/env python3

import seaborn as sns
import matplotlib.pyplot as plt

iris = sns.load_dataset("iris")
species = iris.pop("species")
# Make long column names
iris.columns = ["________".join(label.split("_")) for label in iris.columns]

g = sns.clustermap(iris, col_cluster=False, yticklabels=False)
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
# Adjust to have the column labels not cut out
plt.subplots_adjust(bottom=0.5)
g.cax.set_position([.15, .2, .03, .45])
plt.savefig("/tmp/adjusted_before.png")

plt.cla()

g = sns.clustermap(iris, col_cluster=False, yticklabels=False)
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
# Adjust to have the column labels not cut out
plt.subplots_adjust(bottom=0.5)
# Remove the dendrogram (https://stackoverflow.com/a/42418968/1878788)
g.ax_row_dendrogram.set_visible(False)
# Use the dendrogram box to reposition the colour bar
dendro_box = g.ax_row_dendrogram.get_position()
dendro_box.x0 = (dendro_box.x0 + 2 * dendro_box.x1) / 3
g.cax.set_position(dendro_box)
# Move the ticks to the left (https://stackoverflow.com/a/36939552/1878788)
g.cax.yaxis.set_ticks_position("left")
# If we add a label to the colour bar
# (cbar_kws={"label" : "the_label"} in clustermap arguments)
# we also need to move the label
# g.cax.yaxis.set_label_position("left")
plt.savefig("/tmp/adjusted_before_using_row_dendrogram_box.png")

This generates the following image:

Edit: The same issue occurs with plt.tight_layout.

Further developing my heatmap, I wanted to add row colours with legends (using an approach proposed in this answer). In my real application case, the legend takes enough horizontal space to be cut out of the image.

I wanted to use plt.tight_layout to adjust the image. This again interferes with the colour bar relocation (and doesn't even solve the cut legend issue...), as illustrated with the following examples.

#!/usr/bin/env python3

import seaborn as sns
import matplotlib.pyplot as plt

iris = sns.load_dataset("iris")
species = iris.pop("species")
# Make long column names
iris.columns = ["________".join(label.split("_")) for label in iris.columns]

# Associating colours with species
species_list = species.unique()
label_colours = dict(zip(species_list, sns.color_palette("colorblind", len(species_list))))
row_colours = species.map(label_colours)

g = sns.clustermap(iris, col_cluster=False, yticklabels=False, row_colors=row_colours, cbar_kws={"label" : "measure"})
# Adding row colour legend
# https://stackoverflow.com/a/27992943/1878788
for (label, colour) in label_colours.items():
    # Make long label
    g.ax_col_dendrogram.bar(0, 0, color=colour, label="Iris___________________{}".format(label))
g.ax_col_dendrogram.legend(loc="center", ncol=3)
# Rotating column labels
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
# Adjust to have the column labels not cut out
plt.subplots_adjust(bottom=0.5)
# Remove the dendrogram (https://stackoverflow.com/a/42418968/1878788)
g.ax_row_dendrogram.set_visible(False)
# Use the dendrogram box to reposition the colour bar
dendro_box = g.ax_row_dendrogram.get_position()
dendro_box.x0 = (dendro_box.x0 + 2 * dendro_box.x1) / 3
g.cax.set_position(dendro_box)
# Move the ticks and labels to the left (https://stackoverflow.com/a/36939552/1878788)
g.cax.yaxis.set_ticks_position("left")
g.cax.yaxis.set_label_position("left")
plt.savefig("/tmp/with_row_colour_lengend.png")

plt.cla()

g = sns.clustermap(iris, col_cluster=False, yticklabels=False, row_colors=row_colours, cbar_kws={"label" : "measure"})
# Adding row colour legend
# https://stackoverflow.com/a/27992943/1878788
for (label, colour) in label_colours.items():
    # Make long label
    g.ax_col_dendrogram.bar(0, 0, color=colour, label="Iris___________________{}".format(label))
g.ax_col_dendrogram.legend(loc="center", ncol=3)
# Rotating column labels
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
# Adjust to have the column labels not cut out
plt.subplots_adjust(bottom=0.5)
# Remove the dendrogram (https://stackoverflow.com/a/42418968/1878788)
g.ax_row_dendrogram.set_visible(False)
# Use the dendrogram box to reposition the colour bar
dendro_box = g.ax_row_dendrogram.get_position()
dendro_box.x0 = (dendro_box.x0 + 2 * dendro_box.x1) / 3
g.cax.set_position(dendro_box)
# Move the ticks and labels to the left (https://stackoverflow.com/a/36939552/1878788)
g.cax.yaxis.set_ticks_position("left")
g.cax.yaxis.set_label_position("left")
plt.tight_layout()
plt.savefig("/tmp/tight_after.png")

plt.cla()

g = sns.clustermap(iris, col_cluster=False, yticklabels=False, row_colors=row_colours, cbar_kws={"label" : "measure"})
# Adding row colour legend
# https://stackoverflow.com/a/27992943/1878788
for (label, colour) in label_colours.items():
    # Make long label
    g.ax_col_dendrogram.bar(0, 0, color=colour, label="Iris___________________{}".format(label))
g.ax_col_dendrogram.legend(loc="center", ncol=3)
plt.tight_layout()
# Rotating column labels
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=90)
# Adjust to have the column labels not cut out
plt.subplots_adjust(bottom=0.5)
# Remove the dendrogram (https://stackoverflow.com/a/42418968/1878788)
g.ax_row_dendrogram.set_visible(False)
# Use the dendrogram box to reposition the colour bar
dendro_box = g.ax_row_dendrogram.get_position()
dendro_box.x0 = (dendro_box.x0 + 2 * dendro_box.x1) / 3
g.cax.set_position(dendro_box)
# Move the ticks and labels to the left (https://stackoverflow.com/a/36939552/1878788)
g.cax.yaxis.set_ticks_position("left")
g.cax.yaxis.set_label_position("left")
plt.savefig("/tmp/tight_before.png")

This results in the following figures:

Without plt.tight_layout, the right-most label is cut (the species should be "virginica"):

Calling plt.tight_layout after relocating the colour bar:

Calling plt.tight_layout before relocating the colour bar:


来源: stackexchange

问:
Silverlight TextBlock: Convert Text to InlineCollection
Consider the following markup declaration:

```<code><TextBlock>
 <Run>abcdefghijklmnopqrstuvwxyz</Run>
 <LineBreak/>
 <Run>0123456789</Run>
</TextBlock>
</code>```

I want to bind any data to a TextBlock and convert this data to an InlineCollection. It would be very elegant to do this with Data Binding. The other way is to observe my Data Source and use the Inlines-Property from the TextBlock class in Code Behind.

I tried the following but it didn't work:

```<code><TextBlock>
 <Binding Path="MyDataSource" Converter="{StaticResource MyTextConverter}"/>
</TextBlock>
</code>```

What I want to do is achieve auto font-scaling by encapsulating my TextBlock in a ViewBox, but also generating LineBreaks after an arbitrary letter count.

Thanks in advance for any help.
Best regards.

答: It's too easy to be true ... "\r\n" at the right position does the job.

ContentLicense: CC BY-SA 2.5

Body:
Consider the following markup declaration:

<TextBlock>
 <Run>abcdefghijklmnopqrstuvwxyz</Run>
 <LineBreak/>
 <Run>0123456789</Run>
</TextBlock>

I want to bind any data to a TextBlock and convert this data to an InlineCollection. It would be very elegant to do this with Data Binding. The other way is to observe my Data Source and use the Inlines-Property from the TextBlock class in Code Behind.

I tried the following but it didn't work:

<TextBlock>
 <Binding Path="MyDataSource" Converter="{StaticResource MyTextConverter}"/>
</TextBlock>

What I want to do is achieve auto font-scaling by encapsulating my TextBlock in a ViewBox, but also generating LineBreaks after an arbitrary letter count.

Thanks in advance for any help.
Best regards.

ContentLicense: CC BY-SA 3.0


问:
How to compare a 3 sets of data in order to sort out how 2 of these data influence the third one?
I have a 3 set data like this:

There is a tool to say what is the most important variable in the removal? Is pH or dosage? I was thinking in a PCA (principal component analysis) however I'm a little lost

答:
Here are some things to try.

From the plot it seems clear that Dosage (column 2) is more closely related to Removal (column 3) than pH (column 1).

Also Dosage has a 61% correlation with Removal whereas pH has a correlation of only -14%.

Neither variable is statistically significant in the lm summary output likely because of the small amount of data.

Stepwise regression based on AIC chooses the Removal ~ Dosage model.

(continued after graph)

```<code>matplot(scale(DF), type = "o")
</code>```

```<code>cor(DF)
##                 pH    Dosage    Removal
## pH       1.0000000 0.0000000 -0.1418573  <-- -14%
## Dosage   0.0000000 1.0000000  0.6091517  <-- 61%
## Removal -0.1418573 0.6091517  1.0000000

summary(lm(Removal ~., DF))

## Call:
## lm(formula = Removal ~ ., data = DF)
##
## Residuals:
##      Min       1Q   Median       3Q      Max
## -15.5556  -7.0556  -4.8889   0.7778  25.7778
##
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)   69.056     39.047   1.769    0.127
## pH            -2.833      6.362  -0.445    0.672  <-- not significant
## Dosage        12.167      6.362   1.912    0.104  <-- not significant
##
## Residual standard error: 15.58 on 6 degrees of freedom
## Multiple R-squared:  0.3912,    Adjusted R-squared:  0.1883
## F-statistic: 1.928 on 2 and 6 DF,  p-value: 0.2257

fm <- step(lm(Removal ~., DF))
## ...snip...

fm
## Call:
## lm(formula = Removal ~ Dosage, data = DF)
##
## Coefficients:
## (Intercept)       Dosage
##       52.06        12.17
</code>```

Note: The input data in reproducible form is:

```<code>DF <- structure(list(pH = c(5, 5, 5, 6, 6, 6, 7, 7, 7), Dosage = c(0L,
1L, 2L, 0L, 1L, 2L, 0L, 1L, 2L), Removal = c(50, 60, 70, 50,
90, 95, 50, 55, 58)), .Names = c("pH", "Dosage", "Removal"), row.names = c(NA,
-9L), class = "data.frame")
</code>```

Body:
Here are some things to try.

From the plot it seems clear that Dosage (column 2) is more closely related to Removal (column 3) than pH (column 1).

Also Dosage has a 61% correlation with Removal whereas pH has a correlation of only -14%.

Neither variable is statistically significant in the lm summary output likely because of the small amount of data.

Stepwise regression based on AIC chooses the Removal ~ Dosage model.

(continued after graph)

matplot(scale(DF), type = "o")

cor(DF)
##                 pH    Dosage    Removal
## pH       1.0000000 0.0000000 -0.1418573  <-- -14%
## Dosage   0.0000000 1.0000000  0.6091517  <-- 61%
## Removal -0.1418573 0.6091517  1.0000000

summary(lm(Removal ~., DF))

## Call:
## lm(formula = Removal ~ ., data = DF)
##
## Residuals:
##      Min       1Q   Median       3Q      Max
## -15.5556  -7.0556  -4.8889   0.7778  25.7778
##
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)   69.056     39.047   1.769    0.127
## pH            -2.833      6.362  -0.445    0.672  <-- not significant
## Dosage        12.167      6.362   1.912    0.104  <-- not significant
##
## Residual standard error: 15.58 on 6 degrees of freedom
## Multiple R-squared:  0.3912,    Adjusted R-squared:  0.1883
## F-statistic: 1.928 on 2 and 6 DF,  p-value: 0.2257

fm <- step(lm(Removal ~., DF))
## ...snip...

fm
## Call:
## lm(formula = Removal ~ Dosage, data = DF)
##
## Coefficients:
## (Intercept)       Dosage
##       52.06        12.17

Note: The input data in reproducible form is:

DF <- structure(list(pH = c(5, 5, 5, 6, 6, 6, 7, 7, 7), Dosage = c(0L,
1L, 2L, 0L, 1L, 2L, 0L, 1L, 2L), Removal = c(50, 60, 70, 50,
90, 95, 50, 55, 58)), .Names = c("pH", "Dosage", "Removal"), row.names = c(NA,
-9L), class = "data.frame")


问:
Undo local commit in Git
I know this question has been asked thousands of time and I tried all solutions and none worked.

I committed to my local 2-3 files and now I want to undo the commit. How can I do that: This is also the first ever commit.

```<code>git reset HEAD^
fatal: ambiguous argument 'HEAD^': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
</code>```

UPDATE:

```<code>git reset --soft HEAD~1
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
</code>```

UPDATE 2:

```<code>git reset --hard HEAD~1
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
</code>```

答:
90% of the relevant info is already here in other answers, but I think a little clarification is in order:

The things you've tried, that you think don't work, aren't working only because of the special case that this is the only commit in the repo.  For example

```<code>git reset HEAD^
</code>```

means to take the index and current branch (assuming there is a current branch) back to the previous commit.  But there is no previous commit, so git doesn't know what you mean.

There are still several ways to undo the commit.  Several people have suggested that deleting the .git directory and rerunning git init might be the simplest.  This assumes there's nothing of value in the .git directory.  Certainly the database is empty (except for the commit you don't want); but maybe there's something you care about in the index; or maybe you have something set up with hooks; or you don't want to re-do configuration, remotes, etc.  Whatever.  There may be reasons why deleting and re-initing isn't the solution for you.

The next suggestion, then, would be to use

```<code>git commit --amend
</code>```

for your next commit.  This will tell git that instead of making a new commit with the current HEAD commit as its parent, it should replace the current HEAD commit with the new commit.  The new commit will get the same parent as the current HEAD commit had (which in this case is "none").  The current branch ref will move to the new commit, effectively removing the current HEAD commit from history.

But maybe for some reason you really want to fix this now instead of waiting for the next commit.  Honestly there's not much reason, but for the sake of argument... Well, you can do that.  It might be something like

```<code>git checkout --detach
git branch -d master
git checkout --orphan master
</code>```

What we're doing here is going into "detached HEAD" state so that we don't have master checked out.  This allows us to delete master, and then recreate it as an "orphan" branch - i.e. one with no history.  This again knocks the bad commit out of the history.

It may be worth noting that none of these techniques will immediately delete the old commit; but they do ensure that it won't be included in any push, or default log output, etc.  The commit will eventually go away, once it rolls off the reflog and the garbage collector catches up.  If you don't want to wait, there are steps you can take to immediately delete the commit.  (Since your repo is basically empty, one option there - again the simplest unless it has negative side effects - would be to delete the .git directory and re-init.)

Title: Undo local commit in Git

Body:
I know this question has been asked thousands of time and I tried all solutions and none worked.

I committed to my local 2-3 files and now I want to undo the commit. How can I do that: This is also the first ever commit.

git reset HEAD^
fatal: ambiguous argument 'HEAD^': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

UPDATE:

git reset --soft HEAD~1
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

UPDATE 2:

git reset --hard HEAD~1
fatal: ambiguous argument 'HEAD~1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

Body:
90% of the relevant info is already here in other answers, but I think a little clarification is in order:

The things you've tried, that you think don't work, aren't working only because of the special case that this is the only commit in the repo.  For example

git reset HEAD^

means to take the index and current branch (assuming there is a current branch) back to the previous commit.  But there is no previous commit, so git doesn't know what you mean.

There are still several ways to undo the commit.  Several people have suggested that deleting the .git directory and rerunning git init might be the simplest.  This assumes there's nothing of value in the .git directory.  Certainly the database is empty (except for the commit you don't want); but maybe there's something you care about in the index; or maybe you have something set up with hooks; or you don't want to re-do configuration, remotes, etc.  Whatever.  There may be reasons why deleting and re-initing isn't the solution for you.

The next suggestion, then, would be to use

git commit --amend

for your next commit.  This will tell git that instead of making a new commit with the current HEAD commit as its parent, it should replace the current HEAD commit with the new commit.  The new commit will get the same parent as the current HEAD commit had (which in this case is "none").  The current branch ref will move to the new commit, effectively removing the current HEAD commit from history.

But maybe for some reason you really want to fix this now instead of waiting for the next commit.  Honestly there's not much reason, but for the sake of argument... Well, you can do that.  It might be something like

git checkout --detach
git branch -d master
git checkout --orphan master

What we're doing here is going into "detached HEAD" state so that we don't have master checked out.  This allows us to delete master, and then recreate it as an "orphan" branch - i.e. one with no history.  This again knocks the bad commit out of the history.

It may be worth noting that none of these techniques will immediately delete the old commit; but they do ensure that it won't be included in any push, or default log output, etc.  The commit will eventually go away, once it rolls off the reflog and the garbage collector catches up.  If you don't want to wait, there are steps you can take to immediately delete the commit.  (Since your repo is basically empty, one option there - again the simplest unless it has negative side effects - would be to delete the .git directory and re-init.)


问:
SQL Query to partition aggregate data from Amazon AMS
I am using Google Big Query to store data from amazon ams. Each day a csv file is loaded into the database that contains the lifetime spend, clicks and impressions.  The data looks something like this:

```<code>date_uploaded,campaign,spend,impressions,clicks
2017-11-01,product a,100,1000,50
2017-11-01,product b,50,500,20
2017-11-02,product a,175,1600,75
2017-11-02,product b,100,1000,50
2017-11-03,product a,250,2200,110
2017-11-03,product b,150,1500,80
</code>```

I would like to transform this data to show the daily spend (difference between previous day) so the end result would look like this:

```<code>date_uploaded,campaign,spend,impressions,clicks
2017-11-02,product a,75,600,25
2017-11-02,product b,50,500,30
2017-11-03,product a,75,600,35
2017-11-03,product b,50,500,30
</code>```

Is there a way to query BQ to partition data in this way?

答:
You can do this with lag. Difference for the first row in a partition would be null and they can be excluded with a where clause filter. This assumes one row per date,campaign. If there are multiple rows, sum up the values for a given day and use lag.

```<code>select * from (
select date_uploaded,campaign,
spend-lag(spend) over(partition by campaign order by date_uploaded) as spend_diff,
impressions-lag(impressions) over(partition by campaign order by date_uploaded) as impressions_diff,
clicks-lag(clicks) over(partition by campaign order by date_uploaded) as clicks_diff
from tbl
) t
where spend_diff is not null and impressions_diff is not null and clicks_diff is not null
</code>```

Body:
I am using Google Big Query to store data from amazon ams. Each day a csv file is loaded into the database that contains the lifetime spend, clicks and impressions.  The data looks something like this:

date_uploaded,campaign,spend,impressions,clicks
2017-11-01,product a,100,1000,50
2017-11-01,product b,50,500,20
2017-11-02,product a,175,1600,75
2017-11-02,product b,100,1000,50
2017-11-03,product a,250,2200,110
2017-11-03,product b,150,1500,80

I would like to transform this data to show the daily spend (difference between previous day) so the end result would look like this:

date_uploaded,campaign,spend,impressions,clicks
2017-11-02,product a,75,600,25
2017-11-02,product b,50,500,30
2017-11-03,product a,75,600,35
2017-11-03,product b,50,500,30

Is there a way to query BQ to partition data in this way?

Body:
You can do this with lag. Difference for the first row in a partition would be null and they can be excluded with a where clause filter. This assumes one row per date,campaign. If there are multiple rows, sum up the values for a given day and use lag.

select * from (
select date_uploaded,campaign,
spend-lag(spend) over(partition by campaign order by date_uploaded) as spend_diff,
impressions-lag(impressions) over(partition by campaign order by date_uploaded) as impressions_diff,
clicks-lag(clicks) over(partition by campaign order by date_uploaded) as clicks_diff
from tbl
) t
where spend_diff is not null and impressions_diff is not null and clicks_diff is not null


问:
Add a website to IIS on localhost
I was trying to add my ASP.NET website in IIS 7.5 on my local computer. I followed these steps in IIS Manager.

Right-click sites>Add website and specify the physical path. (I chose the app pool as Default app pool)

Right-click on the WebSite just added>Manage>Browse.

On trying to browse the website, I am getting this error

The requested page cannot be accessed because the related configuration data for the page is invalid

Here's the screenshot:

答:
Have a run through this page

http://blogs.iis.net/webtopics/archive/2010/03/08/troubleshooting-http-500-19-errors-in-iis-7.aspx

ContentLicense: CC BY-SA 4.0

Title: Add a website to IIS on localhost


问:
keep previously selected value in dropdown jquery
I am trying to keep the same option value selected even after the click on dropdown, but It just keeps on saying undefined. Here is my code:

 var previous_value;
        $(".acc").on('shown.bs.select', function(){previous_value = this.value;}).change(function() {
                if($('img').is(':visible')){
                    if(window.confirm('Please save or data is lost')){
                        var t = $('.acc option:selected').val()
                       alert(t);
                    }else {
                       //code here
                     }
                    }
                     else {
                      //code here
                     }
            });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img  class = "<?php echo $i ?>" src="" alt="" height="22" width="30"> <br/>

    <label> AD Mgr </label><br/>
                    <select class = "acc"  >
                    <option  value="1" selected>1</option>
                    <option  value="2">2</option>
                    <option  value="3">3</option>
                     </select></code>```

Thank you

答:
I'm not familiar with bootstrap so I can't explain this point but, clearly, the issue in your case is that on('shown.bs.select', ...) doesn't fire, so previous_value remains undefined.

Nevertheless the solution to match your need is pretty simple: you must unconditionally set previous_value at start.

Here is a modified version of your code, where not only alert() shows new and previous values, but also the dropdown remains always unchanged, like you ask for:

var previous_value =
  $(".acc").change(function() {
    if ($('img').is(':visible')) {
      if (window.confirm('Please save or data is lost')) {
        var t = $('.acc option:selected').val();
        alert('New value: ' + t + '\nPrev value: ' + previous_value);
        $(this).find('option[value=' + previous_value + ']').prop({selected: true});
      } else {
        //code here
      }
    } else {
      //code here
    }
  })
  .val();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img  class = "<?php echo $i ?>" src="" alt="" height="22" width="30">
<br/>
<label> AD Mgr </label>
<br/>
  <select class="acc">
    <option value="1" selected>1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select></code>```

Body:
I am trying to keep the same option value selected even after the click on dropdown, but It just keeps on saying undefined. Here is my code:

 var previous_value;
        $(".acc").on('shown.bs.select', function(){previous_value = this.value;}).change(function() {
                if($('img').is(':visible')){
                    if(window.confirm('Please save or data is lost')){
                        var t = $('.acc option:selected').val()
                       alert(t);
                    }else {
                       //code here
                     }
                    }
                     else {
                      //code here
                     }
            });

<img  class = "<?php echo $i ?>" src="" alt="" height="22" width="30">

     AD Mgr

                    <select class = "acc"  >
                    <option  value="1" selected>1</option>
                    <option  value="2">2</option>
                    <option  value="3">3</option>
                     </select>

Thank you

Body:
I'm not familiar with bootstrap so I can't explain this point but, clearly, the issue in your case is that on('shown.bs.select', ...) doesn't fire, so previous_value remains undefined.

Nevertheless the solution to match your need is pretty simple: you must unconditionally set previous_value at start.

Here is a modified version of your code, where not only alert() shows new and previous values, but also the dropdown remains always unchanged, like you ask for:

var previous_value =
  $(".acc").change(function() {
    if ($('img').is(':visible')) {
      if (window.confirm('Please save or data is lost')) {
        var t = $('.acc option:selected').val();
        alert('New value: ' + t + '\nPrev value: ' + previous_value);
        $(this).find('option[value=' + previous_value + ']').prop({selected: true});
      } else {
        //code here
      }
    } else {
      //code here
    }
  })
  .val();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img  class = "<?php echo $i ?>" src="" alt="" height="22" width="30">
<br/>
<label> AD Mgr </label>
<br/>
  <select class="acc">
    <option value="1" selected>1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>


问:
Magento 2 - Version 2.2 - Override Zend_Mail_Transport_Sendmail
Hallo everyone,

since the release of Magento 2.2 the old override Zend_Mail_Transport_Sendmail does not work anymore.

before, an rewrite in etc/di.xml and model/Transport.php worked.

```<code><preference for="Magento\Framework\Mail\Transport" type="MyModul\MyPlugin\Model\Transport"/>
</code>```

and

```<code>namespace MyModul\MyPlugin\Model;

class Transport extends \Zend_Mail_Transport_Sendmail implements \Magento\Framework\Mail\TransportInterface
{

    protected $_message;

    /**
     * @param \Magento\Framework\Mail\MessageInterface $message
     * @throws \Zend_Mail_Exception
     */
    public function __construct(
        \Magento\Framework\Mail\MessageInterface $message
    )
    {
        if (!$message instanceof \Zend_Mail) {
            throw new \InvalidArgumentException('The message should be an instance of \Zend_Mail');
        }

        parent::__construct('-f ' . 'test@test.de');
        $this->_message = $message;
    }

   /**
     * Send a mail using this transport
     *
     * @return void
     * @throws \Magento\Framework\Exception\MailException
     */
    public function sendMessage()
    {
        try {
            parent::send($this->_message);
        } catch (\Exception $e) {
            throw new \Magento\Framework\Exception\MailException(new \Magento\Framework\Phrase($e->getMessage()), $e);
        }
    }

    /**
     * @inheritdoc
     */
    public function getMessage()
    {
        return $this->_message;
    }

    /**
     * Send mail using PHP native mail()
     *
     * @access public
     * @return void
     * @throws Zend_Mail_Transport_Exception if parameters is set
     *         but not a string
     * @throws Zend_Mail_Transport_Exception on mail() failure
     */
    public function _sendMail()
    {

        /**
         *  revert changes from update to 2.1.7
         *
         *  mailing was not working with Envelope >= 2.1.7
         */
        if ($this->parameters === null) {
            set_error_handler(array($this, '_handleMailErrors'));
            $result = mail(
                $this->recipients,
                $this->_mail->getSubject(),
                $this->body,
                $this->header);
            restore_error_handler();
        } else {
            if(!is_string($this->parameters)) {
                /**
                 * @see Zend_Mail_Transport_Exception
                 *
                 * Exception is thrown here because
                 * $parameters is a public property
                 */
                #require_once 'Zend/Mail/Transport/Exception.php';
                throw new Zend_Mail_Transport_Exception(
                    'Parameters were set but are not a string'
                );
            }

            set_error_handler(array($this, '_handleMailErrors'));
            $result = mail(
                $this->recipients,
                $this->_mail->getSubject(),
                $this->body,
                $this->header,
                $this->parameters);
            restore_error_handler();
        }

        if ($this->_errstr !== null || !$result) {
            /**
             * @see Zend_Mail_Transport_Exception
             */
            #require_once 'Zend/Mail/Transport/Exception.php';
            throw new Zend_Mail_Transport_Exception('Unable to send mail. ' . $this->_errstr);
        }
    }
}
</code>```

But now i am kind of lost

I tryed creating a plugin, which seem to be the ways it is supposed to be done now.

```<code><type name="\Magento\Framework\Mail\Transport">
    <plugin sortOrder="50" name="SendMailPlugin" type="MyModul\MyPlugin\Plugin\SendMailPlugin"/>
</type>
</code>```

I also read about overriding "TransportInterface", but i am not getting it to work. I only need it to call the constructor on my plugin.

best regards and thanks in advance

UPDATE:

It is working again now. The Problem was really just the TransportInterface. I thought i tryed that already or maybe it had something to do with "generation" cache ...

```<code><preference for="Magento\Framework\Mail\TransportInterface" type="MyModul\MyPlugin\Model\Transport" />
</code>```

So when override a class the preference needs to point to the interface.

I did not get the plugin version to work yet. In my first attempts i was not even sure how to call the methode in the plugin "after__construct" or "afterConstruct". Also it is calling the parent::contruct.

If i get it to work in the end i will post it.

Thanks you all for your help.

UPDATE 2:

A Plugin solution ist not possible in this case, since contruct methodes can not be set for a plugin.

https://www.mageplaza.com/magento-2-module-development/magento-2-plugin-interceptor.html

答:
Bartosz Herba

solution worked in single shot. Thank you.

Body:
Hallo everyone,

since the release of Magento 2.2 the old override Zend_Mail_Transport_Sendmail does not work anymore.

before, an rewrite in etc/di.xml and model/Transport.php worked.

<preference for="Magento\Framework\Mail\Transport" type="MyModul\MyPlugin\Model\Transport"/>

and

namespace MyModul\MyPlugin\Model;

class Transport extends \Zend_Mail_Transport_Sendmail implements \Magento\Framework\Mail\TransportInterface
{

    protected $_message;

    /**
     * @param \Magento\Framework\Mail\MessageInterface $message
     * @throws \Zend_Mail_Exception
     */
    public function __construct(
        \Magento\Framework\Mail\MessageInterface $message
    )
    {
        if (!$message instanceof \Zend_Mail) {
            throw new \InvalidArgumentException('The message should be an instance of \Zend_Mail');
        }

        parent::__construct('-f ' . 'test@test.de');
        $this->_message = $message;
    }

   /**
     * Send a mail using this transport
     *
     * @return void
     * @throws \Magento\Framework\Exception\MailException
     */
    public function sendMessage()
    {
        try {
            parent::send($this->_message);
        } catch (\Exception $e) {
            throw new \Magento\Framework\Exception\MailException(new \Magento\Framework\Phrase($e->getMessage()), $e);
        }
    }

    /**
     * @inheritdoc
     */
    public function getMessage()
    {
        return $this->_message;
    }

    /**
     * Send mail using PHP native mail()
     *
     * @access public
     * @return void
     * @throws Zend_Mail_Transport_Exception if parameters is set
     *         but not a string
     * @throws Zend_Mail_Transport_Exception on mail() failure
     */
    public function _sendMail()
    {

        /**
         *  revert changes from update to 2.1.7
         *
         *  mailing was not working with Envelope >= 2.1.7
         */
        if ($this->parameters === null) {
            set_error_handler(array($this, '_handleMailErrors'));
            $result = mail(
                $this->recipients,
                $this->_mail->getSubject(),
                $this->body,
                $this->header);
            restore_error_handler();
        } else {
            if(!is_string($this->parameters)) {
                /**
                 * @see Zend_Mail_Transport_Exception
                 *
                 * Exception is thrown here because
                 * $parameters is a public property
                 */
                #require_once 'Zend/Mail/Transport/Exception.php';
                throw new Zend_Mail_Transport_Exception(
                    'Parameters were set but are not a string'
                );
            }

            set_error_handler(array($this, '_handleMailErrors'));
            $result = mail(
                $this->recipients,
                $this->_mail->getSubject(),
                $this->body,
                $this->header,
                $this->parameters);
            restore_error_handler();
        }

        if ($this->_errstr !== null || !$result) {
            /**
             * @see Zend_Mail_Transport_Exception
             */
            #require_once 'Zend/Mail/Transport/Exception.php';
            throw new Zend_Mail_Transport_Exception('Unable to send mail. ' . $this->_errstr);
        }
    }
}

But now i am kind of lost

I tryed creating a plugin, which seem to be the ways it is supposed to be done now.

<type name="\Magento\Framework\Mail\Transport">
    <plugin sortOrder="50" name="SendMailPlugin" type="MyModul\MyPlugin\Plugin\SendMailPlugin"/>
</type>

I also read about overriding "TransportInterface", but i am not getting it to work. I only need it to call the constructor on my plugin.

best regards and thanks in advance

UPDATE:

It is working again now. The Problem was really just the TransportInterface. I thought i tryed that already or maybe it had something to do with "generation" cache ...

<preference for="Magento\Framework\Mail\TransportInterface" type="MyModul\MyPlugin\Model\Transport" />

So when override a class the preference needs to point to the interface.

I did not get the plugin version to work yet. In my first attempts i was not even sure how to call the methode in the plugin "after__construct" or "afterConstruct". Also it is calling the parent::contruct.

If i get it to work in the end i will post it.

Thanks you all for your help.

UPDATE 2:

A Plugin solution ist not possible in this case, since contruct methodes can not be set for a plugin.

https://www.mageplaza.com/magento-2-module-development/magento-2-plugin-interceptor.html


问:
How to add params to form_for, but don't want to add them to model?
I have two models named quiz and question

quiz has_many questions

I want to add params to the quiz new form_for, so I can use them in quizs_controller. Such as from and to, the user can input the integer to get the questions in the from xx to xx range.

But I don't want to add the from and to params in the quiz model.

I want to know how to implement this.

Thanks.

Edit

quizzes/new.html.erb

```<code><%= form_for [:admin, @quiz] do |f| %>

  <div class="form-group">
    <%= f.label :title, "Title:" %>
    <%= f.text_field :title, :class => "form-control" %>
  </div>

  <div class="form-group">
    <%= f.label "Range:" %>

    <!-- I want to know how to add `from` and `to` params here -->

  </div>

  <%= f.submit "Submit", data: { disable_with: "Submitting..." }, class: "btn btn-primary" %>
  <%= link_to "Cancel", admin_quizzes_path %>

<% end %>
</code>```

quizzes_controller.rb

```<code>def new
  @quiz = Quiz.new
end

def create
  @quiz = Quiz.new(quiz_params)
  @questions = @quiz.questions
  # And I want to gain the `from` and `to` here to **FILTER** THE questions

  if @quiz.save
    redirect_to admin_quizzes_path
  else
    render :new
  end
end
</code>```

答:
Inside your form add:

```<code><div class="form-group">
  <%= label_for :from %>
  <%= number_field_tag :from, :class => "form-control" %>
</div>
</code>```

Same for to.

In your controller you can reference them as:

```<code>def create
  @quiz = Quiz.new(quiz_params)
  @from = params[:from]
end
</code>```

Whether this worked for you?

Body:
I have two models named quiz and question

quiz has_many questions

I want to add params to the quiz new form_for, so I can use them in quizs_controller. Such as from and to, the user can input the integer to get the questions in the from xx to xx range.

But I don't want to add the from and to params in the quiz model.

I want to know how to implement this.

Thanks.

Edit

quizzes/new.html.erb

<%= form_for [:admin, @quiz] do |f| %>

    <%= f.label :title, "Title:" %>
    <%= f.text_field :title, :class => "form-control" %>

    <%= f.label "Range:" %>

  <%= f.submit "Submit", data: { disable_with: "Submitting..." }, class: "btn btn-primary" %>
  <%= link_to "Cancel", admin_quizzes_path %>

<% end %>

quizzes_controller.rb

def new
  @quiz = Quiz.new
end

def create
  @quiz = Quiz.new(quiz_params)
  @questions = @quiz.questions
  # And I want to gain the `from` and `to` here to **FILTER** THE questions

  if @quiz.save
    redirect_to admin_quizzes_path
  else
    render :new
  end
end

Body:
Inside your form add:

<div class="form-group">
  <%= label_for :from %>
  <%= number_field_tag :from, :class => "form-control" %>
</div>

Same for to.

In your controller you can reference them as:

def create
  @quiz = Quiz.new(quiz_params)
  @from = params[:from]
end

Whether this worked for you?


问:
jQuery: how to get the id of a div (with a class named "hidden")
can you help me please ?

I'm searching for a solution to get an id from a hidden div and interact the id in an AJAX query when a click is happened

PHP code :

```<code>while ( $contents_print = mysqli_fetch_array( $req_print ) ) {
echo '
        <div class="post print" id="staggered-test">
            <img src="../00_sources/images/upload/pic_min/' . $contents_print[ 'pic_min' ] . '" alt="' . $contents_print[ 'pic_min' ] . '"/>
                <div class="post-content">
                    <a href="#modal" class="modal-action modal-trigger">Détail</a>
                    <div class="row"><blockquote>' . $contents_print[ 'detail_projet' ] . '</blockquote></div>
                </div>
            <div class="post-content valign-wrapper"><h4 class="header center">' . $contents_print[ 'nom_projet' ] . '</h4></div>
        </div>
    ';

echo '<div class="hidden" id="'.$contents_print[ 'id_projet' ].'"></div>';
}
</code>```

jQuery

```<code>$( document ).ready( function () {
  $(".post").siblings('div:hidden').attr("id").click(function() {
    var url_id = $(this).attr('id');
    //alert(url_id);
  });

  $.ajax({
    url: 'core/libs/contents-services.php?action=getFilterContent&id='+url_id,
    type: "get",
    dataType: "html",
    success: function ( reponse ) {
      $( '#modal' ).html( reponse );
      url_id = reponse.url_id;
    }
  });

  // the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
  $( '.modal' ).modal();
});
</code>```

May be I'm missing something, my code doesn't work

Please help me. Thanks a lot !

答:
Use a data- attribute to store the project id on your link

```<code>'<a class="modal-action" data-id_projet="'.$contents_print[ 'id_projet' ].'"...>'
</code>```

Then use that to reference the modal container

```<code>$('.post .modal-action').click(function(e){
    e.preventDefault();
    var id_projet= $(this).data('id_projet');
    var $hidennDiv = $('#' +id_projet);
    // do your ajax and whatever you want to do with the hidden div
})
</code>```

beyond this it is really not clear what objective is

Body:
can you help me please ?

I'm searching for a solution to get an id from a hidden div and interact the id in an AJAX query when a click is happened

PHP code :

while ( $contents_print = mysqli_fetch_array( $req_print ) ) {
echo '

                    Détail

' . $contents_print[ 'detail_projet' ] . '

' . $contents_print[ 'nom_projet' ] . '

    ';

echo '

';
}

jQuery

$( document ).ready( function () {
  $(".post").siblings('div:hidden').attr("id").click(function() {
    var url_id = $(this).attr('id');
    //alert(url_id);
  });

  $.ajax({
    url: 'core/libs/contents-services.php?action=getFilterContent&id='+url_id,
    type: "get",
    dataType: "html",
    success: function ( reponse ) {
      $( '#modal' ).html( reponse );
      url_id = reponse.url_id;
    }
  });

  // the "href" attribute of the modal trigger must specify the modal ID that wants to be triggered
  $( '.modal' ).modal();
});

May be I'm missing something, my code doesn't work

Please help me. Thanks a lot !

Body:
Use a data- attribute to store the project id on your link

'<a class="modal-action" data-id_projet="'.$contents_print[ 'id_projet' ].'"...>'

Then use that to reference the modal container

$('.post .modal-action').click(function(e){
    e.preventDefault();
    var id_projet= $(this).data('id_projet');
    var $hidennDiv = $('#' +id_projet);
    // do your ajax and whatever you want to do with the hidden div
})

beyond this it is really not clear what objective is


问:
How to get all the ID's of Duplicate Name and pass it to table
The below is the Data which i have. ProductId and Name is string datatype

```<code> ProductId  Name
 "101"      John
 "201"      Marry
 "301"      Marry
 "401"      John
 "501"      John
</code>```

I need to identify the duplicate Name and retrieve their ProductId's  and ultimately append these Id's like below structure.These result will be in DataTable(c#).

```<code> ProductId             Name
"101,401,501"          John`
"201,301"              Marry
</code>```

Please give me solution how to achieve.

答:
Here's a way with STUFF

```<code>create table #MyTable(ProductId int, [Name] varchar(16))
insert into #MyTable
values
(101,'John'),
(201,'Marry'),
(301,'Marry'),
(401,'John'),
(501,'John')

select distinct
    t.[Name]
    ,ProductId = STUFF((
                      SELECT ',' + cast(t2.ProductId as char(3))
                      FROM #MyTable t2
                      WHERE t.[Name] = t2.[Name]
                      FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from
    #MyTable t

drop table #MyTable
</code>```

ONLINE DEMO

Body:
The below is the Data which i have. ProductId and Name is string datatype

 ProductId  Name
 "101"      John
 "201"      Marry
 "301"      Marry
 "401"      John
 "501"      John

I need to identify the duplicate Name and retrieve their ProductId's  and ultimately append these Id's like below structure.These result will be in DataTable(c#).

 ProductId             Name
"101,401,501"          John`
"201,301"              Marry

Please give me solution how to achieve.

Body:
Here's a way with STUFF

create table #MyTable(ProductId int, [Name] varchar(16))
insert into #MyTable
values
(101,'John'),
(201,'Marry'),
(301,'Marry'),
(401,'John'),
(501,'John')

select distinct
    t.[Name]
    ,ProductId = STUFF((
                      SELECT ',' + cast(t2.ProductId as char(3))
                      FROM #MyTable t2
                      WHERE t.[Name] = t2.[Name]
                      FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
from
    #MyTable t

drop table #MyTable

ONLINE DEMO


问:
Span class getText() using Selenium WebDriver with Java
Its a table inside one of the row contains the below td available, I want to get the span class value in separate string (its dynamic n number of span may available),
means 1111 FRANKLIN STREET OAKLAND, CALIFORNIA 94607-5200:

HTML

```<code><td colspan="5">
    <p class="caption">Assignee</p>
    <a class="ng-binding ng-scope" alt="View assignment(s)" ui-sref="search.resultAssignee(goToAssignee(assignee))" ng-repeat-start="assignee in abstract.patAssigneeName track by $index" href="#assigneeName=THE%20REGENTS%20OF%20THE%20UNIVERSITY%20OF%20CALIFORNIA">UNIVERSITY OF CALIFORNIA</a>
    <p class="ng-scope">
        <span class="ng-binding ng-scope" ng-if="abstract.patAssigneeAddress1[$index] !== ''">1111 FRANKLIN STREET<br></span>
        <span class="ng-binding ng-scope" ng-if="abstract.patAssigneeCity[$index] !== '' && abstract.patAssigneeState[$index] !== ''">OAKLAND, CALIFORNIA 94607-5200<br></span>
        <span class="ng-binding"> </span>
    </p>
    <br class="ng-scope" ng-repeat-end="">
</td>
</code>```

I getting the assignee name easily with below XPath (iterate with table):

```<code>String recAssignee = driver.findElement(By.xpath(" //*[@id='printable-area']/table[" + r + "]/tbody/tr[4]/td/a")).getText().replace("Assignee", "");
</code>```

Please help to get the span class value.

答:
As you mentioned you are able to get the assignee name easily with below xpath:

```<code>String recAssignee = driver.findElement(By.xpath(" //*[@id='printable-area']/table[" + r + "]/tbody/tr[4]/td/a")).getText().replace("Assignee", "");
</code>```

Now, to get the span class value in separate string, e.g. 1111 FRANKLIN STREET OAKLAND , CALIFORNIA 94607-5200, you can use the following code block :

```<code>List<WebElement> myElements = driver.findElements(By.xpath("//*[@id='printable-area']/table[" + r + "]/tbody/tr[4]/td/a[@class='ng-binding ng-scope']/span[@class='ng-binding ng-scope']"));
List<String> partA = new ArrayList<String>();
List<String> partB = new ArrayList<String>();
for(int i=0; i<myElements.size(); i=i+2)
{
    String textA = myElements.get(i).getAttribute("innerHTML");
    partA.add(textA);
}

for(int j=1; j<myElements.size(); j=j+2)
{
    String textB = myElements.get(j).getAttribute("innerHTML");
    partB.add(textB);
}
System.out.println("The Complete Addresses are : ");
for(int k=0; k<partA.size();k++)
    System.out.println(partA.get(k) + " , " + partB.get(k));
</code>```

Body:
Its a table inside one of the row contains the below td available, I want to get the span class value in separate string (its dynamic n number of span may available),
means 1111 FRANKLIN STREET OAKLAND, CALIFORNIA 94607-5200:

HTML

Assignee

    UNIVERSITY OF CALIFORNIA

        1111 FRANKLIN STREET

        OAKLAND, CALIFORNIA 94607-5200

I getting the assignee name easily with below XPath (iterate with table):

String recAssignee = driver.findElement(By.xpath(" //*[@id='printable-area']/table[" + r + "]/tbody/tr[4]/td/a")).getText().replace("Assignee", "");

Please help to get the span class value.

Body:
As you mentioned you are able to get the assignee name easily with below xpath:

String recAssignee = driver.findElement(By.xpath(" //*[@id='printable-area']/table[" + r + "]/tbody/tr[4]/td/a")).getText().replace("Assignee", "");

Now, to get the span class value in separate string, e.g. 1111 FRANKLIN STREET OAKLAND , CALIFORNIA 94607-5200, you can use the following code block :

List<WebElement> myElements = driver.findElements(By.xpath("//*[@id='printable-area']/table[" + r + "]/tbody/tr[4]/td/a[@class='ng-binding ng-scope']/span[@class='ng-binding ng-scope']"));
List<String> partA = new ArrayList<String>();
List<String> partB = new ArrayList<String>();
for(int i=0; i<myElements.size(); i=i+2)
{
    String textA = myElements.get(i).getAttribute("innerHTML");
    partA.add(textA);
}

for(int j=1; j<myElements.size(); j=j+2)
{
    String textB = myElements.get(j).getAttribute("innerHTML");
    partB.add(textB);
}
System.out.println("The Complete Addresses are : ");
for(int k=0; k<partA.size();k++)
    System.out.println(partA.get(k) + " , " + partB.get(k));


问:
Python - If row more than, do something
I'm new to Python and i'm trying to create a block of code that prints a statement if a value is more than a value I've defined. The below code however isn't working, it's not printing anything despite the values of row[4] being greater than '10'. Even when I try == '55.9280': it still doesn't satisfy the criteria, and itsn't printing anything. Thanks in advance!

The list is an output of a MySQL statement string convetred into a list. With row[4] being QueryTime.

```<code>Forename: Surname: Email: Querytime:
</code>```

e.g.

```<code>for row in list:
    print row[4]
    if row[4] > '10':
        print("is greater than")
</code>```

row 4 =

```<code>55.9280
45.5300
40.2040
38.7850
32.8320
32.5820
31.6290
30.0630
29.4950
28.9780
</code>```

答:
It seems that row is a list of integers. Your mistake is that you are comparing an integer with a string.
Correct code:

```<code>for row in list:
    print row[4]
    if row[4] > 10:
        print("is greater than")
</code>```

Title: Python - If row more than, do something

Body:
I'm new to Python and i'm trying to create a block of code that prints a statement if a value is more than a value I've defined. The below code however isn't working, it's not printing anything despite the values of row[4] being greater than '10'. Even when I try == '55.9280': it still doesn't satisfy the criteria, and itsn't printing anything. Thanks in advance!

The list is an output of a MySQL statement string convetred into a list. With row[4] being QueryTime.

Forename: Surname: Email: Querytime:

e.g.

for row in list:
    print row[4]
    if row[4] > '10':
        print("is greater than")

row 4 =

55.9280
45.5300
40.2040
38.7850
32.8320
32.5820
31.6290
30.0630
29.4950
28.9780

Body:
It seems that row is a list of integers. Your mistake is that you are comparing an integer with a string.
Correct code:

for row in list:
    print row[4]
    if row[4] > 10:
        print("is greater than")


问:
Generate password in python
I'dl like to generate some alphanumeric passwords in python. Some possible ways are:

```<code>import string
from random import sample, choice
chars = string.letters + string.digits
length = 8
''.join(sample(chars,length)) # way 1
''.join([choice(chars) for i in range(length)]) # way 2
</code>```

But I don't like both because:

way 1 only unique chars selected and you can't generate passwords where length > len(chars)

way 2 we have i variable unused and I can't find good way how to avoid that

So, any other good options?

P.S. So here we are with some testing with timeit for 100000 iterations:

```<code>''.join(sample(chars,length)) # way 1; 2.5 seconds
''.join([choice(chars) for i in range(length)]) # way 2; 1.8 seconds (optimizer helps?)
''.join(choice(chars) for _ in range(length)) # way 3; 1.8 seconds
''.join(choice(chars) for _ in xrange(length)) # way 4; 1.73 seconds
''.join(map(lambda x: random.choice(chars), range(length))) # way 5; 2.27 seconds
</code>```

So, the winner is ''.join(choice(chars) for _ in xrange(length)).

答:
I suggest the following for those stuck on python <3.6:

```<code>import os, math, string, struct

def generate_password(pass_len):
    symbols = string.printable.strip()
    return ''.join([symbols[x * len(symbols) / 256] for x in struct.unpack('%dB' % (pass_len,), os.urandom(pass_len))])
</code>```

This has the advantage over Ben Mosher's solution that the each symbol from symbols has an equal change of occurring whereas using modulus slightly favors the first symbols in the alpabet. The alphabet of symbols is also larger in this suggestion.

Title: Generate password in python

Body:
I'dl like to generate some alphanumeric passwords in python. Some possible ways are:

import string
from random import sample, choice
chars = string.letters + string.digits
length = 8
''.join(sample(chars,length)) # way 1
''.join([choice(chars) for i in range(length)]) # way 2

But I don't like both because:

way 1 only unique chars selected and you can't generate passwords where length > len(chars)

way 2 we have i variable unused and I can't find good way how to avoid that

So, any other good options?

P.S. So here we are with some testing with timeit for 100000 iterations:

''.join(sample(chars,length)) # way 1; 2.5 seconds
''.join([choice(chars) for i in range(length)]) # way 2; 1.8 seconds (optimizer helps?)
''.join(choice(chars) for _ in range(length)) # way 3; 1.8 seconds
''.join(choice(chars) for _ in xrange(length)) # way 4; 1.73 seconds
''.join(map(lambda x: random.choice(chars), range(length))) # way 5; 2.27 seconds

So, the winner is ''.join(choice(chars) for _ in xrange(length)).

Body:
I suggest the following for those stuck on python <3.6:

import os, math, string, struct

def generate_password(pass_len):
    symbols = string.printable.strip()
    return ''.join([symbols[x * len(symbols) / 256] for x in struct.unpack('%dB' % (pass_len,), os.urandom(pass_len))])

This has the advantage over Ben Mosher's solution that the each symbol from symbols has an equal change of occurring whereas using modulus slightly favors the first symbols in the alpabet. The alphabet of symbols is also larger in this suggestion.


问:
Vue model is not working and doesn't perform the function
This is my form file and it includes the VUE input-field, I want to only show that field only when I checked that option Manually set new password. That is the last field where the issue is present.

      var app = new Vue({
        el: '#app',
        data: {
          password_options: 'keep'
        }
        computed: {
          canShowThis() {
            return ['auto', 'manual'].includes(this.password_options)
          }
        }
      });```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <script src="https://npmcdn.com/vue/dist/vue.js"></script>

    <div class="field">
        <label for="password" class="label">Password</label>
        <p class="control">
            <b-radio-group v-model="password_options">
                <div class="field">
                    <b-radio name="password_options" value="keep" selected>
                        Do Not Change Password
                    </b-radio>
                </div>
                <div class="field">
                    <b-radio name="password_options" value="auto">
                        Auto Generate New Password
                    </b-radio>
                </div>
                <div class="field">
                    <b-radio name="password_options" value="manual">
                        Manually Set New Password
                    </b-radio>
                    <p class="control">
                        <input type="text" class="input m-b-10 m-t-10" name="password" id="password"
                               v-if="canShowThis" placeholder="Manually give a password to this user">
                    </p>
                </div>
            </b-radio-group>
        </p>
    </div>

    <button class="button is-primary">
        <i class="fa fa-refresh m-r-10"></i>Update User
    </button>

 </code>```

答:
I hope I understood your problem correctly. Here is a way how to show/hide input field with radio button.

Initiate function "toggleField" on radio button check:

    Manually Set New Password

```

<p>Initiate toggle variable:</p>

<pre class="lang-js prettyprint-override"><code>data: function() {
  return {
    toggle: false
  }
</code>```

Create a method that would toggle it's value:

methods: {
  toggleField() {
    this.toggle = !this.toggle;
  },
```

<p>Wrap the input field in div tag and add v-if statement:</p>

<pre class="lang-html prettyprint-override"><code><div v-if="toggle === true">
    <p class="control">
        <input type="text" class="input" name="password"
               id="password" v-if="password_options == 'manual'"
               placeholder="Manually give a password to this user">
    </p>
</div>
</code>```

Body:
This is my form file and it includes the VUE input-field, I want to only show that field only when I checked that option Manually set new password. That is the last field where the issue is present.

      var app = new Vue({
        el: '#app',
        data: {
          password_options: 'keep'
        }
        computed: {
          canShowThis() {
            return ['auto', 'manual'].includes(this.password_options)
          }
        }
      });

        Password

                        Do Not Change Password

                        Auto Generate New Password

                        Manually Set New Password

                        <input type="text" class="input m-b-10 m-t-10" name="password" id="password"
                               v-if="canShowThis" placeholder="Manually give a password to this user">

    <button class="button is-primary">
        Update User
    </button>

Body:
I hope I understood your problem correctly. Here is a way how to show/hide input field with radio button.

Initiate function "toggleField" on radio button check:

<b-radio name="password_options" value="manual" @change-value="toggleField">
    Manually Set New Password
</b-radio>

Initiate toggle variable:

data: function() {
  return {
    toggle: false
  }

Create a method that would toggle it's value:

methods: {
  toggleField() {
    this.toggle = !this.toggle;
  },

Wrap the input field in div tag and add v-if statement:

<div v-if="toggle === true">
    <p class="control">
        <input type="text" class="input" name="password"
               id="password" v-if="password_options == 'manual'"
               placeholder="Manually give a password to this user">
    </p>
</div>


问:
change default hibernate mapping strategy for enums
When using Hibernate, the dafault mapping strategy for enums is ORDINAL. Because I think the STRING strategy is more robust, I want to change the default mapping strategy to favor that.

Currently I have to use the following on any enum:

```<code>@Enumerated(EnumType.STRING)
@Column(nullable=false)
private MyEnum myEnum;
</code>```

Is there a way to tell hibernate to always use the STRING strategy? My research did not come up with some property that allows to change this behaviour.

Or is it impossible because JPA specifies ORDINAL as default and we should explicitly annotate it to stay O/R-Mapper neutral?

答:
I agree with you that EnumType.STRING is more robust especially when refactoring source code as chaging order of constants in enum is often done by inadvertance (or simply because someone sorts them alphabeticaly).

But you also right that there is no way to change the default behaviour, as ORDINAL mapping has been defined as default by design (may be because a Numeric Column is more efficient than a varchar typed column).

Body:
When using Hibernate, the dafault mapping strategy for enums is ORDINAL. Because I think the STRING strategy is more robust, I want to change the default mapping strategy to favor that.

Currently I have to use the following on any enum:

@Enumerated(EnumType.STRING)
@Column(nullable=false)
private MyEnum myEnum;

Is there a way to tell hibernate to always use the STRING strategy? My research did not come up with some property that allows to change this behaviour.

Or is it impossible because JPA specifies ORDINAL as default and we should explicitly annotate it to stay O/R-Mapper neutral?


问:
Can os and Home screen update the android app widget at will?
I want to make and app with widget to present some data,and i want to be sure it will not become a battery drain source and add all the checks i have to,so there is no problem.

So android documentation actually says that ACTION_APPWIDGET_UPDATE may be sent in response to a new instance for this AppWidget provider having been instantiated, the requested update interval having lapsed, or the system booting.

But i came into this bizarre answer here

Android widget update called twice after device boot

that suggest that the home screen can actually update your widget n times at will.Seems bizarre,and i cant find something similar,do i really have no control over this?

答:
As in the previous answer you found, there is no way to limit how many times the home screen might update the widget - it is responsibility of the homescreen and you cannot control this.

You could add a limit in your update implementation instead. For example, record the time the checks are made. If the widget update is requested again too soon after the last one, ignore it until the required amount of time passes.


问:
How do I put two
s side-by-side, with the left
 taking up 100% of the space not taken up by the right
?
I've got a basic issue. Two
s side-by-side, the left
 needs to be able to have a 'flexible' width, as in when the
 on the right isn't displayed, the left
 will then stretch to 100%.

My code currently is as follows, which doesn't fulfil the above requirement.

```<code><html>
        <head>
        <style>
        #container {
                display: block;
        }

        #box-left {
                width: 100%;
                height: 100px;
                background-color: red;
                float: left;
        }

        #box-right {
                width: 15%;
                height: 100px;
                background-color: blue;
                float: right;
        }
        </style>
        </head>
        <div id="container">
                <div id="box-left"></div>
                <div id="box-right"></div>
        </div>
        <body>

        </body>
</code>```

Any pointers would be much appreciated.

答:
If you reverse the order in which #box-left and #box-right appear in the HTML, and remove the width property from #box-left in the CSS, it should work how you describe:

```<code>#box-left {
        height: 100px;
        background-color: red;
        float: left;
}

...

<div id="container">
        <div id="box-right"></div>
        <div id="box-left"></div>
</div>
</code>```

You might not want that source order though, in which case
s (or the CSS equivalent) are the only HTML/CSS layout system that allows for what you want to do.

Title: How do I put two <div>s side-by-side, with the left <div> taking up 100% of the space not taken up by the right <div>?

Body:
I've got a basic issue. Two
s side-by-side, the left
 needs to be able to have a 'flexible' width, as in when the
 on the right isn't displayed, the left
 will then stretch to 100%.

My code currently is as follows, which doesn't fulfil the above requirement.

Any pointers would be much appreciated.

Body:
If you reverse the order in which #box-left and #box-right appear in the HTML, and remove the width property from #box-left in the CSS, it should work how you describe:

#box-left {
        height: 100px;
        background-color: red;
        float: left;
}

...

<div id="container">
        <div id="box-right"></div>
        <div id="box-left"></div>
</div>

You might not want that source order though, in which case <table>s (or the CSS equivalent) are the only HTML/CSS layout system that allows for what you want to do.


问:
Gigya - Error 500000 - Could not connect to host
Below is my code:

```<code>$method  = "accounts.getJWTPublicKey";

$request = new GSRequest($apiKey, $secret, $method, '', true, $userkey);

$request->setAPIDomain("eu1.gigya.com");

$response = $request->send();
</code>```

When it reached the send function, the error 500000 is displayed with the message

Could not connect to host.

Can't really find any solution to this on the internet. Some proposed solution that I have found on gigya was maybe I should:

Use another Certificate - which can't be the problem because it works on my local and another server on which I was testing.

A network misconfiguration! Can't find which misconfiguration might have caused this if any.

Had someone been through this and solved this issue?

I am using the PHP SDK given by gigya to communicate with gigya from drupal.

答:
accounts.getJWTPublicKey is one of Gigya's only publicly accessible APIs. It does not require the same authorization parameters as a secure API. You should be able to access it directly with only the site's API key, like:

```<code>https://accounts.eu1.gigya.com/accounts.getJWTPublicKey?apiKey=<API_KEY>
</code>```

I have just confirmed this works on the US Data center, but I don't currently have an EU apikey to check. Let me know if there are still issues accessing the EU data center this way.

Developer's Guide

UPDATED November 19th

I just had a chance to look at your code and SDK together. If the example you included is the entire request, it is missing the apiKey parameter for the target site. The full request should look like this:

```<code>$request = new GSRequest($apiKey, $secret, $method, null, true, $userkey);

$request->setAPIDomain("eu1.gigya.com");

$request->setParam("apiKey", "THE_API_KEY_OF_THE_TARGET_SITE"); //This is missing from your example

$response = $request->send();
</code>```

Body:
Below is my code:

$method  = "accounts.getJWTPublicKey";

$request = new GSRequest($apiKey, $secret, $method, '', true, $userkey);

$request->setAPIDomain("eu1.gigya.com");

$response = $request->send();

When it reached the send function, the error 500000 is displayed with the message

Could not connect to host.

Can't really find any solution to this on the internet. Some proposed solution that I have found on gigya was maybe I should:

Use another Certificate - which can't be the problem because it works on my local and another server on which I was testing.

A network misconfiguration! Can't find which misconfiguration might have caused this if any.

Had someone been through this and solved this issue?

I am using the PHP SDK given by gigya to communicate with gigya from drupal.

Body:
accounts.getJWTPublicKey is one of Gigya's only publicly accessible APIs. It does not require the same authorization parameters as a secure API. You should be able to access it directly with only the site's API key, like:

https://accounts.eu1.gigya.com/accounts.getJWTPublicKey?apiKey=<API_KEY>

I have just confirmed this works on the US Data center, but I don't currently have an EU apikey to check. Let me know if there are still issues accessing the EU data center this way.

Developer's Guide

UPDATED November 19th

I just had a chance to look at your code and SDK together. If the example you included is the entire request, it is missing the apiKey parameter for the target site. The full request should look like this:

$request = new GSRequest($apiKey, $secret, $method, null, true, $userkey);

$request->setAPIDomain("eu1.gigya.com");

$request->setParam("apiKey", "THE_API_KEY_OF_THE_TARGET_SITE"); //This is missing from your example

$response = $request->send();


问:
Sending Outlook 2013 E-Mail With Powershell, Task Scheduler (E-Mail Appears in Drafts; Doesn't Send)
I'm trying to send an email from my Outlook Account to my Outlook Account via Powershell and using Task Scheduler to run that script.

My Tash Scheduler is configured as such:

```<code>PowerShell -NoProfile -ExecutionPolicy Bypass -File "<script location\script name.ps1>" -Parameter 'Value'
</code>```

And my PowerShell script looks like:

```<code>$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem("olMailItem")
$Mail.To = "<My Email>"
$Mail.Subject = "Subject"
$Mail.Body = "Body"
$Mail.Send()
</code>```

The e-mail gets sent successfully if I run the PS1 script myself by double clicking on it.

If I have the scheduler do it, using my account, I can see the e-mail pop into the Drafts folder of my Outlook, the Drafts folder flickers some, and the e-mail disappears.

The only thing I found when searching that it might be related to is Object Model Guard.  But I don't know how to fix that.

Any ideas on how to fix my situation?

EDIT:

I think it has to do with the setting "Run only when user is logged on" versus "Run whether user is logged on or not".

It works if I choose "Run only when user is logged on" but when I choose "Run whether user is logged on or not", it does the situation I mention above, even if I give it my password ahead of time.

答:
FIXED!

Can't believe after all of that searching and trying, I got it to work.

Having the Task Scheduler call a .BAT file that contains your PowerShell command fixed the issue, in my case:

```<code>PowerShell -NoProfile -ExecutionPolicy Bypass -File "<script location\script name.ps1>" -Parameter 'Value'
</code>```

No idea why this works.

Body:
I'm trying to send an email from my Outlook Account to my Outlook Account via Powershell and using Task Scheduler to run that script.

My Tash Scheduler is configured as such:

PowerShell -NoProfile -ExecutionPolicy Bypass -File "

Body:
FIXED!

Can't believe after all of that searching and trying, I got it to work.

Having the Task Scheduler call a .BAT file that contains your PowerShell command fixed the issue, in my case:

PowerShell -NoProfile -ExecutionPolicy Bypass -File "<script location\script name.ps1>" -Parameter 'Value'

No idea why this works.


问:
Using Directive for Focusing Input Field
I'm using a directive for focusing an input field. This works great, when entering first time the page. But this method is not called when I navigate back, or pop to a specific page. I guess it's because ngAfterViewInit() is not called anymore. I tried to use ionViewDidEnter() / onPageDidEnter() but in this case, the focus get not called at all.

Using in some page:

```<code> <ion-input type="text" [(ngModel)]="matrikel" focus>
</code>```

focuser.ts

```<code>@Directive({
    selector: '[focus]' // Attribute selector
})

export class FocusDirective {

    @Input() focus: any;

    constructor(private el: ElementRef, private renderer: Renderer, private globalVariables: GlobalsVariable) { }

   ngAfterViewInit(){

            const searchInput = this.el.nativeElement.querySelector('input');
            setTimeout(() => {
                this.renderer.invokeElementMethod(searchInput, 'focus', []);
            }, 650);
}

}
</code>```

答:
You have to use ionViewCanEnter(). Which will call before the ionViewDidLoad().

html

```<code><ion-input #focusInput type="text" [(ngModel)]="matrikel">
</code>```

focuser.ts

```<code>import { ViewChild } from '@angular/core';

    export class FocusDirective {
    @ViewChild('focusInput') focus: any;

    constructor(private el: ElementRef, private renderer: Renderer, private globalVariables: GlobalsVariable) { }

    ionViewCanEnter() {
        setTimeout(() => {
          this.focus.setFocus();
        }, 500);
   }
   }
</code>```

Body:
I'm using a directive for focusing an input field. This works great, when entering first time the page. But this method is not called when I navigate back, or pop to a specific page. I guess it's because ngAfterViewInit() is not called anymore. I tried to use ionViewDidEnter() / onPageDidEnter() but in this case, the focus get not called at all.

Using in some page:

 <ion-input type="text" [(ngModel)]="matrikel" focus>

focuser.ts

@Directive({
    selector: '[focus]' // Attribute selector
})

export class FocusDirective {

    @Input() focus: any;

    constructor(private el: ElementRef, private renderer: Renderer, private globalVariables: GlobalsVariable) { }

   ngAfterViewInit(){

            const searchInput = this.el.nativeElement.querySelector('input');
            setTimeout(() => {
                this.renderer.invokeElementMethod(searchInput, 'focus', []);
            }, 650);
}

}

Body:
You have to use ionViewCanEnter(). Which will call before the ionViewDidLoad().

html

<ion-input #focusInput type="text" [(ngModel)]="matrikel">

focuser.ts

import { ViewChild } from '@angular/core';

    export class FocusDirective {
    @ViewChild('focusInput') focus: any;

    constructor(private el: ElementRef, private renderer: Renderer, private globalVariables: GlobalsVariable) { }

    ionViewCanEnter() {
        setTimeout(() => {
          this.focus.setFocus();
        }, 500);
   }
   }


问:
Reserved Keyword in Where clause
Consider the following setup

```<code>create table #test([user] varchar(10))
insert into #test([user]) values ('test')
</code>```

when user column is enclosed with square brackets then the query returns result else it does not return result even though there is a matching record

```<code>SELECT *
FROM   #test WHERE [user] = 'test' -- returns record

SELECT *
FROM   #test WHERE user = 'test' --did not return record
</code>```

This begs the following two questions

Why is the first query works and the second query does not ?

Why the reserved keyword is allowed to use in where clause without escaping it ?

答:
User is a reserved keyword for a reason. Try this:

```<code>SELECT User;
</code>```

For me, it returns a single row with value dbo.

So the query without escaping user is perfectly valid, it just doesn't fit the value you are comparing it to.

Title: Reserved Keyword in Where clause

Body:
Consider the following setup

create table #test([user] varchar(10))
insert into #test([user]) values ('test')

when user column is enclosed with square brackets then the query returns result else it does not return result even though there is a matching record

SELECT *
FROM   #test WHERE [user] = 'test' -- returns record

SELECT *
FROM   #test WHERE user = 'test' --did not return record

This begs the following two questions

Why is the first query works and the second query does not ?

Why the reserved keyword is allowed to use in where clause without escaping it ?

Body:
User is a reserved keyword for a reason. Try this:

SELECT User;

For me, it returns a single row with value dbo.

So the query without escaping user is perfectly valid, it just doesn't fit the value you are comparing it to.


问:
C structure assignment of same address valid?
If I have something like this in my code:

```<code>void f(struct foo *x, struct foo *y)
{
  *x = *y; // structure copy (memcpy?)
}
</code>```

If x and y point to the same address, what happens?

Is this valid code, and what if the compiler converts the assignment into a memcpy call with potentially-invalid operands (they aren't allowed to overlap)?

[Yes, I know I can use "restrict" in this case, but the actual code we found which made us consider this is automatically-generated by bison so we were wondering if it should always be valid and whether the compiler should use memmove or something else which allows overlap..]

答: This is valid code. The compiler can not assume x != y, so it must use safe memmove.</p>

Body:
If I have something like this in my code:

void f(struct foo *x, struct foo *y)
{
  *x = *y; // structure copy (memcpy?)
}

If x and y point to the same address, what happens?

Is this valid code, and what if the compiler converts the assignment into a memcpy call with potentially-invalid operands (they aren't allowed to overlap)?

[Yes, I know I can use "restrict" in this case, but the actual code we found which made us consider this is automatically-generated by bison so we were wondering if it should always be valid and whether the compiler should use memmove or something else which allows overlap..]


问:
Module could not be found (VSTS Build with Windows 10 SDK for Creators update )
We are creating appxbundle on VSTS for UWP apps. The builds are successful, however at runtime we are getting exception while accessing the following method:

```<code>public static Task<DeviceManagementClient> CreateAsync(IDeviceTwin deviceTwin, IDeviceManagementRequestHandler hostAppHandler);
</code>```

Exception:

```<code>    The specified module could not be found.
    (Exception from HRESULT: 0x8007007E) at System.StubHelpers.StubHelpers.GetWinRTFactoryObject(IntPtr pCPCMD)
at SystemConfiguratorProxyClient.SCProxyClient..ctor() at Microsoft.Devices.Management.SystemConfiguratorProxy..ctor()
at Microsoft.Devices.Management.DeviceManagementClient.<CreateAsync>d__7.MoveNext() ---
</code>```

Build Machine:
Windows Server 2012 R2 with Windows 10 SDK Fall creators update

Runtime:
Dragonboard with Windows 10 RS3 build

We followed the UWP build template for creating the app packages.

What are we missing?

答: The problem was we had a custom Nuget package which was built in Debug version, hence it was not working in release build configuration. Thanks!</p>

Body:
We are creating appxbundle on VSTS for UWP apps. The builds are successful, however at runtime we are getting exception while accessing the following method:

public static Task<DeviceManagementClient> CreateAsync(IDeviceTwin deviceTwin, IDeviceManagementRequestHandler hostAppHandler);

Exception:

    The specified module could not be found.
    (Exception from HRESULT: 0x8007007E) at System.StubHelpers.StubHelpers.GetWinRTFactoryObject(IntPtr pCPCMD)
at SystemConfiguratorProxyClient.SCProxyClient..ctor() at Microsoft.Devices.Management.SystemConfiguratorProxy..ctor()
at Microsoft.Devices.Management.DeviceManagementClient.<CreateAsync>d__7.MoveNext() ---

Build Machine:
Windows Server 2012 R2 with Windows 10 SDK Fall creators update

Runtime:
Dragonboard with Windows 10 RS3 build

We followed the UWP build template for creating the app packages.

What are we missing?


问:
Xamarin : Adding condition inside isvisible in xaml
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have an  inside listview-viewcell, having 250 width and height.
Sometimes the value of mediaUrl is null. I want to hide the Image for null mediaUrl values and make visible for other values.
My problem is if the value of the mediaUrl is null showing blank space in the UI. Inside isVisible property how can I apply this condition?
My code is giving below:        </p>

```<code>    <StackLayout>
        <ListView>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout>
                        <Image
                            WidthRequest="250"
                            HeightRequest="250"
                            Source="{Binding mediaUrl}"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>
</code>```

<p>Anybody please suggest a solution with working code.
Thanks in advance       </p>

答:
the solution of Steve Chadbourne is good.

you should declare the converter this :

```<code><ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="SAMPLE.Sample">

<!--RESOURCES-->
<ContentPage.Resources>
    <ResourceDictionary>
        <local:NullToBoolConverter x:Key="NullToBoolConverter"/>
    </ResourceDictionary>
</ContentPage.Resources>

<!-- CONTENT -->
<ContentPage.Content>
    <ListView >
        Use Converter
    </ListView>
</ContentPage.Content>
</code>```

Body:
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have an  inside listview-viewcell, having 250 width and height.
Sometimes the value of mediaUrl is null. I want to hide the Image for null mediaUrl values and make visible for other values.
My problem is if the value of the mediaUrl is null showing blank space in the UI. Inside isVisible property how can I apply this condition?
My code is giving below:

    <StackLayout>
        <ListView>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout>
                        <Image
                            WidthRequest="250"
                            HeightRequest="250"
                            Source="{Binding mediaUrl}"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>

Anybody please suggest a solution with working code.
Thanks in advance

Body:
the solution of Steve Chadbourne is good.

you should declare the converter this :

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="SAMPLE.Sample">

<!--RESOURCES-->
<ContentPage.Resources>
    <ResourceDictionary>
        <local:NullToBoolConverter x:Key="NullToBoolConverter"/>
    </ResourceDictionary>
</ContentPage.Resources>

<!-- CONTENT -->
<ContentPage.Content>
    <ListView >
        Use Converter
    </ListView>
</ContentPage.Content>