问:
I have an array containing different div IDs how do i target specific IDs from within the aray javascript/jquery
So I have an array in my script.js file. The array contains around 12 different things. I use the array to store divs IDs'. Because I want to load those divs dynamically. I've done that I loaded the divs dynamically but now I want to use that array for loading things inside the first div(a title a picture and so on).

```<code>let donorFeatureNames = [
    'SpawnVehicle',
    'RepairVehicle',
    'RocketVoltic',
    'MoreVehicle',
    'ChatColors',
    'Deagle',
    'M4',
    'Sniper',
    'CopFeature',
    'CrimFeature',
    'Changeskin',
    'Cash'
]

function loadFeatures () {
    for (i = 0; i < 12; i++) {
        $('#featureMenu').append('<div id=' + '"' + donorFeatureNames[i] + '"' + 'class="item notLoaded"></div>')

        $("'#" + donorFeatureNames[i] + "'").append(span class="title">' + $(this).data('donorfeature') + '</span>)
    }
</code>```

I hope you understand what I'm asking. Cause I'm not that good at explaining things.

答:
Huangism answered my question.
$("'#" + donorFeatureNames[i] + "'") isn't correct, but this is: $("#" + donorFeatureNames[i])

That's basically what I asked.
Thanks a lot man!

Body:
So I have an array in my script.js file. The array contains around 12 different things. I use the array to store divs IDs'. Because I want to load those divs dynamically. I've done that I loaded the divs dynamically but now I want to use that array for loading things inside the first div(a title a picture and so on).

let donorFeatureNames = [
    'SpawnVehicle',
    'RepairVehicle',
    'RocketVoltic',
    'MoreVehicle',
    'ChatColors',
    'Deagle',
    'M4',
    'Sniper',
    'CopFeature',
    'CrimFeature',
    'Changeskin',
    'Cash'
]

function loadFeatures () {
    for (i = 0; i < 12; i++) {
        $('#featureMenu').append('

')

        $("'#" + donorFeatureNames[i] + "'").append(span class="title">' + $(this).data('donorfeature') + ')
    }

I hope you understand what I'm asking. Cause I'm not that good at explaining things.


来源: stackexchange

问:
Redirecting PDF links from another domain using htaccess
We have two domains, let's call them first.com and second.com

We have a directory in second.com called reports, where all our PDFs are located, but we would like to these same PDFs accessible from first.com as well.

Can we redirect let's say first.com/reports/84839049.pdf to second.com/reports/84839049.pdf using htaccess?

答:
Yes.

redirect /requested/url http://second.com/result/url

http://httpd.apache.org/docs/1.3/mod/mod_alias.html#redirect

You may want to consider using mod_rewrite though, unless you asked for an .htaccess configuration specifically because you have no access to the server configuration and mod_rewrite is disabled or not loaded.

http://httpd.apache.org/docs/current/mod/mod_rewrite.html
http://webdesign.about.com/od/mod_rewrite/qt/site_redirects.htm

You'll need some grasp of regex for mod_rewrite, but it can make configuration of the redirects a lot faster than having to add a redirect for every file on your site(s).

ContentLicense: CC BY-SA 2.5


问:
Splitting A Set Of Numbers Among Arrays
I am creating a game where I need to divide numbers 1-21 among the 7 players to divide the 21 cards among them, so each player gets 3 cards. I need it to be random, so I tried to make a function where for every number, it will add it to a random one of the 7 arrays, and if the array it was trying to add to already had three numbers (or in this case cards) then it would give that number to another card. Thank you in advance, David.</p>

答:
This will give you a List<int> that contains 21 randomly shuffled numbers.

```<code>var numbers =  Enumerable.Range(1, 21);
var random = new Random();
var result = numbers.OrderBy(i => random.Next()).ToList();
</code>```

Now, you can assign the first player the first three numbers, the second the next three, and so on.

ContentLicense: CC BY-SA 3.0

Title: Splitting A Set Of Numbers Among Arrays

Body:
This will give you a List<int> that contains 21 randomly shuffled numbers.

var numbers =  Enumerable.Range(1, 21);
var random = new Random();
var result = numbers.OrderBy(i => random.Next()).ToList();

Now, you can assign the first player the first three numbers, the second the next three, and so on.


问:
Crystal Reports Code 128 Barcode Printing Shape Instead of Number
I have a formula field with a font of Code 128, to print string input from a user.

It prints fine every time except when two (2) zeros are next to each other. But the thing is its fine when it prints 100, but say I do 1000, it prints some rectangle shape in the barcode. Again 1001 it prints fine, 10001 it prints with a rectangle.

Here is the formula field:

@QuantityBarCode

```<code>' http://support.wisys.com/documentation/Crystal_Report_IDAutomation_Basic_Syntax_Barcode_Settings.htm

Dim DataToEncode As String
DataToEncode = Trim({@Quantity}) ' Quantity
Dim PrintableString As String
Dim DataToFormat As String
Dim WeightedTotal As Number
Dim CurrentValue As Number
Dim CheckDigitValue As Number
Dim C128CheckDigit As String
Dim StringLength As Number
Dim I As Number
Dim CurrentCharNum As Number
Dim CurrentEncoding As String
Dim C128Start As String
Dim CorrectFNC As Number
Dim CurrentChar As String
CorrectFNC = 0
PrintableString = ""
DataToFormat = DataToEncode
DataToEncode = ""

'Here we select character set A, B or C for the START character
StringLength = Len(DataToFormat)
CurrentCharNum = Asc(Mid(DataToFormat, 1, 1))
If CurrentCharNum < 32 Then C128Start = Chr(203)
If CurrentCharNum > 31 And CurrentCharNum < 127 Then C128Start = Chr(204)
If ((StringLength > 4) And IsNumeric(Mid(DataToFormat, 1, 4))) Then C128Start = Chr(205)

'202 & 212-215 is for the FNC1, with this Start C is mandatory
If CurrentCharNum = 202 Then C128Start = Chr(205)
If CurrentCharNum = 212 Then C128Start = Chr(205)
If CurrentCharNum = 213 Then C128Start = Chr(205)
If CurrentCharNum = 214 Then C128Start = Chr(205)
If CurrentCharNum = 215 Then C128Start = Chr(205)
If C128Start = Chr(203) Then CurrentEncoding = "A"
If C128Start = Chr(204) Then CurrentEncoding = "B"
If C128Start = Chr(205) Then CurrentEncoding = "C"

For I = 1 To StringLength
    'check for FNC1 in any set which is ASCII 202 and ASCII 212-215
    CurrentCharNum = Asc(Mid(DataToFormat, I, 1))
If ((CurrentCharNum = 202) Or (CurrentCharNum = 212) Or (CurrentCharNum = 213) Or (CurrentCharNum = 214) Or (CurrentCharNum = 215)) Then
        DataToEncode = DataToEncode & Chr(202)
    'check for switching to character set C
ElseIf ((I < StringLength - 2) And (IsNumeric(Mid(DataToFormat, I, 1))) And (IsNumeric(Mid(DataToFormat, I + 1, 1))) And (IsNumeric(Mid(DataToFormat, I, 4)))) Or ((I < StringLength) And (IsNumeric(Mid(DataToFormat, I, 1))) And (IsNumeric(Mid(DataToFormat, I + 1, 1))) And (CurrentEncoding = "C")) Then
    'switch to set C if not already in it
        If CurrentEncoding <> "C" Then DataToEncode = DataToEncode & Chr(199)
        CurrentEncoding = "C"
        CurrentChar = Mid(DataToFormat, I, 2)
        CurrentValue = Val(CurrentChar)
    'set the CurrentValue to the number of String CurrentChar
If (CurrentValue < 95 And CurrentValue > 0) Then DataToEncode = DataToEncode &                                                                                Chr(CurrentValue + 32)
        If CurrentValue > 94 Then DataToEncode = DataToEncode & Chr(CurrentValue + 100)
        If CurrentValue = 0 Then DataToEncode = DataToEncode & Chr(194)
        I = I + 1
    'check for switching to character set A
ElseIf (I <= StringLength) And ((Asc(Mid(DataToFormat, I, 1)) < 31) Or  ((CurrentEncoding = "A") And (Asc(Mid(DataToFormat, I, 1)) > 32 And (Asc(Mid(DataToFormat, I, 1))) < 96))) Then
    'switch to set A if not already in it
        If CurrentEncoding <> "A" Then DataToEncode = DataToEncode & Chr(201)
        CurrentEncoding = "A"
    'Get the ASCII value of the next character
        CurrentCharNum = Asc(Mid(DataToFormat, I, 1))
        If CurrentCharNum = 32 Then
            DataToEncode = DataToEncode & Chr(194)
        ElseIf CurrentCharNum < 32 Then
            DataToEncode = DataToEncode & Chr(CurrentCharNum + 96)
        ElseIf CurrentCharNum > 32 Then
            DataToEncode = DataToEncode & Chr(CurrentCharNum)
        End If
    'check for switching to character set B
 ElseIf (I <= StringLength) And (((Asc(Mid(DataToFormat, I, 1))) > 31) And ((Asc(Mid(DataToFormat, I, 1)))) < 127) Then
    'switch to set B if not already in it
        If CurrentEncoding <> "B" Then DataToEncode = DataToEncode & Chr(200)
        CurrentEncoding = "B"
    'Get the ASCII value of the next character
        CurrentCharNum = Asc(Mid(DataToFormat, I, 1))
        If CurrentCharNum = 32 Then
            DataToEncode = DataToEncode & Chr(194)
        Else
            DataToEncode = DataToEncode & Chr(CurrentCharNum)
        End If
    End If
Next I

'<<<< Calculate Modulo 103 Check Digit >>>>
WeightedTotal = Asc(C128Start) - 100
StringLength = Len(DataToEncode)
For I = 1 To StringLength
    CurrentCharNum = Asc(Mid(DataToEncode, I, 1))
    If CurrentCharNum < 135 Then CurrentValue = CurrentCharNum - 32
    If CurrentCharNum > 134 Then CurrentValue = CurrentCharNum - 100
    If CurrentCharNum = 194 Then CurrentValue = 0
    CurrentValue = CurrentValue * I
    WeightedTotal = WeightedTotal + CurrentValue
    If CurrentCharNum = 32 Then CurrentCharNum = 194
    PrintableString = PrintableString & Chr(CurrentCharNum)
Next I
CheckDigitValue = (WeightedTotal Mod 103)
If CheckDigitValue < 95 And CheckDigitValue > 0 Then C128CheckDigit = Chr(CheckDigitValue + 32)
If CheckDigitValue > 94 Then C128CheckDigit = Chr(CheckDigitValue + 100)
If CheckDigitValue = 0 Then C128CheckDigit = Chr(194)
DataToEncode = ""

' Final Barcode format
Formula = C128Start & PrintableString & C128CheckDigit & Chr(206) & " "
</code>```

The image shows 1000 as text (user input) and the barcode prints with the rectangle and I also added the barcode text to the bottom right corner to show what the barcode text looks like when encoded. I have noticed that the asterisk seems to be in the text when I get this weird shape.

Any help would be greatly appreciated :)

答:
I tried the code above and Mateusz solution but it is not entirely correct.

In order to effectively correct the code provided and create some readable barcodes when 0s are next to each other, you need to change chr(194) to chr(32) everywhere you see it in the code.

Body:
I have a formula field with a font of Code 128, to print string input from a user.

It prints fine every time except when two (2) zeros are next to each other. But the thing is its fine when it prints 100, but say I do 1000, it prints some rectangle shape in the barcode. Again 1001 it prints fine, 10001 it prints with a rectangle.

Here is the formula field:

@QuantityBarCode

' http://support.wisys.com/documentation/Crystal_Report_IDAutomation_Basic_Syntax_Barcode_Settings.htm

Dim DataToEncode As String
DataToEncode = Trim({@Quantity}) ' Quantity
Dim PrintableString As String
Dim DataToFormat As String
Dim WeightedTotal As Number
Dim CurrentValue As Number
Dim CheckDigitValue As Number
Dim C128CheckDigit As String
Dim StringLength As Number
Dim I As Number
Dim CurrentCharNum As Number
Dim CurrentEncoding As String
Dim C128Start As String
Dim CorrectFNC As Number
Dim CurrentChar As String
CorrectFNC = 0
PrintableString = ""
DataToFormat = DataToEncode
DataToEncode = ""

'Here we select character set A, B or C for the START character
StringLength = Len(DataToFormat)
CurrentCharNum = Asc(Mid(DataToFormat, 1, 1))
If CurrentCharNum < 32 Then C128Start = Chr(203)
If CurrentCharNum > 31 And CurrentCharNum < 127 Then C128Start = Chr(204)
If ((StringLength > 4) And IsNumeric(Mid(DataToFormat, 1, 4))) Then C128Start = Chr(205)

'202 & 212-215 is for the FNC1, with this Start C is mandatory
If CurrentCharNum = 202 Then C128Start = Chr(205)
If CurrentCharNum = 212 Then C128Start = Chr(205)
If CurrentCharNum = 213 Then C128Start = Chr(205)
If CurrentCharNum = 214 Then C128Start = Chr(205)
If CurrentCharNum = 215 Then C128Start = Chr(205)
If C128Start = Chr(203) Then CurrentEncoding = "A"
If C128Start = Chr(204) Then CurrentEncoding = "B"
If C128Start = Chr(205) Then CurrentEncoding = "C"

For I = 1 To StringLength
    'check for FNC1 in any set which is ASCII 202 and ASCII 212-215
    CurrentCharNum = Asc(Mid(DataToFormat, I, 1))
If ((CurrentCharNum = 202) Or (CurrentCharNum = 212) Or (CurrentCharNum = 213) Or (CurrentCharNum = 214) Or (CurrentCharNum = 215)) Then
        DataToEncode = DataToEncode & Chr(202)
    'check for switching to character set C
ElseIf ((I < StringLength - 2) And (IsNumeric(Mid(DataToFormat, I, 1))) And (IsNumeric(Mid(DataToFormat, I + 1, 1))) And (IsNumeric(Mid(DataToFormat, I, 4)))) Or ((I < StringLength) And (IsNumeric(Mid(DataToFormat, I, 1))) And (IsNumeric(Mid(DataToFormat, I + 1, 1))) And (CurrentEncoding = "C")) Then
    'switch to set C if not already in it
        If CurrentEncoding <> "C" Then DataToEncode = DataToEncode & Chr(199)
        CurrentEncoding = "C"
        CurrentChar = Mid(DataToFormat, I, 2)
        CurrentValue = Val(CurrentChar)
    'set the CurrentValue to the number of String CurrentChar
If (CurrentValue < 95 And CurrentValue > 0) Then DataToEncode = DataToEncode &                                                                                Chr(CurrentValue + 32)
        If CurrentValue > 94 Then DataToEncode = DataToEncode & Chr(CurrentValue + 100)
        If CurrentValue = 0 Then DataToEncode = DataToEncode & Chr(194)
        I = I + 1
    'check for switching to character set A
ElseIf (I <= StringLength) And ((Asc(Mid(DataToFormat, I, 1)) < 31) Or  ((CurrentEncoding = "A") And (Asc(Mid(DataToFormat, I, 1)) > 32 And (Asc(Mid(DataToFormat, I, 1))) < 96))) Then
    'switch to set A if not already in it
        If CurrentEncoding <> "A" Then DataToEncode = DataToEncode & Chr(201)
        CurrentEncoding = "A"
    'Get the ASCII value of the next character
        CurrentCharNum = Asc(Mid(DataToFormat, I, 1))
        If CurrentCharNum = 32 Then
            DataToEncode = DataToEncode & Chr(194)
        ElseIf CurrentCharNum < 32 Then
            DataToEncode = DataToEncode & Chr(CurrentCharNum + 96)
        ElseIf CurrentCharNum > 32 Then
            DataToEncode = DataToEncode & Chr(CurrentCharNum)
        End If
    'check for switching to character set B
 ElseIf (I <= StringLength) And (((Asc(Mid(DataToFormat, I, 1))) > 31) And ((Asc(Mid(DataToFormat, I, 1)))) < 127) Then
    'switch to set B if not already in it
        If CurrentEncoding <> "B" Then DataToEncode = DataToEncode & Chr(200)
        CurrentEncoding = "B"
    'Get the ASCII value of the next character
        CurrentCharNum = Asc(Mid(DataToFormat, I, 1))
        If CurrentCharNum = 32 Then
            DataToEncode = DataToEncode & Chr(194)
        Else
            DataToEncode = DataToEncode & Chr(CurrentCharNum)
        End If
    End If
Next I

'<<<< Calculate Modulo 103 Check Digit >>>>
WeightedTotal = Asc(C128Start) - 100
StringLength = Len(DataToEncode)
For I = 1 To StringLength
    CurrentCharNum = Asc(Mid(DataToEncode, I, 1))
    If CurrentCharNum < 135 Then CurrentValue = CurrentCharNum - 32
    If CurrentCharNum > 134 Then CurrentValue = CurrentCharNum - 100
    If CurrentCharNum = 194 Then CurrentValue = 0
    CurrentValue = CurrentValue * I
    WeightedTotal = WeightedTotal + CurrentValue
    If CurrentCharNum = 32 Then CurrentCharNum = 194
    PrintableString = PrintableString & Chr(CurrentCharNum)
Next I
CheckDigitValue = (WeightedTotal Mod 103)
If CheckDigitValue < 95 And CheckDigitValue > 0 Then C128CheckDigit = Chr(CheckDigitValue + 32)
If CheckDigitValue > 94 Then C128CheckDigit = Chr(CheckDigitValue + 100)
If CheckDigitValue = 0 Then C128CheckDigit = Chr(194)
DataToEncode = ""

' Final Barcode format
Formula = C128Start & PrintableString & C128CheckDigit & Chr(206) & " "

The image shows 1000 as text (user input) and the barcode prints with the rectangle and I also added the barcode text to the bottom right corner to show what the barcode text looks like when encoded. I have noticed that the asterisk seems to be in the text when I get this weird shape.

Any help would be greatly appreciated :)


问:
R: Dynamically referencing column names when using "$" or "[:]" syntax?
Let's say in R I have a data frame (called df) with a bunch of columns containing integer data named "Var1foo", "Var2foo", and so on.

Now suppose I want to create a new column called sum1 that adds up everything between "Var3foo" and "Var6foo". I might do:

```<code>df$sum1 <- rowSums(df[Var3foo:Var6foo])
</code>```

Or, I might do something a bit more complicated and create a new column called foobar with apply() like so:

```<code>eenie = 3
meenie = 2
df$foobar <- apply(df, 1, function(x) if (sum(x[Var2foo:Var7foo]) == eenie & sum(x[1:Var3foo]) != meenie) 1 else 0)
</code>```

The problem is I always have to explicitly write out the column names or index when referring to those columns. What if I want to refer to column "Varxfoo" where x <- 8 or "Varyfoo" where y <- 12?

What I mean is, I wouldn't be able to do df$paste0("Var", x, "foo") or sum(x[paste0("Var", x, "foo"):paste0("Var", y, "foo")]).

I also considered using dplyr::mutate() to create df$sum1 and df$foobar but it seems to also need explicit column (variable) names.

What should I do? Thanks!!

答:
Maybe you could refer the column with

```<code>df[paste0("Var", x, "foo")]
</code>```

If you keep using such things a lot, you could use some function to reduce your work,

```<code>int2name <- function(x, prefix = "", suffix = ""){
    paste0(prefix, x, suffix)
}
</code>```

And then you can use:

```<code>df[int2name(2:4, prefix = "Var", suffix = "foo")]
</code>```

Body:
Let's say in R I have a data frame (called df) with a bunch of columns containing integer data named "Var1foo", "Var2foo", and so on.

Now suppose I want to create a new column called sum1 that adds up everything between "Var3foo" and "Var6foo". I might do:

df$sum1 <- rowSums(df[Var3foo:Var6foo])

Or, I might do something a bit more complicated and create a new column called foobar with apply() like so:

eenie = 3
meenie = 2
df$foobar <- apply(df, 1, function(x) if (sum(x[Var2foo:Var7foo]) == eenie & sum(x[1:Var3foo]) != meenie) 1 else 0)

The problem is I always have to explicitly write out the column names or index when referring to those columns. What if I want to refer to column "Varxfoo" where x <- 8 or "Varyfoo" where y <- 12?

What I mean is, I wouldn't be able to do df$paste0("Var", x, "foo") or sum(x[paste0("Var", x, "foo"):paste0("Var", y, "foo")]).

I also considered using dplyr::mutate() to create df$sum1 and df$foobar but it seems to also need explicit column (variable) names.

What should I do? Thanks!!

Body:
Maybe you could refer the column with

df[paste0("Var", x, "foo")]

If you keep using such things a lot, you could use some function to reduce your work,

int2name <- function(x, prefix = "", suffix = ""){
    paste0(prefix, x, suffix)
}

And then you can use:

df[int2name(2:4, prefix = "Var", suffix = "foo")]


问:
Url change but still on the same page django
When i change to the page "lostitems" it successfull show up, but when i change to another page "addlostitem" it's still on the same page as before, but the url change the way that i want

Urls.py

```<code>url(r'lostitems/$', views.LostItemsView.as_view(), name='lost_items'),
url(r'lostitems/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),
</code>```

Views.py

```<code>class LostItemsView(generic.ListView):
    model = Wallet
    template_name = 'lostfound/lost_items.html'

class RegisterLostView(View):
    model = Wallet
    template_name = 'lostfound/register_lost.html'
</code>```

答:
Its because your URL patterns matches (partially) with the first in order, this should fix that:

```<code>url(r'^lostitems/$', views.LostItemsView.as_view(), name='lost_items'),
url(r'^lostitems/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),
</code>```

Notice I have added the ^ hat sign in beginning to force full match.

Body:
When i change to the page "lostitems" it successfull show up, but when i change to another page "addlostitem" it's still on the same page as before, but the url change the way that i want

Urls.py

url(r'lostitems/$', views.LostItemsView.as_view(), name='lost_items'),
url(r'lostitems/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),

Views.py

class LostItemsView(generic.ListView):
    model = Wallet
    template_name = 'lostfound/lost_items.html'

class RegisterLostView(View):
    model = Wallet
    template_name = 'lostfound/register_lost.html'

Body:
Its because your URL patterns matches (partially) with the first in order, this should fix that:

url(r'^lostitems/$', views.LostItemsView.as_view(), name='lost_items'),
url(r'^lostitems/addlostitems/$', views.RegisterLostView.as_view(), name='register_lost'),

Notice I have added the ^ hat sign in beginning to force full match.


答:
How about something like

```<code>String header = "Test Header";

int desiredLength = 50;
int split = (desiredLength - header.length()) / 2;

for ( int x = 0; x < split; x++ ) {

    System.out.print("*");
}

System.out.print( " " + header + " " );

for ( int x = 0; x < split; x++ ) {

    System.out.print("*");
}
</code>```

This can obviously be improved upon, but the concept still holds.

Take your desired length, subtract the length of chars you have, cut it in half, then print them on either side of the string.

You will also need some special handling if you are using an odd number of characters.

Title: Autofill static character in string to match string length

Body:
I'm using this method as a line separator in a console and I wanted to make it easy to pass through titles.

public class Test {
    private int consoleLineSeparatorLength = "***************************************************************".length();

    private void printTitleLineSeparator(String title){
        String lineTitleSeperatorBorder = "";
        String lineTitleSeperator = "* " + title + " *";
        for(int charInString = 0; charInString < consoleLineSeparatorLength; charInString++){
            lineTitleSeperatorBorder += "*";
        }

        System.out.println();
        System.out.println(lineTitleSeperatorBorder);
        System.out.println(lineTitleSeperator);
        System.out.println(lineTitleSeperatorBorder);
        System.out.println();
    }

    public static void main(String[] args) {
        Test tester = new Test();

        tester.printTitleLineSeparator("Select Character");
        tester.printTitleLineSeparator("Select Stats");
        tester.printTitleLineSeparator("Select Display Method");

    }
}

Current Output...

***************************************************************
* Select Character *
***************************************************************

***************************************************************
* Select Stats *
***************************************************************

***************************************************************
* Select Display Method *
***************************************************************

Expected output...

***************************************************************
*********************** Select Character **********************
***************************************************************

***************************************************************
************************* Select Stats ************************
***************************************************************

***************************************************************
******************** Select Display Method ********************
***************************************************************

If the center title is an even amount of characters including whitespaces (meaning one side or the other will have one extra asterisk), put the extra asterisk on the left side so everything still looks centered.

Anyone have any ideas how to do this?

Body:
How about something like

String header = "Test Header";

int desiredLength = 50;
int split = (desiredLength - header.length()) / 2;

for ( int x = 0; x < split; x++ ) {

    System.out.print("*");
}

System.out.print( " " + header + " " );

for ( int x = 0; x < split; x++ ) {

    System.out.print("*");
}

This can obviously be improved upon, but the concept still holds.

Take your desired length, subtract the length of chars you have, cut it in half, then print them on either side of the string.

You will also need some special handling if you are using an odd number of characters.


问:
Decoding VP9 with Alpha Channel in Android, is it possible?
Currently FFmpeg support VP9 compression to yuva420p.

Using grafika as code base I am implemented playing VP9 yuva420p encoded video in Android (using SurfaceTexture and MediaCodec), but I can't get Alpha channel from the video.

I checked that video encoded with VideoAlphaMode; ID: 0x53c0 size: 4, so I am sure that video contains alpha channel.

So the question is: does Android 4.4+ decoder supports VP9 with Alpha channel?

答:
Recommend you start by building the latest version of libvpx itself on a 64-bit Linux workstation.  The libvpx test suite should include a test for alpha-channel.  Ensure that test passes.  If it doesn't, that's a bad sign, because libvpx is the reference implementation for VP9.

If it does, the next step would be to attempt an alpha decode and overlay using a higher-level library, still on Linux.  I suggest using GStreamer 1.8.2 or higher.  Overlay your clip on top of the "videotestsrc" generator, which will generate most video formats.

If either of those tests fail, I would recommend you closely investigate why before proceeding.

The reason for starting on Linux is that you will have an easier time building and troubleshooting, and I suspect you may be hitting an edge of the specification that hasn't even been implemented in the reference implementation (libvpx), or which is difficult to integrate into higher-level libraries (hence the GStreamer suggestion).

That said, while I have significant experience with VP8 and libvpx, I have not used the VP9-specific feature set.  I'm curious to follow your efforts, however, and may be able to offer advice as you make progress.


问:
Taking a 3 year average across in a panel data set with NAs
I have the following dataframe, called DF,

```<code>Country Year Var1 Var2
USA 2010 5 3
USA 2011 6 5
USA 2012 NA 8
USA 2013 4 NA
USA 2014 NA 6
USA 2015 6 9
CHN 2010 NA 5
CHN 2011 7 NA
CHN 2012 6 NA
CHN 2013 4 4
CHN 2014 NA 6
CHN 2015 NA 8
EGY 2010 3 NA
EGY 2011 3 5
EGY 2012 3 6
EGY 2013 NA 8
EGY 2014 NA NA
EGY 2015 NA 2
</code>```

I want to take a 3 year average of the data. However, if there are only two years of available data within a particular three year interval, I want to ignore the NA and take a two year average. Similarly, if data is only available for one year within a particular three year interval, I want to keep that data point as the "average" for that three year interval. Basically, within each three year interval, I want to take the mean, and ignoring the NAs.

I have tried the following solution recommended in : R: Calculating 5 year averages in panel data

```<code>int<-cut(DF$Year,seq(2010,2016,by=3),right=F)
id<-c("Var1", "Var2")
ag<-aggregate(DF[id],list(DF$Country,int), mean)
</code>```

It yielded the following:

```<code>Group.1 Group.2 Var1 Var2
CHN [2010,2013) NA NA
EGY [2010,2013) 3 NA
USA [2010,2013) NA 5.333333
CHN [2013,2016) NA 6.000000
EGY [2013,2016) NA NA
USA [2013,2016) NA NA
</code>```

But the output I am interested in is:

```<code>Group.1 Group.2 Var1 Var2
CHN [2010,2013) 6.5 5
EGY [2010,2013) 3 5.5
USA [2010,2013) 5.5 5.3
CHN [2013,2016) 4 6
EGY [2013,2016) NA 5
USA [2013,2016) 5 7.5
</code>```

答:
You are almost there, only one addition to your code is required:

```<code>int <- cut(DF$Year, seq(2010, 2016, by = 3), right = FALSE)
id <- c("Var1", "Var2")
ag <- aggregate(DF[id], list(DF$Country, int), mean, na.rm = TRUE)
#                                                    |
#-----------------------------------------------------

ag
#  Group.1     Group.2 Var1     Var2
#1     CHN [2010,2013)  6.5 5.000000
#2     EGY [2010,2013)  3.0 5.500000
#3     USA [2010,2013)  5.5 5.333333
#4     CHN [2013,2016)  4.0 6.000000
#5     EGY [2013,2016)  NaN 5.000000
#6     USA [2013,2016)  5.0 7.500000
</code>```

aggregate() accepts further arguments passed to or used by methods. This way, you can pass the na.rm = TRUE parameter to mean().

Body:
I have the following dataframe, called DF,

Country Year Var1 Var2
USA 2010 5 3
USA 2011 6 5
USA 2012 NA 8
USA 2013 4 NA
USA 2014 NA 6
USA 2015 6 9
CHN 2010 NA 5
CHN 2011 7 NA
CHN 2012 6 NA
CHN 2013 4 4
CHN 2014 NA 6
CHN 2015 NA 8
EGY 2010 3 NA
EGY 2011 3 5
EGY 2012 3 6
EGY 2013 NA 8
EGY 2014 NA NA
EGY 2015 NA 2

I want to take a 3 year average of the data. However, if there are only two years of available data within a particular three year interval, I want to ignore the NA and take a two year average. Similarly, if data is only available for one year within a particular three year interval, I want to keep that data point as the "average" for that three year interval. Basically, within each three year interval, I want to take the mean, and ignoring the NAs.

I have tried the following solution recommended in : R: Calculating 5 year averages in panel data

int<-cut(DF$Year,seq(2010,2016,by=3),right=F)
id<-c("Var1", "Var2")
ag<-aggregate(DF[id],list(DF$Country,int), mean)

It yielded the following:

Group.1 Group.2 Var1 Var2
CHN [2010,2013) NA NA
EGY [2010,2013) 3 NA
USA [2010,2013) NA 5.333333
CHN [2013,2016) NA 6.000000
EGY [2013,2016) NA NA
USA [2013,2016) NA NA

But the output I am interested in is:

Group.1 Group.2 Var1 Var2
CHN [2010,2013) 6.5 5
EGY [2010,2013) 3 5.5
USA [2010,2013) 5.5 5.3
CHN [2013,2016) 4 6
EGY [2013,2016) NA 5
USA [2013,2016) 5 7.5

Body:
You are almost there, only one addition to your code is required:

int <- cut(DF$Year, seq(2010, 2016, by = 3), right = FALSE)
id <- c("Var1", "Var2")
ag <- aggregate(DF[id], list(DF$Country, int), mean, na.rm = TRUE)
#                                                    |
#-----------------------------------------------------

ag
#  Group.1     Group.2 Var1     Var2
#1     CHN [2010,2013)  6.5 5.000000
#2     EGY [2010,2013)  3.0 5.500000
#3     USA [2010,2013)  5.5 5.333333
#4     CHN [2013,2016)  4.0 6.000000
#5     EGY [2013,2016)  NaN 5.000000
#6     USA [2013,2016)  5.0 7.500000

aggregate() accepts further arguments passed to or used by methods. This way, you can pass the na.rm = TRUE parameter to mean().


问:
"Cannot create infinite type" error in Haskell
I'd like to know why Haskell accepts this

```<code>perms xs = [ x:y | i <- [0..(length xs - 1)], x <- [xs!!i], y <- perms (takeOut i xs)]
</code>```

but won't accept that:

```<code>perms xs = [ x:(perms y) | i <- [0..(length xs - 1)], x <- [xs!!i], y <- (takeOut i xs)]
</code>```

It complains that

[1 of 1] Compiling Main             ( abc.hs, interpreted )

```<code>Occurs check: cannot construct the infinite type: t = [t]
  Expected type: t -> [t]
  Inferred type: [t] -> [[a]]
In the second argument of `(:)', namely `(perms y)'
In the expression: x : (perms y)
</code>```

I can understand what it says, I just cannot is on why the first one is OK and the second one is not!

EDIT: Ah, of course I also have

```<code>perms [] = [[]]
</code>```

at the top.

Thanks

答:
In the first expression you have x:y which means, that if x :: a then y :: [a].
In x : perms y if x :: a then it must be that perms y :: [a], but perms y :: [[a]] (list of permutations).
Typechecker tries to unify [a] and [[a]] and fails.

Body:
I'd like to know why Haskell accepts this

perms xs = [ x:y | i <- [0..(length xs - 1)], x <- [xs!!i], y <- perms (takeOut i xs)]

but won't accept that:

perms xs = [ x:(perms y) | i <- [0..(length xs - 1)], x <- [xs!!i], y <- (takeOut i xs)]

It complains that

[1 of 1] Compiling Main             ( abc.hs, interpreted )

Occurs check: cannot construct the infinite type: t = [t]
  Expected type: t -> [t]
  Inferred type: [t] -> [[a]]
In the second argument of `(:)', namely `(perms y)'
In the expression: x : (perms y)

I can understand what it says, I just cannot is on why the first one is OK and the second one is not!

EDIT: Ah, of course I also have

perms [] = [[]]

at the top.

Thanks


问:
SQLiteDatabase.execSQL(query) - Multiple SQL commands inside the onCreate() method not working
I am new to android. I haven't worked with SQLite DBs before.

I think this is a very basic question, but I am unable to find the solution.

The code is here (assume declarations)

```<code>public void onCreate(SQLiteDatabase db) {

    String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + FORMULA + "("
            + CAT_CD + " TEXT ," + S_CAT_CD + " TEXT, PRIMARY
 KEY(CAT_CD,S_CAT_CD))";
    db.execSQL(CREATE_CATEGORIES_TABLE);

    String CREATE_CAT_DESC_TABLE="CREATE TABLE "+ FORMULA_CAT_DESC + "
("+CAT_CD+" TEXT PRIMARY KEY, "+ DESC +" TEXT ) ";
    db.execSQL(CREATE_CAT_DESC_TABLE);

    String CREATE_CURRENCY_TABLE="CREATE TABLE "+ VI_CURRENCY + "("+
CURRENCY_CD +" TEXT PRIMARY KEY, "+ CURRENCY_SIGN +" TEXT ) ";
    db.execSQL(CREATE_CURRENCY_TABLE);

   String query=  "INSERT INTO "+ VI_CURRENCY +" ("+CURRENCY_CD +",
"+CURRENCY_SIGN+ ") VALUES " +
            "('INR', '₹'), " +
            " ('USD','$') " +
            "('JPY','¥') ";
    db.execSQL(query);
 }
</code>```

The first three commands execute successfully, while by executing the insert command,  SQLite throws an exeption.

答:
In Android, writing operation is slow, So in your case, if you have hundreds of data, you can use transactions in SQLite database.

```<code>db.beginTransaction();
try {
    for(/*your loop*/) {
        String query =  /*your query*/

        db.execSQL(query);
    }
    db.setTransactionSuccessful();
} finally {
    db.endTransaction();
}
</code>```

For more detail, Please refer this, official doc.

Body:
I am new to android. I haven't worked with SQLite DBs before.

I think this is a very basic question, but I am unable to find the solution.

The code is here (assume declarations)

public void onCreate(SQLiteDatabase db) {

    String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + FORMULA + "("
            + CAT_CD + " TEXT ," + S_CAT_CD + " TEXT, PRIMARY
 KEY(CAT_CD,S_CAT_CD))";
    db.execSQL(CREATE_CATEGORIES_TABLE);

    String CREATE_CAT_DESC_TABLE="CREATE TABLE "+ FORMULA_CAT_DESC + "
("+CAT_CD+" TEXT PRIMARY KEY, "+ DESC +" TEXT ) ";
    db.execSQL(CREATE_CAT_DESC_TABLE);

    String CREATE_CURRENCY_TABLE="CREATE TABLE "+ VI_CURRENCY + "("+
CURRENCY_CD +" TEXT PRIMARY KEY, "+ CURRENCY_SIGN +" TEXT ) ";
    db.execSQL(CREATE_CURRENCY_TABLE);

   String query=  "INSERT INTO "+ VI_CURRENCY +" ("+CURRENCY_CD +",
"+CURRENCY_SIGN+ ") VALUES " +
            "('INR', '₹'), " +
            " ('USD','$') " +
            "('JPY','¥') ";
    db.execSQL(query);
 }

The first three commands execute successfully, while by executing the insert command,  SQLite throws an exeption.

Body:
In Android, writing operation is slow, So in your case, if you have hundreds of data, you can use transactions in SQLite database.

db.beginTransaction();
try {
    for(/*your loop*/) {
        String query =  /*your query*/

        db.execSQL(query);
    }
    db.setTransactionSuccessful();
} finally {
    db.endTransaction();
}

For more detail, Please refer this, official doc.


问:
Jenkins parameter is getting replaced by a white space
I have a parameterized build (copied from an existing job) in Jenkins. While building, my parameter is getting replaced by a white space. Here I am sharing what I have.

Parameter Name: BuildDate (I tried using %% and ${} but no luck)

Windows batch command:

```<code>copy \\Network_drive\dir1\dir2\dir3%BuildDate%\filename*.zip .
</code>```

Output from Jenkins console:

```<code>c:\jenkins\workspace\my_build_job_name>copy \\Network_drive\dir1\dir2\dir3\ \filename*.zip .
\\Network_drive\dir1\dir2\dir3\ \filename*.zip
The system cannot find the path specified. 0 file(s) copied

c:\jenkins\workspace\my_build_job_name>exit 1
Build step 'Execute Windows batch command' marked build as failure
Notifying upstream projects of job completion Finished: FAILURE*
</code>```

Note: We have a Windows/Linux mixed environment. Whenever we want to run shell scripts, we use Cygwin, batch should directly run.

答: Finally it turned out that one of the parameters was not populating due to hitting "rebuild last". Re-running the whole pipeline did it work. I still wonder why it was not populating but its all hood now!!!</p>

Body:
I have a parameterized build (copied from an existing job) in Jenkins. While building, my parameter is getting replaced by a white space. Here I am sharing what I have.

Parameter Name: BuildDate (I tried using %% and ${} but no luck)

Windows batch command:

copy \\Network_drive\dir1\dir2\dir3%BuildDate%\filename*.zip .

Output from Jenkins console:

c:\jenkins\workspace\my_build_job_name>copy \\Network_drive\dir1\dir2\dir3\ \filename*.zip .
\\Network_drive\dir1\dir2\dir3\ \filename*.zip
The system cannot find the path specified. 0 file(s) copied

c:\jenkins\workspace\my_build_job_name>exit 1
Build step 'Execute Windows batch command' marked build as failure
Notifying upstream projects of job completion Finished: FAILURE*

Note: We have a Windows/Linux mixed environment. Whenever we want to run shell scripts, we use Cygwin, batch should directly run.


问:
When changing from excel 97-2003 ETL displays an error message
Excel connection manager won´t allow me to switch the Excel version. I'll attach the error messages. Thank You.

Screen Shots

答:
You need to install the driver for Access 2013 to be compatible with the latest Excel documents. Careful to install the correct version (32 bit vs. 64 bit):

https://www.microsoft.com/en-us/download/details.aspx?id=39358


问:
Auditing in a SQL Server Docker Container
I'm currently using a SQL Server docker container, setup according to the following: Run the SQL Server 2017 container image on Docker on Linux, Mac, or Windows.

I'm unfamiliar with Auditing within SQL Server, but all the documentation I can find for it appear to be using SSMS to configure the process. I am unable to use SSMS in my particular context.

Is there a way to setup SQL Server Auditing within the SQL Server docker container?

答:
There are ways to connect your sqlserver from outside using SSMS..like i mentioned in this answer:Connect to Remote MSSQL db from Linux Docker container

This link has SSMS equivalent scripts for auditing..

first you need to try creating server level audit on

```<code>USE master ;
GO
-- Create the server audit.
CREATE SERVER AUDIT Payrole_Security_Audit
    TO FILE ( FILEPATH =
linux file path) ;
GO
-- Enable the server audit.
ALTER SERVER AUDIT Payrole_Security_Audit
WITH (STATE = ON) ;
</code>```

then you could individual databases as well or server level events as well.Below is one small example for database level audit

```<code>USE AdventureWorks2012 ;
GO
-- Create the database audit specification.
CREATE DATABASE AUDIT SPECIFICATION Audit_Pay_Tables
FOR SERVER AUDIT Payrole_Security_Audit
ADD (SELECT , INSERT
     ON HumanResources.EmployeePayHistory BY dbo )
WITH (STATE = ON) ;
GO
</code>```

you can run above scripts through sqlcmd,my answer i mentioned has more details on how to do this

further i think VSCODE is more flexible to run ssms scripts than sqlcmd.you can download it for free and configure mssql extension

Body:
There are ways to connect your sqlserver from outside using SSMS..like i mentioned in this answer:Connect to Remote MSSQL db from Linux Docker container

This link has SSMS equivalent scripts for auditing..

first you need to try creating server level audit on

USE master ;
GO
-- Create the server audit.
CREATE SERVER AUDIT Payrole_Security_Audit
    TO FILE ( FILEPATH =
linux file path) ;
GO
-- Enable the server audit.
ALTER SERVER AUDIT Payrole_Security_Audit
WITH (STATE = ON) ;

then you could individual databases as well or server level events as well.Below is one small example for database level audit

USE AdventureWorks2012 ;
GO
-- Create the database audit specification.
CREATE DATABASE AUDIT SPECIFICATION Audit_Pay_Tables
FOR SERVER AUDIT Payrole_Security_Audit
ADD (SELECT , INSERT
     ON HumanResources.EmployeePayHistory BY dbo )
WITH (STATE = ON) ;
GO

you can run above scripts through sqlcmd,my answer i mentioned has more details on how to do this

further i think VSCODE is more flexible to run ssms scripts than sqlcmd.you can download it for free and configure mssql extension


问:
Embedded System - Polling
I have about 6 sensors (GPS, IMU, etc.) that I need to constantly collect data from. For my purposes, I need a reading from each (within a small time frame) to have a complete data packet. Right now I am using interrupts, but this results in more data from certain sensors than others, and, as mentioned, I need to have the data matched up.

Would it be better to move to a polling-based system in which I could poll each sensor in a set order? This way I could have data from each sensor every 'cycle'.

I am, however, worried about the speed of polling because this system needs to operate close to real time.

答:
Polling is a pretty good and easy to implement idea in case your sensors can provide data practically instantly (in comparison to your desired output frequency). It does get into a nightmare when you have data sources that need a significant (or even variable) time to provide a reading or require an asynchronous "initiate/collect" cycle. You'd have to sort your polling cycles to accommodate the "slowest" data source.

What might be a solution in case you know the average "data conversion rate" of each of your sources, is to set up a number of timers (per data source)  that trigger at poll time - data conversion rate and kick in the measurement from those timer ISRs. Then have one last timer that triggers at poll timer + some safety margin that collects all the conversion results.

On the other hand, your apparent problem of "having too many measurements" from the "fast" data sources wouldn't bother me too much as long as you don't have anything reasonable to do with that wasted CPU/sensor load.

A last and easier approach, in case you have some cycles to waste, is: Simply sort the data sources from "slowest" to "fastest" and initiate a measurement in that order, then wait for results in the same order and poll.

Title: Embedded System - Polling


问:
What is the best pattern for two way communication between classes?
I have classes that need to communicate with each other. The problem is that if you make one contain the other (a child parent relationship) then things get tricky. You either need to pass an instance of the parent into the child, (then which one do you create first if you are using dependency injection) or you can use delegates/events. But I want to enforce the fact that the parent must be able to handle the event that the child raises. Not too sure how to do that. I also don't want multiple subscribers to the event.

The parent-child relationship just feels wrong for two way communication. Unfortunately it is not a case that one of the objects always initiates and the other responds. Either can initiate and the other should respond.

Is there another pattern that I am missing?

UPDATE:
Sorry this is quite hard to explain. I forgot to add that when one class sends a message to another class it is not expecting the response immediately. The response comes in asynchronously which is why you either need an instance of the parent to call the right method or a delegate/event. Sorry the example below is pseudo code. Hopefully it is enough to get the idea. Should I look at the mediator pattern.

```<code>public class Foo
    {
        public void SendMessageAToBar()
        {
            MessageA msg = new MessageA();
            Bar.ReceiveMessageAFromFoo(msg);
        }

        public void ReceiveMessageARespFromBar(MessageAResp msgResp)
        {
            //Got a response do something
        }

        public void ReceiveMessageBFromBar(MessageB msg)
        {
            //Do something msg
            MessageBResp msgBResp = new MessageBResp();
            Bar.ReceiveMessageBRespFromFoo()
        }
    }

    public class Bar
    {

        public void ReceiveMessageAFromFoo(MessageA msg)
        {
            //DO something.
            MessageAResp resp = new MessageAResp();
            Foo.ReceiveMessageARespFromBar(resp);
        }

        public void SendMessageBToFoo()
        {
            MessageB msg = new MessageB();
            Foo.ReceiveMessageBFromBar(msg);
        }

        public void ReceiveMessageBRespFromFoo(MessageBResp msgResp)
        {
            //Got a response do something
        }
    }
</code>```

答:
Maybe you should use a bootstrapper:

```<code>class Main
{
    void Main(...)
    {
        A a = new A();
        B b = new B();

        a.MessagePosted += (sender, messageArgs) => b.ReadMessage(messageArgs.Message);
        b.MessagePosted += (sender, messageArgs) => a.ReadMessage(messageArgs.Message);
    }
}
</code>```

Now, both A and B are blissfully unaware of each other.

Body:
I have classes that need to communicate with each other. The problem is that if you make one contain the other (a child parent relationship) then things get tricky. You either need to pass an instance of the parent into the child, (then which one do you create first if you are using dependency injection) or you can use delegates/events. But I want to enforce the fact that the parent must be able to handle the event that the child raises. Not too sure how to do that. I also don't want multiple subscribers to the event.

The parent-child relationship just feels wrong for two way communication. Unfortunately it is not a case that one of the objects always initiates and the other responds. Either can initiate and the other should respond.

Is there another pattern that I am missing?

UPDATE:
Sorry this is quite hard to explain. I forgot to add that when one class sends a message to another class it is not expecting the response immediately. The response comes in asynchronously which is why you either need an instance of the parent to call the right method or a delegate/event. Sorry the example below is pseudo code. Hopefully it is enough to get the idea. Should I look at the mediator pattern.

public class Foo
    {
        public void SendMessageAToBar()
        {
            MessageA msg = new MessageA();
            Bar.ReceiveMessageAFromFoo(msg);
        }

        public void ReceiveMessageARespFromBar(MessageAResp msgResp)
        {
            //Got a response do something
        }

        public void ReceiveMessageBFromBar(MessageB msg)
        {
            //Do something msg
            MessageBResp msgBResp = new MessageBResp();
            Bar.ReceiveMessageBRespFromFoo()
        }
    }

    public class Bar
    {

        public void ReceiveMessageAFromFoo(MessageA msg)
        {
            //DO something.
            MessageAResp resp = new MessageAResp();
            Foo.ReceiveMessageARespFromBar(resp);
        }

        public void SendMessageBToFoo()
        {
            MessageB msg = new MessageB();
            Foo.ReceiveMessageBFromBar(msg);
        }

        public void ReceiveMessageBRespFromFoo(MessageBResp msgResp)
        {
            //Got a response do something
        }
    }

Body:
Maybe you should use a bootstrapper:

class Main
{
    void Main(...)
    {
        A a = new A();
        B b = new B();

        a.MessagePosted += (sender, messageArgs) => b.ReadMessage(messageArgs.Message);
        b.MessagePosted += (sender, messageArgs) => a.ReadMessage(messageArgs.Message);
    }
}

Now, both A and B are blissfully unaware of each other.


问:
how can I convert string into HTML. I want the actual href to show/display instead of the text
how can I convert string into HTML. I want the actual href to show/display instead of the text. </p>

```<code>    var zzz = "test";
    var value0 = 14251876;
    var value1 = "AAAA";

    var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';
    var EmailBody = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';
    EmailBody = EmailBody + $($.parseHTML('<div><a href="/Apps/app_editevent.jsp?eventid=' + value1 + '" target="_blank">' + value0 + '</a></div>'));
    send_msg(false,'',20,0,'mailer@test.ca',1081636,'',EmailSubject,EmailBody);
</code>```

答:
Just use append to add it as  html to your div as

```<code>$('div').append('<div><a href="/Apps/app_editevent.jsp?eventid=' + value1 + '" target="_blank">' + value0 + '</a></div>');
</code>```

Body:
how can I convert string into HTML. I want the actual href to show/display instead of the text.

    var zzz = "test";
    var value0 = 14251876;
    var value1 = "AAAA";

    var EmailSubject = 'Transcription Assigned   Due (' + zzz + ')';
    var EmailBody = 'Dear ' + zzz + ',\n\n' + 'A dictation for the following Service has been assigned to you;\n\n' + 'Service Name: ' + zzz + '\n\n' + 'Thank you,\n' + 'Assessments\n' + '(416) 111 - 2222';
    EmailBody = EmailBody + $($.parseHTML('
' + value0 + '
'));
    send_msg(false,'',20,0,'mailer@test.ca',1081636,'',EmailSubject,EmailBody);

Body:
Just use append to add it as  html to your div as

$('div').append('<div><a href="/Apps/app_editevent.jsp?eventid=' + value1 + '" target="_blank">' + value0 + '</a></div>');


问:
AngularJS controller Registration
I inherited a nodejs/angularJS project and I am getting errors just trying to display a $scope variable in my html. I keep on getting the error "The Controller with the name 'loginCtrl' is not registered. All I am trying to do is something basic, display an isAdmin variable which is a boolean, and I cannot figure out what I am doing wrong. My http call in my login.js is working fine and I can see when debugging that my $scope.isAdmin variable does populate as expected.

login.js

```<code>(function () {
'use strict';
angular
    .module('loginApp', ['ngMaterial', 'ngSanitize'])
    .controller('loginCtrl', loginCtrl)
    .config(function ($mdThemingProvider) {
        $mdThemingProvider.theme('default')
        .primaryPalette('blue')
    });
function loginCtrl($scope, $http, $log, $mdDialog, $window) {
    $scope.error = '';
    $scope.isAdmin = false;
    $scope.submit = function () {
        $http({
            method: 'POST',
            url: '/login',
            headers: {'Content-Type': 'application/json'},
            data: {'username': $scope.username, 'password': $scope.userpassword},
        }).then(function successCallback(response, data) {
            if (response.data.successful) {
                $scope.isAdmin = response.data.isAdmin;
              ...
           ...
</code>```

my naviagtion.ejs partial
As a test I just wanted to see either true or false on the line item

```<code><!-- views/partials/header.ejs -->
<div class="navbar navbar-inverse navbar-fixed-top" ng-controller="loginCtrl">

<div class="navbar-collapse collapse">
  <ul class="nav navbar-nav">
    <li><a href="/index">Home</a></li>
    <li><a href="/admin">Admin</a></li>
    <li><a href="/logout">Log out</a></li>
    <li><a href="">Test: {{isAdmin}} </a></li>
  </ul>
</code>```

and my index.html
I think this is where the problem is. I have my login.js script injected at the bottom of my page but the ng-app productName is meant to populate the second div for the /partials/checkboxes, which works just fine.

```<code><body ng-app="productName">
<div class="container">
    <% include ./partials/navigation %>
</div>
<div>
    <% include ./partials/checkboxes %>
</div><!--bower:js-->
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/lib/angular/angular.js"></script>
<script src="/lib/angular-animate/angular-animate.js"></script>
<script src="/lib/angular-aria/angular-aria.js"></script>
<script src="/lib/angular-messages/angular-messages.js"></script>
<script src="/lib/angular-sanitize/angular-sanitize.js"></script>

<!--endbower-->
<!--inject:js-->
<script src="/js/login.js"></script>
<!--endinject-->
</body>

</html>
</code>```

答: You are defining the name of app in "angular.module" as "loginApp" while in body tag your app name is "productName" please correct it first.</p>

Title: AngularJS controller Registration

Body:
I inherited a nodejs/angularJS project and I am getting errors just trying to display a $scope variable in my html. I keep on getting the error "The Controller with the name 'loginCtrl' is not registered. All I am trying to do is something basic, display an isAdmin variable which is a boolean, and I cannot figure out what I am doing wrong. My http call in my login.js is working fine and I can see when debugging that my $scope.isAdmin variable does populate as expected.

login.js

(function () {
'use strict';
angular
    .module('loginApp', ['ngMaterial', 'ngSanitize'])
    .controller('loginCtrl', loginCtrl)
    .config(function ($mdThemingProvider) {
        $mdThemingProvider.theme('default')
        .primaryPalette('blue')
    });
function loginCtrl($scope, $http, $log, $mdDialog, $window) {
    $scope.error = '';
    $scope.isAdmin = false;
    $scope.submit = function () {
        $http({
            method: 'POST',
            url: '/login',
            headers: {'Content-Type': 'application/json'},
            data: {'username': $scope.username, 'password': $scope.userpassword},
        }).then(function successCallback(response, data) {
            if (response.data.successful) {
                $scope.isAdmin = response.data.isAdmin;
              ...
           ...

my naviagtion.ejs partial
As a test I just wanted to see either true or false on the line item

Home

Admin

Log out

Test: {{isAdmin}}

and my index.html
I think this is where the problem is. I have my login.js script injected at the bottom of my page but the ng-app productName is meant to populate the second div for the /partials/checkboxes, which works just fine.

    <% include ./partials/navigation %>

    <% include ./partials/checkboxes %>


问:
ASP.NET MVC - Execute controller action without redirecting
I am trying to execute an action on a controller without redirecting to the associated view for that action. For a good example of what I am trying to achieve take a look at the music.xbox.com website. When you add a song to a selected playlist from a popup menu - the page just shows a notification without any redirect or refresh. how is this possible?

What I have is the following:
I have a _playlistPopupMenu partial view that renders the list of playlists as follows:

_PlaylistPopupMenu

```<code>@model List<OneMusic.Models.GetPlaylists_Result>
@if (Model.Count > 0)
{
    <li style="height:2px" class="divider"></li>
    foreach (var item in Model)
    {
        <li style="height:30px">@Html.DisplayFor(p => item.Name)
            @Html.ActionLink(item.Name, "AddSong", "Playlist", new { playlistId =   @item.PlaylistId, songId = 1 }, "")
       </li>
    }
}
</code>```

The PlaylistController AddSong action is as follows:

```<code>public PartialViewResult AddSong(int? playlistId, int? songId)
{
    if (ModelState.IsValid)
    {
        db.AddSongToPlaylist(playlistId, songId);
        db.SaveChanges();
        return PartialView("_AddToPlaylist", "");
    }
    return PartialView("_AddToPlaylist", "");
}
</code>```

I am struggling with what to put in the _AddToPlaylist partial view which I think I need to be able to display a notification of some kind (Possiblly using PNotify add in for Bootstrap). MVC wants to always redirect to  ../Playlist/AddSong?playlistId=1&songId=1

Any ideas on how to complete this last part of the problem would be great.

答:
using System.Web.Mvc;

using System.Web.Mvc.Html;

```<code>public ActionResult Index()
{
    HtmlHelper helper = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView(ControllerContext, "Index"), new ViewDataDictionary(), new TempDataDictionary(), new System.IO.StringWriter()), new ViewPage());
    helper.RenderAction("Index2");

    return View();
}

public ActionResult Index2(/*your arg*/)
{
    //your code
    return new EmptyResult();
}
</code>```

Body:
I am trying to execute an action on a controller without redirecting to the associated view for that action. For a good example of what I am trying to achieve take a look at the music.xbox.com website. When you add a song to a selected playlist from a popup menu - the page just shows a notification without any redirect or refresh. how is this possible?

What I have is the following:
I have a _playlistPopupMenu partial view that renders the list of playlists as follows:

_PlaylistPopupMenu

@model List<OneMusic.Models.GetPlaylists_Result>
@if (Model.Count > 0)
{

    foreach (var item in Model)
    {

@Html.DisplayFor(p => item.Name)
            @Html.ActionLink(item.Name, "AddSong", "Playlist", new { playlistId =   @item.PlaylistId, songId = 1 }, "")

    }
}

The PlaylistController AddSong action is as follows:

public PartialViewResult AddSong(int? playlistId, int? songId)
{
    if (ModelState.IsValid)
    {
        db.AddSongToPlaylist(playlistId, songId);
        db.SaveChanges();
        return PartialView("_AddToPlaylist", "");
    }
    return PartialView("_AddToPlaylist", "");
}

I am struggling with what to put in the _AddToPlaylist partial view which I think I need to be able to display a notification of some kind (Possiblly using PNotify add in for Bootstrap). MVC wants to always redirect to  ../Playlist/AddSong?playlistId=1&songId=1

Any ideas on how to complete this last part of the problem would be great.

Body:
using System.Web.Mvc;

using System.Web.Mvc.Html;

public ActionResult Index()
{
    HtmlHelper helper = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView(ControllerContext, "Index"), new ViewDataDictionary(), new TempDataDictionary(), new System.IO.StringWriter()), new ViewPage());
    helper.RenderAction("Index2");

    return View();
}

public ActionResult Index2(/*your arg*/)
{
    //your code
    return new EmptyResult();
}


问:
Stellar js not working
I'm trying to create a parallax effect on my website, and I've followed the directions exactly as it says from the main source but it's still not working. Here are the code snippets.

HTML

```<code><div id="home-section" data-stellar-background-ratio="0.5"></div>
<div id="site"></div>
</code>```

CSS

```<code>#home-section {
    background-image: url(inspiration.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-attachment: fixed;
    width: 100%;
    height: 100vh;
    position: relative;
}
#site {
    height: 4000px;
    width: 100%;
    position: relative;
}
</code>```

JQ

```<code><script src="js/jquery-3.1.1.js"></script>
<script src="js/jquery.stellar.min.js"></script>
<script>
$.stellar();
</script>
</code>```

Here's a codepen.

答:
Since it is no longer supported, Stellar is not meant to be used with jQuery 3.x. You should see the following error thrown in your dev tools console (or something similar to this):

Uncaught TypeError: f.getClientRects is not a function

Use a version of jQuery 2.x and it will work without any further changes.

Title: Stellar js not working

Body:
I'm trying to create a parallax effect on my website, and I've followed the directions exactly as it says from the main source but it's still not working. Here are the code snippets.

HTML

CSS

#home-section {
    background-image: url(inspiration.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-attachment: fixed;
    width: 100%;
    height: 100vh;
    position: relative;
}
#site {
    height: 4000px;
    width: 100%;
    position: relative;
}

JQ

Here's a codepen.


问:
How to create n strings of random lengths the sum of which is equal to a given amount?
I'm trying to create an algorithm to create n strings of random length the sum of which is equal to a given amount.

An example to make it clearer:

```<code>total = 20;
n = 7;

strings = ['aaaa', 'a', 'aaaaaaa', 'aa', 'aaa', 'aa', 'a'];
</code>```

So I have 7 strings of random lengths and the sum of their individual lengths is (unless I made an error counting) 20.

Till now I came up with this recursive function:

```<code>gaps = [];
function createGapsArray(total, n) {
    if (n == 1) {
        var gapLength = total;
    } else {
        var gapLength = getRandomInt(1, total / 2);
    }

  var gap = "";
  for (var i = 0; i < gapLength; i++) {
    gap += "a";
  }
  gaps.push(gap);

  if (n > 1 && total > 0) {
    createGapsArray(total - gapLength, --n);
  }
}
</code>```

Which doesn't really work. Usually it finishes before generating all the n segments I want. With the few tests that I've done, it seems that dividing the total by 4 instead of 2, gets the job done. Like:

```<code>var gapLength = getRandomInt(1, total / 4);
</code>```

But the choice of this constraint is just arbitrary. I'm wondering if there is a better approach to this.

Also, I'm aware that with my approach the algorithm is likely to generate longer segments at first and smaller ones towards the end. I wouldn't mind an even distribution, but it's not a big deal because for what I need it I can simply shuffle the array once it's done.

答:
Strictly speaking, you can't do this, because you're adding constraints to at least the last "string" that violate the desired randomness property. Of course, how strictly you need to interpret the requirement for randomness depends largely on what you're doing in the bigger problem domain.

What you could do instead, is start with an initial string of the desired length, and then iteratively generate a random split point until you have the desired number of fragments. To be truly random, you'd have to allow for some of those fragments to be empty (e.g. what happens if you randomly pick a single-character fragment to split?), but that could probably be worked around without doing too much violence to the randomness of the overall result...

Body:
I'm trying to create an algorithm to create n strings of random length the sum of which is equal to a given amount.

An example to make it clearer:

total = 20;
n = 7;

strings = ['aaaa', 'a', 'aaaaaaa', 'aa', 'aaa', 'aa', 'a'];

So I have 7 strings of random lengths and the sum of their individual lengths is (unless I made an error counting) 20.

Till now I came up with this recursive function:

gaps = [];
function createGapsArray(total, n) {
    if (n == 1) {
        var gapLength = total;
    } else {
        var gapLength = getRandomInt(1, total / 2);
    }

  var gap = "";
  for (var i = 0; i < gapLength; i++) {
    gap += "a";
  }
  gaps.push(gap);

  if (n > 1 && total > 0) {
    createGapsArray(total - gapLength, --n);
  }
}

Which doesn't really work. Usually it finishes before generating all the n segments I want. With the few tests that I've done, it seems that dividing the total by 4 instead of 2, gets the job done. Like:

var gapLength = getRandomInt(1, total / 4);

But the choice of this constraint is just arbitrary. I'm wondering if there is a better approach to this.

Also, I'm aware that with my approach the algorithm is likely to generate longer segments at first and smaller ones towards the end. I wouldn't mind an even distribution, but it's not a big deal because for what I need it I can simply shuffle the array once it's done.


问:
How can I avoid global state?
So, I was reading the Google testing blog, and it says that global state is bad and makes it hard to write tests.  I believe it--my code is difficult to test right now.  So how do I avoid global state?

The biggest things I use global state (as I understand it) for is managing key pieces of information between our development, acceptance, and production environments.  For example, I have a static class named "Globals" with a static member called "DBConnectionString."  When the application loads, it determines which connection string to load, and populates Globals.DBConnectionString.  I load file paths, server names, and other information in the Globals class.

Some of my functions rely on the global variables.  So, when I test my functions, I have to remember to set certain globals first or else the tests will fail.  I'd like to avoid this.

Is there a good way to manage state information?  (Or am I understanding global state incorrectly?)

答:
Dependency injection is what you're looking for. Rather than have those functions go out and look for their dependencies, inject the dependencies into the functions. That is, when you call the functions pass the data they want to them. That way it's easy to put a testing framework around a class because you can simply inject mock objects where appropriate.

It's hard to avoid some global state, but the best way to do this is to use factory classes at the highest level of your application, and everything below that very top level is based on dependency injection.

Two main benefits: one, testing is a heck of a lot easier, and two, your application is much more loosely coupled. You rely on being able to program against the interface of a class rather than its implementation.

OwnerDisplayName: Jim

Title: How can I avoid global state?

OwnerDisplayName: Andrew


问:
Div with horizontal scrolling only
I have a fixed width DIV containing a table with many columns, and need to allow the user to scroll the table horizontally within the DIV.

This needs to work on IE6 and IE7 only (internal client application).

The following works in IE7:

```<code>overflow-x: scroll;
</code>```

Can anyone help with a solution that works in IE6 as well?

答:
```<code>overflow-x: scroll;
overflow-y: hidden;
</code>```

EDIT:

It works for me:

```<code><div style='overflow-x:scroll;overflow-y:hidden;width:250px;height:200px'>
    <div style='width:400px;height:250px'></div>
</div>
</code>```

OwnerDisplayName: Richard E

Title: Div with horizontal scrolling only

Body:
I have a fixed width DIV containing a table with many columns, and need to allow the user to scroll the table horizontally within the DIV.

This needs to work on IE6 and IE7 only (internal client application).

The following works in IE7:

overflow-x: scroll;

Can anyone help with a solution that works in IE6 as well?

Body:
overflow-x: scroll;
overflow-y: hidden;

EDIT:

It works for me:

<div style='overflow-x:scroll;overflow-y:hidden;width:250px;height:200px'>
    <div style='width:400px;height:250px'></div>
</div>

OwnerDisplayName: Diodeus

LastEditorDisplayName: Diodeus


问:
determining if a flash drive exists from a batch file without error messages
I have batch files with the construct:

```<code>if exist F:\ copy /y Application.exe F:\
</code>```

at the end of a compile, to copy the executable to a USB key if it is plugged in.  It has worked fine with USB keys but when I had a USB multi card reader plugged in (this looks like drives E:..H:, and if there is no SD card plugged in, when I execute the above batch line, I get a "Windows - no disk" snag message.

If there is a card plugged in, I don't get the message, (and the file is copied), if the card reader is not plugged in, I don't get the message and the file is not copied (obviously), but in neither of these cases does the batch file stop running.  It's only if the card reader is plugged in but there is no card in the drive.

Can I check quietly for no "disk" in these USB drives from a batch file?

答: I think that there used to be that you could run command.com with a /F parameter to make it always automatically fail those error messages so that it didn't break on them. Not sure about it though and not at all sure if that still works on modern Windows.

Body:
I have batch files with the construct:

if exist F:\ copy /y Application.exe F:\

at the end of a compile, to copy the executable to a USB key if it is plugged in.  It has worked fine with USB keys but when I had a USB multi card reader plugged in (this looks like drives E:..H:, and if there is no SD card plugged in, when I execute the above batch line, I get a "Windows - no disk" snag message.

If there is a card plugged in, I don't get the message, (and the file is copied), if the card reader is not plugged in, I don't get the message and the file is not copied (obviously), but in neither of these cases does the batch file stop running.  It's only if the card reader is plugged in but there is no card in the drive.

Can I check quietly for no "disk" in these USB drives from a batch file?


问:
when i type _ (underscore) in my search form based on php , why results still come out?
```<code>$i_name  = mysqli_real_escape_string($con,$_GET['search']);

$search_item = "SELECT * FROM items WHERE itemname LIKE '%$i_name%' ORDER by 1 DESC LIMIT 5";
$find_item  =  mysqli_query($con,$search_item);
$count_item =  mysqli_num_rows($find_item);
</code>```

What am I doing wrong?

答:
% is a wildcard to match an arbitrary number of characters (including zero characters). _ is a wildcard to match any single character.

So your LIKE evaluates to: an arbitrary number of characters followed by any single character followed by an arbitrary number of characters.  Which is anything that contains one or more characters.

You need to escape wildcards in $i_name using \% and \_.

See MySQL Pattern Matching

Body:
$i_name  = mysqli_real_escape_string($con,$_GET['search']);

$search_item = "SELECT * FROM items WHERE itemname LIKE '%$i_name%' ORDER by 1 DESC LIMIT 5";
$find_item  =  mysqli_query($con,$search_item);
$count_item =  mysqli_num_rows($find_item);

What am I doing wrong?


问:
MySQL : How to give a default value to a foreign key when I don't use it?
Right now I have a table that has two foreign key, both that reference to different tables. When I insert a value in one foreign key field, but not in the other one, my insert fails because the foreign key constraint. How can I give a default value, like NULL or 0, to a column that references a foreign key, when I am not using it, or make the foreign key optional? I am using MySQL and XAMPP for my tables.</p>

答:
First, if its a key it can not be optional also can not be null/default, its simple logic.
I don't remember how to but you could create a group of keys (composed key) then the pair  you can set a default value always that at least one of them is uniq:</p>

```<code><key1.a ,   0   >,
<key1.b ,   0   >,
<   0   , key2.a >,
<   0   , key2.b >,
<key1.a , key2.b >,
<key1.a , key2.c >,etc...
</code>```

Body:
First, if its a key it can not be optional also can not be null/default, its simple logic.
I don't remember how to but you could create a group of keys (composed key) then the pair  you can set a default value always that at least one of them is uniq:

<key1.a ,   0   >,
<key1.b ,   0   >,
<   0   , key2.a >,
<   0   , key2.b >,
<key1.a , key2.b >,
<key1.a , key2.c >,etc...


问:
Create Information content corpora to be used by webnet from a custom dump
I am using Brown corpus ic-brown.dat for calculating the information content of a word using wordnet nltk library. But results are not good looking. I was wondering how can i build my own custome.dat (information content file).</p>

```<code>custom_ic = wordnet_ic.ic('custom.dat')
</code>```

答:
In (...)/nltk_data/corpora/wordnet_ic/ you will find IC-compute.sh  that contains some calls to some Perl scripts to generate the IC dat files from a given corpus. I founded the instructions tricky, and I do not have the require Perl scripts, so I decided to create a python script by analyzing the dat files structure and wordnet.ic() function.

You can compute your own IC counts by calling the wordnet.ic() function over a corpus reader object. In fact, you only need an object with a word() function that returns all the words in the corpus. For more details check the ic function (line 1729 to 1789) in the file ..../nltk/corpus/reader/wordnet.py.

For example, for the XML version of the BNC corpus (2007):

```<code>reader_bnc = nltk.corpus.reader.BNCCorpusReader(root='../Corpus/2554/2554/download/Texts/', fileids=r'[A-K]/\w*/\w*\.xml')
bnc_ic = wn.ic(reader_bnc, False, 0.0)
</code>```

To generate the .dat file I created the following functions:

```<code>def is_root(synset_x):
    if synset_x.root_hypernyms()[0] == synset_x:
        return True
    return False

def generate_ic_file(IC, output_filename):
    """Dump in output_filename the IC counts.
    The expected format of IC is a dict
    {'v':defaultdict, 'n':defaultdict, 'a':defaultdict, 'r':defaultdict}"""
    with codecs.open(output_filename, 'w', encoding='utf-8') as fid:
        # Hash code of WordNet 3.0
        fid.write("wnver::eOS9lXC6GvMWznF1wkZofDdtbBU"+"\n")

        # We only stored nouns and verbs because those are the only POS tags
        # supported by wordnet.ic() function
        for tag_type in ['v', 'n']:#IC:
            for key, value in IC[tag_type].items():
                if key != 0:
                    synset_x = wn.of2ss(of="{:08d}".format(key)+tag_type)
                    if is_root(synset_x):
                        fid.write(str(key)+tag_type+" "+str(value)+" ROOT\n")
                    else:
                        fid.write(str(key)+tag_type+" "+str(value)+"\n")
    print("Done")

generate_ic_file(bnc_ic, "../custom.dat")
</code>```

Then, just call the function:

```<code>custom_ic = wordnet_ic.ic('../custom.dat')
</code>```

The imports needed are:

```<code>import nltk
from nltk.corpus import wordnet as wn
from nltk.corpus import wordnet_ic
import codecs
</code>```

Body:
I am using Brown corpus ic-brown.dat for calculating the information content of a word using wordnet nltk library. But results are not good looking. I was wondering how can i build my own custome.dat (information content file).

custom_ic = wordnet_ic.ic('custom.dat')

Body:
In (...)/nltk_data/corpora/wordnet_ic/ you will find IC-compute.sh  that contains some calls to some Perl scripts to generate the IC dat files from a given corpus. I founded the instructions tricky, and I do not have the require Perl scripts, so I decided to create a python script by analyzing the dat files structure and wordnet.ic() function.

You can compute your own IC counts by calling the wordnet.ic() function over a corpus reader object. In fact, you only need an object with a word() function that returns all the words in the corpus. For more details check the ic function (line 1729 to 1789) in the file ..../nltk/corpus/reader/wordnet.py.

For example, for the XML version of the BNC corpus (2007):

reader_bnc = nltk.corpus.reader.BNCCorpusReader(root='../Corpus/2554/2554/download/Texts/', fileids=r'[A-K]/\w*/\w*\.xml')
bnc_ic = wn.ic(reader_bnc, False, 0.0)

To generate the .dat file I created the following functions:

def is_root(synset_x):
    if synset_x.root_hypernyms()[0] == synset_x:
        return True
    return False

def generate_ic_file(IC, output_filename):
    """Dump in output_filename the IC counts.
    The expected format of IC is a dict
    {'v':defaultdict, 'n':defaultdict, 'a':defaultdict, 'r':defaultdict}"""
    with codecs.open(output_filename, 'w', encoding='utf-8') as fid:
        # Hash code of WordNet 3.0
        fid.write("wnver::eOS9lXC6GvMWznF1wkZofDdtbBU"+"\n")

        # We only stored nouns and verbs because those are the only POS tags
        # supported by wordnet.ic() function
        for tag_type in ['v', 'n']:#IC:
            for key, value in IC[tag_type].items():
                if key != 0:
                    synset_x = wn.of2ss(of="{:08d}".format(key)+tag_type)
                    if is_root(synset_x):
                        fid.write(str(key)+tag_type+" "+str(value)+" ROOT\n")
                    else:
                        fid.write(str(key)+tag_type+" "+str(value)+"\n")
    print("Done")

generate_ic_file(bnc_ic, "../custom.dat")

Then, just call the function:

custom_ic = wordnet_ic.ic('../custom.dat')

The imports needed are:

import nltk
from nltk.corpus import wordnet as wn
from nltk.corpus import wordnet_ic
import codecs


问:
How to see real call stack in WinDbg when we break with CTRL + Break
When we have a regular breakpoint, the debugger breaks there and we see the call stack. But what if we break the execution using CTRL + Break? I would expect the currently running thread to break whererbrt it was but what I see typically is the following:

```<code> # ChildEBP RetAddr
00 02b7fdc4 7762f216 ntdll!DbgBreakPoint
01 02b7fdf4 76c0336a ntdll!DbgUiRemoteBreakin+0x3c
02 02b7fe00 775c9902 kernel32!BaseThreadInitThunk+0xe
03 02b7fe40 775c98d5 ntdll!__RtlUserThreadStart+0x70
04 02b7fe58 00000000 ntdll!_RtlUserThreadStart+0x1b
*** WARNING: Unable to verify checksum for ThreadDemo.exe
</code>```

But how do I get to the actual code of current thread that got interrupted?

I am running a long loop as below which takes sometime and I expect it to break there.

```<code>void Bank::Deposit(void* param)
{
    Bank * bank = (Bank *)param;

    char *who = (char*) bank->bankName;

    int i;
    printf("%s: begin deposite\n", who);
    for (i = 0; i < 1000000000; i++) {
        bank->balance = bank->balance + 1;
    }
    printf("%s: done\n", who);

    return;
}
</code>```

In this case when it breaks, one of the other thread does break in this function but this is a simple demo. How can I know in real windows application where did the application really stopped (and what was it doing) when I have many threads?

答:
There is no 'current thread that is running' when you hit ctrl-c. Zero, one or more threads may be running and so the debugger doesn't even try to work out 'which' one to break - it instead breaks in its own thread. Just because you have a single thread which is probably running at the time (but not necessarily so) doesn't change this.

But you can get what you want. When you hit ctrl-c it breaks the debugger thread and stops all other threads. You can list all threads and their callstacks by typing:

~*k

You can also switch to another thread by typing:

~Ns

where N is the ID of the thread to switch to.

Once you've set the 'current thread' to the one you want, you can type k to list its callstack and other thread specific commands.

EDIT:

see this for a decent list of windbg thread specific commands

Body:
When we have a regular breakpoint, the debugger breaks there and we see the call stack. But what if we break the execution using CTRL + Break? I would expect the currently running thread to break whererbrt it was but what I see typically is the following:

 # ChildEBP RetAddr
00 02b7fdc4 7762f216 ntdll!DbgBreakPoint
01 02b7fdf4 76c0336a ntdll!DbgUiRemoteBreakin+0x3c
02 02b7fe00 775c9902 kernel32!BaseThreadInitThunk+0xe
03 02b7fe40 775c98d5 ntdll!__RtlUserThreadStart+0x70
04 02b7fe58 00000000 ntdll!_RtlUserThreadStart+0x1b
*** WARNING: Unable to verify checksum for ThreadDemo.exe

But how do I get to the actual code of current thread that got interrupted?

I am running a long loop as below which takes sometime and I expect it to break there.

void Bank::Deposit(void* param)
{
    Bank * bank = (Bank *)param;

    char *who = (char*) bank->bankName;

    int i;
    printf("%s: begin deposite\n", who);
    for (i = 0; i < 1000000000; i++) {
        bank->balance = bank->balance + 1;
    }
    printf("%s: done\n", who);

    return;
}

In this case when it breaks, one of the other thread does break in this function but this is a simple demo. How can I know in real windows application where did the application really stopped (and what was it doing) when I have many threads?


问:
Updating gui with JNativeHook?
I'm trying to update my GUI (for example changing text/color of jButton and jLabel via hotkey) using jnativehooks so it updates my GUI when I press a hotkey, however after hours of searching and trying, I'm still not having any luck.

I have tried revalidate/validate/repaint etc but doesn't seem to be working (its calling the hotkey f9 and running the script in that section fine as it prints out the system.out), I'm a novice so I must be missing something simple :(

Here is my project (from scratch so only essentials, with the jnativehook library): https://www.dropbox.com/sh/keyp0tb2nobjg8t/AABOUQFqBWETRoX9D1vtcZe2a?dl=0

main.java: https://www.dropbox.com/sh/keyp0tb2nobjg8t/AAA0aib7y_k0uKtJ4sbnYHN7a/src?dl=0&preview=Main.java

Any help would be appreciated.

Main class code for anyone that cant view dropbox: https://hastebin.com/uqarilawop.java (too many indenting to post on stackoverflow as I dont know what I'm missing)

答:
You are not using the library in a Thread safe way for Swing.  All UI events occur on the Swing Dispatch thread so you need to switch the native library to use Swing instead of its built in dispatcher!  Please see https://github.com/kwhat/jnativehook/wiki/Swing

// Set the event dispatcher to a swing safe executor service.
GlobalScreen.setEventDispatcher(new SwingDispatchService());

Title: Updating gui with JNativeHook?


问:
Shopify webhook failing to return a successful response
I have created shopify app in which I have used webhooks for checkout/update. Webhook is working fine but I am getting this error message.

Your webhook for checkouts/update
  at https://www.smsblitz.io/smsblitz/abondoned?shop=smsblitz.myshopify.com&user=iman%5Egemconsultinginc.org is
  failing to return a successful response.This webhook has been
  attempted 23 times. If your webhook continues to fail, it will be
  removed and your application will not receive any more notifications.

Please help me to solve this issue.

Thanks

答:
Your webhook is not working fine. It is failing to respond to Shopify. So until you fix that, Shopify is counting the failures and letting you know, that soon, they will just stop that Webhook, and you'll have to recreate it. </p>

<p>To solve the issue, POST a webhook to your endpoint and verify it returns a 200 OK. </p>

Body:
Your webhook is not working fine. It is failing to respond to Shopify. So until you fix that, Shopify is counting the failures and letting you know, that soon, they will just stop that Webhook, and you'll have to recreate it.

To solve the issue, POST a webhook to your endpoint and verify it returns a 200 OK.


问:
camel java dsl pass bean method return value to header
Java - Apache Camel 2.17 JAVA DSL

My route process the data and return the dates it processed, i want to pass List<LocalDate> returned from myBean.processData to the log and set in header.

following is my code

```<code>from("route1")
.bean("myBean","processData")
.log("how do i log the response of processData return")
. setHeader("processDataReturnValue") // how can pass processData return
</code>```

value to header ?

答:
The following code is what you are looking for:

```<code>from("route1")
   .bean("myBean","processData")
   .log("***** processData return value: ${body.toString()} *****")
   .setHeader("myHeader", body());
</code>```

From "Camel in Action" ch. 4. Using beans with Camel:

"At runtime, a Camel exchange is routed, and at a given point in the route, it reaches the BeanProcessor. The BeanProcessor then processes the exchange, performing these general steps:

Looks up the bean in the registry

Selects the method to invoke on the bean

Binds to the parameters of the selected method (for example, using the body of the input message as a parameter; this is covered in detail in section 4.5)

Invokes the method

Handles any invocation errors that occur (any exceptions thrown from the bean will be set on the Camel exchange for further error handling)

Sets the method’s reply (if there is one) as the body on the output message on the Camel exchange

I have tested the route using MyBean similar to:

```<code>@Component
public class MyBean {

    public List<LocalDate> processData(Exchange exchange) {
        return Lists.newArrayList(LocalDate.now(),
                   LocalDate.now().minusYears(1L));
   }
}
</code>```

P.S. I would consider hiding logging, setting headers and actual bean invocation in a processor.

Body:
Java - Apache Camel 2.17 JAVA DSL

My route process the data and return the dates it processed, i want to pass List<LocalDate> returned from myBean.processData to the log and set in header.

following is my code

from("route1")
.bean("myBean","processData")
.log("how do i log the response of processData return")
. setHeader("processDataReturnValue") // how can pass processData return

value to header ?

Body:
The following code is what you are looking for:

from("route1")
   .bean("myBean","processData")
   .log("***** processData return value: ${body.toString()} *****")
   .setHeader("myHeader", body());

From "Camel in Action" ch. 4. Using beans with Camel:

"At runtime, a Camel exchange is routed, and at a given point in the route, it reaches the BeanProcessor. The BeanProcessor then processes the exchange, performing these general steps:

Looks up the bean in the registry

Selects the method to invoke on the bean

Binds to the parameters of the selected method (for example, using the body of the input message as a parameter; this is covered in detail in section 4.5)

Invokes the method

Handles any invocation errors that occur (any exceptions thrown from the bean will be set on the Camel exchange for further error handling)

Sets the method’s reply (if there is one) as the body on the output message on the Camel exchange

I have tested the route using MyBean similar to:

@Component
public class MyBean {

    public List<LocalDate> processData(Exchange exchange) {
        return Lists.newArrayList(LocalDate.now(),
                   LocalDate.now().minusYears(1L));
   }
}

P.S. I would consider hiding logging, setting headers and actual bean invocation in a processor.


问:
How to edit a cell and delete a row by clicking icon in Angular JS 1.3?
Still be a angular learner.

I have my page like

The code is:

```<code>    @{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div ng-controller="EmpCtrl">
    <div>
        <h2 align="center">Angular JS Basic Example</h2>
        <h5 align="center">Employee List</h5>
        <table border="1" cellpadding="10" align="center">
            <tr>
                <th>
                    Edit
                </th>
                <th>
                    Employee Id
                </th>
                <th>
                    Employee Name
                </th>
                <th>
                    Address
                </th>
                <th>
                    Email Id
                </th>
                <th>
                    Delete
                </th>
            </tr>
            <tr ng-repeat="emp in employees">
                <td>
                    <a href="#" class="btn btn-default btn-sm">
                        <i class="glyphicon glyphicon-edit"></i>
                    </a>
                </td>
                <td>
                    {{emp.EmployeeId}}
                </td>
                <td>
                    {{emp.EmployeeName}}
                </td>
                <td>
                    {{emp.Address}}
                </td>
                <td>
                    {{emp.EmailId}}
                </td>
                <td>
                    <a href="#"
                       onclick="return confirm('Delete this Employee?');"
                       class="btn btn-default btn-sm">
                        <i class="glyphicon glyphicon-trash"></i>
                    </a>
                </td>
            </tr>
        </table>
    </div>
</div>
</code>```

I have the js code for getting all employees. It works well.

```<code>app.controller("EmpCtrl", function ($scope, EmployeeService) {
GetAllEmployee();

function GetAllEmployee() {

    var getAllEmployee = EmployeeService.getEmployee();
    getAllEmployee.then(function (emp) {
        $scope.employees = emp.data;
    }, function () {
        alert('Data not found');
    });
 }
});
</code>```

My asp mvc service code to delete methos is

```<code> [HttpDelete]
    public void DeleteEmployee(int id)
    {
        using (DatabaseContext db = new DatabaseContext())
        {
            var employeeList = db.EmployeeModels.ToList();
            var temp = employeeList.Find(x => x.EmployeeId == id);
            employeeList.Remove(temp);
            db.SaveChanges();
        }
    }
</code>```

I want to click the edit/delete icon to edit or delete, I guess that I have to add other javascript functions to do that.(Maybe ng-clcik??) But I don't know exactly, so how to edit a cell or delete a row?

答:
This will depend on how your UI looks. Delete is easy, just declare a function in your controller and pass the index of the row to the function like this:

In your controller:

```<code>$scope.delFn = function(index){
     var response = confirm('Delete this Employee?');
     if(response) {
     $scope.employees.splice(index, 1);
   }
}
</code>```

In your view: instead of onclick, use ng-click

```<code>  <td>
     <a href="#"
        ng-click="delFn($index)"
        class="btn btn-default btn-sm">
        <i class="glyphicon glyphicon-trash"></i>
      </a>
  </td>
</code>```

where $index is implicitly available from ng-repeat. Or you can do this to make it explicit stated.

```<code><tr ng-repeat="emp in employees track by $index">
</code>```

Can you figure out the edit yourself? since you are using table tag. It looks like you can make a popup/modal, pass in the index of the row in your edit function, get the selected employee from $scope.employees, display the selected one in the popup and make it editable with input tag.

Body:
Still be a angular learner.

I have my page like

The code is:

    @{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Angular JS Basic Example

Employee List

                    Edit

                    Employee Id

                    Employee Name

                    Address

                    Email Id

                    Delete

                    {{emp.EmployeeId}}

                    {{emp.EmployeeName}}

                    {{emp.Address}}

                    {{emp.EmailId}}

I have the js code for getting all employees. It works well.

app.controller("EmpCtrl", function ($scope, EmployeeService) {
GetAllEmployee();

function GetAllEmployee() {

    var getAllEmployee = EmployeeService.getEmployee();
    getAllEmployee.then(function (emp) {
        $scope.employees = emp.data;
    }, function () {
        alert('Data not found');
    });
 }
});

My asp mvc service code to delete methos is

 [HttpDelete]
    public void DeleteEmployee(int id)
    {
        using (DatabaseContext db = new DatabaseContext())
        {
            var employeeList = db.EmployeeModels.ToList();
            var temp = employeeList.Find(x => x.EmployeeId == id);
            employeeList.Remove(temp);
            db.SaveChanges();
        }
    }

I want to click the edit/delete icon to edit or delete, I guess that I have to add other javascript functions to do that.(Maybe ng-clcik??) But I don't know exactly, so how to edit a cell or delete a row?

Body:
This will depend on how your UI looks. Delete is easy, just declare a function in your controller and pass the index of the row to the function like this:

In your controller:

$scope.delFn = function(index){
     var response = confirm('Delete this Employee?');
     if(response) {
     $scope.employees.splice(index, 1);
   }
}

In your view: instead of onclick, use ng-click

  <td>
     <a href="#"
        ng-click="delFn($index)"
        class="btn btn-default btn-sm">
        <i class="glyphicon glyphicon-trash"></i>
      </a>
  </td>

where $index is implicitly available from ng-repeat. Or you can do this to make it explicit stated.

<tr ng-repeat="emp in employees track by $index">

Can you figure out the edit yourself? since you are using table tag. It looks like you can make a popup/modal, pass in the index of the row in your edit function, get the selected employee from $scope.employees, display the selected one in the popup and make it editable with input tag.