问:
How to set a timercalling a member method in F#?
I am trying to achieve this:

```<code>type Test() =

    member val MyTimer : Timer = new Timer(TimerCallback TimerEvent)

    member mutable Status : bool = false
    ...

    member this.StartTimer =
        this.MyTimer....

    member this.TimerEvent =
        if this.Status...
</code>```

I need to create a timer that is part of the class instance, needs to be referenced by several methods (to start / stop it) but also, the timer ballback needs to be able to access some of the inner states.

I can't find the syntax to create the timer object so that it has access to class members and class members have access to it.

But I think I'm having some confusion:

It looks like I can do the timer like this:

```<code>        member this.Timer : Timer = new Timer(TimerCallback (fun x -> printfn "%A" x))
</code>```

but I though member was reserved for methods and val for the fields? can anyone clarify this? I can do member this.xxx, but I can't do val this.xxx..

答:
I found this post because I need to implement a scheduled job in F# for the first time.
I'm also learning F# and it is the first time I saw "val", so I read something about it.

Regarding your question.

"member val ... " is a particular case described here:
The val Kweyword

Another use of the val keyword is in conjunction with the member keyword to declare an auto-implemented property.

I think this answer your question.

Said that, I looked up to your code:

```<code>member this.Timer : Timer = new Timer(TimerCallback (fun x -> printfn "%A" x))
</code>```

This is not correct to me because it exposes the Timer publicly.

I like the idea to have an object (the Timer) declared but not initialized, so that I can refer to its instance within multiple methods (Start/Stop) and (most important) Dispose it properly.

So, also regarding your doubt about the syntax...

I can't find the syntax to create the timer object so that it has access to class members and class members have access to it.

I came out with the following example:

open System
open System.Threading

type public ExampleJob () as me =

    let timer_elapsed:TimerCallback = TimerCallback(fun (state) -> me.OnCall(state) )
    [<DefaultValue>] val mutable private timer:Timer    // no need to initialize

    member __.IsActive with get() = __.timer <> null

    member __.Start(frequency:TimeSpan) =
        __.Stop()  // Dispose previous timer if exists
        __.timer <- new Timer(timer_elapsed)
        __.timer.Change(0, int(frequency.TotalMilliseconds)) |> ignore

    member __.Stop() =
        if __.timer <> null then __.timer.Dispose() ; __.timer <- null

    member private __.OnCall (state:obj) =
        // do the real work here
        // The state object is the Timer object.
        Console.WriteLine(sprintf"OnCall(%i) at %s" ((state :?> Timer).GetHashCode()) (DateTime.Now.ToString("ss:fff")))

    interface IDisposable with
        member this.Dispose(): unit =
            this.Stop()
```

<p>Checking the Timer itself is enough to expose the <em>Status</em> (IsActive/IsRunning).<br>
<em>Start/Stop</em> can be called in any sequence an number of times. A new call to <em>Start()</em> will reset the current timer to the new desired frequency.<br>
<strong>It is not thread safe</strong> and I haven't tested it enough, so I'm not 100% sure the timer "survives" when/if the whole class is no more referenced.<br>
Anyway I hope this is a useful example.  </p>

<p><strong>[Update]</strong>  </p>

<p>new version with the suggestion of Ben  </p>

<pre class="lang-ml prettyprint-override"><code>open System

type ExampleJob () =

    let timer = new Timers.Timer()
    let OnCall = fun(args) ->
                 // do real job here
                 Console.WriteLine(sprintf"OnCall(%O) at %s" args (DateTime.Now.ToString("ss:fff")))

    do timer.Elapsed.Add(OnCall) // carefull to add it only once

    member this.IsActive with get() = timer.Enabled

    member this.Start(frequency:TimeSpan) =
        timer.Interval <- frequency.TotalMilliseconds
        timer.AutoReset <- true
        timer.Enabled <- true
        OnCall() // first call (if needed)
        timer.Start()

    member this.Stop() = timer.Enabled <- false

    interface IDisposable with
        member this.Dispose(): unit =
            timer.Dispose()
</code>```

Body:
I am trying to achieve this:

type Test() =

    member val MyTimer : Timer = new Timer(TimerCallback TimerEvent)

    member mutable Status : bool = false
    ...

    member this.StartTimer =
        this.MyTimer....

    member this.TimerEvent =
        if this.Status...

I need to create a timer that is part of the class instance, needs to be referenced by several methods (to start / stop it) but also, the timer ballback needs to be able to access some of the inner states.

I can't find the syntax to create the timer object so that it has access to class members and class members have access to it.

But I think I'm having some confusion:

It looks like I can do the timer like this:

        member this.Timer : Timer = new Timer(TimerCallback (fun x -> printfn "%A" x))

but I though member was reserved for methods and val for the fields? can anyone clarify this? I can do member this.xxx, but I can't do val this.xxx..

Body:
I found this post because I need to implement a scheduled job in F# for the first time.
I'm also learning F# and it is the first time I saw "val", so I read something about it.

Regarding your question.

"member val ... " is a particular case described here:
The val Kweyword

Another use of the val keyword is in conjunction with the member keyword to declare an auto-implemented property.

I think this answer your question.

Said that, I looked up to your code:

member this.Timer : Timer = new Timer(TimerCallback (fun x -> printfn "%A" x))

This is not correct to me because it exposes the Timer publicly.

I like the idea to have an object (the Timer) declared but not initialized, so that I can refer to its instance within multiple methods (Start/Stop) and (most important) Dispose it properly.

So, also regarding your doubt about the syntax...

I can't find the syntax to create the timer object so that it has access to class members and class members have access to it.

I came out with the following example:

open System
open System.Threading

type public ExampleJob () as me =

    let timer_elapsed:TimerCallback = TimerCallback(fun (state) -> me.OnCall(state) )
    [<DefaultValue>] val mutable private timer:Timer    // no need to initialize

    member __.IsActive with get() = __.timer <> null

    member __.Start(frequency:TimeSpan) =
        __.Stop()  // Dispose previous timer if exists
        __.timer <- new Timer(timer_elapsed)
        __.timer.Change(0, int(frequency.TotalMilliseconds)) |> ignore

    member __.Stop() =
        if __.timer <> null then __.timer.Dispose() ; __.timer <- null

    member private __.OnCall (state:obj) =
        // do the real work here
        // The state object is the Timer object.
        Console.WriteLine(sprintf"OnCall(%i) at %s" ((state :?> Timer).GetHashCode()) (DateTime.Now.ToString("ss:fff")))

    interface IDisposable with
        member this.Dispose(): unit =
            this.Stop()

Checking the Timer itself is enough to expose the Status (IsActive/IsRunning).

Start/Stop can be called in any sequence an number of times. A new call to Start() will reset the current timer to the new desired frequency.

It is not thread safe and I haven't tested it enough, so I'm not 100% sure the timer "survives" when/if the whole class is no more referenced.

Anyway I hope this is a useful example.

[Update]

new version with the suggestion of Ben

open System

type ExampleJob () =

    let timer = new Timers.Timer()
    let OnCall = fun(args) ->
                 // do real job here
                 Console.WriteLine(sprintf"OnCall(%O) at %s" args (DateTime.Now.ToString("ss:fff")))

    do timer.Elapsed.Add(OnCall) // carefull to add it only once

    member this.IsActive with get() = timer.Enabled

    member this.Start(frequency:TimeSpan) =
        timer.Interval <- frequency.TotalMilliseconds
        timer.AutoReset <- true
        timer.Enabled <- true
        OnCall() // first call (if needed)
        timer.Start()

    member this.Stop() = timer.Enabled <- false

    interface IDisposable with
        member this.Dispose(): unit =
            timer.Dispose()


来源: stackexchange

问:
Rowwise coloring in facet_grid in ggplot
I have created a circle grid with each row showing a state's standing on 7 different parameters based on circle sizes. These parameters are in percentage and add up to 100 for each state. For my facet_grid, I'd like to color and size each circle based on the scale for individual states and not as per the entire grid. I'll elaborate on with an example.

circle grid

```<code>library(ggforce)
library(tidyverse)
library (ggplot)
library(reshape2)

d <- data.frame("state" = c("Alabama", "Florida", "Washington", "New York"),
       "A" = c(20, 25, 45, 11),
       "B" = c(25, 25, 10, 4),
       "C" = c(50, 5, 20, 5),
       "D" = c(5, 45, 25, 80))

d1 <- melt(d, id.vars = "state")

p3 <- ggplot(d1) +
  geom_circle(aes(x0 = 0.5, y0 = 0.5, r = value, color = "white", fill = value), data = d1) +
  scale_fill_continuous(low = "#5fc5bd", high = "#f37021") +
  scale_color_manual(values = "white") +
  coord_fixed() +
  theme_bw() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.ticks = element_blank() ,
        legend.position = "none",
        panel.border = element_blank(),
           axis.title.x=element_blank(),
           axis.title.y=element_blank(),
        axis.text = element_blank())

p3 <- p3 + facet_grid(state ~ variable, labeller=label_wrap_gen(width=10)) +
  theme(strip.text.x = element_text(size = 10, face = "bold"),
          strip.text.y = element_text(size = 10, face = "bold"),
          strip.background = element_rect(colour = "gray", fill = "white"))
p3
</code>```

As of now the circles on the graph is scaling as per the largest values in the entire dataset. I'd like it to consider values for each state and scale the circle sizes based on the values for each state - so the biggest circle in Alabama should be C, colored orange (highest value for that state) and likewise for other states. Any ideas would be really helpful, thanks.

答:
You can add a new column to df1 to achieve this:

```<code>d1 <- melt(d, id.vars = "state") %>%
      group_by(state) %>%
      mutate(per_state = value/max(value))
</code>```

Now you set r = per_state and fill = per_state to get this:

ContentLicense: CC BY-SA 4.0

Body:
I have created a circle grid with each row showing a state's standing on 7 different parameters based on circle sizes. These parameters are in percentage and add up to 100 for each state. For my facet_grid, I'd like to color and size each circle based on the scale for individual states and not as per the entire grid. I'll elaborate on with an example.

circle grid

library(ggforce)
library(tidyverse)
library (ggplot)
library(reshape2)

d <- data.frame("state" = c("Alabama", "Florida", "Washington", "New York"),
       "A" = c(20, 25, 45, 11),
       "B" = c(25, 25, 10, 4),
       "C" = c(50, 5, 20, 5),
       "D" = c(5, 45, 25, 80))

d1 <- melt(d, id.vars = "state")

p3 <- ggplot(d1) +
  geom_circle(aes(x0 = 0.5, y0 = 0.5, r = value, color = "white", fill = value), data = d1) +
  scale_fill_continuous(low = "#5fc5bd", high = "#f37021") +
  scale_color_manual(values = "white") +
  coord_fixed() +
  theme_bw() +
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        axis.ticks = element_blank() ,
        legend.position = "none",
        panel.border = element_blank(),
           axis.title.x=element_blank(),
           axis.title.y=element_blank(),
        axis.text = element_blank())

p3 <- p3 + facet_grid(state ~ variable, labeller=label_wrap_gen(width=10)) +
  theme(strip.text.x = element_text(size = 10, face = "bold"),
          strip.text.y = element_text(size = 10, face = "bold"),
          strip.background = element_rect(colour = "gray", fill = "white"))
p3

As of now the circles on the graph is scaling as per the largest values in the entire dataset. I'd like it to consider values for each state and scale the circle sizes based on the values for each state - so the biggest circle in Alabama should be C, colored orange (highest value for that state) and likewise for other states. Any ideas would be really helpful, thanks.

Body:
You can add a new column to df1 to achieve this:

d1 <- melt(d, id.vars = "state") %>%
      group_by(state) %>%
      mutate(per_state = value/max(value))

Now you set r = per_state and fill = per_state to get this:


问:
Function that changes the cell color
I am creating a function where if a cell has Yellow color and if I enter 0 in that cell, then it pops up a message box Red then colors the cell Red. And then if I enter 1 it reverts the color to Yellow.

Here's my code:

```<code>Function ColorChange(range)
    If range.Interior.ColorIndex = 6 And range.Value < 1 Then
        MsgBox "Project Delay!", vbCritical, "Attention required!"
        range.Interior.ColorIndex = 3
    Else
        If range.Interior.ColorIndex = 3 And range.Value > 0 Then
            range.Interior.ColorIndex = 6
        End If
    End If
End Function
</code>```

答:
1) It is not necessary to use a function. In VBA you can program classically (and run the macro manually) or you can program event. It means that a macro will be running in case of a particular event (like a mouse-click or a modification in the sheet). That is why Siddarth Rout spoke about Worksheet_change, it is an event. In this case, define your Sub in this way and the following code will be executed in case of Worksheet modification.

2) You have to define a Private Sub for the specific worksheet. Private Sub Worksheet_change() and you put in argument ByVal Target As range. It means that you will receive information about the range that have been changed (Target).

3) After you will use Target.Address to define the range used by your code.

4) Your 2 intricate if statements are not necessary. It is better to use an if statement and an else if statement.

5) The following code is OK for me:

```<code>Private Sub Worksheet_change(ByVal Target As range)

If range(Target.Address).Interior.ColorIndex = 6 And range(Target.Address).Value < 1 Then
    MsgBox "Project Delay!", vbCritical, "Attention required!"
    range(Target.Address).Interior.ColorIndex = 3
ElseIf range(Target.Address).Interior.ColorIndex = 3 And range(Target.Address).Value > 0 Then
    range(Target.Address).Interior.ColorIndex = 6
End If

End Sub
</code>```

Title: Function that changes the cell color

Body:
I am creating a function where if a cell has Yellow color and if I enter 0 in that cell, then it pops up a message box Red then colors the cell Red. And then if I enter 1 it reverts the color to Yellow.

Here's my code:

Function ColorChange(range)
    If range.Interior.ColorIndex = 6 And range.Value < 1 Then
        MsgBox "Project Delay!", vbCritical, "Attention required!"
        range.Interior.ColorIndex = 3
    Else
        If range.Interior.ColorIndex = 3 And range.Value > 0 Then
            range.Interior.ColorIndex = 6
        End If
    End If
End Function

Body:
1) It is not necessary to use a function. In VBA you can program classically (and run the macro manually) or you can program event. It means that a macro will be running in case of a particular event (like a mouse-click or a modification in the sheet). That is why Siddarth Rout spoke about Worksheet_change, it is an event. In this case, define your Sub in this way and the following code will be executed in case of Worksheet modification.

2) You have to define a Private Sub for the specific worksheet. Private Sub Worksheet_change() and you put in argument ByVal Target As range. It means that you will receive information about the range that have been changed (Target).

3) After you will use Target.Address to define the range used by your code.

4) Your 2 intricate if statements are not necessary. It is better to use an if statement and an else if statement.

5) The following code is OK for me:

Private Sub Worksheet_change(ByVal Target As range)

If range(Target.Address).Interior.ColorIndex = 6 And range(Target.Address).Value < 1 Then
    MsgBox "Project Delay!", vbCritical, "Attention required!"
    range(Target.Address).Interior.ColorIndex = 3
ElseIf range(Target.Address).Interior.ColorIndex = 3 And range(Target.Address).Value > 0 Then
    range(Target.Address).Interior.ColorIndex = 6
End If

End Sub


问:
How to store inkPicture control content in SQL Server table and read the content back to inkPicture control?
I have an MS Access 2010 application. I have a form with an inkPicture control named InkSign, where the user can put a signature. I store the content of the inkPicture control in een variant variable named sig like this:

```<code>sig = Me.InkSign.Ink.save()
</code>```

Now I can read back this variant data into the control using:

```<code>Dim newInk As New InkDisp
newInk.Load sig
Me.InkSign.Ink.DeleteStrokes
Me.InkSign.InkEnabled = False
Set InkSign.Ink = newInk
Me.InkSign.InkEnabled = True
</code>```

I want to persist and read back the signature data in a SQL Server database table.

I have tried this:

```<code>Private Sub btnSaveSig_Click()
    Dim rst As ADODB.Recordset

    sig = Me.InkSign.Ink.save()

    Set rst = New ADODB.Recordset
    With rst
        '.CursorLocation = adUseClient
        .Open "SELECT * FROM sign WHERE signID = 1", cnnC, adOpenKeyset, adLockOptimistic
        If .BOF And .EOF Then .AddNew
        .Fields("signDate") = Date
        .Fields("signedBy") = "Pipo"
        .Fields("sign") = sig
        .Fields("docType") = "so"
        .Fields("docID") = "1"
        .Update
        .Close
    End With
    Set rst = Nothing
    MsgBox "signature saved"

End Sub
</code>```

The column sign is of type NVARCHAR(MAX). The data gets stored, but looks like Chinese characters. But is this the correct way to store this binary data?

I am trying to read back the data, but it fails on this line: newInk.Load sig

```<code>Private Sub LoadSignature()
    Dim newInk As New InkDisp

    sig = Nz(cLookup("sign", "sign", "signID = 1"), "")
    If IsEmpty(sig) Then Exit Sub

    newInk.Load sig
    Me.InkSign.Ink.DeleteStrokes
    Me.InkSign.InkEnabled = False
    Set InkSign.Ink = newInk
    Me.InkSign.InkEnabled = True
End Sub
</code>```

The clookup function is a function that retrieves data from a SQL Server table.
The error I get is

Invalid procedure call or argument

I think I should use a ADO stream object to write and read back the data. But I do not know how.

Can anyone help me to get this code working?

Thanks, Emphyrio

答:
Try, not tested.</p>

```<code>Private Sub btnSaveSig_Click()
    Dim rst As ADODB.Recordset
    Dim oStream As ADODB.Stream
    Dim fn As String

    sig = Me.InkSign.Ink.Save()

    'Set rst = New ADODB.Recordset
    Set oStream = New ADODB.Stream

    fn = "c:\myImageFile" '<~~"Your image file path"

    With oStream
        .Type = adTypeBinary
        .Open
        .LoadFromFile fn
    End With

    If oStream.Size > 0 Then
        With rst
            '.CursorLocation = adUseClient
            .Open "SELECT * FROM sign WHERE signID = 1", cnnC, adOpenKeyset, adLockOptimistic
            If .BOF And .EOF Then .AddNew
            .Fields("signDate") = Date
            .Fields("signedBy") = "Pipo"
            .Fields("sign") = oStream.Read '<~~ image read
            .Fields("docType") = "so"
            .Fields("docID") = "1"
            .Update
            .Close
        End With
    End If
    Set rst = Nothing
    oStream.Close
    Set oStream = Nothing
    MsgBox "signature saved"

End Sub
</code>```

Body:
I have an MS Access 2010 application. I have a form with an inkPicture control named InkSign, where the user can put a signature. I store the content of the inkPicture control in een variant variable named sig like this:

sig = Me.InkSign.Ink.save()

Now I can read back this variant data into the control using:

Dim newInk As New InkDisp
newInk.Load sig
Me.InkSign.Ink.DeleteStrokes
Me.InkSign.InkEnabled = False
Set InkSign.Ink = newInk
Me.InkSign.InkEnabled = True

I want to persist and read back the signature data in a SQL Server database table.

I have tried this:

Private Sub btnSaveSig_Click()
    Dim rst As ADODB.Recordset

    sig = Me.InkSign.Ink.save()

    Set rst = New ADODB.Recordset
    With rst
        '.CursorLocation = adUseClient
        .Open "SELECT * FROM sign WHERE signID = 1", cnnC, adOpenKeyset, adLockOptimistic
        If .BOF And .EOF Then .AddNew
        .Fields("signDate") = Date
        .Fields("signedBy") = "Pipo"
        .Fields("sign") = sig
        .Fields("docType") = "so"
        .Fields("docID") = "1"
        .Update
        .Close
    End With
    Set rst = Nothing
    MsgBox "signature saved"

End Sub

The column sign is of type NVARCHAR(MAX). The data gets stored, but looks like Chinese characters. But is this the correct way to store this binary data?

I am trying to read back the data, but it fails on this line: newInk.Load sig

Private Sub LoadSignature()
    Dim newInk As New InkDisp

    sig = Nz(cLookup("sign", "sign", "signID = 1"), "")
    If IsEmpty(sig) Then Exit Sub

    newInk.Load sig
    Me.InkSign.Ink.DeleteStrokes
    Me.InkSign.InkEnabled = False
    Set InkSign.Ink = newInk
    Me.InkSign.InkEnabled = True
End Sub

The clookup function is a function that retrieves data from a SQL Server table.
The error I get is

Invalid procedure call or argument

I think I should use a ADO stream object to write and read back the data. But I do not know how.

Can anyone help me to get this code working?

Thanks, Emphyrio

Body:
Try, not tested.

Private Sub btnSaveSig_Click()
    Dim rst As ADODB.Recordset
    Dim oStream As ADODB.Stream
    Dim fn As String

    sig = Me.InkSign.Ink.Save()

    'Set rst = New ADODB.Recordset
    Set oStream = New ADODB.Stream

    fn = "c:\myImageFile" '<~~"Your image file path"

    With oStream
        .Type = adTypeBinary
        .Open
        .LoadFromFile fn
    End With

    If oStream.Size > 0 Then
        With rst
            '.CursorLocation = adUseClient
            .Open "SELECT * FROM sign WHERE signID = 1", cnnC, adOpenKeyset, adLockOptimistic
            If .BOF And .EOF Then .AddNew
            .Fields("signDate") = Date
            .Fields("signedBy") = "Pipo"
            .Fields("sign") = oStream.Read '<~~ image read
            .Fields("docType") = "so"
            .Fields("docID") = "1"
            .Update
            .Close
        End With
    End If
    Set rst = Nothing
    oStream.Close
    Set oStream = Nothing
    MsgBox "signature saved"

End Sub


问:
Segmentation fault (core dumped) after calling vfprintf function
Here's the code

```<code>static FILE *flLog = nullptr;
const char logFilename[] = "log.txt";

void logprintf ( const char *fmt, ... ) {

    if ( flLog == nullptr ) {
        flLog = fopen(logFilename, "a" );
        if ( flLog == nullptr )
            return;
    }

    time_t rawTime;
    struct tm * timeInfo;

    time ( &rawTime );
    timeInfo = localtime ( &rawTime );

    fprintf( flLog, "[%d-%d-%d %02d:%02d:%02d] ",
             timeInfo->tm_year, timeInfo->tm_mon, timeInfo->tm_mday,
             timeInfo->tm_hour, timeInfo->tm_min, timeInfo->tm_sec);

    va_list ap;
    va_start( ap, fmt );
    vprintf( fmt, ap );
    vfprintf( flLog, fmt, ap );
    va_end( ap );

    fprintf( flLog, "\n" );
    printf( "\n" );
    fflush( flLog );
}
</code>```

I just can't figure out what's wrong with that. The function's weird that it works well when it's provided 2 arguments, but give segmentation fault when it's provided 3 or more arguments.

And somewhere in my project, the where has been called:

```<code>logprintf("Security warning: %s tried to give a invalid VUA (%s).\n", ip, vua);
</code>```

After calling that, I got this output:

```<code>[1]    9770 segmentation fault (core dumped)  ./build/apps/server
</code>```

答:
Once you've passed a va_list to a function, you must use va_end().  The preamble to the standard specification of <stdarg.h> says:

The object ap may be passed as an argument to another function; if that function invokes the va_arg macro with parameter ap, the value of ap in the calling function is indeterminate and shall be passed to the va_end macro prior to any further reference to ap.253)

253) It is permitted to create a pointer to a va_list and pass that pointer to another function, in which case the original function may make further use of the original list after the other function returns.

You have:

```<code>va_list ap;
va_start( ap, fmt );
vprintf( fmt, ap );
vfprintf( flLog, fmt, ap );
va_end( ap );
</code>```

You need:

```<code>va_list ap;

va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);

va_start(ap);
vfprintf(flLog, fmt, ap);
va_end(ap);
</code>```

Body:
Here's the code

static FILE *flLog = nullptr;
const char logFilename[] = "log.txt";

void logprintf ( const char *fmt, ... ) {

    if ( flLog == nullptr ) {
        flLog = fopen(logFilename, "a" );
        if ( flLog == nullptr )
            return;
    }

    time_t rawTime;
    struct tm * timeInfo;

    time ( &rawTime );
    timeInfo = localtime ( &rawTime );

    fprintf( flLog, "[%d-%d-%d %02d:%02d:%02d] ",
             timeInfo->tm_year, timeInfo->tm_mon, timeInfo->tm_mday,
             timeInfo->tm_hour, timeInfo->tm_min, timeInfo->tm_sec);

    va_list ap;
    va_start( ap, fmt );
    vprintf( fmt, ap );
    vfprintf( flLog, fmt, ap );
    va_end( ap );

    fprintf( flLog, "\n" );
    printf( "\n" );
    fflush( flLog );
}

I just can't figure out what's wrong with that. The function's weird that it works well when it's provided 2 arguments, but give segmentation fault when it's provided 3 or more arguments.

And somewhere in my project, the where has been called:

logprintf("Security warning: %s tried to give a invalid VUA (%s).\n", ip, vua);

After calling that, I got this output:

[1]    9770 segmentation fault (core dumped)  ./build/apps/server

Body:
Once you've passed a va_list to a function, you must use va_end().  The preamble to the standard specification of <stdarg.h> says:

The object ap may be passed as an argument to another function; if that function invokes the va_arg macro with parameter ap, the value of ap in the calling function is indeterminate and shall be passed to the va_end macro prior to any further reference to ap.253)

253) It is permitted to create a pointer to a va_list and pass that pointer to another function, in which case the original function may make further use of the original list after the other function returns.

You have:

va_list ap;
va_start( ap, fmt );
vprintf( fmt, ap );
vfprintf( flLog, fmt, ap );
va_end( ap );

You need:

va_list ap;

va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);

va_start(ap);
vfprintf(flLog, fmt, ap);
va_end(ap);


问:
Binding click events to a Tab in Ext JS
Aloha again, SO.

I'm busy working on a project that is pretty much all ExtJS for the frontend work. I'm using version 4.0.0, presuming that is something necessary to know. I've got some code along the following:

```<code>panel = Ext.create("Ext.panel.Panel",{
        //initializing stuffs
})
</code>```

A few of those then

```<code> tabs = Ext.create("Ext.tab.Panel", {
        //initialize config
        items: [
               //the panels
        ]
  })
</code>```

Now my big problem here is, I need to be able to bind an event to the actual tabs. I'm aware of being able to bind events to the tab panel and tab bar,  but I need to actually bind the click event to one of the tabs in the panel. I tried something along the lines of this:

```<code>panel = Ext.create("Ext.panel.Panel", {
        //initializing stuffs
        listeners: {
                 click: {
                        fn: function() {
                            console.log("in click listener for panel")
                        }
                  }
         }
 })
</code>```

However, the problem is, based on what I can tell, that binds to the actual panel itself, and not to the tab up in the tab bar. On an interesting side note, it actually doesn't even bind to the actual panel, as far as functionality is concerned, because I never see that console log information.

In any case, would any of you here happen to know how to bind events directly to the tabs? Or even how to get access to the tabs directly? I've been sifting through the ExtJS API docs, but I still can't find anything, so, it'd be awesome if someone here could help! :D

Just to make it clear, I'm not trying to hook into the tab changing. I'm trying to hook into the actual click event of clicking the tab, because I am going to be checking if it is the middle mouse button being clicked so I can close the tab if it is.

答: You can add listeners to TabPanel itself that listen to beforetabchange and/or tabchange

ContentLicense: CC BY-SA 3.0

Title: Binding click events to a Tab in Ext JS

Body:
Aloha again, SO.

I'm busy working on a project that is pretty much all ExtJS for the frontend work. I'm using version 4.0.0, presuming that is something necessary to know. I've got some code along the following:

panel = Ext.create("Ext.panel.Panel",{
        //initializing stuffs
})

A few of those then

 tabs = Ext.create("Ext.tab.Panel", {
        //initialize config
        items: [
               //the panels
        ]
  })

Now my big problem here is, I need to be able to bind an event to the actual tabs. I'm aware of being able to bind events to the tab panel and tab bar,  but I need to actually bind the click event to one of the tabs in the panel. I tried something along the lines of this:

panel = Ext.create("Ext.panel.Panel", {
        //initializing stuffs
        listeners: {
                 click: {
                        fn: function() {
                            console.log("in click listener for panel")
                        }
                  }
         }
 })

However, the problem is, based on what I can tell, that binds to the actual panel itself, and not to the tab up in the tab bar. On an interesting side note, it actually doesn't even bind to the actual panel, as far as functionality is concerned, because I never see that console log information.

In any case, would any of you here happen to know how to bind events directly to the tabs? Or even how to get access to the tabs directly? I've been sifting through the ExtJS API docs, but I still can't find anything, so, it'd be awesome if someone here could help! :D

Just to make it clear, I'm not trying to hook into the tab changing. I'm trying to hook into the actual click event of clicking the tab, because I am going to be checking if it is the middle mouse button being clicked so I can close the tab if it is.


问:
Add hover:after with jquery?
I am finding myself having problems with a simple css+jquery hover state. I have a list of elements:

```<code><div class="list">
  <div class="one">
    <span><h1>element oneA</h1></span>
  </div>
  <div class="two">
    <span><h1>element two</h1></span>
  </div>
  <div class="three">
    <span><h1>element three</h1></span>
  </div>
  <div class="four">
    <span><h1>element four</h1></span>
  </div>
  <div class="five">
    <span><h1>element five</h1></span>
  </div>

</div>
</code>```

The effect I want to achieve is hover on any of the elements and have the entire .list div move elegantly to the left. Because I want to apply the effect to the parent, I decided to use jquery instead of simple css. Which worked so:

```<code>$(document).ready(function(){
    $(".one, .two, .three, .four, .five").hover(
    function(){ $('.list').addClass("Mydivadd")},
    function(){ $('.list').removeClass('Mydivadd')}
  );
});
</code>```

(the class I added being a change in position). The problem was that this option resulted in a lot of intense flickering. So I did some googling and I ran into this beautiful smooth transition, obviously adapted to my positioning needs:

```<code>.list .one
{
  transition: ease all 0.5s;
  width: 100%;
}

.list .one:hover
{
  position: relative;
  transform: translateX(-20rem);
}
.lists .one:hover:after
{
  content: "";
  width: calc(100% + 20rem);
  position: absolute;
  right: -20rem;
}
</code>```

which works perfectly but obviously only applies to one of the items inside the big div. So my question is: is there any way to add that hover:after css that prevents the flickering to my jquery function? I feel like the solution is obvious and right in front of me but I can't see it.

thank you very much in advance for your time, sorry for the long question :)

答:
You can apply with jQuery only inline css. :before or after cannot set inline.

However,

If you want to add it to all items, do:

```<code>.lists>div:hover{...}
.lists>div:hover:after{...}
</code>```

Or add a common class to all the items, and replace the .one to that class in the css

Title: Add hover:after with jquery?

Body:
I am finding myself having problems with a simple css+jquery hover state. I have a list of elements:

element oneA

element two

element three

element four

element five

The effect I want to achieve is hover on any of the elements and have the entire .list div move elegantly to the left. Because I want to apply the effect to the parent, I decided to use jquery instead of simple css. Which worked so:

$(document).ready(function(){
    $(".one, .two, .three, .four, .five").hover(
    function(){ $('.list').addClass("Mydivadd")},
    function(){ $('.list').removeClass('Mydivadd')}
  );
});

(the class I added being a change in position). The problem was that this option resulted in a lot of intense flickering. So I did some googling and I ran into this beautiful smooth transition, obviously adapted to my positioning needs:

.list .one
{
  transition: ease all 0.5s;
  width: 100%;
}

.list .one:hover
{
  position: relative;
  transform: translateX(-20rem);
}
.lists .one:hover:after
{
  content: "";
  width: calc(100% + 20rem);
  position: absolute;
  right: -20rem;
}

which works perfectly but obviously only applies to one of the items inside the big div. So my question is: is there any way to add that hover:after css that prevents the flickering to my jquery function? I feel like the solution is obvious and right in front of me but I can't see it.

thank you very much in advance for your time, sorry for the long question :)

Body:
You can apply with jQuery only inline css. :before or after cannot set inline.

However,

If you want to add it to all items, do:

.lists>div:hover{...}
.lists>div:hover:after{...}

Or add a common class to all the items, and replace the .one to that class in the css


问:
How to delete a column (attribute) from a GAE datastore?
I have a persistent class stored in a GAE datastore. I have removed one of the attributes from the class. The new records in this table show a value <none> for the removed attribute. But is there a way I can completely drop this column off the table?

Thanks.

Added the following 'migration' code according to moraes' suggestion, but it isn't achieving the desired result:

```<code>PersistenceManager pm = PMF.get().getPersistenceManager();
try {
    Query q = pm.newQuery(UserLogin.class);
    Collection<UserLogin> list = (Collection<UserLogin>) q.execute();

    Iterator<UserLogin> iter = list.iterator();
    while (iter.hasNext()) {
        UserLogin obj = (UserLogin) iter.next();
        obj.setLoginDate(obj.getLoginDate());
    }

    pm.makePersistentAll(list);

} finally {
    pm.close();
}
</code>```

答: The datastore viewer gets its list of columns from the datastore stats, which are updated on a regular basis. If you've removed that column from every entity that had it, wait a day or two and the datastore viewer will stop showing it.</p>

Body:
I have a persistent class stored in a GAE datastore. I have removed one of the attributes from the class. The new records in this table show a value <none> for the removed attribute. But is there a way I can completely drop this column off the table?

Thanks.

Added the following 'migration' code according to moraes' suggestion, but it isn't achieving the desired result:

PersistenceManager pm = PMF.get().getPersistenceManager();
try {
    Query q = pm.newQuery(UserLogin.class);
    Collection<UserLogin> list = (Collection<UserLogin>) q.execute();

    Iterator<UserLogin> iter = list.iterator();
    while (iter.hasNext()) {
        UserLogin obj = (UserLogin) iter.next();
        obj.setLoginDate(obj.getLoginDate());
    }

    pm.makePersistentAll(list);

} finally {
    pm.close();
}


问:
How to pass the AJAX responseText into a variable
I want to know how to pass the AJAX responseText into a variable? I want to use it in another part of programe. The code "document.getElementById("showData").innerHTML = xhttp.responseText;" can display the return string correctly, but I cannot use a variable to receive it. </p>

```<code><?PHP
$currHr=date('H')-1;
?>

<form action="">

<Select name="SelTime" onchange="rainSum(this.value)">
<?php
if ($currHr>0){
for ($i=$currHr; $i>=0; $i--)
{
    echo "<option value=".$i.">".$i.":00";
    echo " - ";
    echo $i.":59</option><br>";
}
}else {
    for ($i=23; $i>=0; $i--)
{
    echo "<option value=".$i.">".$i.":00";
    echo " - ";
    echo $i.":59</option><br>";
}
}
?>
</Select>
</form>

<p id="showData">Let AJAX change this text.</p>

<script>

function rainSum(str)
{
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function ()
  {

 if (xhttp.readyState === 4 && xhttp.status === 200)
 {
   document.getElementById("showData").innerHTML = xhttp.responseText;
   window.x=xhttp.responseText;
    }
  };

  xhttp.open("GET", "barD.php?SelTime="+str, true);
  xhttp.send();
}

document.write(window.x);</script>
</code>```

答:
if you mean the x variable should contain the response data  it's already containing the response since its a global variable

you dont need window.x  you just declare a variable outside the function

like this

```<code>var ResponseTXT='';

    function rainSum(str)
    {
      var xhttp = new XMLHttpRequest();

      xhttp.onreadystatechange = function ()
      {

     if (xhttp.readyState === 4 && xhttp.status === 200)
     {
       document.getElementById("showData").innerHTML = xhttp.responseText;
       ResponseTXT=xhttp.responseText;
        }
      };

      xhttp.open("GET", "barD.php?SelTime="+str, true);
      xhttp.send();
    }
</code>```

Body:
I want to know how to pass the AJAX responseText into a variable? I want to use it in another part of programe. The code "document.getElementById("showData").innerHTML = xhttp.responseText;" can display the return string correctly, but I cannot use a variable to receive it.

<?PHP
$currHr=date('H')-1;
?>

<form action="">

<Select name="SelTime" onchange="rainSum(this.value)">
<?php
if ($currHr>0){
for ($i=$currHr; $i>=0; $i--)
{
    echo "<option value=".$i.">".$i.":00";
    echo " - ";
    echo $i.":59</option>
";
}
}else {
    for ($i=23; $i>=0; $i--)
{
    echo "<option value=".$i.">".$i.":00";
    echo " - ";
    echo $i.":59</option>
";
}
}
?>
</Select>
</form>

Let AJAX change this text.

Body:
if you mean the x variable should contain the response data  it's already containing the response since its a global variable

you dont need window.x  you just declare a variable outside the function

like this

var ResponseTXT='';

    function rainSum(str)
    {
      var xhttp = new XMLHttpRequest();

      xhttp.onreadystatechange = function ()
      {

     if (xhttp.readyState === 4 && xhttp.status === 200)
     {
       document.getElementById("showData").innerHTML = xhttp.responseText;
       ResponseTXT=xhttp.responseText;
        }
      };

      xhttp.open("GET", "barD.php?SelTime="+str, true);
      xhttp.send();
    }


答:
You have to mention the format in as.Date which is present in your data. In this case, you can directly use as.Date

```<code>df2$year <- format(as.Date(df2$DATE), "%Y")
#Or explicitly mention
#df2$year <- format(as.Date(df2$DATE, "%Y-%m-%d"), "%Y")
</code>```

Or use year function from lubridate

```<code>df2$year <- lubridate::year(df2$DATE)
</code>```

Title: Lubridate is creating new a 'year' column, but returning NAs

Body:
When I do:

df2$year <- format(as.Date(df2$DATE, "%m/%d/%y") , "%Y")

It returns a columnn called 'year' full of NA's

data

structure (list(DATE = structure(1:6, .Label = c("1951-01-01", "1951-04-01", "1951-07-01", "1951-10-01", "1952-01-01", "1952-04-01", "1952-07-01", "1952-10-01", "1953-01-01", "1953-04-01", "1953-07-01", [...]), class = "factor"), GPDIC1 = c(300.363, 307.326, 284.697, 262.013, 268.85, 248.58)), .Names = c("DATE", "GPDIC1"), row.names = c(NA, 6L), class = "data.frame")

Body:
You have to mention the format in as.Date which is present in your data. In this case, you can directly use as.Date

df2$year <- format(as.Date(df2$DATE), "%Y")
#Or explicitly mention
#df2$year <- format(as.Date(df2$DATE, "%Y-%m-%d"), "%Y")

Or use year function from lubridate

df2$year <- lubridate::year(df2$DATE)


问:
Laravel set cookie in API not set
I using laravel 5 as Rest API, and I want to set a cookie in controller:

```<code>return response()->json(['success' => $data], $this-> successStatus)->cookie('name', 'myvalue');
</code>```

this return with response cookie successfully, but can not access in front, I also used:

```<code>Cookie::queue($name, $value);
</code>```

Or

```<code>Cookie::queue(Cookie::make('cookieName', 'value'));
</code>```

Or all way in google, stackoverflow, but none of these set cookie in browser, I need to set http only cookie in browser via laravel controller. how can i do this?

I also used php cookie, no success

答:
Cookies will be set on web middleware group only not api. According to docs,  Laravel comes with web and api middleware groups that contain common middleware you may want to apply to your web UI and API routes:

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        //...
    ],

    'api' => [
        'throttle:60,1',
        'auth:api',
    ],
];
```

<p>As you can see, <code>EncryptCookies</code> and <code>AddQueuedCookiesToResponse</code> middlewares are applied to <code>web</code> group only but not <code>api</code>.</p>

<pre class="lang-php prettyprint-override"><code>// This works and sets encrypted cookie on response.
Route::group(['middleware' => ['web']], function () {
    return response()
        ->cookie('name', 'value');
});

// This won't set cookie on response.
Route::group(['middleware' => ['api']], function () {
    return response()
        ->cookie('name', 'value');
});
</code>```

Title: Laravel set cookie in API not set

Body:
I using laravel 5 as Rest API, and I want to set a cookie in controller:

return response()->json(['success' => $data], $this-> successStatus)->cookie('name', 'myvalue');

this return with response cookie successfully, but can not access in front, I also used:

Cookie::queue($name, $value);

Or

Cookie::queue(Cookie::make('cookieName', 'value'));

Or all way in google, stackoverflow, but none of these set cookie in browser, I need to set http only cookie in browser via laravel controller. how can i do this?

I also used php cookie, no success

Body:
Cookies will be set on web middleware group only not api. According to docs,  Laravel comes with web and api middleware groups that contain common middleware you may want to apply to your web UI and API routes:

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        //...
    ],

    'api' => [
        'throttle:60,1',
        'auth:api',
    ],
];

As you can see, EncryptCookies and AddQueuedCookiesToResponse middlewares are applied to web group only but not api.

// This works and sets encrypted cookie on response.
Route::group(['middleware' => ['web']], function () {
    return response()
        ->cookie('name', 'value');
});

// This won't set cookie on response.
Route::group(['middleware' => ['api']], function () {
    return response()
        ->cookie('name', 'value');
});


问:
Unset multiple properties using C# mongodb driver
I have this mongo query that I want to run using the C# MongoDB driver:</p>

```<code>db.test.update(
   { rate: "unknown" },
   { $unset: { qt: "", cost: "", res: "", ... } }
)
</code>```

答:
The documentation didn't cover this case, but I'm glad the tests are good enough, though it takes some time to dig into them.
Here's the test where I came to know one can chain multiple Unset methods: TestUnsetTwice

Here's my final solution:
Provided a list of properties to update, loop through each property and call the Unset method on UpdateDefinition.

```<code>FilterDefinition<TDocument> filterDefinition = Builders<TDocument>.Filter.Eq("rate", "unknown");
UpdateDefinition<TDocument> updateDefinition = null;
UpdateDefinitionBuilder<TDocument> updateDefinitionBuilder = Builders<TDocument>.Update;

foreach (String o in propertiesToDelete)
{
     if(updateDefinition == null)
        updateDefinition = updateDefinitionBuilder.Unset(o);
     else
        updateDefinition = updateDefinition.Unset(o);
}

var collection = GetCollection<TDocument>();
var updateRes = collection.UpdateOne(filterDefinition, updateDefinition);
</code>```

Body:
I have this mongo query that I want to run using the C# MongoDB driver:

db.test.update(
   { rate: "unknown" },
   { $unset: { qt: "", cost: "", res: "", ... } }
)

Body:
The documentation didn't cover this case, but I'm glad the tests are good enough, though it takes some time to dig into them.
Here's the test where I came to know one can chain multiple Unset methods: TestUnsetTwice

Here's my final solution:
Provided a list of properties to update, loop through each property and call the Unset method on UpdateDefinition.

FilterDefinition<TDocument> filterDefinition = Builders<TDocument>.Filter.Eq("rate", "unknown");
UpdateDefinition<TDocument> updateDefinition = null;
UpdateDefinitionBuilder<TDocument> updateDefinitionBuilder = Builders<TDocument>.Update;

foreach (String o in propertiesToDelete)
{
     if(updateDefinition == null)
        updateDefinition = updateDefinitionBuilder.Unset(o);
     else
        updateDefinition = updateDefinition.Unset(o);
}

var collection = GetCollection<TDocument>();
var updateRes = collection.UpdateOne(filterDefinition, updateDefinition);


问:
How can I find the count of semicolon separated values?
I have a list of all email ids which I have copied from the 'To' field, from an email I received in MS Outlook. These values (email ids) are separated by a semicolon. I have copied this big list of email ids into Excel. Now I want to find the number of email ids in this list; basically by counting the number of semi colons.

One way I can do this is by writing C code. i.e. store the big list as string buffer, and keep comparing the chars to ";" in a while(char == ';') loop.
But I want to do it quickly.

Is there any quick way to find that out using either:

1.) Regular expression (I use powergrep for processing the regexps)

2.) In excel itself (any excel macro/plugin for that?)

3.) DOS script method

4.) Any other quick way of getting it done?

答: Load the list in your favorite (not Notepad!) editor, replace ; by \n, see in the status bar how many lines you have, remove the last line if needed.</p>

OwnerDisplayName: goldenmean

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

OwnerDisplayName: PhiLho


问:
Visual Studio Code - Convert spaces to tabs
I have both TypeScript and HTML files in my project, in both files tabs are converted to spaces.

I want to turn the auto-conversion off and make sure that my project has only tabs.

Edit:

With this setting it seems to work in HTML files but not in TypeScript files.

{
  "editor.insertSpaces": false
}
```

答:
Highlight your Code (in file)

Click Tab Size in bottom righthand corner of application window

Select the appropriate Convert Indentation to Tabs


问:
Add CSS but keep inline style
What I'm doing wrong.

Need to add CSS with JavaScript but I have to keep all the inline styles.

In this case when user clicks h1 element, the color of the inline style needs to stay the same and just add new style from javascript.

Here is fiddle: https://jsfiddle.net/59qfxwcu/

```<code><h1 style="color: red;">Test</h1>
<h1 style="color: green;">Test</h1>

<script>
function some(){
    var element = document.querySelectorAll('h1');

      element.forEach(function(item){

        item.onclick = function(){
            var inlineCss = this.style;

                item.style.cssText = inlineCss + 'background: blue; font-size: 12px;';
          }

      });
}

some();

</script>
</code>```

答:
You need to use style.background and style.fontSize javascript properties:

function some(el) {
  var element = document.querySelectorAll('h1');

  element.forEach(function(item) {

    item.onclick = function() {
      item.style.background = 'blue';  // Change the background of the element
      item.style.fontSize = '12px';    // Change the font-size of the element
    }

  });
}

some();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 style="color: red;">Test</h1>
<h1 style="color: green;">Test</h1></code>```

Title: Add CSS but keep inline style

Body:
What I'm doing wrong.

Need to add CSS with JavaScript but I have to keep all the inline styles.

In this case when user clicks h1 element, the color of the inline style needs to stay the same and just add new style from javascript.

Here is fiddle: https://jsfiddle.net/59qfxwcu/

Test

Test

Body:
You need to use style.background and style.fontSize javascript properties:

function some(el) {
  var element = document.querySelectorAll('h1');

  element.forEach(function(item) {

    item.onclick = function() {
      item.style.background = 'blue';  // Change the background of the element
      item.style.fontSize = '12px';    // Change the font-size of the element
    }

  });
}

some();

<h1 style="color: red;">Test</h1>
<h1 style="color: green;">Test</h1>


问:
Disabling TouchPad on Ubuntu 18.04 (Temporarily)
I was using Ubuntu 16.04 on my System76 Oryx laptop.  The trackpad is very sensitive so I used to disable it using Fn+F1.  That is not working anymore in 18.04.  I looked around and found:

```<code>synclient TouchpadOff=1
</code>```

When I set that it seemed to work for a second then reset...

```<code>$ synclient TouchpadOff=0
$ synclient | grep TouchpadOff
    TouchpadOff             = 0
$ synclient | grep TouchpadOff
    TouchpadOff             = 1
</code>```

I also found:

```<code>xinput set-prop "SynPS/2 Synaptics TouchPad" "Device Enabled" 0
</code>```

But that seems more permanent.  When I tried to set back to 1, it remains off.  Seems I need to reboot now to turn it back on.  I used to be able to toggle with Fn+F1.

答:
You can create a custom Shortcut with the following command:

```<code>gnome-terminal -- /bin/bash -c "file='/tmp/touch-disable'; id=$(xinput | grep YOUR_DEVICE_STRING | grep -o 'id=[0-9]\+' | grep -o '[0-9]\+'); if [ -f $file ]; then xinput enable $id; rm $file; else xinput disable $id; touch $file; fi"
</code>```

This command will toggle the the Pointer device.

How to create the shortcut:

1 - Open a Terminal and find the device:

```<code>$xinput
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ HOLTEK USB Wireless Device                id=9    [slave  pointer  (2)]
⎜   ↳ TPPS/2 IBM TrackPoint                     id=14   [slave  pointer  (2)]
⎜   ↳ Synaptics TM3075-002                      id=13   [slave  pointer  (2)]  <-- this is my touchpad
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Sleep Button                              id=8    [slave  keyboard (3)]
    ↳ Integrated Camera: Integrated C           id=10   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=11   [slave  keyboard (3)]
    ↳ ThinkPad Extra Buttons                    id=12   [slave  keyboard (3)]
</code>```

2 - Open Gnome-Settings/Devices/Keyboards Shortcuts
Keyboard Settings

3 - Add new Shortcut by using the '+'-button
Add Shortcut

4 - Copy descriped command and replace "YOUR_DEVICE_STRING". Example: "Synaptics TM3075-002"

5 - Name the Shortcut and set the define one

Description:

To toggle the Touchpad enable/disable we create a file in /tmp as marker we have disabled the pointer device. By the second execution we will remove the file, so we know the next time we the device is enabled. The state change is archived by the xinput enable/disable .

That means the command can be also as example:

```<code>gnome-terminal -- /bin/bash -c "file='/tmp/touch-disable'; id='Synaptics TM3075-002'; if [ -f $file ]; then xinput enable $id; rm $file; else xinput disable $id; touch $file; fi"
</code>```

To be able to run this command, we can use the gnome-terminal withe the bash shell.

Body:
I was using Ubuntu 16.04 on my System76 Oryx laptop.  The trackpad is very sensitive so I used to disable it using Fn+F1.  That is not working anymore in 18.04.  I looked around and found:

synclient TouchpadOff=1

When I set that it seemed to work for a second then reset...

$ synclient TouchpadOff=0
$ synclient | grep TouchpadOff
    TouchpadOff             = 0
$ synclient | grep TouchpadOff
    TouchpadOff             = 1

I also found:

xinput set-prop "SynPS/2 Synaptics TouchPad" "Device Enabled" 0

But that seems more permanent.  When I tried to set back to 1, it remains off.  Seems I need to reboot now to turn it back on.  I used to be able to toggle with Fn+F1.

Body:
You can create a custom Shortcut with the following command:

gnome-terminal -- /bin/bash -c "file='/tmp/touch-disable'; id=$(xinput | grep YOUR_DEVICE_STRING | grep -o 'id=[0-9]\+' | grep -o '[0-9]\+'); if [ -f $file ]; then xinput enable $id; rm $file; else xinput disable $id; touch $file; fi"

This command will toggle the the Pointer device.

How to create the shortcut:

1 - Open a Terminal and find the device:

$xinput
⎡ Virtual core pointer                      id=2    [master pointer  (3)]
⎜   ↳ Virtual core XTEST pointer                id=4    [slave  pointer  (2)]
⎜   ↳ HOLTEK USB Wireless Device                id=9    [slave  pointer  (2)]
⎜   ↳ TPPS/2 IBM TrackPoint                     id=14   [slave  pointer  (2)]
⎜   ↳ Synaptics TM3075-002                      id=13   [slave  pointer  (2)]  <-- this is my touchpad
⎣ Virtual core keyboard                     id=3    [master keyboard (2)]
    ↳ Virtual core XTEST keyboard               id=5    [slave  keyboard (3)]
    ↳ Power Button                              id=6    [slave  keyboard (3)]
    ↳ Video Bus                                 id=7    [slave  keyboard (3)]
    ↳ Sleep Button                              id=8    [slave  keyboard (3)]
    ↳ Integrated Camera: Integrated C           id=10   [slave  keyboard (3)]
    ↳ AT Translated Set 2 keyboard              id=11   [slave  keyboard (3)]
    ↳ ThinkPad Extra Buttons                    id=12   [slave  keyboard (3)]

2 - Open Gnome-Settings/Devices/Keyboards Shortcuts
Keyboard Settings

3 - Add new Shortcut by using the '+'-button
Add Shortcut

4 - Copy descriped command and replace "YOUR_DEVICE_STRING". Example: "Synaptics TM3075-002"

5 - Name the Shortcut and set the define one

Description:

To toggle the Touchpad enable/disable we create a file in /tmp as marker we have disabled the pointer device. By the second execution we will remove the file, so we know the next time we the device is enabled. The state change is archived by the xinput enable/disable .

That means the command can be also as example:

gnome-terminal -- /bin/bash -c "file='/tmp/touch-disable'; id='Synaptics TM3075-002'; if [ -f $file ]; then xinput enable $id; rm $file; else xinput disable $id; touch $file; fi"

To be able to run this command, we can use the gnome-terminal withe the bash shell.


问:
How do I fix cfWheels ERROR: Wheels.TableNotFound?
I am new to Cfwheels and MVC.  Cfwheels website is up and running.

I have successfully completed https://guides.cfwheels.org/docs/beginner-tutorial-hello-world .

Now I am trying to just test the cfwheels to mySql database connection.  I have NO tables in the mySql database.

The error I get is;

Wheels.TableNotFound ttt_shows table could not be found in the
  database.

Suggested action

Add a table named ttt_shows to your database or tell CFWheels to use a
  different table for this model. For example you can tell a user model
  to use a table called tbl_users by creating a User.cfc file in the
  models folder, creating an init method inside it and then calling
  table("tbl_users") from within it.

The ttt_shows table could not be found in the database.
  <
  Error location: Line 4 in views\ttt_show\cf_info_mysql.cfm ;

```<code><cfset mySqlVerStruct= model("ttt_show").getMySqlVersion1() />
</code>```

Tag context;

Error thrown on line 169 in wheels\model\adapters\Base.cfc

   called from line 72 in wheels\model\initialization.cfm

   called from line 1 in root.cfm

   called from line 576 in wheels\global\internal.cfm

   called from line 861 in wheels\global\internal.cfm

   called from line 164 in wheels\global\cfml.cfm

   called from line 14 in wheels\global\cfml.cfm

   called from line 206 in wheels\global\public.cfm

   called from line 4 in views\ttt_show\cf_info_mysql.cfm

   called from line 128 in wheels\global\cfml.cfm

   called from line 434 in wheels\controller\rendering.cfm

   called from line 157 in wheels\controller\rendering.cfm

   called from line 53 in wheels\controller\rendering.cfm

   called from line 141 in wheels\controller\processing.cfm

   called from line 95 in wheels\controller\processing.cfm

   called from line 198 in wheels\dispatch\request.cfm

   called from line 1 in wheels\index.cfm

   called from line 1 in index.cfm

   called from line 1 in wheels\events\onrequest.cfm

Note: A related/subpart of my question is; In CfWheels, how do I create a model that does not have an associated database table?  In the future I will need to code a model that does not have a database attached - but does CRUD operations against an xml or json file.
Thanks in advance for any help / guidance.

So far I have the following code;

MySql Version Query using;  model("ttt_show").getMySqlVersion1()

<cfset mySqlVerStruct= model("ttt_show").getMySqlVersion1() />

<cfdump var="#mySqlVerStruct#" label="MySql version" />```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><cfcomponent extends="Model">
  <!--- FILE: ..\models\ttt_show.cfc --->
  <cffunction name="init">
  </cffunction>

  <!--- - -   getMySqlVersion1()  - - --->
  <cffunction name="getMySqlVersion1">
    <!--- USED BY ..\views\ttt_show\cf_info_mysql.cfm --->
    <cfset retStruct=S tructNew( "qryMySqlVersion1") />
    <cfset retStruct.errorStr="" />
    <cfset retStruct.datasource="#get('dataSourceName')#" />
    <cfset retStruct.username="#get('dataSourceUserName')#" />
    <cfset retStruct.password="#get('dataSourcePassword')#" />
    <cfset retStruct.qry="" />
    <cfreturn retStruct>
  </cffunction>

  <!--- - -   getMySqlVersion2()  - - --->
  <cffunction name="getMySqlVersion2">
    <!--- USED BY ..\views\ttt_show\cf_info_mysql.cfm --->
    <cfquery name="MySqlVersion2" debug="no" datasource="#APPLICATION.wheels.DATASOURCENAME#" timeout="5">
      select version() as mysql_version
    </cfquery>
    <cfreturn MySqlVersion2>
  </cffunction>

  <!--- - -   Create...Table()  - - --->
  <cffunction name="createEmptyTable">
    <cfquery result="myCreateTblResults" datasource="#get('dataSourceName')#">
      CREATE TABLE IF NOT EXISTS `tbl_masters` ( `id` int(11) unsigned NOT NULL auto_increment COMMENT 'unique primary key id', `textValue` varchar(255) default NULL COMMENT 'any text value', `numValue` int(11) default NULL COMMENT 'any numeric value', `dtValue`
      datetime default NULL COMMENT 'any datetime value', `recStatus` tinyint(4) NOT NULL default '1' COMMENT 'Status of This Record', `dtCreated` datetime NOT NULL COMMENT 'date that record was created', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8
      COMMENT='Stores any general key/value pairs for app, MASTER in master-slaves relationship';
    </cfquery>

    <!--- return false: error: not tested yet --->
    <cfreturn false>
  </cffunction>
</cfcomponent></code>```

<cfcomponent extends="Controller">

    <cffunction name="cf_info_mysql">
    </cffunction>

</cfcomponent>```

答:
After reading further, I found out the general answer (but have not tested code yet).

At https://guides.cfwheels.org/docs/object-relational-mapping under the heading; "Models Without Database Tables",  documentation explains that in your model/*.cfm file, you need to add;

```<code>function config() {
  table(false);
  }
</code>```

From the document;

"With that in place, you have the foundation for a model that never
  touches the database. When you call methods like save(), create(),
  update(), and delete() on a tableless model, the entire model
  lifecycle will still run, including object validation and object
  callbacks."

Now if I can just find a source code example of this type of model.

Body:
I am new to Cfwheels and MVC.  Cfwheels website is up and running.

I have successfully completed https://guides.cfwheels.org/docs/beginner-tutorial-hello-world .

Now I am trying to just test the cfwheels to mySql database connection.  I have NO tables in the mySql database.

The error I get is;

Wheels.TableNotFound ttt_shows table could not be found in the
  database.

Suggested action

Add a table named ttt_shows to your database or tell CFWheels to use a
  different table for this model. For example you can tell a user model
  to use a table called tbl_users by creating a User.cfc file in the
  models folder, creating an init method inside it and then calling
  table("tbl_users") from within it.

The ttt_shows table could not be found in the database.
  <
  Error location: Line 4 in views\ttt_show\cf_info_mysql.cfm ;

<cfset mySqlVerStruct= model("ttt_show").getMySqlVersion1() />

Tag context;

Error thrown on line 169 in wheels\model\adapters\Base.cfc

   called from line 72 in wheels\model\initialization.cfm

   called from line 1 in root.cfm

   called from line 576 in wheels\global\internal.cfm

   called from line 861 in wheels\global\internal.cfm

   called from line 164 in wheels\global\cfml.cfm

   called from line 14 in wheels\global\cfml.cfm

   called from line 206 in wheels\global\public.cfm

   called from line 4 in views\ttt_show\cf_info_mysql.cfm

   called from line 128 in wheels\global\cfml.cfm

   called from line 434 in wheels\controller\rendering.cfm

   called from line 157 in wheels\controller\rendering.cfm

   called from line 53 in wheels\controller\rendering.cfm

   called from line 141 in wheels\controller\processing.cfm

   called from line 95 in wheels\controller\processing.cfm

   called from line 198 in wheels\dispatch\request.cfm

   called from line 1 in wheels\index.cfm

   called from line 1 in index.cfm

   called from line 1 in wheels\events\onrequest.cfm

Note: A related/subpart of my question is; In CfWheels, how do I create a model that does not have an associated database table?  In the future I will need to code a model that does not have a database attached - but does CRUD operations against an xml or json file.
Thanks in advance for any help / guidance.

So far I have the following code;

MySql Version Query using;  model("ttt_show").getMySqlVersion1()

<cfset mySqlVerStruct= model("ttt_show").getMySqlVersion1() />

<cfdump var="#mySqlVerStruct#" label="MySql version" />

<cfcomponent extends="Model">

  <cffunction name="init">
  </cffunction>

  <cffunction name="getMySqlVersion1">

    <cfset retStruct=S tructNew( "qryMySqlVersion1") />
    <cfset retStruct.errorStr="" />
    <cfset retStruct.datasource="#get('dataSourceName')#" />
    <cfset retStruct.username="#get('dataSourceUserName')#" />
    <cfset retStruct.password="#get('dataSourcePassword')#" />
    <cfset retStruct.qry="" />
    <cfreturn retStruct>
  </cffunction>

  <cffunction name="getMySqlVersion2">

    <cfquery name="MySqlVersion2" debug="no" datasource="#APPLICATION.wheels.DATASOURCENAME#" timeout="5">
      select version() as mysql_version
    </cfquery>
    <cfreturn MySqlVersion2>
  </cffunction>

  <cffunction name="createEmptyTable">
    <cfquery result="myCreateTblResults" datasource="#get('dataSourceName')#">
      CREATE TABLE IF NOT EXISTS `tbl_masters` ( `id` int(11) unsigned NOT NULL auto_increment COMMENT 'unique primary key id', `textValue` varchar(255) default NULL COMMENT 'any text value', `numValue` int(11) default NULL COMMENT 'any numeric value', `dtValue`
      datetime default NULL COMMENT 'any datetime value', `recStatus` tinyint(4) NOT NULL default '1' COMMENT 'Status of This Record', `dtCreated` datetime NOT NULL COMMENT 'date that record was created', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8
      COMMENT='Stores any general key/value pairs for app, MASTER in master-slaves relationship';
    </cfquery>

    <cfreturn false>
  </cffunction>
</cfcomponent>

<cfcomponent extends="Controller">

    <cffunction name="cf_info_mysql">
    </cffunction>

</cfcomponent>

Body:
After reading further, I found out the general answer (but have not tested code yet).

At https://guides.cfwheels.org/docs/object-relational-mapping under the heading; "Models Without Database Tables",  documentation explains that in your model/*.cfm file, you need to add;

function config() {
  table(false);
  }

From the document;

"With that in place, you have the foundation for a model that never
  touches the database. When you call methods like save(), create(),
  update(), and delete() on a tableless model, the entire model
  lifecycle will still run, including object validation and object
  callbacks."

Now if I can just find a source code example of this type of model.


问:
Display hidden html code with jQuery
There is another solution to display a hidden input when a user choose an option from the select tag?
I want to put the HTML code outside the JS code.

jQuery code:

```<code>$(function() {

    var message = new Array(),
        $paymentOption = $("#payement_option"),
        $messageDisplay = $("#message_display");

    message[1] = '<input type="text" name="email" size="30" />';

    $paymentOption.change(function() {

        var messageIndex = $(this).val();

        $messageDisplay.empty();

        if (messageIndex > 0)
            $messageDisplay.append(message[messageIndex]);

    });

});
</code>```

HTML code like this:

```<code><select name="option"><option value="0">yes</option><option value="1">no</option</select>
</code>```

the output:

```<code><div id="message_display"></div>
</code>```

EDIT:

I want something like:

```<code><div id="message_display">
    <input type="text" name="email" size="30" />
</div>
</code>```

答:
Are you trying to do something like this?</p>

```<code>$('#myselect').change(function(){
    var box = $(this);
    if (box.val() === 'some predetermined value') {
        $("#message_display").show();
    }
});
</code>```

Title: Display hidden html code with jQuery

Body:
There is another solution to display a hidden input when a user choose an option from the select tag?
I want to put the HTML code outside the JS code.

jQuery code:

$(function() {

    var message = new Array(),
        $paymentOption = $("#payement_option"),
        $messageDisplay = $("#message_display");

    message[1] = '<input type="text" name="email" size="30" />';

    $paymentOption.change(function() {

        var messageIndex = $(this).val();

        $messageDisplay.empty();

        if (messageIndex > 0)
            $messageDisplay.append(message[messageIndex]);

    });

});

HTML code like this:

<select name="option"><option value="0">yes</option><option value="1">no</option</select>

the output:

EDIT:

I want something like:

    <input type="text" name="email" size="30" />

Body:
Are you trying to do something like this?

$('#myselect').change(function(){
    var box = $(this);
    if (box.val() === 'some predetermined value') {
        $("#message_display").show();
    }
});


问:
Access Environment based application.properties file in class not managed by spring
I am working on spring boot project having version 2.1.6.RELEASE and xslt 1.0.

I have a class that has a set of static methods used to generate the set of URL's using custom logic related to the application.

```<code>public class URLGenerator{

    public static String generateURLA(String param1,String param2,String param3)
    {
        String restServiceUrl=<acess url from application.properties>
        //code to invoke third party service
        RestTemplate restTemplate=new RestTemplate();
        String url=restTemplate.invoke()
        return url;
    }
}
</code>```

In the above method, I have to make a rest call to third party service to retrieve the final URL. The URL to invoke the service is different for every environment so I have stored the URL inside the application-{env}.properties file.

I will not be able to change the above method to non static as there are several xsl files invoke the above method.

What is the best way to access the environment based application.properties file in class which is not managed by Spring?

答:
You can simply autowire Environment and get the property:

```<code>@Autowired
private Environment env;

public void method() {
    String url = env.getProperty("service.url");
    // ...
}
</code>```

If it's not a bean, you can simply create a service, that does that:

```<code>@Service
class PropertyService implements InitializingBean {

    @Autowired
    private Environment env;

    private static PropertyService instance;

    public void method() {
        String url = env.getProperty("service.url");
        // ...
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        instance = this;
    }

    public static PropertyService get() {
        return instance;
    }
}
</code>```

Body:
I am working on spring boot project having version 2.1.6.RELEASE and xslt 1.0.

I have a class that has a set of static methods used to generate the set of URL's using custom logic related to the application.

public class URLGenerator{

    public static String generateURLA(String param1,String param2,String param3)
    {
        String restServiceUrl=<acess url from application.properties>
        //code to invoke third party service
        RestTemplate restTemplate=new RestTemplate();
        String url=restTemplate.invoke()
        return url;
    }
}

In the above method, I have to make a rest call to third party service to retrieve the final URL. The URL to invoke the service is different for every environment so I have stored the URL inside the application-{env}.properties file.

I will not be able to change the above method to non static as there are several xsl files invoke the above method.

What is the best way to access the environment based application.properties file in class which is not managed by Spring?

Body:
You can simply autowire Environment and get the property:

@Autowired
private Environment env;

public void method() {
    String url = env.getProperty("service.url");
    // ...
}

If it's not a bean, you can simply create a service, that does that:

@Service
class PropertyService implements InitializingBean {

    @Autowired
    private Environment env;

    private static PropertyService instance;

    public void method() {
        String url = env.getProperty("service.url");
        // ...
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        instance = this;
    }

    public static PropertyService get() {
        return instance;
    }
}


问:
Problem with Decrement Operator in While Loop
I'm trying to write a program that calculates the sum of all the numbers in a diagonal section of a multiplication chart (basically from row 12 column 1 of the array to row 1 column 12). The problem is, in the code the Rowcounter refuses to decrease after every loop while the Colcounter increases just fine. What am I doing wrong?

```<code>    public Integer  ComputeDiagonalSum(int multiplier)
{
    Integer [][] MultiArray = new Integer[multiplier][multiplier];
    int RowCounter = MultiArray.length - 1;
    int ColCounter = 0;
    Integer DiagonalSum = 0;

    while(RowCounter > 0)
    {
        int RowNumber = RowCounter + 1;
        //
        //Compute inner loop
        while(ColCounter < MultiArray[multiplier - 1].length)
        {
            int ColNumber = ColCounter + 1;
            //Load each box in the current column of the current row
            MultiArray[RowCounter][ColCounter] = RowNumber * ColNumber;
            DiagonalSum += MultiArray[RowCounter][ColCounter];
            ColCounter++;
        }
      //doesn't work
        RowCounter--;
    }
    return DiagonalSum;
}
</code>```

Link to image of multiplication chart:
https://www.google.com/search?client=ms-android-samsung-ga-rev1&sxsrf=ACYBGNQo4QAYAF-MjmvCR4jcbz3RqDx0eg%3A1581776894027&ei=_v9HXvKbAYilUoveveAE&q=multiplication+chart+&oq=multiplication+chart+&gs_l=mobile-gws-wiz-serp.3..35i39j0i22i30.1455.2670..3471...0.0..0.765.1392.5-1j1......0....1.0tdlwHvu690#imgrc=jtyeYkOxpQT3CM:

答: The issue is not that your RowCounter does not decrease, but that you need to move initialization of ColCounter inside the first loop, at the beginning. The evaluation of while(ColCounter < MultiArray[multiplier - 1].length) will always return false after the first iteration, because ColCounter has reached the size of your array.

Body:
I'm trying to write a program that calculates the sum of all the numbers in a diagonal section of a multiplication chart (basically from row 12 column 1 of the array to row 1 column 12). The problem is, in the code the Rowcounter refuses to decrease after every loop while the Colcounter increases just fine. What am I doing wrong?

    public Integer  ComputeDiagonalSum(int multiplier)
{
    Integer [][] MultiArray = new Integer[multiplier][multiplier];
    int RowCounter = MultiArray.length - 1;
    int ColCounter = 0;
    Integer DiagonalSum = 0;

    while(RowCounter > 0)
    {
        int RowNumber = RowCounter + 1;
        //
        //Compute inner loop
        while(ColCounter < MultiArray[multiplier - 1].length)
        {
            int ColNumber = ColCounter + 1;
            //Load each box in the current column of the current row
            MultiArray[RowCounter][ColCounter] = RowNumber * ColNumber;
            DiagonalSum += MultiArray[RowCounter][ColCounter];
            ColCounter++;
        }
      //doesn't work
        RowCounter--;
    }
    return DiagonalSum;
}

Link to image of multiplication chart:
https://www.google.com/search?client=ms-android-samsung-ga-rev1&sxsrf=ACYBGNQo4QAYAF-MjmvCR4jcbz3RqDx0eg%3A1581776894027&ei=_v9HXvKbAYilUoveveAE&q=multiplication+chart+&oq=multiplication+chart+&gs_l=mobile-gws-wiz-serp.3..35i39j0i22i30.1455.2670..3471...0.0..0.765.1392.5-1j1......0....1.0tdlwHvu690#imgrc=jtyeYkOxpQT3CM:


问:
How to test a nested error thrown from an async function?
Consider the following functions

const aPrivateAsyncQuery = async () => {
  try {
    return await axios.post('someURL', {query: 'someQuery'})
  } catch (error) {
    throw new Error(`A thrown error: ${error}`)
  }
}
```

<pre class="lang-js prettyprint-override"><code>export const aPublicAsyncFunction = async someVariable => {
  const data = await aPrivateAsyncQuery()
  if (data[someVariable]){
    return data[someVariable]
  }
  return {}
}
</code>```

How can one test that aPrivateAsyncQuery throws an error when aPublicAsyncFunction is called?

I currently have the following test... which mentions that no throw happened.

  it('should throw when nested function throws', async () => {
    const someVariable = 'foo'

    axios.post.mockRejectedValue(new Error('bar'))

    expect(async () => { await aPublicAsyncFunction(someVariable) }).toThrow()
  })
```

<p>Thanks in advance!</p>

<hr>

<p><strong>EDIT</strong></p>

<p>The following implementation worked perfectly:</p>

<pre class="lang-js prettyprint-override"><code>  it('should throw when nested function throws', async () => {
    const someVariable = 'foo'

    axios.post.mockRejectedValue(new Error('bar'))

    await expect(aPublicAsyncFunction(someVariable)).rejects.toThrowError('bar')
  })
</code>```

答:
It seems that expect toThrow is not very well supported with async functions.

As per that issue, you can test your method with the syntax:

```<code>it('should throw when nested function throws', async () => {
    const someVariable = 'foo'

    jest.spyOn(axios, 'post')
        .mockImplementation(() => Promise.reject(new Error('bar')));

    await expect(aPublicAsyncFunction(someVariable)).rejects.toThrow(new Error('A thrown error: Error: bar'));
});
</code>```

Body:
Consider the following functions

const aPrivateAsyncQuery = async () => {
  try {
    return await axios.post('someURL', {query: 'someQuery'})
  } catch (error) {
    throw new Error(`A thrown error: ${error}`)
  }
}

export const aPublicAsyncFunction = async someVariable => {
  const data = await aPrivateAsyncQuery()
  if (data[someVariable]){
    return data[someVariable]
  }
  return {}
}

How can one test that aPrivateAsyncQuery throws an error when aPublicAsyncFunction is called?

I currently have the following test... which mentions that no throw happened.

  it('should throw when nested function throws', async () => {
    const someVariable = 'foo'

    axios.post.mockRejectedValue(new Error('bar'))

    expect(async () => { await aPublicAsyncFunction(someVariable) }).toThrow()
  })

Thanks in advance!

EDIT

The following implementation worked perfectly:

  it('should throw when nested function throws', async () => {
    const someVariable = 'foo'

    axios.post.mockRejectedValue(new Error('bar'))

    await expect(aPublicAsyncFunction(someVariable)).rejects.toThrowError('bar')
  })

Body:
It seems that expect toThrow is not very well supported with async functions.

As per that issue, you can test your method with the syntax:

it('should throw when nested function throws', async () => {
    const someVariable = 'foo'

    jest.spyOn(axios, 'post')
        .mockImplementation(() => Promise.reject(new Error('bar')));

    await expect(aPublicAsyncFunction(someVariable)).rejects.toThrow(new Error('A thrown error: Error: bar'));
});


问:
trying to use exact strings for IndexOf within a filterfunction for an array Javascript
I'm currently creating a search function with filter options for an json array:

```<code>if (ploc != " - " ) {
    var filteredarray7 = filteredarray6.filter(function(orte){
        return orte['Painting Location'].indexOf(ploc) !== -1 ;
    });
} else {
    var filteredarray7 = filteredarray6;
}
</code>```

the variable ploc can be a number from 1-12 or the string " - ", ['Painting Location'] can be strings like "1; 2; 4; 12;", "1" or "3; 5; 12" while each number in this string resembles a category of painting location.

My question: What changes do i need to do, that it returns all objects that include for example 1 in their strings but not those with 10, 11, 12 unless 1 is also part of the string.

Sry for my bad english, it has been a long time since I have written something in a foreign language.

答:
If I understand you correctly, you better to use regular expressions.

```<code>return orte['Painting Location'].search(new Regexp('(^|;)\s*' + ploc + '\s*($|;)')) != -1;
</code>```

Or:

```<code>return !!orte['Painting Location'].match(new Regexp('(^|;)\s*' + ploc + '\s*($|;)'));
</code>```

Read here about RegExp in JavaScript.

Body:
I'm currently creating a search function with filter options for an json array:

if (ploc != " - " ) {
    var filteredarray7 = filteredarray6.filter(function(orte){
        return orte['Painting Location'].indexOf(ploc) !== -1 ;
    });
} else {
    var filteredarray7 = filteredarray6;
}

the variable ploc can be a number from 1-12 or the string " - ", ['Painting Location'] can be strings like "1; 2; 4; 12;", "1" or "3; 5; 12" while each number in this string resembles a category of painting location.

My question: What changes do i need to do, that it returns all objects that include for example 1 in their strings but not those with 10, 11, 12 unless 1 is also part of the string.

Sry for my bad english, it has been a long time since I have written something in a foreign language.

Body:
If I understand you correctly, you better to use regular expressions.

return orte['Painting Location'].search(new Regexp('(^|;)\s*' + ploc + '\s*($|;)')) != -1;

Or:

return !!orte['Painting Location'].match(new Regexp('(^|;)\s*' + ploc + '\s*($|;)'));

Read here about RegExp in JavaScript.


问:
QOpenGLWidget's makeCurrent does not work?
I am trying to use QOpenGLWidget without subclassing.

When I  try to make OpenGL calls outside of QOpenGLWidget's methods or signals, nothing seems to happen. For example, following code clears window black despite me setting glClearColor:

```<code>MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
{
    auto glw = new QOpenGLWidget( this );
    glw->makeCurrent();
    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    glw->doneCurrent();

    connect( glw, &QOpenGLWidget::aboutToCompose, [=] {
        glClear( GL_COLOR_BUFFER_BIT );
    });

    setCentralWidget( glw );
}
</code>```

However, when I move glClearColor inside the lambda connected to the aboutToCompose signal, widget is cleared with white color.

答: You can call auto *ctx = QOpenGLContext::currentContext(); to check if makeCurrent succeeded.

Body:
I am trying to use QOpenGLWidget without subclassing.

When I  try to make OpenGL calls outside of QOpenGLWidget's methods or signals, nothing seems to happen. For example, following code clears window black despite me setting glClearColor:

MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
{
    auto glw = new QOpenGLWidget( this );
    glw->makeCurrent();
    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    glw->doneCurrent();

    connect( glw, &QOpenGLWidget::aboutToCompose, [=] {
        glClear( GL_COLOR_BUFFER_BIT );
    });

    setCentralWidget( glw );
}

However, when I move glClearColor inside the lambda connected to the aboutToCompose signal, widget is cleared with white color.


答:
You are leading with an asynchronous state, in an asynchronous scenario you cannot assign the value to a variable in the traditional way, because, you must wait for the function to return its result, this can be done in several ways, one of them is doing async function as in the example and then consume, suscribe or call the async function and wait for its result and then use it

```<code>async function rainSum(str) {
    const response = await fetch(`barD.php?SelTime=${str}`);

    return await response.json();
}

// subscribe to the asynchronous function
rainSum("some string").then(response => console.log(response));
</code>```

Some relevant links

fetch
Promises, async/await

Take time to understand the difference between synchronous and asynchronous functions and the javascript methods to lead with these cases, it is very common to work with asynchronous functions in javascript and it is wise to familiarize yourself with the concept

Title: How to pass the AJAX responseText into a variable

Body:
I want to know how to pass the AJAX responseText into a variable? I want to use it in another part of programe. The code "document.getElementById("showData").innerHTML = xhttp.responseText;" can display the return string correctly, but I cannot use a variable to receive it.

<?PHP
$currHr=date('H')-1;
?>

<form action="">

<Select name="SelTime" onchange="rainSum(this.value)">
<?php
if ($currHr>0){
for ($i=$currHr; $i>=0; $i--)
{
    echo "<option value=".$i.">".$i.":00";
    echo " - ";
    echo $i.":59</option>
";
}
}else {
    for ($i=23; $i>=0; $i--)
{
    echo "<option value=".$i.">".$i.":00";
    echo " - ";
    echo $i.":59</option>
";
}
}
?>
</Select>
</form>

Let AJAX change this text.

Body:
You are leading with an asynchronous state, in an asynchronous scenario you cannot assign the value to a variable in the traditional way, because, you must wait for the function to return its result, this can be done in several ways, one of them is doing async function as in the example and then consume, suscribe or call the async function and wait for its result and then use it

async function rainSum(str) {
    const response = await fetch(`barD.php?SelTime=${str}`);

    return await response.json();
}

// subscribe to the asynchronous function
rainSum("some string").then(response => console.log(response));

Some relevant links

fetch
Promises, async/await

Take time to understand the difference between synchronous and asynchronous functions and the javascript methods to lead with these cases, it is very common to work with asynchronous functions in javascript and it is wise to familiarize yourself with the concept


问:
OOP in python with example for cuboid class
I have created a class to calculate area and perimeter of rectangle in python.

I want to expand this class and calculate area and volume of a cuboid

My try is the following

```<code>class Rectangle ():
    def __init__(self, L, W):
        self.length = L
        self.width = W

    def rect_perimeter(self):
        return 2 * (self.length + self.width)

    def rect_area(self):
        return self.length * self.width

class RectangularCuboid (Rectangle):
    def __init__(self, H):
        self.height = H
        Rectangle.__init__ (self, L, W)

    def rect_area(self):
        return 2 * (self.length * self.width + self.width * self.height + self.height * self.lenght)

    def rect_volume(self):
        return self.length * self.width * self.height

RC = RectangularCuboid(30, 20, 10)
R = Rectangular(30,20)
RC.rect_area()
RC.rect_volume()
print('Rectangle Cuboid Area:', RC.rect_area(), ', Rectangle Cuboid Volume:', RC.rect_volume())
</code>```

but I get the following error

```<code>Traceback (most recent call last):
  File "C:/Users/User/.PyCharmCE2019.3/config/scratches/scratch.py", line 24, in <module>
    RC = RectangularCuboid(30, 20, 10)
TypeError: __init__() takes 2 positional arguments but 4 were given

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

what am I missing?

答:
```<code>class Rectangle ():
    def __init__(self, L, W):
        self.length = L
        self.width = W

    def rect_perimeter(self):
        return 2 * (self.length + self.width)

    def rect_area(self):
        return self.length * self.width

class RectangularCuboid (Rectangle):
    def __init__(self, H,L,W):
        self.height = H
        self.length = L
        self.width = W

    def rect_area(self):
        return 2 * (self.length * self.width + self.width * self.height + self.height * self.length)

    def rect_volume(self):
        return self.length * self.width * self.height

RC = RectangularCuboid(30,20, 10)

RC.rect_area()
RC.rect_volume()
print('Rectangle Cuboid Area:', RC.rect_area(), ', Rectangle Cuboid Volume:', RC.rect_volume())
</code>```

<p>This should work
 RectangularCuboid inherits from Rectangle but the init is overridden, so you need to adapt it to your needs. </p>

Body:
I have created a class to calculate area and perimeter of rectangle in python.

I want to expand this class and calculate area and volume of a cuboid

My try is the following

class Rectangle ():
    def __init__(self, L, W):
        self.length = L
        self.width = W

    def rect_perimeter(self):
        return 2 * (self.length + self.width)

    def rect_area(self):
        return self.length * self.width

class RectangularCuboid (Rectangle):
    def __init__(self, H):
        self.height = H
        Rectangle.__init__ (self, L, W)

    def rect_area(self):
        return 2 * (self.length * self.width + self.width * self.height + self.height * self.lenght)

    def rect_volume(self):
        return self.length * self.width * self.height

RC = RectangularCuboid(30, 20, 10)
R = Rectangular(30,20)
RC.rect_area()
RC.rect_volume()
print('Rectangle Cuboid Area:', RC.rect_area(), ', Rectangle Cuboid Volume:', RC.rect_volume())

but I get the following error

Traceback (most recent call last):
  File "C:/Users/User/.PyCharmCE2019.3/config/scratches/scratch.py", line 24, in <module>
    RC = RectangularCuboid(30, 20, 10)
TypeError: __init__() takes 2 positional arguments but 4 were given

Process finished with exit code 1

what am I missing?

Body:
class Rectangle ():
    def __init__(self, L, W):
        self.length = L
        self.width = W

    def rect_perimeter(self):
        return 2 * (self.length + self.width)

    def rect_area(self):
        return self.length * self.width

class RectangularCuboid (Rectangle):
    def __init__(self, H,L,W):
        self.height = H
        self.length = L
        self.width = W

    def rect_area(self):
        return 2 * (self.length * self.width + self.width * self.height + self.height * self.length)

    def rect_volume(self):
        return self.length * self.width * self.height

RC = RectangularCuboid(30,20, 10)

RC.rect_area()
RC.rect_volume()
print('Rectangle Cuboid Area:', RC.rect_area(), ', Rectangle Cuboid Volume:', RC.rect_volume())

This should work
 RectangularCuboid inherits from Rectangle but the init is overridden, so you need to adapt it to your needs.


问:
please give one scenario when to use spark-submit --files
when to use --files with spark-submit. what will happen internally?
Sorry to ask this basic question but I did not find much documentation about --files
please provide any example or scenario..

Thanks in adv,

答:
You can see details about an option by doing spark-submit --help. Here is what it says which is pretty clear. You can use it for resolving a file dependency, example - distributing a config file while submitting the application.

```<code>--files FILES               Comma-separated list of files to be placed in the working
                              directory of each executor. File paths of these files
                              in executors can be accessed via SparkFiles.get(fileName).
</code>```

Body:
You can see details about an option by doing spark-submit --help. Here is what it says which is pretty clear. You can use it for resolving a file dependency, example - distributing a config file while submitting the application.

--files FILES               Comma-separated list of files to be placed in the working
                              directory of each executor. File paths of these files
                              in executors can be accessed via SparkFiles.get(fileName).


问:
float output from php function
I have a simple php replace function, that I need to return a "0" (for resale) and a "1" (for newbuilt)

```<code>. function multi_rep2( $oldVar = '' ) {
    $searchVal2 = array("newbuilt", "resale");
    $replaceVal2 = array("1", "0");
    return str_replace($searchVal2, $replaceVal2, $oldVar);
}
</code>```

In my output I get "1", but not "0". I figured out that I have to convert the zero to a float value to be returned. I tried a few things with the floatval() function, but can not get it to work.

Anyone who can set me in the right direction?

Kind, regards.

答:
As others have stated, this function works. To parse the value to float do something like:

```<code>function multi_rep2( $oldVar = '' ) {
    $searchVal2 = array("newbuilt", "resale");
    $replaceVal2 = array("1", "0");
    return floatval(str_replace($searchVal2, $replaceVal2, $oldVar));
}
// yields: float(0)
var_dump(multi_rep2('resale'));
</code>```

Sandbox

Title: float output from php function

Body:
I have a simple php replace function, that I need to return a "0" (for resale) and a "1" (for newbuilt)

. function multi_rep2( $oldVar = '' ) {
    $searchVal2 = array("newbuilt", "resale");
    $replaceVal2 = array("1", "0");
    return str_replace($searchVal2, $replaceVal2, $oldVar);
}

In my output I get "1", but not "0". I figured out that I have to convert the zero to a float value to be returned. I tried a few things with the floatval() function, but can not get it to work.

Anyone who can set me in the right direction?

Kind, regards.

Body:
As others have stated, this function works. To parse the value to float do something like:

function multi_rep2( $oldVar = '' ) {
    $searchVal2 = array("newbuilt", "resale");
    $replaceVal2 = array("1", "0");
    return floatval(str_replace($searchVal2, $replaceVal2, $oldVar));
}
// yields: float(0)
var_dump(multi_rep2('resale'));

Sandbox


答:
You may use

```<code>$response = new \Illuminate\Http\JsonResponse(['success' => $data], $this->successStatus);
$response->withCookie(cookie($cookieName, $cookieVal, 45000));
return $response;
</code>```

Illuminate\Http\JsonResponse

Title: Laravel set cookie in API not set

Body:
I using laravel 5 as Rest API, and I want to set a cookie in controller:

return response()->json(['success' => $data], $this-> successStatus)->cookie('name', 'myvalue');

this return with response cookie successfully, but can not access in front, I also used:

Cookie::queue($name, $value);

Or

Cookie::queue(Cookie::make('cookieName', 'value'));

Or all way in google, stackoverflow, but none of these set cookie in browser, I need to set http only cookie in browser via laravel controller. how can i do this?

I also used php cookie, no success

Body:
You may use

$response = new \Illuminate\Http\JsonResponse(['success' => $data], $this->successStatus);
$response->withCookie(cookie($cookieName, $cookieVal, 45000));
return $response;

Illuminate\Http\JsonResponse


问:
Parsing request body prohibits request signature verification
I'm trying to build a serverless Slackbot using Lambda function. I end up with an error while verifying the Request URL through the Slack event API. @slack/events-api is the dependency that I'm using to capture the slack events.

Here is my code.

```<code>const sls = require('serverless-http');
const { createEventAdapter } = require('@slack/events-api');
require('dotenv').config();

const { SLACK_SIGNING_SECRET } = process.env
const slackEvents = createEventAdapter( SLACK_SIGNING_SECRET || '' );

slackEvents.on('message', async event => {
  console.log('received!')
});

module.exports.server = sls(slackEvents.requestListener());
</code>```

This is the error that I'm getting while verifing the request url

Slack Request URL verification

Can someone help me with this?

答:
Just ran into this exact issue, and took a look into http-handler.js in node-slack-events.

All we have to do is store the raw request body as rawBody before serverless-http parses it.

serverless-http lets you transform the request, before it is sent to the app—great opportunity for a fix:

module.exports.handler = serverless(app, {
  request(request) {
    request.rawBody = request.body;
  },
});
```

Body:
I'm trying to build a serverless Slackbot using Lambda function. I end up with an error while verifying the Request URL through the Slack event API. @slack/events-api is the dependency that I'm using to capture the slack events.

Here is my code.

const sls = require('serverless-http');
const { createEventAdapter } = require('@slack/events-api');
require('dotenv').config();

const { SLACK_SIGNING_SECRET } = process.env
const slackEvents = createEventAdapter( SLACK_SIGNING_SECRET || '' );

slackEvents.on('message', async event => {
  console.log('received!')
});

module.exports.server = sls(slackEvents.requestListener());

This is the error that I'm getting while verifing the request url

Slack Request URL verification

Can someone help me with this?