问:
DoEvent() Returns 0 BUT Run-time Error 2585 This action can't be carried out while processing a form or report event
This code was running without a hitch, but now getting Error 2585.

I have looked at Gustav's answer and Gord Thompson's answer but unless I am missing something (quite possible!) the first does not work and the second seems inapplicable. I saw on another site a suggestion that there might be a duplicate record ID, but I check for that possibility.

I put a call to DoEvent() in response to this error but it returns zero. I also wait for 10 seconds to let other processes run. Still receive the error.

```<code>Private Sub SaveData_Click()
  Dim myForm As Form
  Dim myTextBox As TextBox
  Dim myDate As Date
  Dim myResponse As Integer

If IsNull(Forms!Ecoli_Data!DateCollected.Value) Then

  myReponse = myResponse = MsgBox("You have not entered all the required data. You may quit data entry by hitting 'Cancel'", vbOKOnly, "No Sample Date")
  Forms!Ecoli_Data.SetFocus
  Forms!Ecoli_Data!Collected_By.SetFocus
  GoTo endOfSub
End If

If Me.Dirty Then Me.Dirty = False

myDate = Me.DateCollected.Value

Dim yearAsString As String, monthAsString As String, dayAsString As String, clientInitial As String

Dim reportNumberText As String

reportNumberText = Me!SampleNumber.Value
Debug.Print "reportNumberText = " & reportNumberText

Debug.Print "CollectedBy Index: " & Me!Collected_By & " Employee Name: " & DLookup("CollectedBy", "Data_Lookup", Me.Collected_By)

Dim whereString As String
whereString = "SampleNumber=" & "'" & reportNumberText & "'"
Debug.Print whereString
On Error GoTo errorHandling
DoCmd.OpenReport "ECOLI_Laboratory_Report", acViewPreview, , whereString
DoCmd.PrintOut
DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo

Dim eventsOpen As Integer
eventsOpen = DoEvents()
Debug.Print "Number of Open Events = " & DoEvents()

    Dim PauseTime, Start, Finish, TotalTime

        PauseTime = 10    ' Set duration.
        Start = Timer    ' Set start time.
        Do While Timer < Start + PauseTime
            DoEvents    ' Yield to other processes.
        Loop
        Finish = Timer    ' Set end time.
        TotalTime = Finish - Start  ' Calculate total time.
    myResponse = MsgBox("Processing Report Took " & TotalTime & " seconds.", vbOKOnly)

myResponse = MsgBox("Do you want to add more data?", vbYesNo, "What Next?")

If myResponse = vbYes Then

    DoCmd.Close acForm, "ECOLI_Data", acSaveYes
</code>```

Error Generated By Line Above and occurs whether response Y or N to MsgBox.

```<code>    DoCmd.OpenForm "ECOLI_Data", acNormal, , , acFormAdd
    DoCmd.GoToRecord , , acNewRec
Else
    DoCmd.Close acForm, "ECOLI_Data", acSaveYes

End If
Exit Sub

 errorHandling:
 If Err.Number = 2501 Then
   myResponse = MsgBox("Printing Job Cancelled", vbOkayOnly, "Report Not Printed")
ElseIf Err.Number = 0 Then
   'Do nothing
Else
   Debug.Print "Error Number: " & Err.Number & ": " & Err.Description

   myResponse = MsgBox("An Error occurred: " & Err.Description, vbOKOnly, "Error #" & Err.Number)
End If

If Application.CurrentProject.AllForms("ECOLI_Data").IsLoaded Then DoCmd.Close acForm, "ECOLI_Data", acSaveNo

If Application.CurrentProject.AllReports("ECOLI_Laboratory_Report").IsLoaded     Then DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo

endOfSub:
End Sub
</code>```

Any idea on what am I missing here? Thanks.

答:
I can't replicate the problem, but the following might help:

I assume you run into troubles because you're closing and opening the form in the same operation. To avoid doing this, you can open up a second copy of the form, and close the form once the second copy is open. This avoids that issue.

To open a second copy of the form:

```<code>Public Myself As Form

Public Sub CopyMe()
    Dim myCopy As New Form_CopyForm
    myCopy.Visible = True
    Set myCopy.Myself = myCopy
End Sub
</code>```

(CopyForm is the form name)

To close a form that may or may not be a form created by this function

```<code>Public Sub CloseMe()
    If Myself Is Nothing Then
        DoCmd.Close acForm, Me.Name
    Else
        Set Myself = Nothing
    End If
End Sub
</code>```

More information on having multiple variants of the same form open can be found here, but my approach differs from the approach suggested here, and doesn't require a second object to hold references and manage copies.

Body:
This code was running without a hitch, but now getting Error 2585.

I have looked at Gustav's answer and Gord Thompson's answer but unless I am missing something (quite possible!) the first does not work and the second seems inapplicable. I saw on another site a suggestion that there might be a duplicate record ID, but I check for that possibility.

I put a call to DoEvent() in response to this error but it returns zero. I also wait for 10 seconds to let other processes run. Still receive the error.

Private Sub SaveData_Click()
  Dim myForm As Form
  Dim myTextBox As TextBox
  Dim myDate As Date
  Dim myResponse As Integer

If IsNull(Forms!Ecoli_Data!DateCollected.Value) Then

  myReponse = myResponse = MsgBox("You have not entered all the required data. You may quit data entry by hitting 'Cancel'", vbOKOnly, "No Sample Date")
  Forms!Ecoli_Data.SetFocus
  Forms!Ecoli_Data!Collected_By.SetFocus
  GoTo endOfSub
End If

If Me.Dirty Then Me.Dirty = False

myDate = Me.DateCollected.Value

Dim yearAsString As String, monthAsString As String, dayAsString As String, clientInitial As String

Dim reportNumberText As String

reportNumberText = Me!SampleNumber.Value
Debug.Print "reportNumberText = " & reportNumberText

Debug.Print "CollectedBy Index: " & Me!Collected_By & " Employee Name: " & DLookup("CollectedBy", "Data_Lookup", Me.Collected_By)

Dim whereString As String
whereString = "SampleNumber=" & "'" & reportNumberText & "'"
Debug.Print whereString
On Error GoTo errorHandling
DoCmd.OpenReport "ECOLI_Laboratory_Report", acViewPreview, , whereString
DoCmd.PrintOut
DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo

Dim eventsOpen As Integer
eventsOpen = DoEvents()
Debug.Print "Number of Open Events = " & DoEvents()

    Dim PauseTime, Start, Finish, TotalTime

        PauseTime = 10    ' Set duration.
        Start = Timer    ' Set start time.
        Do While Timer < Start + PauseTime
            DoEvents    ' Yield to other processes.
        Loop
        Finish = Timer    ' Set end time.
        TotalTime = Finish - Start  ' Calculate total time.
    myResponse = MsgBox("Processing Report Took " & TotalTime & " seconds.", vbOKOnly)

myResponse = MsgBox("Do you want to add more data?", vbYesNo, "What Next?")

If myResponse = vbYes Then

    DoCmd.Close acForm, "ECOLI_Data", acSaveYes

Error Generated By Line Above and occurs whether response Y or N to MsgBox.

    DoCmd.OpenForm "ECOLI_Data", acNormal, , , acFormAdd
    DoCmd.GoToRecord , , acNewRec
Else
    DoCmd.Close acForm, "ECOLI_Data", acSaveYes

End If
Exit Sub

 errorHandling:
 If Err.Number = 2501 Then
   myResponse = MsgBox("Printing Job Cancelled", vbOkayOnly, "Report Not Printed")
ElseIf Err.Number = 0 Then
   'Do nothing
Else
   Debug.Print "Error Number: " & Err.Number & ": " & Err.Description

   myResponse = MsgBox("An Error occurred: " & Err.Description, vbOKOnly, "Error #" & Err.Number)
End If

If Application.CurrentProject.AllForms("ECOLI_Data").IsLoaded Then DoCmd.Close acForm, "ECOLI_Data", acSaveNo

If Application.CurrentProject.AllReports("ECOLI_Laboratory_Report").IsLoaded     Then DoCmd.Close acReport, "ECOLI_Laboratory_Report", acSaveNo

endOfSub:
End Sub

Any idea on what am I missing here? Thanks.

Body:
I can't replicate the problem, but the following might help:

I assume you run into troubles because you're closing and opening the form in the same operation. To avoid doing this, you can open up a second copy of the form, and close the form once the second copy is open. This avoids that issue.

To open a second copy of the form:

Public Myself As Form

Public Sub CopyMe()
    Dim myCopy As New Form_CopyForm
    myCopy.Visible = True
    Set myCopy.Myself = myCopy
End Sub

(CopyForm is the form name)

To close a form that may or may not be a form created by this function

Public Sub CloseMe()
    If Myself Is Nothing Then
        DoCmd.Close acForm, Me.Name
    Else
        Set Myself = Nothing
    End If
End Sub

More information on having multiple variants of the same form open can be found here, but my approach differs from the approach suggested here, and doesn't require a second object to hold references and manage copies.


来源: stackexchange

问:
TFS2018 web edit Build Definition Template
I am using TFS2018 and I have saved a build definition template. Is there a way to edit the template?</p>

答:
Not directly using the website.
You could do 2 things:

a) Create new Build from the existing template, edit and save as Template.
This can be done with the website.

b) Use the rest-api to update your template: Create or update a build definition template - visualstudio.com

ContentLicense: CC BY-SA 3.0


问:
How To Select multiple cells in DataGridView
I have a DataGridView in my Form. The Functionality is as below.

Clicking on header selects the whole column.

Clicking on any cell other than the column header selects the entire row

I have set multiselect to true. I am able to select multiple cells by using the mouse. but I want to do it programmatically.

答:
It's important to allow the DataGridView to complete loading its data before attempting to select (multiple) items. You can do that in the DataBindingComplete event handler.
Here's a working example:</p>

```<code>    List<int> items = new List<int>() { 2, 4 };
    private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        dataGridView1.ClearSelection();

        int lastItem = 0; // Save the last match to scroll to it later
        bool cellSelected = false;

        for (int i = dataGridView1.Rows.Count - 1; i >= 0; i--)
        {
            if (items.Contains((int)dataGridView1.Rows[i].Cells[0].Value))
            {
                lastItem = i;

                dataGridView1.Rows[i].Selected = true;

                if (!cellSelected) // gotta select only one cell
                {
                    dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0];
                    cellSelected = true;
                }
            }
        }

        dataGridView1.FirstDisplayedScrollingRowIndex = lastItem;
    }
</code>```

Body:
It's important to allow the DataGridView to complete loading its data before attempting to select (multiple) items. You can do that in the DataBindingComplete event handler.
Here's a working example:

    List<int> items = new List<int>() { 2, 4 };
    private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        dataGridView1.ClearSelection();

        int lastItem = 0; // Save the last match to scroll to it later
        bool cellSelected = false;

        for (int i = dataGridView1.Rows.Count - 1; i >= 0; i--)
        {
            if (items.Contains((int)dataGridView1.Rows[i].Cells[0].Value))
            {
                lastItem = i;

                dataGridView1.Rows[i].Selected = true;

                if (!cellSelected) // gotta select only one cell
                {
                    dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0];
                    cellSelected = true;
                }
            }
        }

        dataGridView1.FirstDisplayedScrollingRowIndex = lastItem;
    }


问:
Code Golf: Finite-state machine!

Finite state machine

A deterministic finite state machine is a simple computation model, widely used as an introduction to automata theory in basic CS courses. It is a simple model, equivalent to regular expression, which determines of a certain input string is Accepted or Rejected. Leaving some formalities aside, A run of a finite state machine is composed of:

alphabet, a set of characters.

states, usually visualized as circles. One of the states must be the start state. Some of the states might be accepting, usually visualized as double circles.

transitions, usually visualized as directed arches between states, are directed links between states associated with an alphabet letter.

input string, a list of alphabet characters.

A run on the machine begins at the starting state. Each letter of the input string is read; If there is a transition between the current state and another state which corresponds to the letter, the current state is changed to the new state. After the last letter was read, if the current state is an accepting state, the input string is accepted. If the last state was not an accepting state, or a letter had no corresponding arch from a state during the run, the input string is rejected.

Note: This short descruption is far from being a full, formal definition of a FSM; Wikipedia's fine article is a great introduction to the subject.

Example

For example, the following machine tells if a binary number, read from left to right, has an even number of 0s:

The alphabet is the set {0,1}.

The states are S1 and S2.

The transitions are (S1, 0) -> S2, (S1, 1) -> S1, (S2, 0) -> S1 and (S2, 1) -> S2.

The input string is any binary number, including an empty string.

The rules:

Implement a FSM in a language of your choice.

Input

The FSM should accept the following input:

```<code><States>       List of state, separated by space mark.
               The first state in the list is the start state.
               Accepting states begin with a capital letter.
<transitions>  One or more lines.
               Each line is a three-tuple:
               origin state, letter, destination state)
<input word>   Zero or more characters, followed by a newline.
</code>```

For example, the aforementioned machine with 1001010 as an input string, would be written as:

```<code>S1 s2
S1 0 s2
S1 1 S1
s2 0 S1
s2 1 s2
1001010
</code>```

Output

The FSM's run, written as <State> <letter> -> <state>, followed by the final state. The output for the example input would be:

```<code>S1 1 -> S1
S1 0 -> s2
s2 0 -> S1
S1 1 -> S1
S1 0 -> s2
s2 1 -> s2
s2 0 -> S1
ACCEPT
</code>```

For the empty input '':

```<code>S1
ACCEPT
</code>```

Note: Following your comments, the S1 line (showing the first state) might be omitted, and the following output is also acceptable:

```<code>ACCEPT
</code>```

For 101:

```<code>S1 1 -> S1
S1 0 -> s2
s2 1 -> s2
REJECT
</code>```

For '10X':

```<code>S1 1 -> S1
S1 0 -> s2
s2 X
REJECT
</code>```

Prize

A 250 rep bounty will be given to the shortest solution.

Reference implementation

A reference Python implementation is available here. Note that output requirements have been relaxed for empty-string input.

Addendum

Output format

Following popular demand, the following output is also acceptable for empty input string:

```<code>ACCEPT
</code>```

or

```<code>REJECT
</code>```

Without the first state written in the previous line.

State names

Valid state names are an English letter followed by any number of letters, _ and digits, much like variable names, e.g. State1, state0, STATE_0.

Input format

Like most code golfs, you can assume your input is correct.

Summary of answers:

Cobol - 4078 characters

Python - 171 characters, 568 characters, 203 characters, 218 characters, 269 characters

sed - 137 characters

ruby - 145 characters, 183 characters

Haskell - 192 characters, 189 characters

LISP - 725 characters

Perl - 184 characters

Bash - 184 characters

Rexx - 205 characters

Lua - 356 characters

F# - 420 characters

C# - 356 characters

Mixal - 898 characters

The sed 137 solution is the shortest, ruby 145 is #2. Currently, I can't get the sed solution to work:

```<code>cat test.fsm | sed -r solution.sed
sed -r solution.sed test.fsm
</code>```

both gave me:

```<code>S1 s2
S1 0 s2
S1 1 S1
s2 0 S1
s2 1 s2
1001010
</code>```0

so unless It there are clarifications the bounty goes to the ruby solution.

答:
bash - 186 185 184 chars

```declare -A a
read s x
while read f m t&&[ $m ];do a[$f $m]=$t;done
for((i=0;i-${#f};i++))do b="$s ${f:i:1}";s=${a[$b]};echo $b -\> $s;done
[ "$s" = "${s,}" ]&&echo REJECT||echo ACCEPT```

Note that this does actually require bash - POSIX sh doesn't have associative arrays or the C-style for syntax (and probably doesn't have all the parameter expansions used either, although I haven't checked).

Edit: alternatively, for the exact same length,

```declare -A a
read s x
while read f m t&&[ $m ];do a[$f $m]=$t;done
while [ $f ];do b="$s ${f:i:1}";f=${f:1};s=${a[$b]};echo $b -\> $s;done
[ "$s" = "${s,}" ]&&echo REJECT||echo ACCEPT```

ContentLicense: CC BY-SA 2.5

Title: Code Golf: Finite-state machine!

Body:
Finite state machine

A deterministic finite state machine is a simple computation model, widely used as an introduction to automata theory in basic CS courses. It is a simple model, equivalent to regular expression, which determines of a certain input string is Accepted or Rejected. Leaving some formalities aside, A run of a finite state machine is composed of:

alphabet, a set of characters.

states, usually visualized as circles. One of the states must be the start state. Some of the states might be accepting, usually visualized as double circles.

transitions, usually visualized as directed arches between states, are directed links between states associated with an alphabet letter.

input string, a list of alphabet characters.

A run on the machine begins at the starting state. Each letter of the input string is read; If there is a transition between the current state and another state which corresponds to the letter, the current state is changed to the new state. After the last letter was read, if the current state is an accepting state, the input string is accepted. If the last state was not an accepting state, or a letter had no corresponding arch from a state during the run, the input string is rejected.

Note: This short descruption is far from being a full, formal definition of a FSM; Wikipedia's fine article is a great introduction to the subject.

Example

For example, the following machine tells if a binary number, read from left to right, has an even number of 0s:

The alphabet is the set {0,1}.

The states are S1 and S2.

The transitions are (S1, 0) -> S2, (S1, 1) -> S1, (S2, 0) -> S1 and (S2, 1) -> S2.

The input string is any binary number, including an empty string.

The rules:

Implement a FSM in a language of your choice.

Input

The FSM should accept the following input:

<States>       List of state, separated by space mark.
               The first state in the list is the start state.
               Accepting states begin with a capital letter.
<transitions>  One or more lines.
               Each line is a three-tuple:
               origin state, letter, destination state)
<input word>   Zero or more characters, followed by a newline.

For example, the aforementioned machine with 1001010 as an input string, would be written as:

S1 s2
S1 0 s2
S1 1 S1
s2 0 S1
s2 1 s2
1001010

Output

The FSM's run, written as <State> <letter> -> <state>, followed by the final state. The output for the example input would be:

S1 1 -> S1
S1 0 -> s2
s2 0 -> S1
S1 1 -> S1
S1 0 -> s2
s2 1 -> s2
s2 0 -> S1
ACCEPT

For the empty input '':

S1
ACCEPT

Note: Following your comments, the S1 line (showing the first state) might be omitted, and the following output is also acceptable:

ACCEPT

For 101:

S1 1 -> S1
S1 0 -> s2
s2 1 -> s2
REJECT

For '10X':

S1 1 -> S1
S1 0 -> s2
s2 X
REJECT

Prize

A 250 rep bounty will be given to the shortest solution.

Reference implementation

A reference Python implementation is available here. Note that output requirements have been relaxed for empty-string input.

Addendum

Output format

Following popular demand, the following output is also acceptable for empty input string:

ACCEPT

or

REJECT

Without the first state written in the previous line.

State names

Valid state names are an English letter followed by any number of letters, _ and digits, much like variable names, e.g. State1, state0, STATE_0.

Input format

Like most code golfs, you can assume your input is correct.

Summary of answers:

Cobol - 4078 characters

Python - 171 characters, 568 characters, 203 characters, 218 characters, 269 characters

sed - 137 characters

ruby - 145 characters, 183 characters

Haskell - 192 characters, 189 characters

LISP - 725 characters

Perl - 184 characters

Bash - 184 characters

Rexx - 205 characters

Lua - 356 characters

F# - 420 characters

C# - 356 characters

Mixal - 898 characters

The sed 137 solution is the shortest, ruby 145 is #2. Currently, I can't get the sed solution to work:

cat test.fsm | sed -r solution.sed
sed -r solution.sed test.fsm

both gave me:

sed: -e expression #1, char 12: unterminated `s' command

so unless It there are clarifications the bounty goes to the ruby solution.

Body:
bash - 186 185 184 chars

declare -A a
read s x
while read f m t&&[ $m ];do a[$f $m]=$t;done
for((i=0;i-${#f};i++))do b="$s ${f:i:1}";s=${a[$b]};echo $b -\> $s;done
[ "$s" = "${s,}" ]&&echo REJECT||echo ACCEPT

Note that this does actually require bash - POSIX sh doesn't have associative arrays or the C-style for syntax (and probably doesn't have all the parameter expansions used either, although I haven't checked).

Edit: alternatively, for the exact same length,

declare -A a
read s x
while read f m t&&[ $m ];do a[$f $m]=$t;done
while [ $f ];do b="$s ${f:i:1}";f=${f:1};s=${a[$b]};echo $b -\> $s;done
[ "$s" = "${s,}" ]&&echo REJECT||echo ACCEPT


问:
Braintree vault should not store same payment method if exists
I have an issue with Braintree,

Suppose a customer logged in on my site, then I create client token for that customer (By passing customer id in Braintree\ClientToken::generate() function ),
so that if he have any existing payment method then it will be loaded automatically at client side.

But if customer selects new payment method which already in vault:

for card same card number, for Paypal same email address,

then it automatically added in vault for that customer, either it exists or not,

So in my case, i don't want to store same payment method(either Paypal or Card) twice or more for same user,

How can i restrict so that same payment method should not store multiple times in vault?

答:
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact
support.

There is actually a parameter you can set in the Client Token generate options called failOnDuplicatePaymentMethod.  If this option is passed as True and the payment method has already been added to the Vault, the request will fail. This can only be passed if a customer_id is passed as well. If the check fails, this option will stop the Drop-in from returning a payment_method_nonce. Unfortunately, this will not work for Paypal Payment methods, and there are a few workarounds for that.

Not Storing in the Vault

You would first need to collect the customer's PayPal email account in the client-side callback. When the payment type is a PayPalAccount , you can then run a Braintree::Customer.search() request on the user's email. If this brings up any customers that have the PayPal email account you specified (which was retrieved from the client-side integration), you wouldn't need to vault the account, you can simply proceed with creating another transaction on the existing token.

Deleting Duplicate Accounts

The second workaround is similar to the first.You collect the customer's PayPal payment method as usual (collect the nonce and pass it to your server) and then use it in a Braintree::PaymentMethod.create or Braintree::Customer.create API request as usual. In the result object returned, you can then check the details of this PayPal transaction, paypal_details and inspect this to find the email address. If this email matches one for a PayPal account for that customer, you can choose to delete the new payment method immediately.

Don't hesitate to reach out to Braintree Support if you need more help.


问:
Hibernate search highlighting not analyzed fields
I'd like to highlight the whole not analyzed fields if they match the search query.

The indexed entity looks as follows:

```<code>@Entity
@Indexed
@AnalyzerDef(
        name = "documentAnalyzer",
        tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
        filters = {
                @TokenFilterDef(factory = ASCIIFoldingFilterFactory.class),
                @TokenFilterDef(factory = LowerCaseFilterFactory.class),
                @TokenFilterDef(
                        factory = StopFilterFactory.class,
                        params = {
                                @Parameter(name = "words", value = "stoplist.properties"),
                                @Parameter(name = "ignoreCase", value = "true")
                        }
                )
        }
)
public class Document {

    ...

    @Field(analyze = Analyze.NO)
    private String notAnalyzedField; // has "x-xxx-xxx" format

    @Field(analyze = Analyze.YES)
    private String analyzedField;

}
</code>```

Suppose I have a Document with notAnalyzedField: "a-bbb-ccc", then I run a search query with the same value and highlight search results using the following code:

```<code>String highlightText(Query query, Analyzer analyzer, String fieldName, String text) {
    QueryScorer queryScorer = new QueryScorer(query);
    SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<span>", "</span>");
    Highlighter highlighter = new Highlighter(formatter, queryScorer);
    return highlighter.getBestFragment(analyzer, fieldName, text);
}
</code>```

As a result I get the following snippet:"a-bbb-ccc".

And it seems reasonable because the analyzer treats a symbol as a stop word and - as a delimiter and doesn't highlight them. But I cannot figure out how I can avoid using analyzer while highlighting this field. There are a few methods in Highlighter class that require TokenStream instead of Analyzer but I'm not sure how to use them.

A result I want to achieve is the whole highlighted field: "a-bbb-ccc"

Is there a way to achieve this with hibernate-search?

答:
Where does your analyzer come from?

You might want to get it from Hibernate Search:

```<code>FullTextEntityManager em = /*...*/;
Analyzer analyzer = em.getSearchFactory()
    .getAnalyzer(Document.class);
highlightText(query, analyzer, fieldName, text);
</code>```

If it doesn't work, try using a KeywordAnalyzer: highlightText(query, new KeywordAnalyzer(), fieldName, text);

Body:
I'd like to highlight the whole not analyzed fields if they match the search query.

The indexed entity looks as follows:

@Entity
@Indexed
@AnalyzerDef(
        name = "documentAnalyzer",
        tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class),
        filters = {
                @TokenFilterDef(factory = ASCIIFoldingFilterFactory.class),
                @TokenFilterDef(factory = LowerCaseFilterFactory.class),
                @TokenFilterDef(
                        factory = StopFilterFactory.class,
                        params = {
                                @Parameter(name = "words", value = "stoplist.properties"),
                                @Parameter(name = "ignoreCase", value = "true")
                        }
                )
        }
)
public class Document {

    ...

    @Field(analyze = Analyze.NO)
    private String notAnalyzedField; // has "x-xxx-xxx" format

    @Field(analyze = Analyze.YES)
    private String analyzedField;

}

Suppose I have a Document with notAnalyzedField: "a-bbb-ccc", then I run a search query with the same value and highlight search results using the following code:

String highlightText(Query query, Analyzer analyzer, String fieldName, String text) {
    QueryScorer queryScorer = new QueryScorer(query);
    SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("", "");
    Highlighter highlighter = new Highlighter(formatter, queryScorer);
    return highlighter.getBestFragment(analyzer, fieldName, text);
}

As a result I get the following snippet:"a-bbb-ccc".

And it seems reasonable because the analyzer treats a symbol as a stop word and - as a delimiter and doesn't highlight them. But I cannot figure out how I can avoid using analyzer while highlighting this field. There are a few methods in Highlighter class that require TokenStream instead of Analyzer but I'm not sure how to use them.

A result I want to achieve is the whole highlighted field: "a-bbb-ccc"

Is there a way to achieve this with hibernate-search?

Body:
Where does your analyzer come from?

You might want to get it from Hibernate Search:

FullTextEntityManager em = /*...*/;
Analyzer analyzer = em.getSearchFactory()
    .getAnalyzer(Document.class);
highlightText(query, analyzer, fieldName, text);

If it doesn't work, try using a KeywordAnalyzer: highlightText(query, new KeywordAnalyzer(), fieldName, text);


问:
Cannot load HTML file with QWebEngineView.setHtml()
The solution of my problem is probably very simple but yet out of my understanding. I am trying to load an HTML file into a QWebEngineView with PyQt5. The way I am doing it is:

```<code>self.webView = QtWebEngineWidgets.QWebEngineView(self.splitter)
html = r"C:\DATI\git\webgis\map.html"
self.webView.setHtml(html)
</code>```

The only thing I get is a string representing the path and name of my HTML file:

C:\DATI\git\webgis\map.html

My map.html looks like this:

```<code><html>
  <head>
    <title>Simple Map</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.5.0/css/ol.css" type="text/css">
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
    <script src="https://openlayers.org/en/v4.5.0/build/ol.js"></script>
    <script src=".js/qwebchannel.js"></script>
    <style>
        body { padding: 0; margin: 0; }
        html, body, #map { height: 100%; }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>
    <script  src="./js/map.js"></script>
  </body>
</html>
</code>```

Strangely (to me at least), if I do self.webView.setHtml("
ciao
"), this will render the HTML properly.

What am I missing?

答:
The setHtml method does exactly what its name suggests: it loads html content from a string. What you are trying to do is load a url, so for that, you need to use the load method:

```<code>url = QtCore.QUrl.fromLocalFile(r"C:\DATI\git\webgis\map.html")
self.webView.load(url)
</code>```

Body:
The solution of my problem is probably very simple but yet out of my understanding. I am trying to load an HTML file into a QWebEngineView with PyQt5. The way I am doing it is:

self.webView = QtWebEngineWidgets.QWebEngineView(self.splitter)
html = r"C:\DATI\git\webgis\map.html"
self.webView.setHtml(html)

The only thing I get is a string representing the path and name of my HTML file:

C:\DATI\git\webgis\map.html

My map.html looks like this:

    <title>Simple Map</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.5.0/css/ol.css" type="text/css">

Strangely (to me at least), if I do self.webView.setHtml("
ciao
"), this will render the HTML properly.

What am I missing?

Body:
The setHtml method does exactly what its name suggests: it loads html content from a string. What you are trying to do is load a url, so for that, you need to use the load method:

url = QtCore.QUrl.fromLocalFile(r"C:\DATI\git\webgis\map.html")
self.webView.load(url)


问:
How to get admin access to files for all user's OneDrive
I am tenant admin for our Office 365 deployment. we have our internal system which need to access all OneDrive sites. We are using my tenant admin credential to get the OAuth token and trying to get files from all OneDrive sites using SharePoint/OneDrive REST API with that OAuth token.

With OAuth token of the tenant admin, we are only able to get the files owned by tenant admin or Shared with tenant admin. we are not able to get the files form other user's OneDrive.

Same result with Microsoft Graph API also. we are only able to get the files owned by tenant admin or Shared with tenant admin. we are not able to get the files form other user's OneDrive.

One Solution for this could be by adding tenant admin to the site collection admin for all OneDrive Sites, but this is not a feasible option for us.

Is there any API, or any other way to get all OneDrive user's file by using OneDrive admin or tenant admin credential ?

Thanks,
Abhi

答:
You can do this using either Delegated or Application permissions. Which one you choose depends on how your application will run and the OAUTH Grant Flow you're using.

If your application runs with an interactive user (i.e. you're sitting in front of it while it runs), then you want to use Delegated permissions and the Authorization Code Grant Flow.

If your application runs as a service (i.e. it runs in the background) then you'll want to use Application permissions and the Client Credentials Grant Flow.

Regardless of the permission model you choose, the permission scopes and endpoints will remain the same.

You'll need one of the following permission scopes in order to access other user's files within the tenant: Files.Read.All, Files.ReadWrite.All, Sites.Read.All, Sites.ReadWrite.All.

In order to see another user's files, you need to address that user's drive directly. This is done via the user's userPrincipalName. For example, to see files in the root of a user's drive you would call:

```<code> https://graph.microsoft.com/v1.0/users/{userPrincipalName}/drive/root/children
</code>```

Hope this helps.

Body:
You can do this using either Delegated or Application permissions. Which one you choose depends on how your application will run and the OAUTH Grant Flow you're using.

If your application runs with an interactive user (i.e. you're sitting in front of it while it runs), then you want to use Delegated permissions and the Authorization Code Grant Flow.

If your application runs as a service (i.e. it runs in the background) then you'll want to use Application permissions and the Client Credentials Grant Flow.

Regardless of the permission model you choose, the permission scopes and endpoints will remain the same.

You'll need one of the following permission scopes in order to access other user's files within the tenant: Files.Read.All, Files.ReadWrite.All, Sites.Read.All, Sites.ReadWrite.All.

In order to see another user's files, you need to address that user's drive directly. This is done via the user's userPrincipalName. For example, to see files in the root of a user's drive you would call:

 https://graph.microsoft.com/v1.0/users/{userPrincipalName}/drive/root/children

Hope this helps.


问:
Assign each extracted comment to a single row write.table R data frame
first of all I am a coding noob and just started coding for the purpose to write my master's thesis at my university. I extracted youtube comments using the tuber package in R in order to carry out a sentiment analysis of those comments. Everything worked fine and I received a data frame with all the comments (11314 observations and 13 variables). However, when i tried to write a .csv file of that data frame in order to look at the comments in Excel I encountered a particular issue. For the comments that contain new paragraphs, the write.table function created a new row. I used the following function:

```<code>write.table(testneuohneduplikate, file = "Testneuohnedulikate.csv",sep = ";", row.names = FALSE, col.names = TRUE, quote = TRUE)
</code>```

Is there a possibility that each comment is written in a single row and not sometimes two or three rows because the comment contains paragraphs?

I hope I was able to explain my problem properly.

Thank you guys in advance and greetings from Germany to wherever you are from :)

答:
Yes, write.table is creating a new row when it encounters a newline character. Here's an example of stripping out newline characters out of the comment string:

```<code>> comment<-"I think this video \n is great"
> cat(comment)
I think this video
 is great

> fixedcomment<-gsub("[\r\n]", "", comment)
> cat(fixedcomment)
I think this video  is great
>
</code>```

you can use 'apply' to apply it to every column in your table, or modify the MARGIN parameter if you only want to do rows or columns.

```<code>> ID<-1:4
> Names<-c('name1','name2','name3','name4')
> Comments<-c("I think this video \n is great", "No it stinks \n I mean it", "Use the Force", "It's time \n to get to work")
> table<-cbind(ID, Names, Comments)

> fixed_table<-apply(X=table,MARGIN=c(1,2),FUN = function(y) gsub("[\r\n]","",y))
</code>```

Body:
first of all I am a coding noob and just started coding for the purpose to write my master's thesis at my university. I extracted youtube comments using the tuber package in R in order to carry out a sentiment analysis of those comments. Everything worked fine and I received a data frame with all the comments (11314 observations and 13 variables). However, when i tried to write a .csv file of that data frame in order to look at the comments in Excel I encountered a particular issue. For the comments that contain new paragraphs, the write.table function created a new row. I used the following function:

write.table(testneuohneduplikate, file = "Testneuohnedulikate.csv",sep = ";", row.names = FALSE, col.names = TRUE, quote = TRUE)

Is there a possibility that each comment is written in a single row and not sometimes two or three rows because the comment contains paragraphs?

I hope I was able to explain my problem properly.

Thank you guys in advance and greetings from Germany to wherever you are from :)

Body:
Yes, write.table is creating a new row when it encounters a newline character. Here's an example of stripping out newline characters out of the comment string:

> comment<-"I think this video \n is great"
> cat(comment)
I think this video
 is great

> fixedcomment<-gsub("[\r\n]", "", comment)
> cat(fixedcomment)
I think this video  is great
>

you can use 'apply' to apply it to every column in your table, or modify the MARGIN parameter if you only want to do rows or columns.

> ID<-1:4
> Names<-c('name1','name2','name3','name4')
> Comments<-c("I think this video \n is great", "No it stinks \n I mean it", "Use the Force", "It's time \n to get to work")
> table<-cbind(ID, Names, Comments)

> fixed_table<-apply(X=table,MARGIN=c(1,2),FUN = function(y) gsub("[\r\n]","",y))


问:
How to join multiple tables with one table?
I'm working on an SQL project, but I found a problem while retrieving data from the database. There are four tables as you can see in the following screenshot:

So my query is about calculating the sum of the units from the tables transac_EUR_M10_17 and transac_EUR_M09_17.

I tried the following SQL Server query but the results are false:

```<code>SELECT cntry.cod_country
    , rg.nom_region
    , SUM(tr.unite) as [sum units M09]
    , SUM(tr1.unite) as [sum units M10]
FROM [Backup].[dbo].[transac_EUR_M09_17] as tr
INNER JOIN [Backup].[dbo].[COUNTRY] as cntry ON tr.[cod_country] = cntry.[cod_country]
INNER JOIN [Backup].[dbo].Region as rg   ON rg.[cod_country] = cntry.[cod_country]
INNER JOIN [Backup].[dbo].[transac_EUR_M10_17] AS tr1  ON tr1.[cod_country] = cntry.[cod_country]
where tr.cod_region = rg.cod_region
    AND tr1.cod_region = rg.cod_region
Group BY cntry.cod_country
    , rg.nom_region
ORDER BY SUM(tr.unite)
    , SUM(tr1.unite) DESC
</code>```

Do you have any advice about how to join two tables with one permanent table?

答:
looking at your data diagram, I would structure my code a bit differently to make sure I get the desired results.

First join the 2 primary tables by Country and region
Then filter by using the country and region tables, omitting any where clause because you include all conditions in the join clauses.

like so

```<code>SELECT cntry.cod_country
    , rg.nom_region
    , SUM(tr.unite) as [sum units M09]
    , SUM(tr1.unite) as [sum units M10]
FROM [Backup].[dbo].[transac_EUR_M09_17] as tr
INNER JOIN [Backup].[dbo].[transac_EUR_M10_17] AS tr1  ON tr1.[cod_country] = tr.[cod_country]
                                                       AND tr1.[cod_region] = tr.[cod_region]
INNER JOIN [Backup].[dbo].[COUNTRY] as cntry ON tr.[cod_country] = cntry.[cod_country]
INNER JOIN [Backup].[dbo].Region as rg   ON rg.[cod_country] = cntry.[cod_country]
                                        AND rg.[cod_region] = tr.[cod_region]
Group BY cntry.cod_country, rg.nom_region
ORDER BY SUM(tr.unite), SUM(tr1.unite) DESC
</code>```

This still may not produce your desired results, but from what you have given, it should correctly join your tables.

Body:
I'm working on an SQL project, but I found a problem while retrieving data from the database. There are four tables as you can see in the following screenshot:

So my query is about calculating the sum of the units from the tables transac_EUR_M10_17 and transac_EUR_M09_17.

I tried the following SQL Server query but the results are false:

SELECT cntry.cod_country
    , rg.nom_region
    , SUM(tr.unite) as [sum units M09]
    , SUM(tr1.unite) as [sum units M10]
FROM [Backup].[dbo].[transac_EUR_M09_17] as tr
INNER JOIN [Backup].[dbo].[COUNTRY] as cntry ON tr.[cod_country] = cntry.[cod_country]
INNER JOIN [Backup].[dbo].Region as rg   ON rg.[cod_country] = cntry.[cod_country]
INNER JOIN [Backup].[dbo].[transac_EUR_M10_17] AS tr1  ON tr1.[cod_country] = cntry.[cod_country]
where tr.cod_region = rg.cod_region
    AND tr1.cod_region = rg.cod_region
Group BY cntry.cod_country
    , rg.nom_region
ORDER BY SUM(tr.unite)
    , SUM(tr1.unite) DESC

Do you have any advice about how to join two tables with one permanent table?

Body:
looking at your data diagram, I would structure my code a bit differently to make sure I get the desired results.

First join the 2 primary tables by Country and region
Then filter by using the country and region tables, omitting any where clause because you include all conditions in the join clauses.

like so

SELECT cntry.cod_country
    , rg.nom_region
    , SUM(tr.unite) as [sum units M09]
    , SUM(tr1.unite) as [sum units M10]
FROM [Backup].[dbo].[transac_EUR_M09_17] as tr
INNER JOIN [Backup].[dbo].[transac_EUR_M10_17] AS tr1  ON tr1.[cod_country] = tr.[cod_country]
                                                       AND tr1.[cod_region] = tr.[cod_region]
INNER JOIN [Backup].[dbo].[COUNTRY] as cntry ON tr.[cod_country] = cntry.[cod_country]
INNER JOIN [Backup].[dbo].Region as rg   ON rg.[cod_country] = cntry.[cod_country]
                                        AND rg.[cod_region] = tr.[cod_region]
Group BY cntry.cod_country, rg.nom_region
ORDER BY SUM(tr.unite), SUM(tr1.unite) DESC

This still may not produce your desired results, but from what you have given, it should correctly join your tables.


问:
ERROR a command prompt dialog is open when i execute my script php
I am a beginner in php and i would send an email using script php. I have xampp as server and when I follow tuto's on internet the script doesn't work and in my file error.log I found the error :Connection Closed Gracefully so i search a solution to this problem ,i found this solution :

Right click on sendmail.exe

Properties

Compatibility

Change the configuration for all users

Execute as Windows XP SP 3

Execute as adminitrator

I follow this steps but when I ececute my file which contain

```<code><?php mail('destinataire@gmail.com','Sample email','Sample Text','From: xxxxxx@gmail.com'); ?>
</code>```

a dialog  come up to ask me to run the 'send mail' app as admin. I click 'Yes' it will show a command prompt dialog and nothing will happen and my page will hang until the command prompt is closed.Dinally i have the error:

Fatal error: Maximum execution time of 30 seconds exceeded in
  E:\xampp\htdocs\sending\tt.php on line 2

Can you help me to solve this problem?

答:
It sounds like the issue is you are getting a UAC prompt (asking for permission to run sendmail as administrator), and the time it takes the script to start running, plus the time for you to see and click the UAC prompt is taking over 30 seconds. Your PHP installation is configured to timeout any scripts after they've run for 30 seconds (so they don't just run indefinitely).

At this point, you can extend PHP execution time using set_time_limit() (for example, set_time_limit( 120 );).

If you would rather disable the prompting all together (not recommended, as you're disabling Windows security measures globally), you can disable UAC.

Body:
I am a beginner in php and i would send an email using script php. I have xampp as server and when I follow tuto's on internet the script doesn't work and in my file error.log I found the error :Connection Closed Gracefully so i search a solution to this problem ,i found this solution :

Right click on sendmail.exe

Properties

Compatibility

Change the configuration for all users

Execute as Windows XP SP 3

Execute as adminitrator

I follow this steps but when I ececute my file which contain

<?php mail('destinataire@gmail.com','Sample email','Sample Text','From: xxxxxx@gmail.com'); ?>

a dialog  come up to ask me to run the 'send mail' app as admin. I click 'Yes' it will show a command prompt dialog and nothing will happen and my page will hang until the command prompt is closed.Dinally i have the error:

Fatal error: Maximum execution time of 30 seconds exceeded in
  E:\xampp\htdocs\sending\tt.php on line 2

Can you help me to solve this problem?


问:
Priority in TestNG with multiple classes
I'm facing with the following problem: I created two classes which include @Tests with priority attribute:

```<code>@Test( priority = 1 )
public void testA1() {
    System.out.println("testA1");
}

@Test( priority = 2 )
public void testA2() {
    System.out.println("testA2");
}

@Test( priority = 3 )
public void testA3() {
    System.out.println("testA3");
}
</code>```

... and ...

```<code>@Test( priority = 1 )
public void testB1() {
    System.out.println("testB1");
}

@Test( priority = 2 )
public void testB2() {
    System.out.println("testB2");
}

@Test( priority = 3 )
public void testB3() {
    System.out.println("testB3");
}
</code>```

I put both classes under one test in testng.xml but when I run the test, it will order my @Tests based  on the priorities from both classes:

```<code>testA1
testB1
testA2
testB2
testA3
testB3
</code>```

I'm expecting the following result:

```<code>testA1
testA2
testA3
testB1
testB2
testB3
</code>```

My question is that how can I prevent to order my @Tests based on both classes and run @Tests only from one class at the same time?

答:
The most correct way is to use dependsOnMethods.
Priority levels are global for test (don't mix with test-methods which are annotated with @Test). In other words:
when testng runs test (from <test> tag) it groups methods by priorities and then run it. In your case both testA1 and testB1 have priority=1, so will be executed at the beginning.

Body:
I'm facing with the following problem: I created two classes which include @Tests with priority attribute:

@Test( priority = 1 )
public void testA1() {
    System.out.println("testA1");
}

@Test( priority = 2 )
public void testA2() {
    System.out.println("testA2");
}

@Test( priority = 3 )
public void testA3() {
    System.out.println("testA3");
}

... and ...

@Test( priority = 1 )
public void testB1() {
    System.out.println("testB1");
}

@Test( priority = 2 )
public void testB2() {
    System.out.println("testB2");
}

@Test( priority = 3 )
public void testB3() {
    System.out.println("testB3");
}

I put both classes under one test in testng.xml but when I run the test, it will order my @Tests based  on the priorities from both classes:

testA1
testB1
testA2
testB2
testA3
testB3

I'm expecting the following result:

testA1
testA2
testA3
testB1
testB2
testB3

My question is that how can I prevent to order my @Tests based on both classes and run @Tests only from one class at the same time?


问:
Duplicate removal not working on table with many NULLs
Perhaps I've been staring at the screen too long but I have the following [legacy] table I'm messing with:

```<code>describe t3_test;
+--------------------+------------------+------+-----+---------+----------------+
| Field              | Type             | Null | Key | Default | Extra          |
+--------------------+------------------+------+-----+---------+----------------+
| provnum            | varchar(24)      | YES  | MUL | NULL    |                |
| trgt_mo            | datetime         | YES  |     | NULL    |                |
| mcare              | varchar(2)       | YES  |     | NULL    |                |
| bed2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| trnsfr2prsn_asst   | varchar(2)       | YES  |     | NULL    |                |
| tlt2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| hygn2prsn_asst     | varchar(2)       | YES  |     | NULL    |                |
| bath2psrn_asst     | varchar(2)       | YES  |     | NULL    |                |
| ampmcare2prsn_asst | varchar(2)       | YES  |     | NULL    |                |
| any2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| n                  | float            | YES  |     | NULL    |                |
| pct                | float            | YES  |     | NULL    |                |
| trgt_qtr           | varchar(12)      | YES  |     | NULL    |                |
| recno              | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| enddate            | date             | YES  |     | NULL    |                |
+--------------------+------------------+------+-----+---------+----------------+
15 rows in set (0.00 sec)
</code>```

I have data that looks like this..

```<code>"555223","2008-10-01 00:00:00",NULL,"1",NULL,NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","5767343","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"1",NULL,NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","4075309","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"0",NULL,NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","4075308","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"0",NULL,NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","5767342","2008-12-31"
"555223","2008-10-01 00:00:00","N",NULL,"1",NULL,NULL,NULL,NULL,NULL,"36","83.7209","2008Q4","4075327","2008-12-31"
"555223","2008-10-01 00:00:00","N","1",NULL,NULL,NULL,NULL,NULL,NULL,"36","83.7209","2008Q4","4075323","2008-12-31"
"555223","2008-10-01 00:00:00","Y","1",NULL,NULL,NULL,NULL,NULL,NULL,"4","9.30233","2008Q4","4075325","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,NULL,"0",NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","4075310","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,NULL,"1",NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","4075311","2008-12-31"
</code>```

The first two lines of the table clearly appear to be dupes (minus the A.I. index "recno"). I've tried a half dozen dupe-removal routines and they are not automatically removed.

At this point I am not sure what exactly is wrong?  Is it possible there's an invisible character somewhere?  Is it possible a letter is in a different character encoding?  When I dump the data to CSV as is listed, it doesn't look any different.

Do you have a delete routine that would work on this file structure that would remove anything that is a dupe (minus the recno field)?  I have been staring at this for two days and for some reason, it escapes me.  (btw, I am aware of the column name anomaly for bathd2psrn_asst - that's not it)

This (original) table has over 13 million records in it.  And is over 3GB in size so I'm looking for the most efficient way to kill dupes.. Any ideas?

Here's an example of one of the dupe-killing techniques I used that did not work:

```<code>DELETE a FROM t3_test as a, t3_test as b WHERE
(a.provnum=b.provnum)
AND (a.trgt_mo=b.trgt_mo OR a.trgt_mo IS NULL AND b.trgt_mo IS NULL)
AND (a.mcare=b.mcare OR a.mcare IS NULL AND b.mcare IS NULL)
AND (a.bed2prsn_asst=b.bed2prsn_asst OR a.bed2prsn_asst IS NULL AND b.bed2prsn_asst IS NULL)
AND (a.trnsfr2prsn_asst=b.trnsfr2prsn_asst OR a.trnsfr2prsn_asst IS NULL AND b.trnsfr2prsn_asst IS NULL)
AND (a.tlt2prsn_asst=b.tlt2prsn_asst OR a.tlt2prsn_asst IS NULL AND b.tlt2prsn_asst IS NULL)
AND (a.hygn2prsn_asst=b.hygn2prsn_asst OR a.hygn2prsn_asst IS NULL AND b.hygn2prsn_asst IS NULL)
AND (a.bath2psrn_asst=b.bath2psrn_asst OR a.bath2psrn_asst IS NULL AND b.bath2psrn_asst IS NULL)
AND (a.ampmcare2prsn_asst=b.ampmcare2prsn_asst OR a.ampmcare2prsn_asst IS NULL AND b.ampmcare2prsn_asst IS NULL)
AND (a.any2prsn_asst=b.any2prsn_asst OR a.any2prsn_asst IS NULL AND b.any2prsn_asst IS NULL)
AND (a.n=b.n OR a.n IS NULL AND b.n IS NULL)
AND (a.pct=b.pct OR a.pct IS NULL AND b.pct IS NULL)
AND (a.trgt_qtr=b.trgt_qtr OR a.trgt_qtr IS NULL AND b.trgt_qtr IS NULL)
AND (a.enddate=b.enddate OR a.enddate IS NULL AND b.enddate IS NULL)
AND (a.recno>b.recno);
</code>```

答:
In the case of this scenario, the problem was not with the SQL statement.  It was a problem with the DATA, but it was not visible.

The two fields designated type "float" held hidden decimal values that were slightly different from each other.  Converting those fields to DECIMAL(a,b) type made the dupes show up and be properly deleted by conventional means.

Special thanks to Gordon Linoff for suggesting looking into this.

Body:
Perhaps I've been staring at the screen too long but I have the following [legacy] table I'm messing with:

describe t3_test;
+--------------------+------------------+------+-----+---------+----------------+
| Field              | Type             | Null | Key | Default | Extra          |
+--------------------+------------------+------+-----+---------+----------------+
| provnum            | varchar(24)      | YES  | MUL | NULL    |                |
| trgt_mo            | datetime         | YES  |     | NULL    |                |
| mcare              | varchar(2)       | YES  |     | NULL    |                |
| bed2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| trnsfr2prsn_asst   | varchar(2)       | YES  |     | NULL    |                |
| tlt2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| hygn2prsn_asst     | varchar(2)       | YES  |     | NULL    |                |
| bath2psrn_asst     | varchar(2)       | YES  |     | NULL    |                |
| ampmcare2prsn_asst | varchar(2)       | YES  |     | NULL    |                |
| any2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| n                  | float            | YES  |     | NULL    |                |
| pct                | float            | YES  |     | NULL    |                |
| trgt_qtr           | varchar(12)      | YES  |     | NULL    |                |
| recno              | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| enddate            | date             | YES  |     | NULL    |                |
+--------------------+------------------+------+-----+---------+----------------+
15 rows in set (0.00 sec)

I have data that looks like this..

"555223","2008-10-01 00:00:00",NULL,"1",NULL,NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","5767343","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"1",NULL,NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","4075309","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"0",NULL,NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","4075308","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"0",NULL,NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","5767342","2008-12-31"
"555223","2008-10-01 00:00:00","N",NULL,"1",NULL,NULL,NULL,NULL,NULL,"36","83.7209","2008Q4","4075327","2008-12-31"
"555223","2008-10-01 00:00:00","N","1",NULL,NULL,NULL,NULL,NULL,NULL,"36","83.7209","2008Q4","4075323","2008-12-31"
"555223","2008-10-01 00:00:00","Y","1",NULL,NULL,NULL,NULL,NULL,NULL,"4","9.30233","2008Q4","4075325","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,NULL,"0",NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","4075310","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,NULL,"1",NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","4075311","2008-12-31"

The first two lines of the table clearly appear to be dupes (minus the A.I. index "recno"). I've tried a half dozen dupe-removal routines and they are not automatically removed.

At this point I am not sure what exactly is wrong?  Is it possible there's an invisible character somewhere?  Is it possible a letter is in a different character encoding?  When I dump the data to CSV as is listed, it doesn't look any different.

Do you have a delete routine that would work on this file structure that would remove anything that is a dupe (minus the recno field)?  I have been staring at this for two days and for some reason, it escapes me.  (btw, I am aware of the column name anomaly for bathd2psrn_asst - that's not it)

This (original) table has over 13 million records in it.  And is over 3GB in size so I'm looking for the most efficient way to kill dupes.. Any ideas?

Here's an example of one of the dupe-killing techniques I used that did not work:

DELETE a FROM t3_test as a, t3_test as b WHERE
(a.provnum=b.provnum)
AND (a.trgt_mo=b.trgt_mo OR a.trgt_mo IS NULL AND b.trgt_mo IS NULL)
AND (a.mcare=b.mcare OR a.mcare IS NULL AND b.mcare IS NULL)
AND (a.bed2prsn_asst=b.bed2prsn_asst OR a.bed2prsn_asst IS NULL AND b.bed2prsn_asst IS NULL)
AND (a.trnsfr2prsn_asst=b.trnsfr2prsn_asst OR a.trnsfr2prsn_asst IS NULL AND b.trnsfr2prsn_asst IS NULL)
AND (a.tlt2prsn_asst=b.tlt2prsn_asst OR a.tlt2prsn_asst IS NULL AND b.tlt2prsn_asst IS NULL)
AND (a.hygn2prsn_asst=b.hygn2prsn_asst OR a.hygn2prsn_asst IS NULL AND b.hygn2prsn_asst IS NULL)
AND (a.bath2psrn_asst=b.bath2psrn_asst OR a.bath2psrn_asst IS NULL AND b.bath2psrn_asst IS NULL)
AND (a.ampmcare2prsn_asst=b.ampmcare2prsn_asst OR a.ampmcare2prsn_asst IS NULL AND b.ampmcare2prsn_asst IS NULL)
AND (a.any2prsn_asst=b.any2prsn_asst OR a.any2prsn_asst IS NULL AND b.any2prsn_asst IS NULL)
AND (a.n=b.n OR a.n IS NULL AND b.n IS NULL)
AND (a.pct=b.pct OR a.pct IS NULL AND b.pct IS NULL)
AND (a.trgt_qtr=b.trgt_qtr OR a.trgt_qtr IS NULL AND b.trgt_qtr IS NULL)
AND (a.enddate=b.enddate OR a.enddate IS NULL AND b.enddate IS NULL)
AND (a.recno>b.recno);


问:
label having sizeToFits() goes out of bounds
I have a tableview in where each cell has a label. The datasource of this label is from the firebase api. Now, initially the label is loaded in a perfect form. As you scroll through and if any label is of a shorter text  width, the rest of the cell, alter their labels to this size.

I even tried applying a stackview around it, but i couldn't help much

Below is the code of cellForRow

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let post = posts[indexPath.row]
    if let cell = tableView.dequeueReusableCell(withIdentifier: "FeedCell", for: indexPath) as? FeedCell {

        cell.caption.text = ""
        cell.configureCell(post: post)
        cell.caption.sizeToFit()
        cell.delegate = self

        return cell
    } else {
        return FeedCell()
    }
}
</code>```

code for function in TableviewCell

```<code>func configureCell(post: Posts, img: UIImage? = nil) {
    self.posts = post
    self.caption.text = posts.caption
}
</code>```

I am really unable to fix this. Any help is much appreciated.

答:
How about using auto-layout to set a minimum width in percentage of a screen size IOS.
Auto-Layout constraint has that multiplier parameter that lets you use a fractional relationship between a superview and its subview.

While both the child view (Label) and its superview are selected, add "equal width". Then change the "multiplier" of the constraint you just added to the proportion you need. For example, for 30%

Body:
I have a tableview in where each cell has a label. The datasource of this label is from the firebase api. Now, initially the label is loaded in a perfect form. As you scroll through and if any label is of a shorter text  width, the rest of the cell, alter their labels to this size.

I even tried applying a stackview around it, but i couldn't help much

Below is the code of cellForRow

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let post = posts[indexPath.row]
    if let cell = tableView.dequeueReusableCell(withIdentifier: "FeedCell", for: indexPath) as? FeedCell {

        cell.caption.text = ""
        cell.configureCell(post: post)
        cell.caption.sizeToFit()
        cell.delegate = self

        return cell
    } else {
        return FeedCell()
    }
}

code for function in TableviewCell

func configureCell(post: Posts, img: UIImage? = nil) {
    self.posts = post
    self.caption.text = posts.caption
}

I am really unable to fix this. Any help is much appreciated.


问:
How to create a function that creates a Cartesian product Iterator from an Iterator of Iterators?
If I want to create a Cartesian product of a list of lists in Haskell, I can do this:

product [] = [[]]
product (xs:xss) = concatMap (\k -> map (k:) (product1 xss)) xs
```

<p>or even this:</p>

<pre class="lang-hs prettyprint-override"><code>sequence xss
</code>```

I'm trying to implement an efficient iterator that would do the same in Rust, but I'm not sure what is wrong with my attempt:

```<code>use std::iter::{empty, once};

fn product<T, I, V>(xss: I) -> Box<Iterator<Item = Iterator<Item = T>>>
where
    T: Clone,
    V: IntoIterator<Item = T>,
    I: IntoIterator<Item = V>,
{
    Box::new(xss.into_iter().fold(once(empty()), |acc, xs| {
        xs.into_iter().flat_map(|x| acc.map(|ys| ys.chain(once(x))))
    }))
}

fn main() {
    let data = vec![[1, 2, 3], [10, 20, 30], [100, 200, 300]];
    let it: Vec<Vec<u32>> = product(data).collect();
    println!("{:?}", it);
}
</code>```

(playground)

Produces these errors:

error[E0308]: mismatched types
  --> src/main.rs:10:9
   |
10 |         xs.into_iter().flat_map(|x| acc.map(|ys| ys.chain(once(x))))
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::iter::Once`, found struct `std::iter::FlatMap`
   |
   = note: expected type `std::iter::Once<std::iter::Empty<T>>`
              found type `std::iter::FlatMap<<V as std::iter::IntoIterator>::IntoIter, std::iter::Map<std::iter::Once<std::iter::Empty<T>>, [closure@src/main.rs:10:45: 10:67 x:_]>, [closure@src/main.rs:10:33: 10:68 acc:_]>`

error[E0271]: type mismatch resolving `<std::iter::Once<std::iter::Empty<T>> as std::iter::Iterator>::Item == std::iter::Iterator<Item=T>`
  --> src/main.rs:9:5
   |
9  | /     Box::new(xss.into_iter().fold(once(empty()), |acc, xs| {
10 | |         xs.into_iter().flat_map(|x| acc.map(|ys| ys.chain(once(x))))
11 | |     }))
   | |_______^ expected struct `std::iter::Empty`, found trait std::iter::Iterator
   |
   = note: expected type `std::iter::Empty<T>`
              found type `std::iter::Iterator<Item=T>`
   = note: required for the cast to the object type `std::iter::Iterator<Item=std::iter::Iterator<Item=T>>`

error[E0277]: the trait bound `[{integer}; 3]: std::iter::Iterator` is not satisfied
  --> src/main.rs:16:29
   |
16 |     let it: Vec<Vec<u32>> = product(data).collect();
   |                             ^^^^^^^ `[{integer}; 3]` is not an iterator; maybe try calling `.iter()` or a similar method
   |
   = help: the trait `std::iter::Iterator` is not implemented for `[{integer}; 3]`
   = note: required because of the requirements on the impl of `std::iter::IntoIterator` for `[{integer}; 3]`
   = note: required by `product`

error: the `collect` method cannot be invoked on a trait object
  --> src/main.rs:16:43
   |
16 |     let it: Vec<Vec<u32>> = product(data).collect();
   |                                           ^^^^^^^
```

The first error is giving me the feeling that Rust cannot even create a lazily consumed iterator with fold because Empty<T> is an Iterator<Item = T> (at least conceptually), but I hope I'm wrong.

答:
The first reason your approach is bound to fail is because you're trying to transpose an algorithm designed to work on lists into an algorithm working on iterators. Lists are suitable for a functional approach, iterators aren't, because they have a state. The next(&mut self) function won't return the same value each time it's called with the same argument, whereas a next(x:xs) function will. This is the reason why the implementation found in itertools clones iterators: to save their initial state and recover it for the next iteration over the set.

The second reason, the one behind the error messages, is that you're fighting against Rust's type system. The result values of all your calls to iterator functions (fold, flat_map, etc.) aren't trait objects but 'concrete types'. For instance iterator.fold(init, fn)'s result type is init's type. That's why the compiler complains when you pass fold a lambda that doesn't return a std::iter::Empty<T>.

But it gets worse. You could imagine to coerce or cast that std::iter::Empty<T> into a trait object. Alas, object safety is required. To put it in a nutshell, "A good intuition is “except in special circumstances, if your trait’s method uses Self, it is not object-safe.". But iterators' main method is next(&mut self).

Body:
If I want to create a Cartesian product of a list of lists in Haskell, I can do this:

product [] = [[]]
product (xs:xss) = concatMap (\k -> map (k:) (product1 xss)) xs

or even this:

sequence xss

I'm trying to implement an efficient iterator that would do the same in Rust, but I'm not sure what is wrong with my attempt:

use std::iter::{empty, once};

fn product<T, I, V>(xss: I) -> Box<Iterator<Item = Iterator<Item = T>>>
where
    T: Clone,
    V: IntoIterator<Item = T>,
    I: IntoIterator<Item = V>,
{
    Box::new(xss.into_iter().fold(once(empty()), |acc, xs| {
        xs.into_iter().flat_map(|x| acc.map(|ys| ys.chain(once(x))))
    }))
}

fn main() {
    let data = vec![[1, 2, 3], [10, 20, 30], [100, 200, 300]];
    let it: Vec<Vec<u32>> = product(data).collect();
    println!("{:?}", it);
}

(playground)

Produces these errors:

error[E0308]: mismatched types
  --> src/main.rs:10:9
   |
10 |         xs.into_iter().flat_map(|x| acc.map(|ys| ys.chain(once(x))))
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `std::iter::Once`, found struct `std::iter::FlatMap`
   |
   = note: expected type `std::iter::Once<std::iter::Empty<T>>`
              found type `std::iter::FlatMap<<V as std::iter::IntoIterator>::IntoIter, std::iter::Map<std::iter::Once<std::iter::Empty<T>>, [closure@src/main.rs:10:45: 10:67 x:_]>, [closure@src/main.rs:10:33: 10:68 acc:_]>`

error[E0271]: type mismatch resolving `<std::iter::Once<std::iter::Empty<T>> as std::iter::Iterator>::Item == std::iter::Iterator<Item=T>`
  --> src/main.rs:9:5
   |
9  | /     Box::new(xss.into_iter().fold(once(empty()), |acc, xs| {
10 | |         xs.into_iter().flat_map(|x| acc.map(|ys| ys.chain(once(x))))
11 | |     }))
   | |_______^ expected struct `std::iter::Empty`, found trait std::iter::Iterator
   |
   = note: expected type `std::iter::Empty<T>`
              found type `std::iter::Iterator<Item=T>`
   = note: required for the cast to the object type `std::iter::Iterator<Item=std::iter::Iterator<Item=T>>`

error[E0277]: the trait bound `[{integer}; 3]: std::iter::Iterator` is not satisfied
  --> src/main.rs:16:29
   |
16 |     let it: Vec<Vec<u32>> = product(data).collect();
   |                             ^^^^^^^ `[{integer}; 3]` is not an iterator; maybe try calling `.iter()` or a similar method
   |
   = help: the trait `std::iter::Iterator` is not implemented for `[{integer}; 3]`
   = note: required because of the requirements on the impl of `std::iter::IntoIterator` for `[{integer}; 3]`
   = note: required by `product`

error: the `collect` method cannot be invoked on a trait object
  --> src/main.rs:16:43
   |
16 |     let it: Vec<Vec<u32>> = product(data).collect();
   |                                           ^^^^^^^

The first error is giving me the feeling that Rust cannot even create a lazily consumed iterator with fold because Empty<T> is an Iterator<Item = T> (at least conceptually), but I hope I'm wrong.


问:
What is the native application API for iphone and android that is equivalent html5 canvas?
I have developed html5 canvas based animations (non-interacive) which work very well in latest desktop browsers but perform miserably on iphone and android. I want to port these web based html5 canvas application to native iphone and android applications. I am looking for something that will provide the quickest way to port such applications to native iphone and android applications without having to learn something completely different like opengl es. Is there such native API ( something like canvas 2d drawing surface) and if so what is the API?</p>

答:
In Android, you have a Canvas. You can elect to use that alongside the existing widget set (e.g., by creating your own View subclass and overriding onDraw() to get the Canvas for the View), if you wish.

Note that I have not played much with the Canvas API, as graphics are not my strong suit, so I don't have all the details of how to use it for you.


问:
Sys arguments with while
The lines in the files will be top to bottom (one under the other)

I have 2 ".txt" file like this :

```
#john.txt
hello
my
name
is
John
#jack.txt
```

second one is like that:

```
hello
your
name
is
Jack
```

I will compare this texts line by line but the problem is when I write

"python john.txt jack.txt " on command line  sys.arg[1] and sys.argv[2]
will provide the lines and compare them . so sys.argv[1] must provide lines in file one by one but I will write"python john.txt jack.txt " only one time.
sample output:

```<code>python john.txt jack.txt
</code>```

```
True
False
True
True
False
```

I say again. the sys.argv[1] and sys.argv[2] will provide file line by line and when the comparison ends. they will take next lines in files how can I do it ?
I think it would done by using while loops but how ?

答:
It will help to compare two files line by line and get expected results.</p>

```<code>import sys

f1 = sys.argv[1]
f2 = sys.argv[2]

f1_data = open(f1, 'r')
f2_data = open(f2, 'r')

result = [True if f1_line == f2_line else False for f1_line, f2_line in zip(f1_data.readlines(), f2_data.readlines())]

# Result will be in list: [True, False, True, True, False]
print(result)
</code>```

Title: Sys arguments with while

Body:
The lines in the files will be top to bottom (one under the other)

I have 2 ".txt" file like this :

#john.txt
hello
my
name
is
John
#jack.txt

second one is like that:

hello
your
name
is
Jack

I will compare this texts line by line but the problem is when I write

"python john.txt jack.txt " on command line  sys.arg[1] and sys.argv[2]
will provide the lines and compare them . so sys.argv[1] must provide lines in file one by one but I will write"python john.txt jack.txt " only one time.
sample output:

python john.txt jack.txt

True
False
True
True
False

I say again. the sys.argv[1] and sys.argv[2] will provide file line by line and when the comparison ends. they will take next lines in files how can I do it ?
I think it would done by using while loops but how ?

Body:
It will help to compare two files line by line and get expected results.

import sys

f1 = sys.argv[1]
f2 = sys.argv[2]

f1_data = open(f1, 'r')
f2_data = open(f2, 'r')

result = [True if f1_line == f2_line else False for f1_line, f2_line in zip(f1_data.readlines(), f2_data.readlines())]

# Result will be in list: [True, False, True, True, False]
print(result)


问:
Programming a live looper with Audiokit?
Hello to all audiokit users,
(I hope this is the right place to ask my question)

I am willing to make a live looping app for ios, mostly because I just can't find what I need in the other currently existing apps.

I am considering the Audiokit framework to do so, for it is very well documented, accessible, user friendly,...

Although, before starting from scratch I wished to have the input of more experienced users than myself:

Is Audiokit adapted for this kind of application? Until now most of the apps I have seen are more 'Synth-like' apps.

Thanks for your feedback!

答:
Yes. Here are two examples of looping apps in the app store built with AudioKit:

Jam Looper

https://itunes.apple.com/us/app/jam-looper-music-maker/id1061465697?mt=8

Loop Maker

https://itunes.apple.com/us/app/loop-maker-amazing-music-maker/id1196282854

Hope that is helpful,


问:
Bearer token based authentication in swagger 3.x
I'm currently using swagger-ui 2.x and following is the authentication I've been using with swagger-ui 2.x.

var key = $(this).val();
swaggerUi.api.clientAuthorizations.add("default", new SwaggerClient.ApiKeyAuthorization("Authorization", "Bearer "+ key, "header"));

Currently, I'm upgrading the swagger-ui into latest 3.x version and I need to know how to achieve above with swagger 3.x. Can I have on bearer token based authentication?

答:
The requestInterceptor can be used used if you want to authenticate "try it out" requests automatically. If you instead want to provide UI where your users can enter their Bearer token, you can add the corresponding security definition to your API definition:

securityDefinitions:
  bearerAuth:
    type: apiKey
    in: header
    name: Authorization
    description: Enter your bearer token in the format **Bearer <token>**

security:
  - bearerAuth: []
```

In this case, Swagger UI will show the "Authorize" button. The users can click this button to enter their bearer token:

That's if you are using OpenAPI 2.0 (fka Swagger 2.0).

OpenAPI 3.0 supports Bearer authentication natively, so that the bearer token can be entered without the "Bearer" prefix.

Body:
The requestInterceptor can be used used if you want to authenticate "try it out" requests automatically. If you instead want to provide UI where your users can enter their Bearer token, you can add the corresponding security definition to your API definition:

securityDefinitions:
  bearerAuth:
    type: apiKey
    in: header
    name: Authorization
    description: Enter your bearer token in the format **Bearer &lt;token>**

security:
  - bearerAuth: []

In this case, Swagger UI will show the "Authorize" button. The users can click this button to enter their bearer token:

That's if you are using OpenAPI 2.0 (fka Swagger 2.0).

OpenAPI 3.0 supports Bearer authentication natively, so that the bearer token can be entered without the "Bearer" prefix.


问:
Powershell - Send CSV data to email in a table
Right now my goal is to download a CSV containing threat data from a url, capture two columns, File Name and the DeviceName, both of which are headers in the CSV. I then want to export that data to a single line in an email, which will then go to two members on our security team to review in a plaintext format. The goal is to make it unnecessary for them to download and copy paste directly from the CSV, as there's a lot of extraneous data in the CSV.

It's a pretty simple script, so everything works fine. My question is: how do I pull two columns of data from the csv and write it to the email body? Ideally in some sort of table, so the two columns are aligned.

I've found some resources online, most notably a script that takes any Object from the PowerShell interface, convert the object (table) into HTML and then sends it by email: https://gallery.technet.microsoft.com/scriptcenter/bd0c8d87-466f-4488-92a2-0f726cb6f4cd

Which is perfect, since this is exactly what I want to do. I'm just not really sure how to properly pass the data from the CSV to the powershell function.

Note this is also my first project in powershell, and it's mostly cobbled together from technet documentation and scraps of code examples I've found online. I'm a junior sysadmin, so not a ton of programming background.

Thanks bunches!

Update 1

So managed to get a bit more success this time around, but unfortunately the emailed output is a garbled list of numbers that don't correspond to any data found within the CSV.

I'm pretty sure my error is somewhere in here, but I'm not quite sure where I'm failing:

```<code>$csv = Import-Csv $output | Select "File Name",DeviceName | ConvertTo-Html
</code>```

The rest of my code is below:

```<code><#
.SYNOPSIS
Send an email with an object in a pretty table
.DESCRIPTION
Send email
.PARAMETER InputObject
Any PSOBJECT or other Table
.PARAMETER Subject
The Subject of the email
.PARAMETER To
The To field is who receives the email
.PARAMETER From
The From address of the email
.PARAMETER CSS
This is the Cascading Style Sheet that will be used to Style the table
.PARAMETER SmtpServer
The SMTP relay server
.EXAMPLE
PS C:\> Send-HtmlEmail -InputObject (Get-process *vmware* | select CPU, WS) -Subject "This is a process report"
An example to send some process information to email recipient
.NOTES
NAME        :  Send-HtmlEmail
VERSION     :  1.1.0
LAST UPDATED:  01/03/2013
AUTHOR      :  Milo
.INPUTS
None
.OUTPUTS
None
#>

function Send-HTMLEmail {
#Requires -Version 2.0
[CmdletBinding()]
 Param
   ([Parameter(Mandatory=$True,
               Position = 0,
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true,
               HelpMessage="Please enter the Inputobject")]
    $InputObject,
    [Parameter(Mandatory=$True,
               Position = 1,
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true,
               HelpMessage="Please enter the Subject")]
    [String]$Subject,
    [Parameter(Mandatory=$False,
               Position = 2,
               HelpMessage="Please enter the To address")]
    [String[]]$To = "smurphy@klick.com",
    [String]$From = "cylancereporting@klick.com",
    [String]$CSS,
    [String]$SmtpServer ="smtp.klick.com"
   )#End Param

if (!$CSS)
{
    $CSS = @"
        <style type="text/css">
            table {
            font-family: Verdana;
            border-style: dashed;
            border-width: 1px;
            border-color: #FF6600;
            padding: 5px;
            background-color: #FFFFCC;
            table-layout: auto;
            text-align: center;
            font-size: 8pt;
            }

            table th {
            border-bottom-style: solid;
            border-bottom-width: 1px;
            font: bold
            }
            table td {
            border-top-style: solid;
            border-top-width: 1px;
            }
            .style1 {
            font-family: Courier New, Courier, monospace;
            font-weight:bold;
            font-size:small;
            }
            </style>
"@
}#End if

$HTMLDetails = @{
    Title = $Subject
    Head = $CSS
    }

$Splat = @{
    To         =$To
    Body       ="$($InputObject | ConvertTo-Html @HTMLDetails)"
    Subject    =$Subject
    SmtpServer =$SmtpServer
    From       =$From
    BodyAsHtml =$True
    }
    Send-MailMessage @Splat

}#Send-HTMLEmail

#Defines variables
$url = "https://protect.cylance.com/Reports/ThreatDataReportV1/threats/BE5ABB1717DB46978BED0AF14A308557"
$output = "$PWD\ThreatsDataReport.csv"

(New-Object System.Net.WebClient).DownloadFile($url, $output)
#Downloads the CSV from $url and saves it to $output

$csv = Import-Csv $output | Select "File Name",DeviceName | ConvertTo-Html

Send-HTMLEmail -InputObject ($csv) -Subject "Cylance: Weekly Summary"
</code>```

Original Code

```<code>$url = "foo.com/directlinktocsv"
$output = "$PSScriptRoot\ThreatsDataReport.csv"
$emailSMTPServer = "smtp.mydomain.com"
$emailFrom = "myemail@mydomain.com"
$emailRecipients = @("Foo <foo@mydomain.com>", "Bar <bar@mydomain.com>")
$emailSubject = "Cylance Detected Threats"
$emailBody = "This is where I want my output to go"

(New-Object System.Net.WebClient).DownloadFile($url, $output)

$csv = Import-Csv $output

    $csv."File Name" | ForEach-Object {
    $_

    }

    $csv.DeviceName | ForEach-Object {

    $_

    }

Send-MailMessage -From $emailFrom -To $emailRecipients -SmtpServer $emailSMTPServer -subject $emailSubject -Body $emailBody
</code>```

答:
If you only want the first row from the CSV file with those column names, you could do something like this:

```<code>$csv = Import-Csv $output | Select-Object -First 1
$emailBody = "File Name: {0}`r`nDevice Name: {1}" -f
  $csv."File Name", $csv.DeviceName
$params = @{
  "From"       = $emailFrom
  "To"         = $emailRecipients
  "SmtpServer" = $emailSMTPServer
  "Subject"    = $emailSubject
  "Body"       = $emailBody
}
Send-MailMessage @params
</code>```

To grab multiple rows of output, you could do something like:

```<code>$emailBody = Import-Csv $output |
  Select-Object "File Name",DeviceName |
  Format-Table -AutoSize | Out-String
$params = @{
  "From"       = $emailFrom
  "To"         = $emailRecipients
  "SmtpServer" = $emailSMTPServer
  "Subject"    = $emailSubject
  "Body"       = $emailBody
}
Send-MailMessage @params
</code>```

Body:
Right now my goal is to download a CSV containing threat data from a url, capture two columns, File Name and the DeviceName, both of which are headers in the CSV. I then want to export that data to a single line in an email, which will then go to two members on our security team to review in a plaintext format. The goal is to make it unnecessary for them to download and copy paste directly from the CSV, as there's a lot of extraneous data in the CSV.

It's a pretty simple script, so everything works fine. My question is: how do I pull two columns of data from the csv and write it to the email body? Ideally in some sort of table, so the two columns are aligned.

I've found some resources online, most notably a script that takes any Object from the PowerShell interface, convert the object (table) into HTML and then sends it by email: https://gallery.technet.microsoft.com/scriptcenter/bd0c8d87-466f-4488-92a2-0f726cb6f4cd

Which is perfect, since this is exactly what I want to do. I'm just not really sure how to properly pass the data from the CSV to the powershell function.

Note this is also my first project in powershell, and it's mostly cobbled together from technet documentation and scraps of code examples I've found online. I'm a junior sysadmin, so not a ton of programming background.

Thanks bunches!

Update 1

So managed to get a bit more success this time around, but unfortunately the emailed output is a garbled list of numbers that don't correspond to any data found within the CSV.

I'm pretty sure my error is somewhere in here, but I'm not quite sure where I'm failing:

$csv = Import-Csv $output | Select "File Name",DeviceName | ConvertTo-Html

The rest of my code is below:

<#
.SYNOPSIS
Send an email with an object in a pretty table
.DESCRIPTION
Send email
.PARAMETER InputObject
Any PSOBJECT or other Table
.PARAMETER Subject
The Subject of the email
.PARAMETER To
The To field is who receives the email
.PARAMETER From
The From address of the email
.PARAMETER CSS
This is the Cascading Style Sheet that will be used to Style the table
.PARAMETER SmtpServer
The SMTP relay server
.EXAMPLE
PS C:\> Send-HtmlEmail -InputObject (Get-process *vmware* | select CPU, WS) -Subject "This is a process report"
An example to send some process information to email recipient
.NOTES
NAME        :  Send-HtmlEmail
VERSION     :  1.1.0
LAST UPDATED:  01/03/2013
AUTHOR      :  Milo
.INPUTS
None
.OUTPUTS
None
#>

function Send-HTMLEmail {
#Requires -Version 2.0
[CmdletBinding()]
 Param
   ([Parameter(Mandatory=$True,
               Position = 0,
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true,
               HelpMessage="Please enter the Inputobject")]
    $InputObject,
    [Parameter(Mandatory=$True,
               Position = 1,
               ValueFromPipeline=$true,
               ValueFromPipelineByPropertyName=$true,
               HelpMessage="Please enter the Subject")]
    [String]$Subject,
    [Parameter(Mandatory=$False,
               Position = 2,
               HelpMessage="Please enter the To address")]
    [String[]]$To = "smurphy@klick.com",
    [String]$From = "cylancereporting@klick.com",
    [String]$CSS,
    [String]$SmtpServer ="smtp.klick.com"
   )#End Param

if (!$CSS)
{
    $CSS = @"

"@
}#End if

$HTMLDetails = @{
    Title = $Subject
    Head = $CSS
    }

$Splat = @{
    To         =$To
    Body       ="$($InputObject | ConvertTo-Html @HTMLDetails)"
    Subject    =$Subject
    SmtpServer =$SmtpServer
    From       =$From
    BodyAsHtml =$True
    }
    Send-MailMessage @Splat

}#Send-HTMLEmail

#Defines variables
$url = "https://protect.cylance.com/Reports/ThreatDataReportV1/threats/BE5ABB1717DB46978BED0AF14A308557"
$output = "$PWD\ThreatsDataReport.csv"

(New-Object System.Net.WebClient).DownloadFile($url, $output)
#Downloads the CSV from $url and saves it to $output

$csv = Import-Csv $output | Select "File Name",DeviceName | ConvertTo-Html

Send-HTMLEmail -InputObject ($csv) -Subject "Cylance: Weekly Summary"

Original Code

$url = "foo.com/directlinktocsv"
$output = "$PSScriptRoot\ThreatsDataReport.csv"
$emailSMTPServer = "smtp.mydomain.com"
$emailFrom = "myemail@mydomain.com"
$emailRecipients = @("Foo <foo@mydomain.com>", "Bar <bar@mydomain.com>")
$emailSubject = "Cylance Detected Threats"
$emailBody = "This is where I want my output to go"

(New-Object System.Net.WebClient).DownloadFile($url, $output)

$csv = Import-Csv $output

    $csv."File Name" | ForEach-Object {
    $_

    }

    $csv.DeviceName | ForEach-Object {

    $_

    }

Send-MailMessage -From $emailFrom -To $emailRecipients -SmtpServer $emailSMTPServer -subject $emailSubject -Body $emailBody

Body:
If you only want the first row from the CSV file with those column names, you could do something like this:

$csv = Import-Csv $output | Select-Object -First 1
$emailBody = "File Name: {0}`r`nDevice Name: {1}" -f
  $csv."File Name", $csv.DeviceName
$params = @{
  "From"       = $emailFrom
  "To"         = $emailRecipients
  "SmtpServer" = $emailSMTPServer
  "Subject"    = $emailSubject
  "Body"       = $emailBody
}
Send-MailMessage @params

To grab multiple rows of output, you could do something like:

$emailBody = Import-Csv $output |
  Select-Object "File Name",DeviceName |
  Format-Table -AutoSize | Out-String
$params = @{
  "From"       = $emailFrom
  "To"         = $emailRecipients
  "SmtpServer" = $emailSMTPServer
  "Subject"    = $emailSubject
  "Body"       = $emailBody
}
Send-MailMessage @params


问:
Use of constexpr in exception message
I was trying to use a constexpr inside an exception message, but this does not work:
The followoing code is compiling well on g++ (using c++11 or c++14).

```<code>#include <exception>

constexpr auto TEST = "test";

class test_throw : public std::exception {
public:
    virtual const char* what() const throw() {
        return (std::string("THROW ")+TEST).c_str();
    }
};

int main()
{
    throw test_throw{};
}
</code>```

I wonder why my exception is outputting an empty message, ok that seems like a bad trick, but I don't understand how the message can be empty.

Is there a way to achieve this without replacing the constexpr by a macro ?

答:
Disaster awaits - here's gcc's warning:

```<code><source>: In member function 'virtual const char* test_throw::what() const':
9 : <source>:9:51: warning: function returns address of local variable [-Wreturn-local-addr]
         return (std::string("THROW ")+TEST).c_str();
</code>```

Here are a few ways to make it safe:

Option 1 - derive from a more concrete standard exception, initialising
the message in the constructor.

```<code>#include <stdexcept>
#include <string>

constexpr auto TEST = "test";

class test_throw : public std::runtime_error
{
public:
    test_throw()
    : runtime_error(std::string("THROW ")+TEST)
    {}
};
</code>```

Option 2 - construct the message in a thread_safe static way:

```<code>class test_throw : public std::exception
{
public:
    const char* what() const noexcept
    {
        thread_local static std::string message;

        try
        {
            message = std::string("THROW ") + TEST;
            return message.c_str();
        }
        catch(...)
        {
            return "can't give you a message";
        }
    }
};
</code>```

Option 3 - reinvent the wheel.

```<code>class test_throw : public std::exception
{
    std::string message_;

public:
    test_throw()
    : message_ { std::string("THROW ") + TEST }
    {}

    const char* what() const noexcept
    {
        return message_.c_str();
    }
};
</code>```

Title: Use of constexpr in exception message

Body:
I was trying to use a constexpr inside an exception message, but this does not work:
The followoing code is compiling well on g++ (using c++11 or c++14).

#include <exception>

constexpr auto TEST = "test";

class test_throw : public std::exception {
public:
    virtual const char* what() const throw() {
        return (std::string("THROW ")+TEST).c_str();
    }
};

int main()
{
    throw test_throw{};
}

I wonder why my exception is outputting an empty message, ok that seems like a bad trick, but I don't understand how the message can be empty.

Is there a way to achieve this without replacing the constexpr by a macro ?

Body:
Disaster awaits - here's gcc's warning:

<source>: In member function 'virtual const char* test_throw::what() const':
9 : <source>:9:51: warning: function returns address of local variable [-Wreturn-local-addr]
         return (std::string("THROW ")+TEST).c_str();

Here are a few ways to make it safe:

Option 1 - derive from a more concrete standard exception, initialising
the message in the constructor.

#include <stdexcept>
#include <string>

constexpr auto TEST = "test";

class test_throw : public std::runtime_error
{
public:
    test_throw()
    : runtime_error(std::string("THROW ")+TEST)
    {}
};

Option 2 - construct the message in a thread_safe static way:

class test_throw : public std::exception
{
public:
    const char* what() const noexcept
    {
        thread_local static std::string message;

        try
        {
            message = std::string("THROW ") + TEST;
            return message.c_str();
        }
        catch(...)
        {
            return "can't give you a message";
        }
    }
};

Option 3 - reinvent the wheel.

class test_throw : public std::exception
{
    std::string message_;

public:
    test_throw()
    : message_ { std::string("THROW ") + TEST }
    {}

    const char* what() const noexcept
    {
        return message_.c_str();
    }
};


问:
How can i move image on z-axis by using accelerometer?
My image is moving in tw0 directions. x and y axis, How can i move image in z direction?</p>

答: The z-direction points towards you, so to say. Try accessing the layer of the view. It should have a z-parameter.</p>


问:
Tcl regexp expression to catch words outside brackets
I want to parse:
([(A touch B) over C] touch {D touch E}) is good.

Using:
( P1 touch P2) is good.

I want to replace P1 and P2 by regular expression to get
P1 = [(A touch B) over C]
P2 =  {D touch E}
My first idea is:
( (.*)  touch (.*)) is good.

But i got wrong matching:
P1 = [(A touch B) over C] touch  {D
P2 = E}

I want to break on the "touch" outside the brackets.
Note: A, B, C... are examples so we should use .*

答:
You may use a regex pattern that will match either a [...] or {...} substrings before touch and then the same pattern after.

It will look like

```<code>\((\[[^][]*]|{[^{}]*}) touch (\[[^][]*]|{[^{}]*})\) is good
</code>```

See the regex demo at regex101.
The (\[[^][]*]|{[^{}]*}) construct is a capturing group that matches either a [ + 0+ chars other than [ and ] and then a ] or a { followed with 0+ chars other than { and } and then }.

One remark: there is no way to match nested balanced bracketed substrings with Tcl regex.

When using Tcl code, you may build the regex dynamically:

```<code>set txt {([(A touch B) over C] touch {D touch E}) is good}
set squares {\[[^][]*\]}
set braces {\{[^{}]*\}}
set cap "($squares|$braces)"
set rx "\\($cap touch $cap\\) is good";
lassign [lrange [regexp -all -inline $rx $txt] 1 end] P1 P2
puts "$P1 ::: $P2"
</code>```

Output: [(A touch B) over C] ::: {D touch E}.

See the Tcl online demo.

Body:
You may use a regex pattern that will match either a [...] or {...} substrings before touch and then the same pattern after.

It will look like

\((\[[^][]*]|{[^{}]*}) touch (\[[^][]*]|{[^{}]*})\) is good

See the regex demo at regex101.
The (\[[^][]*]|{[^{}]*}) construct is a capturing group that matches either a [ + 0+ chars other than [ and ] and then a ] or a { followed with 0+ chars other than { and } and then }.

One remark: there is no way to match nested balanced bracketed substrings with Tcl regex.

When using Tcl code, you may build the regex dynamically:

set txt {([(A touch B) over C] touch {D touch E}) is good}
set squares {\[[^][]*\]}
set braces {\{[^{}]*\}}
set cap "($squares|$braces)"
set rx "\\($cap touch $cap\\) is good";
lassign [lrange [regexp -all -inline $rx $txt] 1 end] P1 P2
puts "$P1 ::: $P2"

Output: [(A touch B) over C] ::: {D touch E}.

See the Tcl online demo.


问:
HTML Different styles

Can anyone tell me what is the difference between the two styles of html code written below.

```<code>return '<div id='suggestionId' class="autocomplete-suggestion">No Message Found</div>';
</code>```

Vs

```<code>var autoCompleteSuggestion;
 autoCompleteSuggestion = $('<div/>').attr({id: 'suggestionId'}).addClass('suggestion').html('No Message Found');
return autoCompleteSuggestion;
</code>```

Results are same, the below mentioned script what kind of scripting is it called. Would like to know more

答:
Neither one of them is just straight HTML.

The first one is vanilla javascript. But should be written like this

```<code>return '<div id=' + suggestionId + ' class="autocomplete-suggestion">No Message Found</div>';
</code>```

Otherwise suggestionId will throw an error and not render the id.

The second one is written using jQuery, but can be modified to be just

```<code>return $('<div/>').attr({id: 'suggestionId'}).addClass('suggestion').html('No Message Found');
</code>```

Both will render the same to the browser.

Title: HTML Different styles

Body:
Can anyone tell me what is the difference between the two styles of html code written below.

return '
No Message Found
';

Vs

var autoCompleteSuggestion;
 autoCompleteSuggestion = $('
').attr({id: 'suggestionId'}).addClass('suggestion').html('No Message Found');
return autoCompleteSuggestion;

Results are same, the below mentioned script what kind of scripting is it called. Would like to know more

Body:
Neither one of them is just straight HTML.

The first one is vanilla javascript. But should be written like this

return '<div id=' + suggestionId + ' class="autocomplete-suggestion">No Message Found</div>';

Otherwise suggestionId will throw an error and not render the id.

The second one is written using jQuery, but can be modified to be just

return $('<div/>').attr({id: 'suggestionId'}).addClass('suggestion').html('No Message Found');

Both will render the same to the browser.


问:
How to call readEntity on a Response twice?
What I'm doing right now is resulting in a:

```<code>java.io.IOException: stream is closed
</code>```

on the 2nd readEntity() since it closes the stream after the first read.

Here is what I'm doing:

```<code>Response response = target.queryParam("start", startIndex)
   .queryParam("end", end)
   .request()
   .accept(MediaType.APPLICATION_XML)
   .header(authorizationHeaderName, authorizationHeaderValue)
   .get();

String xml = response.readEntity(String.class);
ourLogger.debug(xml);

MyClass message = response.readEntity(MyClass.class); //throws IOException
</code>```

答:
/You can use Response#bufferEntity(), which will allow you to read the entity stream multiple times.

```<code>Response response = ...
response.bufferEntity();
String s = response.readEntity(String.class);
MyEntity me = response.readEntity(MyEntity.class);
response.close();
</code>```

Update

After you read the entity with readEntity(), the result of the reading is cached and is available with the call to getEntity(). This information doesn't really answer the OP's question, but I thought it was useful information to add in.

Body:
What I'm doing right now is resulting in a:

java.io.IOException: stream is closed

on the 2nd readEntity() since it closes the stream after the first read.

Here is what I'm doing:

Response response = target.queryParam("start", startIndex)
   .queryParam("end", end)
   .request()
   .accept(MediaType.APPLICATION_XML)
   .header(authorizationHeaderName, authorizationHeaderValue)
   .get();

String xml = response.readEntity(String.class);
ourLogger.debug(xml);

MyClass message = response.readEntity(MyClass.class); //throws IOException

Body:
/You can use Response#bufferEntity(), which will allow you to read the entity stream multiple times.

Response response = ...
response.bufferEntity();
String s = response.readEntity(String.class);
MyEntity me = response.readEntity(MyEntity.class);
response.close();

Update

After you read the entity with readEntity(), the result of the reading is cached and is available with the call to getEntity(). This information doesn't really answer the OP's question, but I thought it was useful information to add in.

ContentLicense: CC BY-SA 4.0