问:
UITableView image on the left hand side

Possible Duplicate:

  adding images to UItableView

I want to add image in UITableView in the left hand side how could I add it?

答:
Try This ,</p>

```<code>UIImageView *backgroundCellImage=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 768, 80)];

    backgroundCellImage.image=[UIImage imageNamed:@"ImageName.png"];

[cell.contentView addSubview:backgroundCellImage];
[backgroundCellImage release];
</code>```

Title: UITableView image on the left hand side

Body:
Try This ,

UIImageView *backgroundCellImage=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 768, 80)];

    backgroundCellImage.image=[UIImage imageNamed:@"ImageName.png"];

[cell.contentView addSubview:backgroundCellImage];
[backgroundCellImage release];


来源: stackexchange

问:
Convert data dictionary from word to excel with R
I got the data dictionary from data provider which contains hundreds vars in different word files and looks like this:

In order to add this dictionary to my current dataset, I need to convert it to certain format in Excel. For example,for first var:"intarm_actual", i would like to create columns in a spreadsheet: col of "variable" puts the left top words, col of "label" store content of "label" (for this var, it is NA, but for second var, it should be "tpe_lab"), col of "type" stors the words of " string(str2), col of "value" stores "4", col of "missing" stores "46/102", col of "tabulation" stores "46 "", 14 "RO",14 "RV",14 "TO",14 "TV"". Ideally, it should look like this:

Could anyone who happens have done this before help to provide some suggestions for this? (I appreciate for any suggestion like what package I should refer and use, any related posts article I should read, similar type of code i can learn...)Can R package "labelled" handle this type of task? Thanks a lot~~!!

update:_________________________________________________

I use package qdapTool to imported one of the docx files, it looks like this:

How can I retrieve the demanded words and assign them to right place in my spreadsheet? Thanks~~!

Update 2:--------------------------------------------

Issue has been solved in another way.

In case someone will encounter the similar situation, 1) This type of codebook file is generated by STATA; 2) Instead of reading this complex text file, the alternative solution is using package of "codebook" in R to generate the new .csv codebook which contains both these information and even more.

答:
assuming that indeed, you have zero clue, I would recommend you to get started with regular expressions in R. I often use the R package stringr to work with regular expressions, and you find the respective cheat sheet here. They will allow you to, e.g., select the word following a ":".

I have never worked with Word Documents in R, but I guess that there are packages out there that allow you to read Word documents into R. Just Google them. :) I am sure they also have good instructions on how to use them.

Another issue you might encounter is encoding. If you have issues with reading the text into read in the correct way, e.g. reading in strange character combinations, that is most likely the source of the problem.

Once you have looked at these things and started working on your own code, you will be able to ask more precise questions.

ContentLicense: CC BY-SA 4.0


问:
Writing a 'for' loop to create a new column and multiply values based on a specified formula in R
I am new to 'for' loops in R, and I'm trying to create a new column in the dataframe and pass a formula through it, with the output being a calculated value in each cell. Here is the data I am working with:

```<code>data <- data.frame(plot1=c(133,
                           134,
                           115,
                           135,
                           119,
                           41,
                           96,
                           147,
                           64,
                           18,
                           123,
                           198,
                           40,
                           142,
                           131,
                           175,
                           52,
                           7,
                           100,
                           30,
                           197,
                           200,
                           45,
                           149,
                           170,
                           87,
                           191,
                           90,
                           50,
                           168,
                           153,
                           70,
                           98,
                           76,
                           12,
                           83,
                           101,
                           26,
                           62,
                           96,
                           52,
                           97,
                           90,
                           65,
                           9,
                           146,
                           182,
                           174,
                           15,
                           78,
                           165,
                           29,
                           186,
                           132,
                           167,
                           6,
                           43,
                           135,
                           148,
                           49,
                           64,
                           102,
                           195,
                           103,
                           105,
                           75,
                           189,
                           28,
                           117,
                           112,
                           187,
                           13,
                           109,
                           123,
                           61,
                           13,
                           160,
                           172,
                           125,
                           34,
                           75,
                           89,
                           19,
                           121,
                           136,
                           3,
                           32,
                           161,
                           111,
                           158,
                           135,
                           78,
                           133,
                           7,
                           182,
                           159,
                           99,
                           155,
                           80,
                           186,
                           120,
                           74,
                           119,
                           105,
                           157,
                           187,
                           46,
                           92,
                           25,
                           48,
                           129,
                           156,
                           180,
                           106,
                           115,
                           188,
                           120,
                           133,
                           61,
                           152,
                           152,
                           31,
                           84,
                           8,
                           20,
                           40,
                           59,
                           136,
                           84,
                           111,
                           167,
                           53,
                           40,
                           121,
                           29,
                           127,
                           135,
                           177,
                           54,
                           103,
                           41,
                           15,
                           21,
                           108,
                           105,
                           139,
                           73,
                           126,
                           59,
                           165,
                           91,
                           56,
                           53,
                           126,
                           26,
                           124,
                           128,
                           86,
                           109,
                           50,
                           40,
                           8,
                           21,
                           177,
                           198,
                           128,
                           160,
                           97,
                           12,
                           128,
                           102,
                           57,
                           197,
                           167,
                           90,
                           33,
                           59,
                           79,
                           167,
                           5,
                           52,
                           58,
                           22,
                           200,
                           38,
                           163,
                           77,
                           188,
                           136,
                           26,
                           10,
                           37,
                           179,
                           98,
                           170,
                           35,
                           30,
                           144,
                           61,
                           58,
                           141,
                           165,
                           37,
                           98,
                           2,
                           103,
                           133,
                           88,
                           172,
                           114,
                           132,
                           89,
                           170,
                           62,
                           12,
                           27),
                   plot2=c(412,
                           303,
                           10,
                           45,
                           161,
                           181,
                           450,
                           647,
                           43,
                           407,
                           170,
                           470,
                           404,
                           505,
                           293,
                           173,
                           217,
                           238,
                           318,
                           443,
                           378,
                           317,
                           29,
                           64,
                           192,
                           249,
                           550,
                           328,
                           605,
                           552,
                           58,
                           226,
                           502,
                           193,
                           506,
                           589,
                           160,
                           261,
                           515,
                           563,
                           550,
                           645,
                           488,
                           547,
                           434,
                           652,
                           70,
                           573,
                           623,
                           351,
                           450,
                           384,
                           82,
                           315,
                           517,
                           626,
                           524,
                           650,
                           466,
                           8,
                           452,
                           624,
                           306,
                           431,
                           460,
                           587,
                           619,
                           139,
                           43,
                           124,
                           38,
                           394,
                           53,
                           436,
                           625,
                           173,
                           509,
                           32,
                           115,
                           156,
                           465,
                           656,
                           584,
                           636,
                           255,
                           212,
                           317,
                           154,
                           153,
                           111,
                           554,
                           653,
                           15,
                           32,
                           118,
                           532,
                           415,
                           615,
                           124,
                           416,
                           546,
                           51,
                           503,
                           448,
                           612,
                           551,
                           286,
                           347,
                           52,
                           435,
                           592,
                           138,
                           182,
                           622,
                           646,
                           5,
                           158,
                           473,
                           640,
                           500,
                           7,
                           578,
                           1,
                           644,
                           230,
                           374,
                           452,
                           307,
                           271,
                           462,
                           647,
                           648,
                           358,
                           262,
                           614,
                           79,
                           278,
                           534,
                           68,
                           359,
                           357,
                           106,
                           589,
                           575,
                           457,
                           555,
                           252,
                           418,
                           371,
                           654,
                           88,
                           609,
                           589,
                           215,
                           435,
                           82,
                           600,
                           266,
                           510,
                           307,
                           537,
                           148,
                           536,
                           290,
                           36,
                           301,
                           27,
                           129,
                           77,
                           595,
                           506,
                           431,
                           293,
                           232,
                           108,
                           246,
                           354,
                           347,
                           460,
                           384,
                           452,
                           261,
                           132,
                           499,
                           463,
                           187,
                           422,
                           319,
                           48,
                           284,
                           241,
                           151,
                           611,
                           496,
                           572,
                           501,
                           644,
                           387,
                           480,
                           221,
                           146,
                           39,
                           400,
                           361,
                           531,
                           69,
                           539,
                           295,
                           249,
                           638,
                           289,
                           83,
                           404,
                           289,
                           547,
                           324))
</code>```

The new column created is data$newCol, and I'm trying to calculate the area of a circle using the data in data$plot2 and then multiply that value by data$plot1. The result should be in the data$newCol column.

Here is what I have tried:

```<code>data$newCol <- for(i in data$newCol) {
  ((3.14(data$plot2^2)) * (data$plot1)
}
</code>```

However, I keep getting this error:

```<code>Error: attempt to apply non-function
</code>```

Can someone help me properly write this loop?

答:
I see a few issues with what you're doing:

To multiply 3.14 by something you need to supply a multiplication operator *. When you write 3.14(x) that is the construction of a function where 3.14 is the name of the function and x is it's arguments. That's what's causing the error

Error: attempt to apply non-function

If data$newCol doesn't exist yet you can't loop over it.

This doesn't need to be a loop because those mathematical operations are vectorized so they will just act element by element down the vectors supplied if they are the same length.

R has a built in constant for pi so you can get better precision than 3.14 if you're interested.

So with that in mind, try this:

data$newCol <- pi * (data$plot2^2) * data$plot1
```

Body:
I am new to 'for' loops in R, and I'm trying to create a new column in the dataframe and pass a formula through it, with the output being a calculated value in each cell. Here is the data I am working with:

data <- data.frame(plot1=c(133,
                           134,
                           115,
                           135,
                           119,
                           41,
                           96,
                           147,
                           64,
                           18,
                           123,
                           198,
                           40,
                           142,
                           131,
                           175,
                           52,
                           7,
                           100,
                           30,
                           197,
                           200,
                           45,
                           149,
                           170,
                           87,
                           191,
                           90,
                           50,
                           168,
                           153,
                           70,
                           98,
                           76,
                           12,
                           83,
                           101,
                           26,
                           62,
                           96,
                           52,
                           97,
                           90,
                           65,
                           9,
                           146,
                           182,
                           174,
                           15,
                           78,
                           165,
                           29,
                           186,
                           132,
                           167,
                           6,
                           43,
                           135,
                           148,
                           49,
                           64,
                           102,
                           195,
                           103,
                           105,
                           75,
                           189,
                           28,
                           117,
                           112,
                           187,
                           13,
                           109,
                           123,
                           61,
                           13,
                           160,
                           172,
                           125,
                           34,
                           75,
                           89,
                           19,
                           121,
                           136,
                           3,
                           32,
                           161,
                           111,
                           158,
                           135,
                           78,
                           133,
                           7,
                           182,
                           159,
                           99,
                           155,
                           80,
                           186,
                           120,
                           74,
                           119,
                           105,
                           157,
                           187,
                           46,
                           92,
                           25,
                           48,
                           129,
                           156,
                           180,
                           106,
                           115,
                           188,
                           120,
                           133,
                           61,
                           152,
                           152,
                           31,
                           84,
                           8,
                           20,
                           40,
                           59,
                           136,
                           84,
                           111,
                           167,
                           53,
                           40,
                           121,
                           29,
                           127,
                           135,
                           177,
                           54,
                           103,
                           41,
                           15,
                           21,
                           108,
                           105,
                           139,
                           73,
                           126,
                           59,
                           165,
                           91,
                           56,
                           53,
                           126,
                           26,
                           124,
                           128,
                           86,
                           109,
                           50,
                           40,
                           8,
                           21,
                           177,
                           198,
                           128,
                           160,
                           97,
                           12,
                           128,
                           102,
                           57,
                           197,
                           167,
                           90,
                           33,
                           59,
                           79,
                           167,
                           5,
                           52,
                           58,
                           22,
                           200,
                           38,
                           163,
                           77,
                           188,
                           136,
                           26,
                           10,
                           37,
                           179,
                           98,
                           170,
                           35,
                           30,
                           144,
                           61,
                           58,
                           141,
                           165,
                           37,
                           98,
                           2,
                           103,
                           133,
                           88,
                           172,
                           114,
                           132,
                           89,
                           170,
                           62,
                           12,
                           27),
                   plot2=c(412,
                           303,
                           10,
                           45,
                           161,
                           181,
                           450,
                           647,
                           43,
                           407,
                           170,
                           470,
                           404,
                           505,
                           293,
                           173,
                           217,
                           238,
                           318,
                           443,
                           378,
                           317,
                           29,
                           64,
                           192,
                           249,
                           550,
                           328,
                           605,
                           552,
                           58,
                           226,
                           502,
                           193,
                           506,
                           589,
                           160,
                           261,
                           515,
                           563,
                           550,
                           645,
                           488,
                           547,
                           434,
                           652,
                           70,
                           573,
                           623,
                           351,
                           450,
                           384,
                           82,
                           315,
                           517,
                           626,
                           524,
                           650,
                           466,
                           8,
                           452,
                           624,
                           306,
                           431,
                           460,
                           587,
                           619,
                           139,
                           43,
                           124,
                           38,
                           394,
                           53,
                           436,
                           625,
                           173,
                           509,
                           32,
                           115,
                           156,
                           465,
                           656,
                           584,
                           636,
                           255,
                           212,
                           317,
                           154,
                           153,
                           111,
                           554,
                           653,
                           15,
                           32,
                           118,
                           532,
                           415,
                           615,
                           124,
                           416,
                           546,
                           51,
                           503,
                           448,
                           612,
                           551,
                           286,
                           347,
                           52,
                           435,
                           592,
                           138,
                           182,
                           622,
                           646,
                           5,
                           158,
                           473,
                           640,
                           500,
                           7,
                           578,
                           1,
                           644,
                           230,
                           374,
                           452,
                           307,
                           271,
                           462,
                           647,
                           648,
                           358,
                           262,
                           614,
                           79,
                           278,
                           534,
                           68,
                           359,
                           357,
                           106,
                           589,
                           575,
                           457,
                           555,
                           252,
                           418,
                           371,
                           654,
                           88,
                           609,
                           589,
                           215,
                           435,
                           82,
                           600,
                           266,
                           510,
                           307,
                           537,
                           148,
                           536,
                           290,
                           36,
                           301,
                           27,
                           129,
                           77,
                           595,
                           506,
                           431,
                           293,
                           232,
                           108,
                           246,
                           354,
                           347,
                           460,
                           384,
                           452,
                           261,
                           132,
                           499,
                           463,
                           187,
                           422,
                           319,
                           48,
                           284,
                           241,
                           151,
                           611,
                           496,
                           572,
                           501,
                           644,
                           387,
                           480,
                           221,
                           146,
                           39,
                           400,
                           361,
                           531,
                           69,
                           539,
                           295,
                           249,
                           638,
                           289,
                           83,
                           404,
                           289,
                           547,
                           324))

The new column created is data$newCol, and I'm trying to calculate the area of a circle using the data in data$plot2 and then multiply that value by data$plot1. The result should be in the data$newCol column.

Here is what I have tried:

data$newCol <- for(i in data$newCol) {
  ((3.14(data$plot2^2)) * (data$plot1)
}

However, I keep getting this error:

Error: attempt to apply non-function

Can someone help me properly write this loop?


问:
Separating two interleaved arrays into continuous sequences
I'm not sure how to best explain my question in words, so I will provide a code example below. But to at least give it a try. I am solving an eigenvalue problem as a function of some external parameter, which results in two eigenvalues. Those two eigenvalues cross, as the function of the external parameter. Eigenvalue sorting then leads to the wrong classification of which eigenvalue belongs to what 'branch' of the problem. I'd like to disentangle that.

Okay, as for the example. We start from the desired result and then mess it up according to what happens in the diagonalization routine.

```<code>xs = np.arange(-np.pi, np.pi, 0.001)
fun_a = np.cos(xs) + 0.5*np.sin(xs)
fun_b = np.cos(xs) - 0.5*xs*np.sin(xs) + 0.2

plt.figure()
plt.plot(xs, fun_a)
plt.plot(xs, fun_b)
</code>```

This results in two smooth branches that cross each other:

Now, what happens is that instead the eigenvalues are sorted, which I can mimmic as follows:

```<code>fun_c = np.zeros_like(fun_a)
fun_c[fun_a>fun_b] = fun_a[fun_a>fun_b]
fun_c[fun_a<=fun_b] = fun_b[fun_a<=fun_b]

fun_d = np.zeros_like(fun_a)
fun_d[fun_a>fun_b] = fun_b[fun_a>fun_b]
fun_d[fun_a<=fun_b] = fun_a[fun_a<=fun_b]

plt.figure()
plt.plot(xs, fun_c)
plt.plot(xs, fun_d)
</code>```

The result is these two branches, which are no longer smooth, continuous branches

What my question boils down to is how we can go from the second case (fun_c, fun_d) to the first case (fun_a, fun_b). I suppose one could use the information in the derivative, to some extent. Using np.diff() reveals a sharp discontinuity at the point where things go wrong. But I don't immediately see how to nicely use that.

edit: I'm starting to think the best assignment would be such that each subsequent point is chosen to minimize the change in the slope. But I'm not yet sure how to do that..

答:
I'm sure there are many adjustments to be made to improve performance, but here's my guess, based on second derivative thresholding:

```<code># first derivative
deriv = np.diff(fun_c)
# second derivative
deriv2 = np.diff(deriv)
# adjust threshold to detect discontinuities
switch_points = deriv2 > 0.0002
# indices of points of intersection
touch_index = np.where(switch_points == True)[0]
# adjustment to prevent false positives
# (sometimes contigous samples like 127,128 are both detected)
duplicate_index = np.where(np.diff(touch_index) == 1)[0]
touch_index = np.delete(touch_index, duplicate_index)
# begin and ending points of sections to swap
begins = touch_index[::2]
ends = touch_index[1::2]

from itertools import zip_longest

# swap values in selected sections
tmp = fun_c.copy() # need a tmp array to swap
for begin, end in zip_longest(begins, ends, fillvalue=len(fun_c)):
    tmp[begin:end] = fun_d[begin:end]

# complete swapping, correcting fun_d
# on the indices we changed before
swapped = tmp != fun_c
fun_d[swapped] = fun_c[swapped]
fun_c = tmp

plt.plot(xs, fun_c)
plt.plot(xs, fun_d)
</code>```

I found it quite dependant on the sampling_rate (might fail if it is too low).

Edit:
If it wasn't for the

```<code>touch_index = np.delete(touch_index, duplicate_index)
</code>```

you could entirely skip all this:

```<code>begins = touch_index[::2]
ends = touch_index[1::2]
from itertools import zip_longest
# swap values in selected sections
tmp = fun_c.copy() # need a tmp array to swap
for begin, end in zip_longest(begins, ends, fillvalue=len(fun_c)):
    tmp[begin:end] = fun_d[begin:end]
</code>```

with just

```<code>np.logical_xor.accumulate(touch_index) | touch_index
</code>```

Body:
I'm not sure how to best explain my question in words, so I will provide a code example below. But to at least give it a try. I am solving an eigenvalue problem as a function of some external parameter, which results in two eigenvalues. Those two eigenvalues cross, as the function of the external parameter. Eigenvalue sorting then leads to the wrong classification of which eigenvalue belongs to what 'branch' of the problem. I'd like to disentangle that.

Okay, as for the example. We start from the desired result and then mess it up according to what happens in the diagonalization routine.

xs = np.arange(-np.pi, np.pi, 0.001)
fun_a = np.cos(xs) + 0.5*np.sin(xs)
fun_b = np.cos(xs) - 0.5*xs*np.sin(xs) + 0.2

plt.figure()
plt.plot(xs, fun_a)
plt.plot(xs, fun_b)

This results in two smooth branches that cross each other:

Now, what happens is that instead the eigenvalues are sorted, which I can mimmic as follows:

fun_c = np.zeros_like(fun_a)
fun_c[fun_a>fun_b] = fun_a[fun_a>fun_b]
fun_c[fun_a<=fun_b] = fun_b[fun_a<=fun_b]

fun_d = np.zeros_like(fun_a)
fun_d[fun_a>fun_b] = fun_b[fun_a>fun_b]
fun_d[fun_a<=fun_b] = fun_a[fun_a<=fun_b]

plt.figure()
plt.plot(xs, fun_c)
plt.plot(xs, fun_d)

The result is these two branches, which are no longer smooth, continuous branches

What my question boils down to is how we can go from the second case (fun_c, fun_d) to the first case (fun_a, fun_b). I suppose one could use the information in the derivative, to some extent. Using np.diff() reveals a sharp discontinuity at the point where things go wrong. But I don't immediately see how to nicely use that.

edit: I'm starting to think the best assignment would be such that each subsequent point is chosen to minimize the change in the slope. But I'm not yet sure how to do that..

Body:
I'm sure there are many adjustments to be made to improve performance, but here's my guess, based on second derivative thresholding:

# first derivative
deriv = np.diff(fun_c)
# second derivative
deriv2 = np.diff(deriv)
# adjust threshold to detect discontinuities
switch_points = deriv2 > 0.0002
# indices of points of intersection
touch_index = np.where(switch_points == True)[0]
# adjustment to prevent false positives
# (sometimes contigous samples like 127,128 are both detected)
duplicate_index = np.where(np.diff(touch_index) == 1)[0]
touch_index = np.delete(touch_index, duplicate_index)
# begin and ending points of sections to swap
begins = touch_index[::2]
ends = touch_index[1::2]

from itertools import zip_longest

# swap values in selected sections
tmp = fun_c.copy() # need a tmp array to swap
for begin, end in zip_longest(begins, ends, fillvalue=len(fun_c)):
    tmp[begin:end] = fun_d[begin:end]

# complete swapping, correcting fun_d
# on the indices we changed before
swapped = tmp != fun_c
fun_d[swapped] = fun_c[swapped]
fun_c = tmp

plt.plot(xs, fun_c)
plt.plot(xs, fun_d)

I found it quite dependant on the sampling_rate (might fail if it is too low).

Edit:
If it wasn't for the

touch_index = np.delete(touch_index, duplicate_index)

you could entirely skip all this:

begins = touch_index[::2]
ends = touch_index[1::2]
from itertools import zip_longest
# swap values in selected sections
tmp = fun_c.copy() # need a tmp array to swap
for begin, end in zip_longest(begins, ends, fillvalue=len(fun_c)):
    tmp[begin:end] = fun_d[begin:end]

with just

np.logical_xor.accumulate(touch_index) | touch_index


问:
Exploding a key not present in JSON in PySpark
I have a JSON input which consists of an array that will be exploded as follows:

new_df = df \
    .withColumn("x", explode_outer(col("x"))) \
        .select(
            col("x.p").alias("xp"),
            col("x.q").alias("xq"),
            col("x.r.l.g").alias("xrlg"),
            col("x.r.m.f").alias("xrmf"),
            col("x.r.n").alias("xrn"),
            col("x.r.o").alias("xro"),
            col("x.r.s").alias("xrs"),
    )
```

Sometimes the input file may be empty or may not have the JSON key 'x'. In such cases the pyspark code fails saying cannot resolve 'x' given input columns: [] .

Is there a way I can keep all the columns of this table and populate them all as NULL if this key is not present in the input JSON?

答:
Another option is to load the file with the schema:

sqlContext.read.format('json').schema(schema_var).load(filename)

but it does require you to provide the full possible schema in schema_var to work.

Body:
I have a JSON input which consists of an array that will be exploded as follows:

new_df = df \
    .withColumn("x", explode_outer(col("x"))) \
        .select(
            col("x.p").alias("xp"),
            col("x.q").alias("xq"),
            col("x.r.l.g").alias("xrlg"),
            col("x.r.m.f").alias("xrmf"),
            col("x.r.n").alias("xrn"),
            col("x.r.o").alias("xro"),
            col("x.r.s").alias("xrs"),
    )

Sometimes the input file may be empty or may not have the JSON key 'x'. In such cases the pyspark code fails saying cannot resolve 'x' given input columns: [] .

Is there a way I can keep all the columns of this table and populate them all as NULL if this key is not present in the input JSON?


问:
How to add new column to table using many side of one-to-many relationship
Is the following achievable using Power BI? I have two tables that have a One-to-many relationship. I am trying to add a new column to Table A (one) which will contain the most recent Event Name from Table B (many).

Desired output - new column on Table A which contains the latest most recent Value from the Many side.

答:
If you need a CalculateColumn (in table A):

```<code>LatestEvent = var _id = [ID]
var _lastDate = CALCULATE(MAX('Table B'[Date]),'Table B'[ID] = _id)
return
calculate( MAX('Table B'[Name]),'Table B'[Date] = _lastDate && _id = 'Table B'[ID])
</code>```

If you need a measure:

```<code>MeasureLatestEvent = var _id = SELECTEDVALUE('Table A'[ID])
var _lastDate = CALCULATE(MAX('Table B'[Date]),'Table B'[ID] = _id)
return
calculate( MAX('Table B'[Name]),'Table B'[Date] = _lastDate && _id = 'Table B'[ID])
</code>```

Body:
If you need a CalculateColumn (in table A):

LatestEvent = var _id = [ID]
var _lastDate = CALCULATE(MAX('Table B'[Date]),'Table B'[ID] = _id)
return
calculate( MAX('Table B'[Name]),'Table B'[Date] = _lastDate && _id = 'Table B'[ID])

If you need a measure:

MeasureLatestEvent = var _id = SELECTEDVALUE('Table A'[ID])
var _lastDate = CALCULATE(MAX('Table B'[Date]),'Table B'[ID] = _id)
return
calculate( MAX('Table B'[Name]),'Table B'[Date] = _lastDate && _id = 'Table B'[ID])


问:
HighCharts : dataLabels errorBar
I want to add on my chart (errorBar type), the min and max values of each point.

as the following link: JSFiddle

I can do it on my various graphics with the following code:

```<code>    dataLabels: {
        enabled: true,
        style: {
            font: 'bold 11px Arial',
            textShadow: '0 0 3px white, 0 0 3px white '
        }
   }
</code>```

Is it possible to do?
Thx

答:
For people still searching for this:

Highchart fixed the labels for the error bars. You can now place a custom high and low label using data labels and custom formatter

```<code> dataLabels: {
        inside: false,
        enabled: true,
        formatter: function() {
          return (this.point.y == this.point.high ? "High: " : "Low: ") + this.point.y
        }
      }
</code>```

https://jsfiddle.net/amalborn/5xLzn204/1/

ContentLicense: CC BY-SA 3.0

Title: HighCharts : dataLabels errorBar

Body:
I want to add on my chart (errorBar type), the min and max values of each point.

as the following link: JSFiddle

I can do it on my various graphics with the following code:

    dataLabels: {
        enabled: true,
        style: {
            font: 'bold 11px Arial',
            textShadow: '0 0 3px white, 0 0 3px white '
        }
   }

Is it possible to do?
Thx

Body:
For people still searching for this:

Highchart fixed the labels for the error bars. You can now place a custom high and low label using data labels and custom formatter

 dataLabels: {
        inside: false,
        enabled: true,
        formatter: function() {
          return (this.point.y == this.point.high ? "High: " : "Low: ") + this.point.y
        }
      }

https://jsfiddle.net/amalborn/5xLzn204/1/


问:
Bind ContextMenu Item inside Button to ViewModel
I'm trying to add a ContextMenu with an ItemMenu to a button

```<code><Button x:Name="RemoteMachine" Command="{Binding ElementName=RemoteMachines, Path=DataContext.RemoteMachineSelectedCommand}" CommandParameter="{Binding}">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Delete" CommandParameter="{Binding}"
                      Command="{Binding ElementName=RemoteMachines, Path=DataContext.DeleteRemoteMachineCommand}"/>
        </ContextMenu>
    </Button.ContextMenu>
</Button>
</code>```

In my model I have the following

```<code>public ICommand RemoteMachineSelectedCommand => new CommandHandler(p => MachineSelectedAction(p, true), true);
public ICommand DeleteRemoteMachineCommand => new CommandHandler(p => DeleteRemoteMachineAction(p), true);
</code>```

The Button command works correctly while the ContextMenu one doesn't.
I suppose I'm binding it someway wrong.

Any suggestion?

答:
You could bind the Tag property of the Button to the command and then bind to it from the MenuItem using the PlacementTarget property of the parent ContextMenu:

```<code><Button x:Name="RemoteMachine"
        Tag="{Binding ElementName=RemoteMachines, Path=DataContext.DeleteRemoteMachineCommand}"
        Command="{Binding ElementName=RemoteMachines, Path=DataContext.RemoteMachineSelectedCommand}"
        CommandParameter="{Binding}">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Delete"
                              CommandParameter="{Binding PlacementTarget.CommandParameter,
                                  RelativeSource={RelativeSource AncestorType=ContextMenu}}"
                              Command="{Binding PlacementTarget.Tag,
                                  RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
        </ContextMenu>
    </Button.ContextMenu>
</Button>
</code>```

Body:
I'm trying to add a ContextMenu with an ItemMenu to a button

<Button x:Name="RemoteMachine" Command="{Binding ElementName=RemoteMachines, Path=DataContext.RemoteMachineSelectedCommand}" CommandParameter="{Binding}">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Delete" CommandParameter="{Binding}"
                      Command="{Binding ElementName=RemoteMachines, Path=DataContext.DeleteRemoteMachineCommand}"/>
        </ContextMenu>
    </Button.ContextMenu>
</Button>

In my model I have the following

public ICommand RemoteMachineSelectedCommand => new CommandHandler(p => MachineSelectedAction(p, true), true);
public ICommand DeleteRemoteMachineCommand => new CommandHandler(p => DeleteRemoteMachineAction(p), true);

The Button command works correctly while the ContextMenu one doesn't.
I suppose I'm binding it someway wrong.

Any suggestion?

Body:
You could bind the Tag property of the Button to the command and then bind to it from the MenuItem using the PlacementTarget property of the parent ContextMenu:

<Button x:Name="RemoteMachine"
        Tag="{Binding ElementName=RemoteMachines, Path=DataContext.DeleteRemoteMachineCommand}"
        Command="{Binding ElementName=RemoteMachines, Path=DataContext.RemoteMachineSelectedCommand}"
        CommandParameter="{Binding}">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Delete"
                              CommandParameter="{Binding PlacementTarget.CommandParameter,
                                  RelativeSource={RelativeSource AncestorType=ContextMenu}}"
                              Command="{Binding PlacementTarget.Tag,
                                  RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
        </ContextMenu>
    </Button.ContextMenu>
</Button>


问:
get the name of a channel using discord.py
how do I get the name of a channel so that this bot will work on any server its put on with no changes to code necessary? ( in the code where I put "what do I put here" is where I want the name to be in a variable)Thanks</p>

```<code>from discord.ext.commands import Bot
import time, asyncio

TOKEN = 'Its a secret'
BOT_PREFIX = ["!"]
client = Bot(command_prefix=BOT_PREFIX)

@client.event
async def on_message(message):
    if message.author == client.user:
        return

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    await start()
    while True:
        currentTime = time.strftime("%M%S", time.gmtime(time.time()))
        if currentTime == "30:00":
            await start()
        await asyncio.sleep(1)

async def start():
    mainChannel = #What do i put here?
    print(mainChannel.name)
    await client.send_message(mainChannel, "Starting countdown", tts = True)

client.run(TOKEN)
</code>```

答:
Well, it's simple to do. However your code can be improved by several way. It will be easier to read your code.

to get the channel and send a message to it, use this

```<code>ch = client.get_channel(channel id)
await ch.send("message")
</code>```

few optimizations to your code

```<code>from discord.ext import commands
import discord
import time

TOKEN = "token"
client = commands.Client(command_prefix="!")

@client.event
async def on_ready():
    print(f"Logged in as {client.user}")
    print(f"ID: {client.id}")
</code>```

Body:
how do I get the name of a channel so that this bot will work on any server its put on with no changes to code necessary? ( in the code where I put "what do I put here" is where I want the name to be in a variable)Thanks

from discord.ext.commands import Bot
import time, asyncio

TOKEN = 'Its a secret'
BOT_PREFIX = ["!"]
client = Bot(command_prefix=BOT_PREFIX)

@client.event
async def on_message(message):
    if message.author == client.user:
        return

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')
    await start()
    while True:
        currentTime = time.strftime("%M%S", time.gmtime(time.time()))
        if currentTime == "30:00":
            await start()
        await asyncio.sleep(1)

async def start():
    mainChannel = #What do i put here?
    print(mainChannel.name)
    await client.send_message(mainChannel, "Starting countdown", tts = True)

client.run(TOKEN)

Body:
Well, it's simple to do. However your code can be improved by several way. It will be easier to read your code.

to get the channel and send a message to it, use this

ch = client.get_channel(channel id)
await ch.send("message")

few optimizations to your code

from discord.ext import commands
import discord
import time

TOKEN = "token"
client = commands.Client(command_prefix="!")

@client.event
async def on_ready():
    print(f"Logged in as {client.user}")
    print(f"ID: {client.id}")


问:
When querying multiple indices, how do I use different search parameters for each respective index in algolia? (Vue Instantsearch)
I am using Vue Instantsearch with multiple indices.

The query takes place in a ais-search-box component, looking through two indices simultaneously and displaying the results in an ais-autocomplete component.

This works well, however I can't find a way to assign each index a respective ais-configure component and therefore have to use the same filter for both indices.
As you might imagine, with both indices containing different properties, this does not work as expected.

The docs mention this:

Since these are two dedicated indices, you can apply different parameters and widgets to the search. You can do it by passing different parameters to ais-configure, or mounting different widgets in each of the ais-index components. (source: https://www.algolia.com/doc/guides/building-search-ui/ui-and-ux-patterns/multi-index-search/vue/)

It seems unclear how one would "pass different parameters to ais-configure"?
Could anyone please provide an example?

答:
There's a github repo with an example a little further down on that same page. here's a deep link to the code in question:

https://github.com/algolia/doc-code-samples/blob/master/Vue%20InstantSearch/multi-index-hits/src/App.vue

You can nest your ais-config for the second search under the ais-index component. Something like:

```<code>      <ais-instant-search
        :search-client="searchClient"
        index-name="instant_search_price_desc"
      >
        <ais-search-box v-model="query" />
        <ais-configure
          :restrictSearchableAttributes="['name']"
          :hitsPerPage="8"
        />
        <ais-hits>
          <template slot="item" slot-scope="{ item }">
            <h3><ais-highlight :hit="item" attribute="name" /></h3>
            <img :src="item.image" />
          </template>
        </ais-hits>
        <hr />
        <ais-index :search-client="searchClient" index-name="instant_search">
          <ais-configure
           :restrictSearchableAttributes="['name']"
           :hitsPerPage="2"
          />
         <ais-hits>
            ...
</code>```

Body:
There's a github repo with an example a little further down on that same page. here's a deep link to the code in question:

https://github.com/algolia/doc-code-samples/blob/master/Vue%20InstantSearch/multi-index-hits/src/App.vue

You can nest your ais-config for the second search under the ais-index component. Something like:

      <ais-instant-search
        :search-client="searchClient"
        index-name="instant_search_price_desc"
      >
        <ais-search-box v-model="query" />
        <ais-configure
          :restrictSearchableAttributes="['name']"
          :hitsPerPage="8"
        />
        <ais-hits>
          <template slot="item" slot-scope="{ item }">
            <h3><ais-highlight :hit="item" attribute="name" /></h3>
            <img :src="item.image" />
          </template>
        </ais-hits>
        <hr />
        <ais-index :search-client="searchClient" index-name="instant_search">
          <ais-configure
           :restrictSearchableAttributes="['name']"
           :hitsPerPage="2"
          />
         <ais-hits>
            ...


问:
I have a problem with elif statement and else statement and dictionary in python
The Code

```<code>men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r1 = input('Please Enter The Number: ')
    r = int(r1)
    if r in men:
        print(men[r])
    elif len(str(r)) > 10:
        print('This is invalid number')
    elif len(str(r)) < 10:
        print('This is invalid number')
    elif r not in men:
        print('Sorry, the number is not found')
    else:
        print('This is invalid number')
</code>```

what I want is that the console print 'This is invalid number' if i have entered any data type in the console except integer but error show up in the console page

OutPut

```<code>Please Enter The Number: d
Traceback (most recent call last):
  File "C:\Users\walee\PycharmProjects\pythonProject\main.py", line 19, in <module>
    mo()
  File "C:\Users\walee\PycharmProjects\pythonProject\main.py", line 7, in mo
    r = int(r1)
ValueError: invalid literal for int() with base 10: 'd'

Process finished with exit code 1
</code>```

first screenshot
second screenshot

答:
I would use str.isdigit() to do this. This function returns a boolean which is True when the string is made only out of numbers and False otherwise. Here's the code:

def mo():
    r1 = input('Please Enter The Number: ')
    if not r1.isdigit():
        print("This is invalid number")
    else:
        r = int(r1)
        if r in men:
            print(men[r])
        elif len(str(r)) > 10:
            print('This is invalid number')
        elif len(str(r)) < 10:
            print('This is invalid number')
        elif r not in men:
            print('Sorry, the number is not found')
        else:
            print('This is invalid number')
```
<p>So, first check whether the input is a number. If it isn't, print that the input is invalid and stop excuting the code, in order to prevent the program from crashing anyway. If it is a number, continue with the rest of the code.</p>
<p>However, I noticed that your code can be simplified into the following:</p>
<pre class="lang-py prettyprint-override"><code>def mo():
    r1 = input('Please Enter The Number: ')
    if not r1.isdigit() or len(r1)!=10:
        print('This is invalid number')
    else:
        r = int(r1)
        if r in men:
            print(men[r])
        else:
            print('Sorry, the number is not found')
</code>```

This code works in the following way:

First, it checks whether the input is a number and its length is equal to 10 ( or, its length is not bigger and not smaller than 10). Then it converts the input into a number and checks whether the number is in the dictionary.

Body:
The Code

men = {1111111111: 'Amal', 2222222222: 'Mohammed', 3333333333: 'Khadijah', 4444444444: 'Abdullah', 5555555555: 'Rawan',
       6666666666: 'Faisal', 7777777777: 'Layla'}

def mo():
    r1 = input('Please Enter The Number: ')
    r = int(r1)
    if r in men:
        print(men[r])
    elif len(str(r)) > 10:
        print('This is invalid number')
    elif len(str(r)) < 10:
        print('This is invalid number')
    elif r not in men:
        print('Sorry, the number is not found')
    else:
        print('This is invalid number')

what I want is that the console print 'This is invalid number' if i have entered any data type in the console except integer but error show up in the console page

OutPut

Please Enter The Number: d
Traceback (most recent call last):
  File "C:\Users\walee\PycharmProjects\pythonProject\main.py", line 19, in <module>
    mo()
  File "C:\Users\walee\PycharmProjects\pythonProject\main.py", line 7, in mo
    r = int(r1)
ValueError: invalid literal for int() with base 10: 'd'

Process finished with exit code 1

first screenshot
second screenshot

Body:
I would use str.isdigit() to do this. This function returns a boolean which is True when the string is made only out of numbers and False otherwise. Here's the code:

def mo():
    r1 = input('Please Enter The Number: ')
    if not r1.isdigit():
        print("This is invalid number")
    else:
        r = int(r1)
        if r in men:
            print(men[r])
        elif len(str(r)) > 10:
            print('This is invalid number')
        elif len(str(r)) < 10:
            print('This is invalid number')
        elif r not in men:
            print('Sorry, the number is not found')
        else:
            print('This is invalid number')

So, first check whether the input is a number. If it isn't, print that the input is invalid and stop excuting the code, in order to prevent the program from crashing anyway. If it is a number, continue with the rest of the code.

However, I noticed that your code can be simplified into the following:

def mo():
    r1 = input('Please Enter The Number: ')
    if not r1.isdigit() or len(r1)!=10:
        print('This is invalid number')
    else:
        r = int(r1)
        if r in men:
            print(men[r])
        else:
            print('Sorry, the number is not found')

This code works in the following way:

First, it checks whether the input is a number and its length is equal to 10 ( or, its length is not bigger and not smaller than 10). Then it converts the input into a number and checks whether the number is in the dictionary.


问:
Facebook Session is not persisting from page - to - page
I am having a rough time with getting the facebook javascript SDK workflow to work. The requirement was to offer a "login" link, not a facebook icon. To do this, I improvised a bit. So far it works really well but the session is not persisting from page to page. I am figuring that the session gets set after the login method but it doesn't look like that. Here is login / logout which works fine:

```<code> function login() {
         FB.login(function(response) {
             if (response.session) {
                 FB.api('/me', function(response) {
                     document.getElementById('socialauth').innerHTML = "<span>Welcome, " + response.name + " </span>"
                     + "<a href=\"javascript:void(0)\" onclick=\"logout();\" style=\"color:white; font-weight: bold;\">(logout)</a>";
                 });

             } else {
             }
         }, { perms: 'email,publish_stream' });

         return false;

     }

    function logout() {
        FB.logout(function(response) {
            document.getElementById('socialauth').innerHTML = "<a href=\"javascript:void(0)\" style=\"color:white; font-weight: bold;\" onclick=\"login();\">login</a>";
        });
    }
</code>```

And here is what I am testing with which doesn't fire:

```<code>$(document).ready(function() {
    FB.getLoginStatus(function(response) {
        if (response.status == "connected") {
            // logged in and connected user, someone you know
            alert("ok - 5 seconds has passed");
        } else {
            // no user session available, someone you dont know
            alert("not ok");
        }
      });

  });
</code>```

I am also trying "javascript:document.cooike" in my URL box and see not evidence of the FB session.

Kindly advise?

答:
You need to make sure your loading the Facebook SDK on each page as well. For a simple solution that uses jQuery check out https://github.com/xocialhost/jquery.xocialCore.js

The first two functions in the plugin deal with initializing FB and authentication.

Using the provided function you'd do something like this:

```<code>$(document).ready(function() {

   $.xcInitFacebook = function({appId:'yourappid',callback:function() {

      FB.getLoginStatus(function(response) {

      if (response.status === 'connected') { alert('logged in'); }
              else { alert('not logged in');  }

   } });

});
</code>```

Body:
I am having a rough time with getting the facebook javascript SDK workflow to work. The requirement was to offer a "login" link, not a facebook icon. To do this, I improvised a bit. So far it works really well but the session is not persisting from page to page. I am figuring that the session gets set after the login method but it doesn't look like that. Here is login / logout which works fine:

 function login() {
         FB.login(function(response) {
             if (response.session) {
                 FB.api('/me', function(response) {
                     document.getElementById('socialauth').innerHTML = "Welcome, " + response.name + " "
                     + "(logout)";
                 });

             } else {
             }
         }, { perms: 'email,publish_stream' });

         return false;

     }

    function logout() {
        FB.logout(function(response) {
            document.getElementById('socialauth').innerHTML = "login";
        });
    }

And here is what I am testing with which doesn't fire:

$(document).ready(function() {
    FB.getLoginStatus(function(response) {
        if (response.status == "connected") {
            // logged in and connected user, someone you know
            alert("ok - 5 seconds has passed");
        } else {
            // no user session available, someone you dont know
            alert("not ok");
        }
      });

  });

I am also trying "javascript:document.cooike" in my URL box and see not evidence of the FB session.

Kindly advise?

Body:
You need to make sure your loading the Facebook SDK on each page as well. For a simple solution that uses jQuery check out https://github.com/xocialhost/jquery.xocialCore.js

The first two functions in the plugin deal with initializing FB and authentication.

Using the provided function you'd do something like this:

$(document).ready(function() {

   $.xcInitFacebook = function({appId:'yourappid',callback:function() {

      FB.getLoginStatus(function(response) {

      if (response.status === 'connected') { alert('logged in'); }
              else { alert('not logged in');  }

   } });

});


问:
Problem using ODBC for PostgeSql in Goldengate Console with dblogin
Hello my name is manuel I have a problem using the ODBC for PostgreSql in Goldengate, I have connection using isql -v DSN but in the goldengate console I can not access using the dblogin, I have seen a similar question for which they say that the DriverUnicodeType=1 is placed to solve the problem and if it solves the previous problem but now I get another error
which is the following
ERROR OGG-03039 Database character set U is not supported.

It is worth mentioning that my architecture is in AWS having GG in an EC2 instance and PostgreSql in RDS in the same VPC.

here is my ODBC.ini

```<code>[test]
Description=PostgreSQL
Driver=/usr/lib/x86_64-linux-gnu/odbc/psqlodbcw.so
Trace=No
TraceFile=/tmp/psqlodbc.log
Database=postgres
Servername=xxxx.xxxxxxxxx.us-east-2.rds.amazonaws.com
UserName=postgres
Password=password
Port=5432
ReadOnly=Yes
RowVersioning=No
ShowSystemTables=No
ShowOidColumn=No
FakeOidIndex=No
ConnSettings=No
DriverUnicodeType=1
TransactionErrorBehavior=2
</code>```

I hope you can help me. Thanks

答:
I'm not sure which version of GoldenGate you are using, but with GoldenGate 19.1 and 21.1, it does not use the PostgreSQL driver, but uses a DataDirect driver that is packaged with GoldenGate.  See this doc for info to see if that helps.

https://docs.oracle.com/en/middleware/goldengate/core/21.3/gghdb/preparing-database-oracle-goldengate-postgresql.html#GUID-C4C055B9-D0D4-4B5A-B611-1E919BB2040E

Body:
Hello my name is manuel I have a problem using the ODBC for PostgreSql in Goldengate, I have connection using isql -v DSN but in the goldengate console I can not access using the dblogin, I have seen a similar question for which they say that the DriverUnicodeType=1 is placed to solve the problem and if it solves the previous problem but now I get another error
which is the following
ERROR OGG-03039 Database character set U is not supported.

It is worth mentioning that my architecture is in AWS having GG in an EC2 instance and PostgreSql in RDS in the same VPC.

here is my ODBC.ini

[test]
Description=PostgreSQL
Driver=/usr/lib/x86_64-linux-gnu/odbc/psqlodbcw.so
Trace=No
TraceFile=/tmp/psqlodbc.log
Database=postgres
Servername=xxxx.xxxxxxxxx.us-east-2.rds.amazonaws.com
UserName=postgres
Password=password
Port=5432
ReadOnly=Yes
RowVersioning=No
ShowSystemTables=No
ShowOidColumn=No
FakeOidIndex=No
ConnSettings=No
DriverUnicodeType=1
TransactionErrorBehavior=2

I hope you can help me. Thanks


问:
Object evaluating in java
I don't understand, why Java acts the way it does.

I have two classes,

Class A:

```<code>public class A {
  public String s = null;

  public A(int s) {
    this.s = "a";
  }

  public A(String s) {
    this.s = "b";
  }

  public int f(A p) {
    return 2;
  }
}
</code>```

Class B:

```<code>public class B extends A {
  public String s = "c";
  public B() {
    super(null);
  }
  public B (String s) {
    this (0);
    this . s = s ;
  }
  public B (int x) {
    super ("d");
  this . s = this . s + x ;
  }
  public int f (A p) {
    return 3;
  }
  public int f(B p) {
    return 4;
}
</code>```

If I know have my main class, in which I run the following code:

public class Test {
  Public static main(String[] args) {
    B b1 = new B("g");
    A ab = new B(6);
    System.out.println(ab.f(b1));
  }
}
```

Why am I getting 3 as an result, and not 2 or 4, like I would expect?
Normally I would assume, if I run the method f of the object ab, and give f the object b1 as a parameter, it would either return 2, not compile (since the only method f in Class A uses an Object A and not an Object B) or it would look for another method f in Class B, that uses an Object B as a parameter and would execute that, in which case the program should return 4.

答:
This is the relevant statement

```<code>ab.f(b1)
</code>```

The fact that you are passing the object reference b1 to the method is irrelevant because none of these methods are doing anything with the parameters being passed. The question here is should calling f() return 3 or 2? It will return 3 because are creating an instance of B (A ab = new B(6);) and this class B overrode the f() method.

What is the impact of A ab = new B(6);?

When you instantiate objects using the superclass to the right of the assignment symbol =, you are actually widening the type of the object created (Making an object of a subclass into an object of a superclass). If the subclass have new methods, those methods will be inaccessible to this object. Only methods declared in the superclass are accessible and, through polymorphism, overridden methods are accessible as well (as was already demonstrated by the example above). However, if we were to add a new method to class B

```<code>public void newMethod() {
    System.out.println("new method");
}
</code>```

and modified the Test class

```<code>public class Test {
    public static void main(String[] args) {
        B b1 = new B("g");
        A ab = new B(6);
        System.out.println(ab.f(b1));
        ab.newMethod(); // compile error
        b1.newMethod();
    }
}
</code>```

newMethod will be inaccessible to instance ab but not to b1. For this reason, the method f(B p) is inaccessible for ab, as you can see in the image below.

Title: Object evaluating in java

Body:
I don't understand, why Java acts the way it does.

I have two classes,

Class A:

public class A {
  public String s = null;

  public A(int s) {
    this.s = "a";
  }

  public A(String s) {
    this.s = "b";
  }

  public int f(A p) {
    return 2;
  }
}

Class B:

public class B extends A {
  public String s = "c";
  public B() {
    super(null);
  }
  public B (String s) {
    this (0);
    this . s = s ;
  }
  public B (int x) {
    super ("d");
  this . s = this . s + x ;
  }
  public int f (A p) {
    return 3;
  }
  public int f(B p) {
    return 4;
}

If I know have my main class, in which I run the following code:

public class Test {
  Public static main(String[] args) {
    B b1 = new B("g");
    A ab = new B(6);
    System.out.println(ab.f(b1));
  }
}

Why am I getting 3 as an result, and not 2 or 4, like I would expect?
Normally I would assume, if I run the method f of the object ab, and give f the object b1 as a parameter, it would either return 2, not compile (since the only method f in Class A uses an Object A and not an Object B) or it would look for another method f in Class B, that uses an Object B as a parameter and would execute that, in which case the program should return 4.

Body:
This is the relevant statement

ab.f(b1)

The fact that you are passing the object reference b1 to the method is irrelevant because none of these methods are doing anything with the parameters being passed. The question here is should calling f() return 3 or 2? It will return 3 because are creating an instance of B (A ab = new B(6);) and this class B overrode the f() method.

What is the impact of A ab = new B(6);?

When you instantiate objects using the superclass to the right of the assignment symbol =, you are actually widening the type of the object created (Making an object of a subclass into an object of a superclass). If the subclass have new methods, those methods will be inaccessible to this object. Only methods declared in the superclass are accessible and, through polymorphism, overridden methods are accessible as well (as was already demonstrated by the example above). However, if we were to add a new method to class B

public void newMethod() {
    System.out.println("new method");
}

and modified the Test class

public class Test {
    public static void main(String[] args) {
        B b1 = new B("g");
        A ab = new B(6);
        System.out.println(ab.f(b1));
        ab.newMethod(); // compile error
        b1.newMethod();
    }
}

newMethod will be inaccessible to instance ab but not to b1. For this reason, the method f(B p) is inaccessible for ab, as you can see in the image below.


问:
Q: Multi-Tenant Azure API Management Design
I have implemented a number of APIs on Azure APIM which are protected by a subscription key, and it all works fine.

I do have a constraint though, as the client application cannot be modified(*) and I can only set the URL as parameter (ie: no additional headers). I have worked around that limitation by implementing a small proxy app that customers can deploy locally and which adds the subscription key. In other words, the client app connects to a local URL, then the proxy calls the API. That also works fine.

I would like however to offer a simpler evaluation for prospects, without the need to deploy the proxy. I thought I could provide each customer their own tenant URL (eg: guid.mydomain.com) and then use that information on Azure APIM to look-up the auth key and call the backend API. That is the part I can't figure out.

I am looking for either alternative design ideas or tips on how to make it work.

Any idea?

Marco

(*) it belongs to another company.

答:
For those that may be interested, I solved the problem by adding a new set of azure functions and a custom wildcard certificate for the subdomain.

In the azure function, the domain and subdomain info can be found in the HttpRequest.Host property. In my case, the subdomain equates to the tenant id, which I can then use to retrieve the subscription key and call the APIM API.


问:
How do I send a local toast in C
I have looking all over internet, but I cannot find any good documentation about windows 10 toast that are not written in C# or C++, I am not very familliar with C# and the dot net framework and it is giving me a bit of a headache. Could someone help me? Some links to good documentation on the subject would be fine with me.</p>

答:
I've heard that mmozeiko's TwitchNotify is a great example of utilizing the toast COM/WinRT API: Implementation. It references multiple documentation links through the code in case you want to deeply examine the topic.

Before reading into it though, I'd recommend taking some COM classes (pun not intended), if you haven't already.

However, don't get discouraged by horrible Windows APIs. Good luck!

Title: How do I send a local toast in C


问:
How to change the selected text color in pydev / eclipse dark theme
I am using Pydev / Eclipse with dark theme.
how can I change the selection color? Here's an screenshot showing a part that is selected and is highlighted with a color that is too bright and makes the foreground not readable:

I followed settings of appearance color options in General > Editors > Text Editors as well as General > Editors > Text Editors > Annotations, but I couldn't find any option for changing that bright blueish color.

Here's an image showing my current setting (as you can see, the background selection color is set as a color that is totally different from this light blue color).

答: You have to restart your Eclipse first to see that 'selection background color' changed for python files.</p>


问:
WebGL fragment shader won't compile
I am attempting to compile a WebGL fragment shader. I believe the error is in the shader's string, but I am unsure what is wrong and why it doesn't compile.

vertex shader:

```<code>const vShader = `
        attribute vec4 vPosition;
        attribute vec4 vColor;

        void main(void){
            gl_Position = vPosition;
            gl_PointSize = 1.0;
        }
    `;
</code>```

fragment shader:

```<code>    const fShader = `
        attribute vec4 vColor;
        precision lowp float;

        void main(){
            gl_FragColor = vColor;
        }
    `;
</code>```

code to compile

```<code>function setShaders(gl, vsSource, fsSource) {
    const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
    const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);

    const program = gl.createProgram();
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);

    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
      alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(program));
      return null;
    }
    return program;
}

function loadShader(gl, type, source) {

    const shader = gl.createShader(type);

    gl.shaderSource(shader, source);
    gl.compileShader(shader);

    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
      alert('An error occurred compiling the shaders: ');
      gl.deleteShader(shader);
      return null;
    }

    return shader;
}
</code>```

The vertex shader compiles but the fragment does not. Am I missing something obvious?

答:
attribute is the keyword for vertex shader input variables. The keyword for interface variables between the vertex shader and the fragment shader is varying:

attribute vec4 vPosition;
varying vec4 vColor;

void main() {
    gl_Position = vPosition;
    gl_PointSize = 1.0;
}
```
<pre class="lang-c prettyprint-override"><code>varying vec4 vColor;
precision lowp float;

void main() {
    gl_FragColor = vColor;
}
</code>```

See alos OpenGL ES Shading Language 1.00 Specification - Varying

Title: WebGL fragment shader won't compile

Body:
I am attempting to compile a WebGL fragment shader. I believe the error is in the shader's string, but I am unsure what is wrong and why it doesn't compile.

vertex shader:

const vShader = `
        attribute vec4 vPosition;
        attribute vec4 vColor;

        void main(void){
            gl_Position = vPosition;
            gl_PointSize = 1.0;
        }
    `;

fragment shader:

    const fShader = `
        attribute vec4 vColor;
        precision lowp float;

        void main(){
            gl_FragColor = vColor;
        }
    `;

code to compile

function setShaders(gl, vsSource, fsSource) {
    const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
    const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);

    const program = gl.createProgram();
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);

    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
      alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(program));
      return null;
    }
    return program;
}

function loadShader(gl, type, source) {

    const shader = gl.createShader(type);

    gl.shaderSource(shader, source);
    gl.compileShader(shader);

    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
      alert('An error occurred compiling the shaders: ');
      gl.deleteShader(shader);
      return null;
    }

    return shader;
}

The vertex shader compiles but the fragment does not. Am I missing something obvious?

Body:
attribute is the keyword for vertex shader input variables. The keyword for interface variables between the vertex shader and the fragment shader is varying:

attribute vec4 vPosition;
varying vec4 vColor;

void main() {
    gl_Position = vPosition;
    gl_PointSize = 1.0;
}

varying vec4 vColor;
precision lowp float;

void main() {
    gl_FragColor = vColor;
}

See alos OpenGL ES Shading Language 1.00 Specification - Varying


问:
How to run a pytest test function on all data files in a folder
I have a set of functions that I am attempting to write pytest unit tests for. The function I am trying to write a test for looks like so:

```<code>def IndexLevel(df: pd.DataFrame, index_row: str, start_col: str, end_col: str) -> pd.DataFrame:

    # Editing df
    return df_index
</code>```

And the pytest function looks like so (df_format_index is a fixture to test df_index shape):

```<code>@pytest.mark.parametrize(
    "df, index_row, start_col, end_col, df_format_index",
    [(function("blah.txt"), "index level", "index level", "Equity 2", df_format_index)],
    indirect=["df_format_index"],
)
def test_IndexLevel(df: pd.DataFrame, index_row: str, start_col: str, end_col: str, df_format_index: pd.DataFrame):
    print("-----test-IndexLevel------")
    assert (IndexLevel(df: pd.DataFrame, index_row, start_col, end_col).shape == df_format_index.shape)

</code>```

These functions work if I hard code the filename, but I would like to thoroughly test them by running the test on all data files in a folder. I have tried to use the following function, but it did not work:

```<code>def pytest_generate_tests(metafunc):
    filelist = glob.glob("Data/*.txt")
    metafunc.parametrize("filename", filelist)
</code>```

How can I run the test on all files in the data folder without editing the original function?

答:
Here's what I ended up doing. Since pytest.mark.parametrize takes a list of tuples, I made a function that returns a list of tuples as testing parameters. Hope it helps somebody!

```<code>def IndexLevel(filename: str, index_row: str, start_col: str, end_col: str) -> pd.DataFrame:
    # Editing a df from the file
    return df_index
</code>```
```<code>def file_loop_index() -> list:
    filenames = []
    files = glob.glob("Data/*.txt")
    for file in files:
        filenames.append(tuple((file, "index level", "s&p500", "equity 2", df_format_index)))
    return filenames

# Testing df_index shape against the dummy dataframe
@pytest.mark.parametrize("filename, index_row, start_col, end_col, df_format_index", file_loop_index(), indirect=["df_format_index"])
def test_IndexLevel(
    filename: str,
    index_row: str,
    start_col: str,
    end_col: str,
    df_format_index: pd.DataFrame,
):
    print("-----test-IndexLevel------")
    assert (IndexLevel(filename, index_row, start_col, end_col).shape == df_format_index.shape)
</code>```

Body:
I have a set of functions that I am attempting to write pytest unit tests for. The function I am trying to write a test for looks like so:

def IndexLevel(df: pd.DataFrame, index_row: str, start_col: str, end_col: str) -> pd.DataFrame:

    # Editing df
    return df_index

And the pytest function looks like so (df_format_index is a fixture to test df_index shape):

@pytest.mark.parametrize(
    "df, index_row, start_col, end_col, df_format_index",
    [(function("blah.txt"), "index level", "index level", "Equity 2", df_format_index)],
    indirect=["df_format_index"],
)
def test_IndexLevel(df: pd.DataFrame, index_row: str, start_col: str, end_col: str, df_format_index: pd.DataFrame):
    print("-----test-IndexLevel------")
    assert (IndexLevel(df: pd.DataFrame, index_row, start_col, end_col).shape == df_format_index.shape)

These functions work if I hard code the filename, but I would like to thoroughly test them by running the test on all data files in a folder. I have tried to use the following function, but it did not work:

def pytest_generate_tests(metafunc):
    filelist = glob.glob("Data/*.txt")
    metafunc.parametrize("filename", filelist)

How can I run the test on all files in the data folder without editing the original function?

Body:
Here's what I ended up doing. Since pytest.mark.parametrize takes a list of tuples, I made a function that returns a list of tuples as testing parameters. Hope it helps somebody!

def IndexLevel(filename: str, index_row: str, start_col: str, end_col: str) -> pd.DataFrame:
    # Editing a df from the file
    return df_index

def file_loop_index() -> list:
    filenames = []
    files = glob.glob("Data/*.txt")
    for file in files:
        filenames.append(tuple((file, "index level", "s&p500", "equity 2", df_format_index)))
    return filenames

# Testing df_index shape against the dummy dataframe
@pytest.mark.parametrize("filename, index_row, start_col, end_col, df_format_index", file_loop_index(), indirect=["df_format_index"])
def test_IndexLevel(
    filename: str,
    index_row: str,
    start_col: str,
    end_col: str,
    df_format_index: pd.DataFrame,
):
    print("-----test-IndexLevel------")
    assert (IndexLevel(filename, index_row, start_col, end_col).shape == df_format_index.shape)


问:
Do not inserting paragraphs where should be linebreaks when copying from word
I have a clueless person as editor on a wordpress site of mine. This person creates their text using MS Word (don't ask me why) they he proceeds to copy from word into Tiny MCE Editor on Wordpress.

His big complain is that everything that was linebreaks on word becomes paragraps on wordpress.

So a text that is like that on word...

```<code>The quick brown
fox jumps over
the lazy dog
</code>```

that should be pasted as

```<code><p>The quick brown<br>
fox jumps over<br>
the lazy dog</p>
</code>```

is pasted like

```<code><p>The quick brown</p>
<p>fox jumps over</p>
<p>the lazy dog</p>
</code>```

it that something that can be done to fix that? (No, he doesn't want to paste a clean text and having to reformat the whole thing).

答:
The issue here is likely how the document is created in Word.  When you press Enter in Word you are creating a new block (e.g. Paragraph).  If you press SHIFT+Enter you are inserting a line break.

When you copy the Word doc it makes an HTML representation of the content and uses blocks (paragraphs) or line breaks (
 tags) based on how the document was created.

If you want to change this once it is pasted you could use a variety of the configuration options for the paste plugin:

https://www.tiny.cloud/docs/plugins/opensource/paste/

The most likely candidate is the paste_postprocess option which allows you to transform the data however you like via code after the paste plugin has completed its work.

Body:
I have a clueless person as editor on a wordpress site of mine. This person creates their text using MS Word (don't ask me why) they he proceeds to copy from word into Tiny MCE Editor on Wordpress.

His big complain is that everything that was linebreaks on word becomes paragraps on wordpress.

So a text that is like that on word...

The quick brown
fox jumps over
the lazy dog

that should be pasted as

The quick brown

fox jumps over

the lazy dog

is pasted like

The quick brown

fox jumps over

the lazy dog

it that something that can be done to fix that? (No, he doesn't want to paste a clean text and having to reformat the whole thing).

Body:
The issue here is likely how the document is created in Word.  When you press Enter in Word you are creating a new block (e.g. Paragraph).  If you press SHIFT+Enter you are inserting a line break.

When you copy the Word doc it makes an HTML representation of the content and uses blocks (paragraphs) or line breaks (<br> tags) based on how the document was created.

If you want to change this once it is pasted you could use a variety of the configuration options for the paste plugin:

https://www.tiny.cloud/docs/plugins/opensource/paste/

The most likely candidate is the paste_postprocess option which allows you to transform the data however you like via code after the paste plugin has completed its work.


问:
Count visitors of pages in react
I'am still learning to code. Current I' am building a news-site as mern-stack. I have a component in which I map over the newsitems, now in the next component I want to have a ranking-list with the ten most-clicked articles. The data comes from a data.js, in which I have an objectEntrie with count: 0 what I would like to increment, and afterwards I want to sort. I hope, someone can help me, because I totally stuck.
Thanks.</p>
```<code>const News = () => {

    const handleClick = (section)=>{

      }

  return <Container>
            <Hr/>
            <NewsTitleHolder>
                <NewsTitle>NEWS</NewsTitle>
                <IoIosArrowForward style={{fontSize:"26px", color: "var(--gray)"}}/>
            </NewsTitleHolder>
            <ArticleHolder>
                {
                    mainnews.map((item)=>(
                        <Link to={{pathname: `/${item.ressort}`}} className="link" key={item.id}>
                        <Section key={item.id} onClick={()=>handleClick(item.id)}>
                            <NewsImg src={item.img} alt={item.id} title={item.title}/>
                            <NewsRessort>{item.ressort}</NewsRessort>
                            <NewsTheme>{item.theme}</NewsTheme>
                            <ContentTitle>{item.title}</ContentTitle>
                            <Content>{item.content}</Content>
                        </Section>
                        </Link>
                    ))
                }
            </ArticleHolder>
  </Container>;
};

export default News;
</code>```

答: Pass item.count to handleClick function instead of item.id and inside handleClick increment it. Then pass an array that consists of news item to a ranking list component via props, but before that make ordering of the array and extract only ten most clicked news items. You can also use Redux to store all news items there and then you can access all news from any component without passing it through a sequence of props</p>

Title: Count visitors of pages in react

Body:
I'am still learning to code. Current I' am building a news-site as mern-stack. I have a component in which I map over the newsitems, now in the next component I want to have a ranking-list with the ten most-clicked articles. The data comes from a data.js, in which I have an objectEntrie with count: 0 what I would like to increment, and afterwards I want to sort. I hope, someone can help me, because I totally stuck.
Thanks.

const News = () => {

    const handleClick = (section)=>{

      }

  return <Container>

            <NewsTitleHolder>
                <NewsTitle>NEWS</NewsTitle>
                <IoIosArrowForward style={{fontSize:"26px", color: "var(--gray)"}}/>
            </NewsTitleHolder>
            <ArticleHolder>
                {
                    mainnews.map((item)=>(
                        <Link to={{pathname: `/${item.ressort}`}} className="link" key={item.id}>

handleClick(item.id)}>
                            <NewsImg src={item.img} alt={item.id} title={item.title}/>
                            <NewsRessort>{item.ressort}</NewsRessort>
                            <NewsTheme>{item.theme}</NewsTheme>
                            <ContentTitle>{item.title}</ContentTitle>
                            <Content>{item.content}</Content>

                        </Link>
                    ))
                }
            </ArticleHolder>
  </Container>;
};

export default News;


问:
Using gdata with only one user in app engine, need to decide
I am building an GAE app that allows users to share documents over different contexts. Nothing too fancy.
I want to use Gdata in such a way that it is the app that owns the documents, and  not the users. This way, I shouldn't need any kind of tokens --one would think.

This is the main idea:

App user creates doc --> App creates doc and owns it --> user can RUD & share the doc

Is there any recommended way to authenticate using just a hard coded user & password?
The ClientLogin, up to now, seems to be the way to go.
http://code.google.com/apis/gdata/docs/auth/clientlogin.html

But I still have some doubts about the following:

Am I putting myself in a scenario of possible restrictions over other alternatives?

Is really ClientLogin the best way to go?

Could really use advice from others' experience here. Procrastination is killing me.

Cheers,

A.

答:
If this is a personal project, and you've only got a very small group of users, the design might be OK.

One really good reason to use OAuth is that you won't need to store the account password somewhere.  Instead you'll be able to implement a simple 'setup' process to get and store an access token.  OAuth is also nice since you'll be able to restrict the access scope.

However, I must say, I find your question very vague -- so more specific answers are difficult.