问:
Call golang function from Tcl sript
We use a third party Tcl parsing library to validation Tcl script for both syntax and semantic checking.  The driver was written in C and defined a set of utility functions.  Then it calls Tcl_CreateObjCommand so the script could call these C functions.  Now we are in the process of porting the main program to go and I could not find a way to do this.  Anyone know a way to call golang functions from Tcl script?

```<code>static int
create_utility_tcl_cmds(Tcl_Interp* interp)
{
    if (Tcl_CreateObjCommand(interp, "ip_v4_address",
                        ip_address, (ClientData)AF_INET, NULL) == NULL) {
        TCL_CHECKER_TCL_CMD_EVENT(0, "ip_v4_address");
        return -1;
    }

    .....
    return 0;
}
</code>```

答:
Assuming you've set the relevant functions as exported and built the Go parts of your project as in

Using Go code in an existing C project

[…]

The important things to note are:

The package needs to be called main

You need to have a main function, although it can be empty.

You need to import the package C

You need special //export comments to mark the functions you want callable from C.

I can compile it as a C callable static library with the following command:

```<code>go build -buildmode=c-archive foo.go
</code>```

Then the core of what remains to be done is to write the C glue function from Tcl's API to your Go code. That will involve a function something like:

static int ip_address_glue(
        ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) {
    // Need an explicit cast; ClientData is really void*
    GoInt address_family = (GoInt) clientData;

    // Check for the right number of arguments
    if (objc != 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "address");
        return TCL_ERROR;
    }

    // Convert the argument to a Go string
    GoString address;
    int len;
    address.p = Tcl_GetStringFromObj(objv[1], &len);
    address.n = len; // This bit is hiding a type mismatch

    // Do the call; I assume your Go function is called ip_address
    ip_address(address_family, address);

    // Assume the Go code doesn't fail, so no need to map the failure back to Tcl

    return TCL_OK;
}
```
<p><sup>(Credit to https://medium.com/learning-the-go-programming-language/calling-go-functions-from-other-languages-4c7d8bcc69bf for providing enough information for me to work out some of the type bindings.)</sup></p>
<p>That's then the function that you register with Tcl as the callback.</p>
<pre class="lang-c prettyprint-override"><code>Tcl_CreateObjCommand(interp, "ip_v4_address", ip_address_glue, (ClientData)AF_INET, NULL);
</code>```

Theoretically, a command registration can fail. Practically, that only happens when the Tcl interpreter (or a few critical namespaces within it) is being deleted.

Mapping a failure into Tcl is going to be easiest if it is encoded at the Go level as an enumeration. Probably easiest to represent success as zero. With that, you'd then do:

GoInt failure_code = ip_address(address_family, address);

switch (failure_code) {
case 0: // Success
    return TCL_OK;
case 1: // First type of failure
    Tcl_SetResult(interp, "failure of type #1", TCL_STATIC);
    return TCL_ERROR;
// ... etc for each expected case ...
default: // Should be unreachable, yes?
    Tcl_SetObjResult(interp, Tcl_ObjPrintf("unexpected failure: %d", failure_code));
    return TCL_ERROR;
}
```

Passing back more complex return types with tuples of values (especially a combination of a success indicator and a “real” result value) should also be possible, but I've not got a Go development environment in order to probe how they're mapped at the C level.

Title: Call golang function from Tcl sript

Body:
We use a third party Tcl parsing library to validation Tcl script for both syntax and semantic checking.  The driver was written in C and defined a set of utility functions.  Then it calls Tcl_CreateObjCommand so the script could call these C functions.  Now we are in the process of porting the main program to go and I could not find a way to do this.  Anyone know a way to call golang functions from Tcl script?

static int
create_utility_tcl_cmds(Tcl_Interp* interp)
{
    if (Tcl_CreateObjCommand(interp, "ip_v4_address",
                        ip_address, (ClientData)AF_INET, NULL) == NULL) {
        TCL_CHECKER_TCL_CMD_EVENT(0, "ip_v4_address");
        return -1;
    }

    .....
    return 0;
}

Body:
Assuming you've set the relevant functions as exported and built the Go parts of your project as in

Using Go code in an existing C project

[…]

The important things to note are:

The package needs to be called main

You need to have a main function, although it can be empty.

You need to import the package C

You need special //export comments to mark the functions you want callable from C.

I can compile it as a C callable static library with the following command:

go build -buildmode=c-archive foo.go

Then the core of what remains to be done is to write the C glue function from Tcl's API to your Go code. That will involve a function something like:

static int ip_address_glue(
        ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) {
    // Need an explicit cast; ClientData is really void*
    GoInt address_family = (GoInt) clientData;

    // Check for the right number of arguments
    if (objc != 2) {
        Tcl_WrongNumArgs(interp, 1, objv, "address");
        return TCL_ERROR;
    }

    // Convert the argument to a Go string
    GoString address;
    int len;
    address.p = Tcl_GetStringFromObj(objv[1], &len);
    address.n = len; // This bit is hiding a type mismatch

    // Do the call; I assume your Go function is called ip_address
    ip_address(address_family, address);

    // Assume the Go code doesn't fail, so no need to map the failure back to Tcl

    return TCL_OK;
}

(Credit to https://medium.com/learning-the-go-programming-language/calling-go-functions-from-other-languages-4c7d8bcc69bf for providing enough information for me to work out some of the type bindings.)

That's then the function that you register with Tcl as the callback.

Tcl_CreateObjCommand(interp, "ip_v4_address", ip_address_glue, (ClientData)AF_INET, NULL);

Theoretically, a command registration can fail. Practically, that only happens when the Tcl interpreter (or a few critical namespaces within it) is being deleted.

Mapping a failure into Tcl is going to be easiest if it is encoded at the Go level as an enumeration. Probably easiest to represent success as zero. With that, you'd then do:

GoInt failure_code = ip_address(address_family, address);

switch (failure_code) {
case 0: // Success
    return TCL_OK;
case 1: // First type of failure
    Tcl_SetResult(interp, "failure of type #1", TCL_STATIC);
    return TCL_ERROR;
// ... etc for each expected case ...
default: // Should be unreachable, yes?
    Tcl_SetObjResult(interp, Tcl_ObjPrintf("unexpected failure: %d", failure_code));
    return TCL_ERROR;
}

Passing back more complex return types with tuples of values (especially a combination of a success indicator and a “real” result value) should also be possible, but I've not got a Go development environment in order to probe how they're mapped at the C level.


来源: stackexchange

问:
string array to data frame conversion in r
I have got this array in a string variable (k) and would like to convert it to a dataframe in r. The as.array(k) does not convert it. What is the best way to do this. Also, considering that there will be nested arrays in the future to be dealt with.</p>

```<code>places = [[\"Abtenau\", \"Abtenau\", 767, 52, 3.0000],[\"Achenkirch\", \"Achenkirch am Achensee\", 248, 61, 6.0000],[\"Adelharz\", \"Adelharz\", 47, 46, 2.0000],[\"Alpbach\", \"Alpbachtal\", 2629, 89, 2.0000]]
</code>```

答:
An option would be jsonlite to convert to a matrix, then change it to data.frame and retype

```<code>library(jsonlite)
library(hablar)
library(dplyr)
fromJSON(places) %>%
     as.data.frame %>%
     retype
# A tibble: 4 x 5
#  V1         V2                        V3    V4    V5
#  <chr>      <chr>                  <int> <int> <int>
#1 Abtenau    Abtenau                  767    52     3
#2 Achenkirch Achenkirch am Achensee   248    61     6
#3 Adelharz   Adelharz                  47    46     2
#4 Alpbach    Alpbachtal              2629    89     2
</code>```

Or this can be done with base R after removing the square brackets with regex

```<code>read.csv(text = gsub('[][]|"', "", gsub("(?<=\\]),(?=\\[)", "\n",
  places, perl = TRUE)), header = FALSE, stringsAsFactors = FALSE)
#          V1                      V2   V3 V4 V5
#1    Abtenau                 Abtenau  767 52  3
#2 Achenkirch  Achenkirch am Achensee  248 61  6
#3   Adelharz                Adelharz   47 46  2
#4    Alpbach              Alpbachtal 2629 89  2
</code>```

data

```<code>places <- "[[\"Abtenau\", \"Abtenau\", 767, 52, 3.0000],[\"Achenkirch\", \"Achenkirch am Achensee\", 248, 61, 6.0000],[\"Adelharz\", \"Adelharz\", 47, 46, 2.0000],[\"Alpbach\", \"Alpbachtal\", 2629, 89, 2.0000]]"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have got this array in a string variable (k) and would like to convert it to a dataframe in r. The as.array(k) does not convert it. What is the best way to do this. Also, considering that there will be nested arrays in the future to be dealt with.

places = [[\"Abtenau\", \"Abtenau\", 767, 52, 3.0000],[\"Achenkirch\", \"Achenkirch am Achensee\", 248, 61, 6.0000],[\"Adelharz\", \"Adelharz\", 47, 46, 2.0000],[\"Alpbach\", \"Alpbachtal\", 2629, 89, 2.0000]]

Body:
An option would be jsonlite to convert to a matrix, then change it to data.frame and retype

library(jsonlite)
library(hablar)
library(dplyr)
fromJSON(places) %>%
     as.data.frame %>%
     retype
# A tibble: 4 x 5
#  V1         V2                        V3    V4    V5
#  <chr>      <chr>                  <int> <int> <int>
#1 Abtenau    Abtenau                  767    52     3
#2 Achenkirch Achenkirch am Achensee   248    61     6
#3 Adelharz   Adelharz                  47    46     2
#4 Alpbach    Alpbachtal              2629    89     2

Or this can be done with base R after removing the square brackets with regex

read.csv(text = gsub('[][]|"', "", gsub("(?<=\\]),(?=\\[)", "\n",
  places, perl = TRUE)), header = FALSE, stringsAsFactors = FALSE)
#          V1                      V2   V3 V4 V5
#1    Abtenau                 Abtenau  767 52  3
#2 Achenkirch  Achenkirch am Achensee  248 61  6
#3   Adelharz                Adelharz   47 46  2
#4    Alpbach              Alpbachtal 2629 89  2

data

places <- "[[\"Abtenau\", \"Abtenau\", 767, 52, 3.0000],[\"Achenkirch\", \"Achenkirch am Achensee\", 248, 61, 6.0000],[\"Adelharz\", \"Adelharz\", 47, 46, 2.0000],[\"Alpbach\", \"Alpbachtal\", 2629, 89, 2.0000]]"


问:
TensorFlow1.13 can't use slice_input_producer
My TensorFlow's version is 1.13.1. When I used tf.train.slice_input_producer, I got a warning message:

WARNING:tensorflow:From test.py:55: slice_input_producer (from tensorflow.python.training.input) is deprecated and will be removed in a future version.

What should I do?

答:
It's just a warning message. As per the official tensorflow documentation here,

Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future
  version. Instructions for updating: Queue-based input pipelines have
  been replaced by tf.data. Use
  tf.data.Dataset.from_tensor_slices(tuple(tensor_list)).shuffle(tf.shape(input_tensor,
  out_type=tf.int64)[0]).repeat(num_epochs). If shuffle=False, omit the
  .shuffle(...).

In a nutshell, it basically says tf.train.slice_input_producer() is deprecated and no longer used. In place of that, you should use tf.data.Dataset.from_tensor_slices().


问:
Laravel API returns a view 404 error instead of JSON error
I am trying to create a RESTful API using laravel, I'm trying to fetch a resource with an invalid ID, and the result is 404 since it is not found, but my problem is the response is not in JSON format, but a View 404 (by default) with HTML. Is there any way to convert the response into JSON? For this situation, I use Homestead.

I try to include a fallback route, but it does not seem to fit this case.

Route::fallback(function () {
    return response()->json(['message' => 'Not Found.'], 404);
});
```

<p>I try to modify the Handler (App\Exceptions), but nothing change.</p>

<pre class="lang-php prettyprint-override"><code>public function render($request, Exception $e)
{
    if ($e instanceof ModelNotFoundException) {
        if ($request->ajax()) {
            return response()->toJson([
                'message' => 'Not Found.',
            ], 404);
        }
    }

    return parent::render($request, $e);
}
</code>```

答:
if your project is only a RESTful API and no views, you could add a new middleware which add ['accept' => 'application/json'] header to all request. this will ensure that all response will return a json, instead of the views

```<code><?php

namespace App\Http\Middleware;

use Closure;

class AddAjaxHeader
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $request->headers->add(['accept' => 'application/json']);
        return $next($request);
    }
}
</code>```

and add it into Kernel.php

Body:
I am trying to create a RESTful API using laravel, I'm trying to fetch a resource with an invalid ID, and the result is 404 since it is not found, but my problem is the response is not in JSON format, but a View 404 (by default) with HTML. Is there any way to convert the response into JSON? For this situation, I use Homestead.

I try to include a fallback route, but it does not seem to fit this case.

Route::fallback(function () {
    return response()->json(['message' => 'Not Found.'], 404);
});

I try to modify the Handler (App\Exceptions), but nothing change.

public function render($request, Exception $e)
{
    if ($e instanceof ModelNotFoundException) {
        if ($request->ajax()) {
            return response()->toJson([
                'message' => 'Not Found.',
            ], 404);
        }
    }

    return parent::render($request, $e);
}

Body:
if your project is only a RESTful API and no views, you could add a new middleware which add ['accept' => 'application/json'] header to all request. this will ensure that all response will return a json, instead of the views

<?php

namespace App\Http\Middleware;

use Closure;

class AddAjaxHeader
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $request->headers->add(['accept' => 'application/json']);
        return $next($request);
    }
}

and add it into Kernel.php


问:
Kotlin Ternary Conditional Operator
What is the equivalent of this expression in Kotlin?

```<code>a ? b : c
</code>```

This is not valid code in Kotlin.

答:
Java's equivalent of ternary operator

```<code>a ? b : c
</code>```

is a simple IF in Kotlin in one line

```<code>if(a) b else c
</code>```

there is no ternary operator (condition ? then : else), because
  ordinary if works fine in this role.

https://kotlinlang.org/docs/reference/control-flow.html#if-expression

Special case for Null comparison

you can use the Elvis operator

```<code>if ( a != null ) a else b
// equivalent to
a ?: b
</code>```

Title: Kotlin Ternary Conditional Operator

Body:
What is the equivalent of this expression in Kotlin?

a ? b : c

This is not valid code in Kotlin.

Body:
Java's equivalent of ternary operator

a ? b : c

is a simple IF in Kotlin in one line

if(a) b else c

there is no ternary operator (condition ? then : else), because
  ordinary if works fine in this role.

https://kotlinlang.org/docs/reference/control-flow.html#if-expression

Special case for Null comparison

you can use the Elvis operator

if ( a != null ) a else b
// equivalent to
a ?: b


问:
Creating new columns in DataFrames under some condition
I'm trying to create a new column in my dataframe, but its values must follow some rule. For example, if the value of the variable Venda is less than 200, then the variable Comissão must be 0.

```<code>if (df['Venda']<200):
    df['Comissão']=0
    df['Direito a Bonus']='Não'
elif (df['Venda']>=200) & (df['Venda']<250):
    df['Comissão']=0.5*df['Venda']
    df['Direito a Bonus']='Sim'
else:
    df['Comissão']=0.7*df['Venda']
    df['Direito a Bonus']='Sim'
</code>```

Running this code, I get the error:

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

答:
You can use DataFrame.apply and then use pandas.concat to combine them:

```<code>df=pd.DataFrame({'Venda':[100,150,200,205,210,250,251]})
print(df)
def check(val):
    if (val<200):
        return [0,'Não']
    elif ((val>=200) and (val<250)):
        return [0.5*val,'Sim']
    else:
        return [0.7*val,'Sim']

df2=pd.DataFrame(list(df.Venda.apply(check)), columns=['Comissão','Direito a Bonus'])
df=pd.concat([df,df2], axis=1)
print(df)
</code>```

Output:

```<code>   Venda
0    100
1    150
2    200
3    205
4    210
5    250
6    251

   Venda  Comissão Direito a Bonus
0    100       0.0             Não
1    150       0.0             Não
2    200     100.0             Sim
3    205     102.5             Sim
4    210     105.0             Sim
5    250     175.0             Sim
6    251     175.7             Sim
</code>```

Body:
I'm trying to create a new column in my dataframe, but its values must follow some rule. For example, if the value of the variable Venda is less than 200, then the variable Comissão must be 0.

if (df['Venda']<200):
    df['Comissão']=0
    df['Direito a Bonus']='Não'
elif (df['Venda']>=200) & (df['Venda']<250):
    df['Comissão']=0.5*df['Venda']
    df['Direito a Bonus']='Sim'
else:
    df['Comissão']=0.7*df['Venda']
    df['Direito a Bonus']='Sim'

Running this code, I get the error:

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Body:
You can use DataFrame.apply and then use pandas.concat to combine them:

df=pd.DataFrame({'Venda':[100,150,200,205,210,250,251]})
print(df)
def check(val):
    if (val<200):
        return [0,'Não']
    elif ((val>=200) and (val<250)):
        return [0.5*val,'Sim']
    else:
        return [0.7*val,'Sim']

df2=pd.DataFrame(list(df.Venda.apply(check)), columns=['Comissão','Direito a Bonus'])
df=pd.concat([df,df2], axis=1)
print(df)

Output:

   Venda
0    100
1    150
2    200
3    205
4    210
5    250
6    251

   Venda  Comissão Direito a Bonus
0    100       0.0             Não
1    150       0.0             Não
2    200     100.0             Sim
3    205     102.5             Sim
4    210     105.0             Sim
5    250     175.0             Sim
6    251     175.7             Sim


问:
Confusion with scanf() or if()
I am not so familiar with C. Therefore, maybe someone will easily find a solution, I will not mind if you share it.
After entering the data in the first scanf() always gives the option else(): "Error".

I was looking for possible options for the problem. I found a lot of things like that,  but nothing that to help me specifically. I think the mistake is in the strcmp(). But I can not say for sure. Will you help?

```<code>#include <stdio.h>
#include <string.h>

int main()
{
        float celsius, fahrenheit;
        char tempConvering[10];

        printf("Enter what to convert to what (F to C; C to F): ");
        scanf(" %s", &tempConvering[10]);

        if(strcmp(tempConvering, "F to C") == 0)
        {
            printf("\nEnter temperature in Fahrenheit: ");
            scanf(" %f", &fahrenheit);
            celsius = fahrenheit * 1.8 + 32;
            printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
        }
        else if(strcmp(tempConvering, "C to F") == 0)
        {
            printf("\nEnter temperature in Celsius: ");
            scanf(" %f", &celsius);
            celsius = (fahrenheit - 32) / 1.8;
            printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
        }
        else
        {
            puts("\nError!");
        }
}
</code>```

答:
```<code>#include <stdio.h>
#include <string.h>

int main()
{
        float celsius, fahrenheit;
        char tempConvering[20];

        printf("what do you want to convert? ");
        scanf("%s", tempConvering);

        if(strcmp(tempConvering, "Fahrenheits") == 0)
        {
            printf("Enter temperature in Fahrenheit: ");
            scanf("%f", &fahrenheit);
            celsius = (fahrenheit - 32) / 1.8;
            printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
        }
        else if(strcmp(tempConvering, "Celsius") == 0)
        {
            printf("Enter temperature in Celsius: ");
            scanf("%f", &celsius);
            fahrenheit = celsius * 9 / 5 + 32;
            printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
        }
        else
        {
            puts("\nError!");
        }
}
</code>```

This was the answer. I have to thank you for the tips, I will try to remember all the details about the scanf(). However, the problem disappeared only when I changed the desired answer not to "F to C" but to "Fahrenheits". Well, respectively, I changed the question. The program instantly earned. Nevertheless, attempts to do something with the scanf() are unsuccessful, to the extent that the same thing happens with the fgets().

In any case, somehow the problem is solved, thank you all!

Title: Confusion with scanf() or if()

Body:
I am not so familiar with C. Therefore, maybe someone will easily find a solution, I will not mind if you share it.
After entering the data in the first scanf() always gives the option else(): "Error".

I was looking for possible options for the problem. I found a lot of things like that,  but nothing that to help me specifically. I think the mistake is in the strcmp(). But I can not say for sure. Will you help?

#include <stdio.h>
#include <string.h>

int main()
{
        float celsius, fahrenheit;
        char tempConvering[10];

        printf("Enter what to convert to what (F to C; C to F): ");
        scanf(" %s", &tempConvering[10]);

        if(strcmp(tempConvering, "F to C") == 0)
        {
            printf("\nEnter temperature in Fahrenheit: ");
            scanf(" %f", &fahrenheit);
            celsius = fahrenheit * 1.8 + 32;
            printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
        }
        else if(strcmp(tempConvering, "C to F") == 0)
        {
            printf("\nEnter temperature in Celsius: ");
            scanf(" %f", &celsius);
            celsius = (fahrenheit - 32) / 1.8;
            printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
        }
        else
        {
            puts("\nError!");
        }
}

Body:
#include <stdio.h>
#include <string.h>

int main()
{
        float celsius, fahrenheit;
        char tempConvering[20];

        printf("what do you want to convert? ");
        scanf("%s", tempConvering);

        if(strcmp(tempConvering, "Fahrenheits") == 0)
        {
            printf("Enter temperature in Fahrenheit: ");
            scanf("%f", &fahrenheit);
            celsius = (fahrenheit - 32) / 1.8;
            printf("%.2f Fahrenheits = %.2f Celsius\n", fahrenheit, celsius);
        }
        else if(strcmp(tempConvering, "Celsius") == 0)
        {
            printf("Enter temperature in Celsius: ");
            scanf("%f", &celsius);
            fahrenheit = celsius * 9 / 5 + 32;
            printf("%.2f Celsius = %.2f Fahrenheits\n", celsius, fahrenheit);
        }
        else
        {
            puts("\nError!");
        }
}

This was the answer. I have to thank you for the tips, I will try to remember all the details about the scanf(). However, the problem disappeared only when I changed the desired answer not to "F to C" but to "Fahrenheits". Well, respectively, I changed the question. The program instantly earned. Nevertheless, attempts to do something with the scanf() are unsuccessful, to the extent that the same thing happens with the fgets().

In any case, somehow the problem is solved, thank you all!


问:
ScrollViewer width to be narrower
I want to override the width of the scroll bar of ScrollViewer in WPF.  I manage to widen its width but when I tried to make it slimmer it didn't work.  It seems that it has a minimum width that can't be overridden.  Below is the code that I have.

Why is the code below does not work to make the width of the scrollbar slimmer?

Thanks

```<code>           <ScrollViewer.Resources>
                <Style TargetType="ScrollBar">
                    <Style.Triggers>
                        <Trigger Property="Orientation" Value="Vertical">
                            <Setter Property="Width" Value="20"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </ScrollViewer.Resources>
</code>```

答:
You need to edit the template.

Place the editor cursor inside the ScrollViewer tag and then in your properties window go to "Miscellaneous -> Template", click the little rectangle to the right and select "Convert to New Resource" from the popup menu:

That will create a new template containing, among other things, a scrollbar named PART_VerticalScrollBar. Put the cursor over that scrollbar tag and repeat the above to template that out as well, this will create a control template that starts like this:

```<code>    <ControlTemplate x:Key="ScrollBarControlTemplate1" TargetType="{x:Type ScrollBar}">
        <Grid x:Name="Bg" SnapsToDevicePixels="True">
            <Grid.RowDefinitions>
                <RowDefinition MaxHeight="{DynamicResource {x:Static SystemParameters.VerticalScrollBarButtonHeightKey}}"/>
</code>```

Now set MaxWidth=10 (or whatever on that Grid element).

The only other problem you may encounter is that if you make it too small then the up/down arrows on the scrollbar buttons might disappear, that's because their default template places a margin around their path:

```<code><Path x:Name="ArrowTop" Data="M0,4C0,4 ..etc ... " Fill="#FF606060" Margin="3,4,3,3" Stretch="Uniform"/>
</code>```

This can be easily solved by removing that margin setting and/or replacing the path altogether with something else.

Title: ScrollViewer width to be narrower

Body:
I want to override the width of the scroll bar of ScrollViewer in WPF.  I manage to widen its width but when I tried to make it slimmer it didn't work.  It seems that it has a minimum width that can't be overridden.  Below is the code that I have.

Why is the code below does not work to make the width of the scrollbar slimmer?

Thanks

           <ScrollViewer.Resources>

                </Style>
            </ScrollViewer.Resources>

Body:
You need to edit the template.

Place the editor cursor inside the ScrollViewer tag and then in your properties window go to "Miscellaneous -> Template", click the little rectangle to the right and select "Convert to New Resource" from the popup menu:

That will create a new template containing, among other things, a scrollbar named PART_VerticalScrollBar. Put the cursor over that scrollbar tag and repeat the above to template that out as well, this will create a control template that starts like this:

    <ControlTemplate x:Key="ScrollBarControlTemplate1" TargetType="{x:Type ScrollBar}">
        <Grid x:Name="Bg" SnapsToDevicePixels="True">
            <Grid.RowDefinitions>
                <RowDefinition MaxHeight="{DynamicResource {x:Static SystemParameters.VerticalScrollBarButtonHeightKey}}"/>

Now set MaxWidth=10 (or whatever on that Grid element).

The only other problem you may encounter is that if you make it too small then the up/down arrows on the scrollbar buttons might disappear, that's because their default template places a margin around their path:

<Path x:Name="ArrowTop" Data="M0,4C0,4 ..etc ... " Fill="#FF606060" Margin="3,4,3,3" Stretch="Uniform"/>

This can be easily solved by removing that margin setting and/or replacing the path altogether with something else.


问:
Jplayer - Creating dynamic play list
I am using jPLayer to play mp3's for a project.  They mp3's will be loaded dynamically from a database.  I am trying to create the links that will load the selected mp3 into the player.  Currently I have which does does not work.  I believe I am doing something incorrectly with the click event telling what mp3 to play.  If I hardcode the path it works fine but I do not want to set it up that way because there could be hundreds of media files.

```
$(document).ready(function(){

    $("#jquery_jplayer_1").jPlayer({
         ready: function () {
            $(this).jPlayer("setMedia", {
            mp3: "http://www.jplayer.org/audio/mp3/Miaow-07-Bubble.mp3"
        }).jPlayer("play");
         },
         ended: function (event) {
        $(this).jPlayer("play");
         },
         swfPath: "js",
         supplied: "mp3"
    });

       $(".song").click(function() {
       $("#jquery_jplayer_1").jPlayer("setMedia", {
        mp3: $(this).attr("name").val();
       });
        $("#jquery_jplayer_1").jPlayer("play");
    return false;
    });

});

```

```<code>        <a href="#" class="song" name="http://www.jplayer.org/audio/mp3/Miaow-07-Bubble.mp3">Song 3</a>
        <a href="#" class="song" name="http://www.jplayer.org/audio/mp3/Miaow-04-Lismore.mp3">Song 4</a>
</code>```

This code does work but I would like to get the info from the href

```
$(".song").click(function() {
        $("#jquery_jplayer_1").jPlayer("setMedia", {
            mp3: "http://www.jplayer.org/audio/mp3/Miaow-04-Lismore.mp3"
        });
        $("#jp_playlist_1 ul").html("<li>Lismore - MP3</li>");
        $("#jquery_jplayer_1").jPlayer("play");
        return false;
    });
```

答:
Try changing this $(this).attr("name").val(); with $(this).attr("name");

also a good idea would be:

```<code><a  class="song" href="http://www.jplayer.org/audio/mp3/Miaow-07-Bubble.mp3">Song 3</a>
</code>```

and then

```<code>$('.song').click(function(eve){
eve.preventDefault();
...
...
...

});
</code>```

and of course

```<code>mp3: $(this).attr("href")
</code>```

ContentLicense: CC BY-SA 3.0

Title: Jplayer - Creating dynamic play list

Body:
I am using jPLayer to play mp3's for a project.  They mp3's will be loaded dynamically from a database.  I am trying to create the links that will load the selected mp3 into the player.  Currently I have which does does not work.  I believe I am doing something incorrectly with the click event telling what mp3 to play.  If I hardcode the path it works fine but I do not want to set it up that way because there could be hundreds of media files.

$(document).ready(function(){

    $("#jquery_jplayer_1").jPlayer({
         ready: function () {
            $(this).jPlayer("setMedia", {
            mp3: "http://www.jplayer.org/audio/mp3/Miaow-07-Bubble.mp3"
        }).jPlayer("play");
         },
         ended: function (event) {
        $(this).jPlayer("play");
         },
         swfPath: "js",
         supplied: "mp3"
    });

       $(".song").click(function() {
       $("#jquery_jplayer_1").jPlayer("setMedia", {
        mp3: $(this).attr("name").val();
       });
        $("#jquery_jplayer_1").jPlayer("play");
    return false;
    });

});

        Song 3
        Song 4

This code does work but I would like to get the info from the href

$(".song").click(function() {
        $("#jquery_jplayer_1").jPlayer("setMedia", {
            mp3: "http://www.jplayer.org/audio/mp3/Miaow-04-Lismore.mp3"
        });
        $("#jp_playlist_1 ul").html("
Lismore - MP3
");
        $("#jquery_jplayer_1").jPlayer("play");
        return false;
    });

Body:
Try changing this $(this).attr("name").val(); with $(this).attr("name");

also a good idea would be:

<a  class="song" href="http://www.jplayer.org/audio/mp3/Miaow-07-Bubble.mp3">Song 3</a>

and then

$('.song').click(function(eve){
eve.preventDefault();
...
...
...

});

and of course

mp3: $(this).attr("href")


问:
Change background image with styled-component
I want to change the backgroundImage dynamiclly, when i try it follow as, it did not work,but when i open the devtools in chrome, can show that background

```<code><RecommendWrapper>
     <RecommendItem imgUrl="../../static/banner.png" >
     </RecommendItem>
</RecommendWrapper>

export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background: url(${(props)=>props.imgUrl});
`;
</code>```

if i use like this,it can work,but can't change image dynamic.

```<code>import banner from "../../statics/banner.png"
export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background:url(${banner});
`;
</code>```

and if i use a network image(url likes "https://syean.cn/img/avatar.jpg") ,it also can work

答:
React, Gatsby and Next.js all generally use Webpack, which compiles your site before deployment. They will minify imagery and change each image's path.

In order to get images to load properly, you have to reference them dynamically as an import. This way, the variable URL will still work after Webpack does its thing.

```<code>import styled from 'styled-components';
import img from './img/bg.gif';

const Content = styled.div`
  border: 1px solid #000;
  background-image: url(${img});
  width: 2000px;
  height: 2000px;
`;
</code>```

Body:
I want to change the backgroundImage dynamiclly, when i try it follow as, it did not work,but when i open the devtools in chrome, can show that background

<RecommendWrapper>
     <RecommendItem imgUrl="../../static/banner.png" >
     </RecommendItem>
</RecommendWrapper>

export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background: url(${(props)=>props.imgUrl});
`;

if i use like this,it can work,but can't change image dynamic.

import banner from "../../statics/banner.png"
export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background:url(${banner});
`;

and if i use a network image(url likes "https://syean.cn/img/avatar.jpg") ,it also can work

Body:
React, Gatsby and Next.js all generally use Webpack, which compiles your site before deployment. They will minify imagery and change each image's path.

In order to get images to load properly, you have to reference them dynamically as an import. This way, the variable URL will still work after Webpack does its thing.

import styled from 'styled-components';
import img from './img/bg.gif';

const Content = styled.div`
  border: 1px solid #000;
  background-image: url(${img});
  width: 2000px;
  height: 2000px;
`;


答:
use reduce. Set day to 1 for first entry.
For next element, check if the date is equal to previous one, if yes then set the day same as previous one else increment it's day count.

const input = [
  {"day":1,"date":"2019-09-01T18:15:00", "firstName":"John", "lastName":"Doe" },
  {"day":2,"date":"2019-09-01T18:15:00", "firstName":"Anna", "lastName":"Smith" },
  {"day":3,"date":"2019-09-02T18:15:00", "firstName":"Peter", "lastName":"Jones" },
  {"day":4,"date":"2019-09-03T18:15:00", "firstName":"John", "lastName":"Doe" },
  {"day":5,"date":"2019-09-03T18:15:00", "firstName":"Anna", "lastName":"Smith" },
  {"day":6,"date":"2019-09-04T18:15:00", "firstName":"Peter", "lastName":"Jones" }
];

const output = input.reduce((accu, {day, date, ...rest}, i) => {
    if(i==0) accu.push({"day": 1, date, ...rest});
    else {
        if(date === accu[i-1].date) {
            accu.push({"day" : accu[i-1].day, date, ...rest})
        } else {
            accu.push({"day": accu[i-1].day + 1, date, ...rest});
        }
    }
    return accu;

}, []);

console.log(output);```

Title: How to give same day numbers for all same dates present in array

Body:
I need to increase day count only if date change.(same date= same day count)

Input:-

{"employees":[
  {"day":1,"date":"2019-09-01T18:15:00", "firstName":"John", "lastName":"Doe" },
  {"day":2,"date":"2019-09-01T18:15:00", "firstName":"Anna", "lastName":"Smith" },
  {"day":3,"date":"2019-09-02T18:15:00", "firstName":"Peter", "lastName":"Jones" },
  {"day":4,"date":"2019-09-03T18:15:00", "firstName":"John", "lastName":"Doe" },
  {"day":5,"date":"2019-09-03T18:15:00", "firstName":"Anna", "lastName":"Smith" },
  {"day":6,"date":"2019-09-04T18:15:00", "firstName":"Peter", "lastName":"Jones" }
]}

Ouput:-

{"employees":[
  {"day":1,"date":"2019-09-01T18:15:00", "firstName":"John", "lastName":"Doe" },
  {"day":1,"date":"2019-09-01T18:15:00", "firstName":"Anna", "lastName":"Smith" },
  {"day":2,"date":"2019-09-02T18:15:00", "firstName":"Peter", "lastName":"Jones" },
  {"day":3,"date":"2019-09-013T18:15:00", "firstName":"John", "lastName":"Doe" },
  {"day":3,"date":"2019-09-013T18:15:00", "firstName":"Anna", "lastName":"Smith" },
  {"day":4,"date":"2019-09-04T18:15:00", "firstName":"Peter", "lastName":"Jones" }
]}


问:
simpledateformat localizing wrong months name list
I created Month-year picker.It was working fine but from couple of days it's creating problem. I was fetching months name list using Simpledateformat localization. But now it's repeating some months name. I don't know why?
please help me out of it.
This is my code:

```<code>private static String[] monthsList() {
    if (MONTHS_LIST == null) {
        int[] months = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
        String[] stringMonths = new String[months.length];
        for (int i = 0; i < months.length; i++) {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat monthDate = new SimpleDateFormat(MONTH_FORMAT, Locale.US);
            calendar.set(Calendar.MONTH, months[i]);
            String monthName = monthDate.format(calendar.getTime());
            stringMonths[i] = capitalize(monthName);
        }
        MONTHS_LIST = stringMonths;
    }
    return MONTHS_LIST;
}
</code>```

Output:

it's the screenshot of Month picker, in which it showing march in place of Feb

答:
I do little bit changes inside your code and now it is giving me the accurate name of months. I also put Log.e for check the name.

```<code>private static String[] monthsList() {
    if (MONTHS_LIST == null) {
        int[] months = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
        String[] stringMonths = new String[months.length];
        for (int i = 0; i < months.length; i++) {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat monthDate = new SimpleDateFormat("MMMM");
            calendar.set(Calendar.MONTH, months[i]);
            String monthName = monthDate.format(calendar.getTime());
            stringMonths[i] = capitalize(monthName);

            Log.e("month name",monthName);
        }
        MONTHS_LIST = stringMonths;
    }
    return MONTHS_LIST;
}
</code>```

Below I put log screenshot for proof.

Body:
I created Month-year picker.It was working fine but from couple of days it's creating problem. I was fetching months name list using Simpledateformat localization. But now it's repeating some months name. I don't know why?
please help me out of it.
This is my code:

private static String[] monthsList() {
    if (MONTHS_LIST == null) {
        int[] months = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
        String[] stringMonths = new String[months.length];
        for (int i = 0; i < months.length; i++) {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat monthDate = new SimpleDateFormat(MONTH_FORMAT, Locale.US);
            calendar.set(Calendar.MONTH, months[i]);
            String monthName = monthDate.format(calendar.getTime());
            stringMonths[i] = capitalize(monthName);
        }
        MONTHS_LIST = stringMonths;
    }
    return MONTHS_LIST;
}

Output:

it's the screenshot of Month picker, in which it showing march in place of Feb

Body:
I do little bit changes inside your code and now it is giving me the accurate name of months. I also put Log.e for check the name.

private static String[] monthsList() {
    if (MONTHS_LIST == null) {
        int[] months = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
        String[] stringMonths = new String[months.length];
        for (int i = 0; i < months.length; i++) {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat monthDate = new SimpleDateFormat("MMMM");
            calendar.set(Calendar.MONTH, months[i]);
            String monthName = monthDate.format(calendar.getTime());
            stringMonths[i] = capitalize(monthName);

            Log.e("month name",monthName);
        }
        MONTHS_LIST = stringMonths;
    }
    return MONTHS_LIST;
}

Below I put log screenshot for proof.


问:
Show first ten characters, expand on click (or hover)
I have a HTML snippet which looks like this:

```<code>```
Traceback (most recent call last):
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 69, in execute_job_and_create_log
    output = self._execute_job_and_create_log()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 127, in _execute_job_and_create_log
    return self.execute_job_and_create_log__ftp()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 133, in execute_job_and_create_log__ftp
    return self._execute_job_and_create_log__ftp()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 140, in _execute_job_and_create_log__ftp
    port=self.job_group.remote.port, session_factory=SessionOnPort) as host:
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 72, in __init__
    self._session = self._make_session()
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 135, in _make_session
    session = factory(*args, **kwargs)
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/error.py", line 151, in __exit__
    raise FTPOSError(*exc_value.args, original_exception=exc_value)
FTPOSError: [Errno 110] Timeout
Debugging info: ftputil 3.4, Python 2.7.13 (linux2)
```
</code>```

Since most users do not care for the details, I would like to hide the traceback and only show the first few characters.

The remaining text should only be visible if you expand the text.

This should be visible as hyperlink: "Traceback ...."

How to do this with?

(I can't modify the html, a JavaScript/jquery/CSS solution is needed)

答:
In case you already have bootstrap in your project. You might want to utilize the built-in popover :)

Steps:
 1. Hide the traceback (using CSS)
 2. Display the button (plain HTML)
 3. Setup javascript code (JS/JQuery)

Hide the traceback using CSS

```<code><style>
    pre{
       display:none;
    }
</style>
```
    Traceback (most recent call last):
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 69, in execute_job_and_create_log
        output = self._execute_job_and_create_log()
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 127, in _execute_job_and_create_log
        return self.execute_job_and_create_log__ftp()
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 133, in execute_job_and_create_log__ftp
        return self._execute_job_and_create_log__ftp()
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 140, in _execute_job_and_create_log__ftp
        port=self.job_group.remote.port, session_factory=SessionOnPort) as host:
      File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 72, in __init__
        self._session = self._make_session()
      File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 135, in _make_session
        session = factory(*args, **kwargs)
      File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/error.py", line 151, in __exit__
        raise FTPOSError(*exc_value.args, original_exception=exc_value)
    FTPOSError: [Errno 110] Timeout
    Debugging info: ftputil 3.4, Python 2.7.13 (linux2)
```
</code>```

Somewhere in your HTML, you prepare and display the popover button

```<code><button type="button" class="btn btn-lg btn-danger" data-placement="bottom" data-toggle="popover" title="The full Traceback">Traceback...</button>
</code>```

Setup the Javascript which would trigger the Bootstrap popover

```<code><script>
    $('[data-toggle="popover"]').popover({
      content: $('pre').text().trim()
    });
</script>
</code>```

Advantages:

You can display any button text that you want. ex: "Display Full Traceback" etc..

Take advantage of Bootstrap popover options. Ex. You can easily manipulate where you want the popover to display (left, right, bottom, top) For more info, you can go to https://getbootstrap.com/docs/4.3/components/popovers/

The flexibility of how you want to handle the "Traceback" data

If you don't have Bootstrap, you may want to do a similar approach in pure HTML, CSS, Javascript, and JQuery as well. Here's how...

```<code><style>
    pre{
      display:none;
    }

    .full-trace-back{
      width: 500px;
      padding: 20px;
      background:#fafafa;
      border: 1px solid #ddd;
      -webkit-border-radius: 5px;
              border-radius: 5px;
    }
</style>

  ```
    Traceback (most recent call last):
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 69, in execute_job_and_create_log
        output = self._execute_job_and_create_log()
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 127, in _execute_job_and_create_log
        return self.execute_job_and_create_log__ftp()
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 133, in execute_job_and_create_log__ftp
        return self._execute_job_and_create_log__ftp()
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 140, in _execute_job_and_create_log__ftp
        port=self.job_group.remote.port, session_factory=SessionOnPort) as host:
      File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 72, in __init__
        self._session = self._make_session()
      File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 135, in _make_session
        session = factory(*args, **kwargs)
      File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/error.py", line 151, in __exit__
        raise FTPOSError(*exc_value.args, original_exception=exc_value)
    FTPOSError: [Errno 110] Timeout
    Debugging info: ftputil 3.4, Python 2.7.13 (linux2)
  ```

  <script>
    (function () {
      let isOpen = false;
      $('.trace-back-link').on('click', toggleFullTraceback);

      function toggleFullTraceback() {
        isOpen = !isOpen;
        if (isOpen) {
          const tracebackData = $('pre').text().trim();
          const tracebackLink = $('.trace-back-link');
          tracebackLink.after( "<p class='full-trace-back'>"+tracebackData+"</p>" );
        }else{
          const fullTraceback = $('.full-trace-back');
          fullTraceback.remove();
        }
      }
    }());
  </script>
</code>```

Body:
I have a HTML snippet which looks like this:

Traceback (most recent call last):
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 69, in execute_job_and_create_log
    output = self._execute_job_and_create_log()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 127, in _execute_job_and_create_log
    return self.execute_job_and_create_log__ftp()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 133, in execute_job_and_create_log__ftp
    return self._execute_job_and_create_log__ftp()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 140, in _execute_job_and_create_log__ftp
    port=self.job_group.remote.port, session_factory=SessionOnPort) as host:
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 72, in __init__
    self._session = self._make_session()
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 135, in _make_session
    session = factory(*args, **kwargs)
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/error.py", line 151, in __exit__
    raise FTPOSError(*exc_value.args, original_exception=exc_value)
FTPOSError: [Errno 110] Timeout
Debugging info: ftputil 3.4, Python 2.7.13 (linux2)

Since most users do not care for the details, I would like to hide the traceback and only show the first few characters.

The remaining text should only be visible if you expand the text.

This should be visible as hyperlink: "Traceback ...."

How to do this with?

(I can't modify the html, a JavaScript/jquery/CSS solution is needed)

Body:
In case you already have bootstrap in your project. You might want to utilize the built-in popover :)

Steps:
 1. Hide the traceback (using CSS)
 2. Display the button (plain HTML)
 3. Setup javascript code (JS/JQuery)

Hide the traceback using CSS

<style>
    pre{
       display:none;
    }
</style>
<pre>
    Traceback (most recent call last):
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 69, in execute_job_and_create_log
        output = self._execute_job_and_create_log()
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 127, in _execute_job_and_create_log
        return self.execute_job_and_create_log__ftp()
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 133, in execute_job_and_create_log__ftp
        return self._execute_job_and_create_log__ftp()
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 140, in _execute_job_and_create_log__ftp
        port=self.job_group.remote.port, session_factory=SessionOnPort) as host:
      File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 72, in __init__
        self._session = self._make_session()
      File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 135, in _make_session
        session = factory(*args, **kwargs)
      File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/error.py", line 151, in __exit__
        raise FTPOSError(*exc_value.args, original_exception=exc_value)
    FTPOSError: [Errno 110] Timeout
    Debugging info: ftputil 3.4, Python 2.7.13 (linux2)
</pre>

Somewhere in your HTML, you prepare and display the popover button

<button type="button" class="btn btn-lg btn-danger" data-placement="bottom" data-toggle="popover" title="The full Traceback">Traceback...</button>

Setup the Javascript which would trigger the Bootstrap popover

<script>
    $('[data-toggle="popover"]').popover({
      content: $('pre').text().trim()
    });
</script>

Advantages:

You can display any button text that you want. ex: "Display Full Traceback" etc..

Take advantage of Bootstrap popover options. Ex. You can easily manipulate where you want the popover to display (left, right, bottom, top) For more info, you can go to https://getbootstrap.com/docs/4.3/components/popovers/

The flexibility of how you want to handle the "Traceback" data

If you don't have Bootstrap, you may want to do a similar approach in pure HTML, CSS, Javascript, and JQuery as well. Here's how...

<style>
    pre{
      display:none;
    }

    .full-trace-back{
      width: 500px;
      padding: 20px;
      background:#fafafa;
      border: 1px solid #ddd;
      -webkit-border-radius: 5px;
              border-radius: 5px;
    }
</style>

  <pre>
    Traceback (most recent call last):
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 69, in execute_job_and_create_log
        output = self._execute_job_and_create_log()
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 127, in _execute_job_and_create_log
        return self.execute_job_and_create_log__ftp()
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 133, in execute_job_and_create_log__ftp
        return self._execute_job_and_create_log__ftp()
      File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 140, in _execute_job_and_create_log__ftp
        port=self.job_group.remote.port, session_factory=SessionOnPort) as host:
      File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 72, in __init__
        self._session = self._make_session()
      File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 135, in _make_session
        session = factory(*args, **kwargs)
      File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/error.py", line 151, in __exit__
        raise FTPOSError(*exc_value.args, original_exception=exc_value)
    FTPOSError: [Errno 110] Timeout
    Debugging info: ftputil 3.4, Python 2.7.13 (linux2)
  </pre>

  <script>
    (function () {
      let isOpen = false;
      $('.trace-back-link').on('click', toggleFullTraceback);

      function toggleFullTraceback() {
        isOpen = !isOpen;
        if (isOpen) {
          const tracebackData = $('pre').text().trim();
          const tracebackLink = $('.trace-back-link');
          tracebackLink.after( "<p class='full-trace-back'>"+tracebackData+"</p>" );
        }else{
          const fullTraceback = $('.full-trace-back');
          fullTraceback.remove();
        }
      }
    }());
  </script>


问:
Comma spit/delimit jsonnode in java
What is the best way to iterate through a comma delimited json node called 'name' in the scenario below?</p>
```<code>GetStoredValue result =
dataManagerService.getStoredValue(itemId).checkedGet();
JsonNode node = mapper.readTree(result.getStoredString());
if (node.has("name")
    && node.has("price")
    && node.has("sku"))
{
    //iterate through comma delimited "name" value and return the dataSources
    //node: {"name":"test1,test2", "price":30, "sku":"123123123"}

    //return:
    //{"name":"test1", "price":30, "sku":"123123123"}
    //{"name":"test2", "price":30, "sku":"123123123"}

    ComboPooledDataSource dataSource = createDataSource(node);
    dataSources.put(itemId, dataSource);
    return dataSources.get(itemId);
}
</code>```

答:
Yes, if you want to split the single node into essentially two, String.split would be the obvious solution.

It would probably be nicest if your target class had a Builder you can create it with, so you can do something like this:

```<code>private List<Product> fromJsonNode(JsonNode node) {
    String[] names = node.get("name").textValue().split(",");
    // create list of known size
    List<Product> products = new ArrayList<>(ids.length);
    // these values will remain the same for all products
    ProductBuilder builder = Product.builder()
                                    .price(node.get("price").numberValue())
                                    .sku(node.get("sku").textValue());
    for (String name : names) {
        // just set the name and create the product with it
        products.add(builder.name(name).build());
    }
    return products;
}
</code>```

Title: Comma spit/delimit jsonnode in java

Body:
What is the best way to iterate through a comma delimited json node called 'name' in the scenario below?

GetStoredValue result =
dataManagerService.getStoredValue(itemId).checkedGet();
JsonNode node = mapper.readTree(result.getStoredString());
if (node.has("name")
    && node.has("price")
    && node.has("sku"))
{
    //iterate through comma delimited "name" value and return the dataSources
    //node: {"name":"test1,test2", "price":30, "sku":"123123123"}

    //return:
    //{"name":"test1", "price":30, "sku":"123123123"}
    //{"name":"test2", "price":30, "sku":"123123123"}

    ComboPooledDataSource dataSource = createDataSource(node);
    dataSources.put(itemId, dataSource);
    return dataSources.get(itemId);
}

Body:
Yes, if you want to split the single node into essentially two, String.split would be the obvious solution.

It would probably be nicest if your target class had a Builder you can create it with, so you can do something like this:

private List<Product> fromJsonNode(JsonNode node) {
    String[] names = node.get("name").textValue().split(",");
    // create list of known size
    List<Product> products = new ArrayList<>(ids.length);
    // these values will remain the same for all products
    ProductBuilder builder = Product.builder()
                                    .price(node.get("price").numberValue())
                                    .sku(node.get("sku").textValue());
    for (String name : names) {
        // just set the name and create the product with it
        products.add(builder.name(name).build());
    }
    return products;
}


问:
Ajax - problem with response inside a div
I am trying to show the value of ajax response inside a div.Ajax. Problem arise when I get the response. Response is showing in the div only for split second and hides automatically. I tried changing id to class but the error persist still. The alert displays properly when tested. What do I miss? I have the following code in my view file.

The div:

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

Ajax:

```<code> $(document).ready(function() {
 $('#submit').click(function() {

 $.ajax
 ({
  type:'post',
  cache: false,
  url:'save.php',
  data: $("#action").serialize(),
  dataType: "html",

 success: function(response) {

if(response == 'success')
{
    alert('success');
}
if(response == 'empty')
{
    alert('empty');

}
if(response == 'bad')
{
     $("#result").html(response);

}
}

 });
});
});
</code>```

save.php:

```<code><?php
$co= 'aaa';

if(!empty($_POST['tosave']))
{

    if($_POST['tosave'] == $co)
{
    $foo = fopen("plik.txt","a+");

            flock($foo, 2);
            fwrite($foo,$_POST['tosave']."\r\n");
            flock($foo ,3);
            fclose($foo);
echo "success";
exit();
} else {

    echo 'bad';
    exit;
}

} else {

echo "empty";
exit;

}
?>
</code>```

答:
This might be because you don't prevent the default behavior on the submit button which is to send the form's data to the specified link, maybe in your case the link is on the same page than your PHP leading to only see the message in the div for a split second before the page reloads itself.

So to prevent this default behavior, you have to catch the event and use the preventDefault() function like so :

```<code>$('#submit').click(function(event) { //we pass the event as an attribute
event.preventDefault(); //we prevent its default behavior so we can do our own stuff below
 $.ajax
 ({
  type:'post',
  cache: false,
  url:'save.php',
  data: $("#action").serialize(),
  dataType: "html",

 success: function(response) {

    if(response == 'success')
    {
       alert('success');
    }
    if(response == 'empty')
    {
       alert('empty');

    }
    if(response == 'bad')
    {
        $("#result").html(response);

    }
}

  });
 });
 });
</code>```

Body:
I am trying to show the value of ajax response inside a div.Ajax. Problem arise when I get the response. Response is showing in the div only for split second and hides automatically. I tried changing id to class but the error persist still. The alert displays properly when tested. What do I miss? I have the following code in my view file.

The div:

Ajax:

 $(document).ready(function() {
 $('#submit').click(function() {

 $.ajax
 ({
  type:'post',
  cache: false,
  url:'save.php',
  data: $("#action").serialize(),
  dataType: "html",

 success: function(response) {

if(response == 'success')
{
    alert('success');
}
if(response == 'empty')
{
    alert('empty');

}
if(response == 'bad')
{
     $("#result").html(response);

}
}

 });
});
});

save.php:

<?php
$co= 'aaa';

if(!empty($_POST['tosave']))
{

    if($_POST['tosave'] == $co)
{
    $foo = fopen("plik.txt","a+");

            flock($foo, 2);
            fwrite($foo,$_POST['tosave']."\r\n");
            flock($foo ,3);
            fclose($foo);
echo "success";
exit();
} else {

    echo 'bad';
    exit;
}

} else {

echo "empty";
exit;

}
?>

Body:
This might be because you don't prevent the default behavior on the submit button which is to send the form's data to the specified link, maybe in your case the link is on the same page than your PHP leading to only see the message in the div for a split second before the page reloads itself.

So to prevent this default behavior, you have to catch the event and use the preventDefault() function like so :

$('#submit').click(function(event) { //we pass the event as an attribute
event.preventDefault(); //we prevent its default behavior so we can do our own stuff below
 $.ajax
 ({
  type:'post',
  cache: false,
  url:'save.php',
  data: $("#action").serialize(),
  dataType: "html",

 success: function(response) {

    if(response == 'success')
    {
       alert('success');
    }
    if(response == 'empty')
    {
       alert('empty');

    }
    if(response == 'bad')
    {
        $("#result").html(response);

    }
}

  });
 });
 });


问:
C#: How to make a string with a path of the Current User's directory?
So basically I need a string "path" to be something like:

```<code>string path = @"C:\Users\CURRENT_USER\file.txt";
</code>```

How could I do that?

Sincerely,

a guy with an internet connection

答:
You can use the Environment.SpecialFolder.UserProfile enumeration.

```<code>string path=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
</code>```

Body:
So basically I need a string "path" to be something like:

string path = @"C:\Users\CURRENT_USER\file.txt";

How could I do that?

Sincerely,

a guy with an internet connection

Body:
You can use the Environment.SpecialFolder.UserProfile enumeration.

string path=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);


答:
You could check the last date and the actual and inclrement the day counter.

var data = { employees: [{ day: 1, date: "2019-09-01T18:15:00", firstName: "John", lastName: "Doe" }, { day: 2, date: "2019-09-01T18:15:00", firstName: "Anna", lastName: "Smith" }, { day: 3, date: "2019-09-02T18:15:00", firstName: "Peter", lastName: "Jones" }, { day: 4, date: "2019-09-03T18:15:00", firstName: "John", lastName: "Doe" }, { day: 5, date: "2019-09-03T18:15:00", firstName: "Anna", lastName: "Smith" }, { day: 6, date: "2019-09-04T18:15:00", firstName: "Peter", lastName: "Jones" }] },
    day = 0;
    result = { employees: data.employees.map((o, i, { [i - 1]: p = {} }) => Object.assign(
        {},
        o,
        { day: o.date === p.date ? day : ++day }
    )) };

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
You could check the last date and the actual and inclrement the day counter.

var data = { employees: [{ day: 1, date: "2019-09-01T18:15:00", firstName: "John", lastName: "Doe" }, { day: 2, date: "2019-09-01T18:15:00", firstName: "Anna", lastName: "Smith" }, { day: 3, date: "2019-09-02T18:15:00", firstName: "Peter", lastName: "Jones" }, { day: 4, date: "2019-09-03T18:15:00", firstName: "John", lastName: "Doe" }, { day: 5, date: "2019-09-03T18:15:00", firstName: "Anna", lastName: "Smith" }, { day: 6, date: "2019-09-04T18:15:00", firstName: "Peter", lastName: "Jones" }] },
    day = 0;
    result = { employees: data.employees.map((o, i, { [i - 1]: p = {} }) => Object.assign(
        {},
        o,
        { day: o.date === p.date ? day : ++day }
    )) };

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Laravel query fiter review in with relation
```<code>$listing = Listing::orderBy('created_at','DESC')->where('user_id', Auth::User()->id)
->with('reviews')
->with('posts')
->get();
</code>```

How can i filter review order when i try this

```<code> ->whereHas('reviews', function ($query) {
            $query->where('status', 'Public');
        })->orderBy('created_at','DESC')
</code>```

I want am trying to use orderBy on review but when i try orderBy on review its filter post also but i do not want to post so please Help !

答:
try this query : </p>

```<code>$listing = Listing::where('user_id', Auth::User()->id)
->with(['reviews','posts'])
->whereHas('reviews', function ($query) {
        $query->where('status', 'Public')->orderBy('created_at','DESC');
    })
->orderBy('created_at','DESC')
->get();
</code>```

Body:
$listing = Listing::orderBy('created_at','DESC')->where('user_id', Auth::User()->id)
->with('reviews')
->with('posts')
->get();

How can i filter review order when i try this

 ->whereHas('reviews', function ($query) {
            $query->where('status', 'Public');
        })->orderBy('created_at','DESC')

I want am trying to use orderBy on review but when i try orderBy on review its filter post also but i do not want to post so please Help !

Body:
try this query :

$listing = Listing::where('user_id', Auth::User()->id)
->with(['reviews','posts'])
->whereHas('reviews', function ($query) {
        $query->where('status', 'Public')->orderBy('created_at','DESC');
    })
->orderBy('created_at','DESC')
->get();


问:
Basic C# question if - else
I was wondering if someone could tell me if this sample is correct please.
Please ignore the if statement i wrote it for demonstration purposes only.

basically what I want to know is, if I need to throw an exception in my else, is it right to have it return false then thrown an exception, like follows:

```<code>public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        return false;
        throw new OutOfMemoryException();
    }
}
</code>```

OR - should I throw exception then return false outside else statement like this:

```<code>public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        throw new OutOfMemoryException();
    }
    return false;
}
</code>```

答:
In both of your examples you are doing something wrong. What do you want to achive?

In the first example throw statement will never be executed and in the second one return false won't be executed.

Title: Basic C# question if - else

Body:
I was wondering if someone could tell me if this sample is correct please.
Please ignore the if statement i wrote it for demonstration purposes only.

basically what I want to know is, if I need to throw an exception in my else, is it right to have it return false then thrown an exception, like follows:

public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        return false;
        throw new OutOfMemoryException();
    }
}

OR - should I throw exception then return false outside else statement like this:

public bool test(Int j)
{
    if(!TestOnJThatcanThrowOutOfMemoryException E)
    {
        return true;
    }
    else
    {
        throw new OutOfMemoryException();
    }
    return false;
}


问:
How can I save an activity state using the save instance state?
I've been working on the Android SDK platform, and it is a little unclear how to save an application's state. So given this minor re-tooling of the 'Hello, Android' example:

package com.android.hello;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloAndroid extends Activity {

  private TextView mTextView = null;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mTextView = new TextView(this);

    if (savedInstanceState == null) {
       mTextView.setText("Welcome to HelloAndroid!");
    } else {
       mTextView.setText("Welcome back.");
    }

    setContentView(mTextView);
  }
}
```

I thought it would be enough for the simplest case, but it always responds with the first message, no matter how I navigate away from the app.

I'm sure the solution is as simple as overriding onPause or something like that, but I've been poking away in the documentation for 30 minutes or so and haven't found anything obvious.

答:
Kotlin

You must override onSaveInstanceState and onRestoreInstanceState to store and retrieve your variables you want to be persistent

Life cycle graph

Store variables

```<code>public override fun onSaveInstanceState(savedInstanceState: Bundle) {
    super.onSaveInstanceState(savedInstanceState)

    // prepare variables here
    savedInstanceState.putInt("kInt", 10)
    savedInstanceState.putBoolean("kBool", true)
    savedInstanceState.putDouble("kDouble", 4.5)
    savedInstanceState.putString("kString", "Hello Kotlin")
}
</code>```

Retrieve variables

```<code>public override fun onRestoreInstanceState(savedInstanceState: Bundle) {
    super.onRestoreInstanceState(savedInstanceState)

    val myInt = savedInstanceState.getInt("kInt")
    val myBoolean = savedInstanceState.getBoolean("kBool")
    val myDouble = savedInstanceState.getDouble("kDouble")
    val myString = savedInstanceState.getString("kString")
    // use variables here
}
</code>```

OwnerDisplayName: Bernard

Body:
I've been working on the Android SDK platform, and it is a little unclear how to save an application's state. So given this minor re-tooling of the 'Hello, Android' example:

package com.android.hello;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class HelloAndroid extends Activity {

  private TextView mTextView = null;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mTextView = new TextView(this);

    if (savedInstanceState == null) {
       mTextView.setText("Welcome to HelloAndroid!");
    } else {
       mTextView.setText("Welcome back.");
    }

    setContentView(mTextView);
  }
}

I thought it would be enough for the simplest case, but it always responds with the first message, no matter how I navigate away from the app.

I'm sure the solution is as simple as overriding onPause or something like that, but I've been poking away in the documentation for 30 minutes or so and haven't found anything obvious.

Body:
Kotlin

You must override onSaveInstanceState and onRestoreInstanceState to store and retrieve your variables you want to be persistent

Life cycle graph

Store variables

public override fun onSaveInstanceState(savedInstanceState: Bundle) {
    super.onSaveInstanceState(savedInstanceState)

    // prepare variables here
    savedInstanceState.putInt("kInt", 10)
    savedInstanceState.putBoolean("kBool", true)
    savedInstanceState.putDouble("kDouble", 4.5)
    savedInstanceState.putString("kString", "Hello Kotlin")
}

Retrieve variables

public override fun onRestoreInstanceState(savedInstanceState: Bundle) {
    super.onRestoreInstanceState(savedInstanceState)

    val myInt = savedInstanceState.getInt("kInt")
    val myBoolean = savedInstanceState.getBoolean("kBool")
    val myDouble = savedInstanceState.getDouble("kDouble")
    val myString = savedInstanceState.getString("kString")
    // use variables here
}


答:
Your User profile path stores in

```<code>Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
</code>```

To get specifc file path from that Folder you need to combine it with hard coded string of your file name, like

```<code> string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "file.txt")
</code>```

Output:

Note: Do not forget to add using System.IO because Path class is present in System.IO

Title: C#: How to make a string with a path of the Current User's directory?

Body:
Your User profile path stores in

Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)

To get specifc file path from that Folder you need to combine it with hard coded string of your file name, like

 string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "file.txt")

Output:

Note: Do not forget to add using System.IO because Path class is present in System.IO


问:
How to adapt Canvas for different phone resolutions? Unity3d
I want to adapt the canvas for different phone resolutions (1280x800, 854x480, etc.).

On Internet I see that I require to use a component for the Canvas - Canvas Scaler, but for me it is somehow incorrect or I'm choosing the wrong settings.

Actually, I can not find a solution, so I'm here. There are 3 options for screenshots of different resolutions, and somewhere something climbs or moves, although I do not need it! https://imgur.com/a/6yhSTdE I did it specifically for the resolution of 1280x800 and here everything looks right. And on a resolution of 854x480, a sprite of the board climbs to the side, at 480x320 on top it climbs the same sprite. How to solve this problem? The configuration of my canvas is on the same link. Translated by Google Translater

答: I found the solution. Canvas needs "overlay" render mode(</p>


问:
Inserting a dynamic number of rows into SQL Server
Is there a way to insert a dynamic number of rows from within sql server (.sql script) given the value of a look up, and setting one column for each insert?
I want to attach a row with the foreign key of every row in a different table.

For instance:

```<code>table 1:
1 j k l m n 2-(fk)
2 j k l m n 3-(fk)
3 k u y k l 2-(fk)

table 2:
2 hi you
3 hey ho
</code>```

Now say I wanted to add 2 rows to table 1, with the fk values from table 2 of 2 and 3.

So the final table would look like:

```<code>table 1:
1 j k l m n 2-(fk)
2 j k l m n 3-(fk)
3 k u y k l 2-(fk)
4 a a a a a 3-(fk)
5 a a a a a 2-(fk)
</code>```

With a programming language, this would be easy. Psuedo:
    For (rows in table 2) DO
        Insert into table 1 'a a a a a rows.id'

How could this be accomplished within sql server?

Edit:

For every row in table 2, get it's id, set it as the fk in a row for table 1, and insert it.

答:
```<code>INSERT [table 1]
SELECT 'a','a','a','a','a', fk
FROM [table 2]
</code>```

OwnerDisplayName: Josh Smeaton

ContentLicense: CC BY-SA 2.5

Body:
Is there a way to insert a dynamic number of rows from within sql server (.sql script) given the value of a look up, and setting one column for each insert?
I want to attach a row with the foreign key of every row in a different table.

For instance:

table 1:
1 j k l m n 2-(fk)
2 j k l m n 3-(fk)
3 k u y k l 2-(fk)

table 2:
2 hi you
3 hey ho

Now say I wanted to add 2 rows to table 1, with the fk values from table 2 of 2 and 3.

So the final table would look like:

table 1:
1 j k l m n 2-(fk)
2 j k l m n 3-(fk)
3 k u y k l 2-(fk)
4 a a a a a 3-(fk)
5 a a a a a 2-(fk)

With a programming language, this would be easy. Psuedo:
    For (rows in table 2) DO
        Insert into table 1 'a a a a a rows.id'

How could this be accomplished within sql server?

Edit:

For every row in table 2, get it's id, set it as the fk in a row for table 1, and insert it.

LastEditorDisplayName: Josh Smeaton


答:
If you throw, the return statement won't get executed.  All you need is:</p>

```<code>public bool test(Int j)
{
   if(!TestOnJThatcanThrowOutOfMemoryException E)
   {
      return true;
   }
   throw new OutOfMemoryException();
}
</code>```

Title: Basic C# question if - else

Body:
If you throw, the return statement won't get executed.  All you need is:

public bool test(Int j)
{
   if(!TestOnJThatcanThrowOutOfMemoryException E)
   {
      return true;
   }
   throw new OutOfMemoryException();
}


问:
Importing multiple CSV files into 1 table - first row doesn't match
I've used the below code before to import multiple csv files from one folder into 1 table in Access Database. However, this time the first row of each file includes an account number, and the column headers are in row 2. So the first row of each file is different, and this code fails on "DoCmd.TransferText acImportDelim, , strTable, strPathFile, blnHasFieldNames"

How do I exclude the first row in each of the files?

I've tried changing the "blnHasFieldNames" to False in hopes that the code would accept any differences in row 1, but this did not work.

Dim strPathFile As String, strFile As String, strPath As String
        Dim strTable As String, strBrowseMsg As String
        Dim blnHasFieldNames As Boolean

```<code>    ' Change this next line to True if the first row in EXCEL worksheet
    ' has field names
    blnHasFieldNames = True

    strBrowseMsg = "Table Name"

    strPath = "FilePath"

    If strPath = "" Then
          MsgBox "No folder was selected.", vbOK, "No Selection"
          Exit Sub
    End If

    ' Replace tablename with the real name of the table into which
    ' the data are to be imported
    strTable = "Table Name"

    strFile = Dir(strPath & "\*.csv")
    Do While Len(strFile) > 0
          strPathFile = strPath & "\" & strFile

    DoCmd.TransferText acImportDelim, , strTable, strPathFile, blnHasFieldNames

    ' Uncomment out the next code step if you want to delete the
    ' EXCEL file after it's been imported
    '       Kill strPathFile

          strFile = Dir()
    Loop
</code>```

The Error I get is (xxxxxx= I used this rather than the name of the account)

Run-time error '2391':
Field 'xxxxxxxxx' doesn't exist in destnation table 'Table Name'

答:
You will have to either open the file, remove the first line, save the file, and run the import; or read the file line by line, skipping the first line, and append the data line by line.

In both cases, the FileSystemObject object can be used.

Body:
I've used the below code before to import multiple csv files from one folder into 1 table in Access Database. However, this time the first row of each file includes an account number, and the column headers are in row 2. So the first row of each file is different, and this code fails on "DoCmd.TransferText acImportDelim, , strTable, strPathFile, blnHasFieldNames"

How do I exclude the first row in each of the files?

I've tried changing the "blnHasFieldNames" to False in hopes that the code would accept any differences in row 1, but this did not work.

Dim strPathFile As String, strFile As String, strPath As String
        Dim strTable As String, strBrowseMsg As String
        Dim blnHasFieldNames As Boolean

    ' Change this next line to True if the first row in EXCEL worksheet
    ' has field names
    blnHasFieldNames = True

    strBrowseMsg = "Table Name"

    strPath = "FilePath"

    If strPath = "" Then
          MsgBox "No folder was selected.", vbOK, "No Selection"
          Exit Sub
    End If

    ' Replace tablename with the real name of the table into which
    ' the data are to be imported
    strTable = "Table Name"

    strFile = Dir(strPath & "\*.csv")
    Do While Len(strFile) > 0
          strPathFile = strPath & "\" & strFile

    DoCmd.TransferText acImportDelim, , strTable, strPathFile, blnHasFieldNames

    ' Uncomment out the next code step if you want to delete the
    ' EXCEL file after it's been imported
    '       Kill strPathFile

          strFile = Dir()
    Loop

The Error I get is (xxxxxx= I used this rather than the name of the account)

Run-time error '2391':
Field 'xxxxxxxxx' doesn't exist in destnation table 'Table Name'


问:
How to change stroke color of CAShaperLayer on button click
I am have create some custom layer and added on UIView ,i have two CAShaper Layer but i am just showing only one example here

```<code>    hexBorderOtline = CAShapeLayer()
    hexBorderOtline.name = "dhiru_border_hidden"
    hexBorderOtline.path = path2.cgPath
    hexBorderOtline.lineCap = .round
    hexBorderOtline.strokeColor = inActiveBorderColor.cgColor
    hexBorderOtline.fillColor = UIColor.clear.cgColor
    self.layer.addSublayer(hexBorderOtline)
</code>```

I want to change it's border color when button is clicked.

```<code>func btnAction()
{
    hexBorderOtline.strokeColor = activeBorderColor.cgColor
}
</code>```

But this is not working , i am posting one reference image  what i need to do on button click .

答:
Your method of toggling the shape layer’s stroke color is correct:

All I’m doing is:

```<code>var enabled = false

@IBAction func didTapButton(_ sender: Any) {
    enabled = !enabled
    hexBorderOtline.strokeColor = enabled ? activeBorderColor.cgColor : inActiveBorderColor.cgColor
}
</code>```

So, your problem rests elsewhere. For example:

Perhaps you have another shape layer that is on top of the one for which you’re changing color.

Or perhaps your ivar, is pointing to another shape layer.

Or perhaps your button isn’t hooked up to your btnAction routine (the absence of any @IBAction or @objc makes me suspect you’re not calling this routine).

It’s going to be something simple like that.

I’d suggest you add print(hexBorderOtline) where you create the CAShapeLayer and again in the btnAction and confirm that both:

You are seeing both sets of print statements; and

They are printing the same memory address associated with the shape layer (i.e. make sure they are they referring to the same shape layer).

But it’s got to be something like that. This is the correct way to change strokeColor and that will update the shape layer automatically for you. Your problem rests elsewhere.

Body:
I am have create some custom layer and added on UIView ,i have two CAShaper Layer but i am just showing only one example here

    hexBorderOtline = CAShapeLayer()
    hexBorderOtline.name = "dhiru_border_hidden"
    hexBorderOtline.path = path2.cgPath
    hexBorderOtline.lineCap = .round
    hexBorderOtline.strokeColor = inActiveBorderColor.cgColor
    hexBorderOtline.fillColor = UIColor.clear.cgColor
    self.layer.addSublayer(hexBorderOtline)

I want to change it's border color when button is clicked.

func btnAction()
{
    hexBorderOtline.strokeColor = activeBorderColor.cgColor
}

But this is not working , i am posting one reference image  what i need to do on button click .

Body:
Your method of toggling the shape layer’s stroke color is correct:

All I’m doing is:

var enabled = false

@IBAction func didTapButton(_ sender: Any) {
    enabled = !enabled
    hexBorderOtline.strokeColor = enabled ? activeBorderColor.cgColor : inActiveBorderColor.cgColor
}

So, your problem rests elsewhere. For example:

Perhaps you have another shape layer that is on top of the one for which you’re changing color.

Or perhaps your ivar, is pointing to another shape layer.

Or perhaps your button isn’t hooked up to your btnAction routine (the absence of any @IBAction or @objc makes me suspect you’re not calling this routine).

It’s going to be something simple like that.

I’d suggest you add print(hexBorderOtline) where you create the CAShapeLayer and again in the btnAction and confirm that both:

You are seeing both sets of print statements; and

They are printing the same memory address associated with the shape layer (i.e. make sure they are they referring to the same shape layer).

But it’s got to be something like that. This is the correct way to change strokeColor and that will update the shape layer automatically for you. Your problem rests elsewhere.


问:
How to create a custom SWT Tooltip using JFACE for an RCP MDirectToolItem?
I would like to create a custom tooltip for an RCP MDirectToolItem or MHandledToolItem. JFace provides the org.eclipse.jface.window.ToolTip class, which I can extend and override the createToolTipContentArea() method. However, to instantiate a JFace ToolTip, I have to give it the SWT Control that will use the ToolTip. I cannot figure out a way to get the underlying SWT Control from the MDirectToolItem.

I have been able to get the MToolBar and the MDirectToolItem (which I defined in the Application.e4xmi) using the EModelService.find() method. I tried getting the underlying SWT Control from the MDirectToolItem, but it does not appear there is a way to do that.

I also tried creating an SWT ToolItem and adding it to the MToolBar, but the children of the MToolBar are only MToolBarElement's.

答:
Tool items don't have a separate control, they are part of the parent ToolBar control. The SWT ToolItem class represents the tool item, this is just derived from Widget rather than Control.

So you will have to set the tool tip on the tool bar control and work out which tool item is active when the tool tip is shown.

The application model classes which represent UI objects all extend the MUIElement interface. This provides a getWidget method to get the UI object.

So for MToolBar you can do:

ToolBar toolbar = (ToolBar)mtoolbar.getWidget();
```

<p>and for <code>MToolItem</code> (either handled or direct) you can do:</p>

<pre class="lang-java prettyprint-override"><code>ToolItem toolitem = (ToolItem)mtoolitem.getWidget();
</code>```

If you create the ToolTip with the NO_RECREATE style it will call the
getToolTipArea method to determine if the tool tip need to be changed. You can use something like the following to have a different area for each tool item:

@Override
protected Object getToolTipArea(final Event event)
{
  // TODO save the ToolBar in the class as 'toolBar'
  ToolItem item = toolBar.getItem(new Point(event.x, event.y));
  if (item != null)
    return item;

  return super.getToolTipArea(event);
}
```

Body:
Tool items don't have a separate control, they are part of the parent ToolBar control. The SWT ToolItem class represents the tool item, this is just derived from Widget rather than Control.

So you will have to set the tool tip on the tool bar control and work out which tool item is active when the tool tip is shown.

The application model classes which represent UI objects all extend the MUIElement interface. This provides a getWidget method to get the UI object.

So for MToolBar you can do:

ToolBar toolbar = (ToolBar)mtoolbar.getWidget();

and for MToolItem (either handled or direct) you can do:

ToolItem toolitem = (ToolItem)mtoolitem.getWidget();

If you create the ToolTip with the NO_RECREATE style it will call the
getToolTipArea method to determine if the tool tip need to be changed. You can use something like the following to have a different area for each tool item:

@Override
protected Object getToolTipArea(final Event event)
{
  // TODO save the ToolBar in the class as 'toolBar'
  ToolItem item = toolBar.getItem(new Point(event.x, event.y));
  if (item != null)
    return item;

  return super.getToolTipArea(event);
}


问:
how to show alternate red and green color of row?
I am using react table in react.I learn from here
https://github.com/tannerlinsley/react-table/tree/v6#codesandbox-examples
and from here
https://www.npmjs.com/package/react-table

I want to show my rows alternate color "red" and "green" having a border of black on each cell.can we show in react table?

here is my code
https://codesandbox.io/s/ecstatic-banzai-zp54o

答:
Set the background to green then using the nth-of-type selector you can target even rows and style their background red. You could also use odd to do this the other way around.

.rt-tr-group{
  background: green;
}
.rt-tr-group:nth-of-type(even){
  background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="rt-tbody" style="min-width: 200px;"><div class="rt-tr-group" role="rowgroup"><div class="rt-tr -odd" role="row"><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;">naveen</div><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;"><div><span class="number">14</span><br><span class="number">jgjg</span></div></div></div></div><div class="rt-tr-group" role="rowgroup"><div class="rt-tr -even" role="row"><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;">test</div><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;"><div><span class="number">18</span><br><span class="number">jggkhkg</span></div></div></div></div><div class="rt-tr-group" role="rowgroup"><div class="rt-tr -odd" role="row"><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;">naveen</div><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;"><div><span class="number">14</span><br><span class="number">jgjg</span></div></div></div></div><div class="rt-tr-group" role="rowgroup"><div class="rt-tr -even" role="row"><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;">test</div><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;"><div><span class="number">18</span><br><span class="number">jggkhkg</span></div></div></div></div></div></code>```

updated sandbox
https://codesandbox.io/s/bu45o?fontsize=14

Body:
Set the background to green then using the nth-of-type selector you can target even rows and style their background red. You could also use odd to do this the other way around.

.rt-tr-group{
  background: green;
}
.rt-tr-group:nth-of-type(even){
  background: red;
}

<div class="rt-tbody" style="min-width: 200px;"><div class="rt-tr-group" role="rowgroup"><div class="rt-tr -odd" role="row"><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;">naveen</div><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;"><div><span class="number">14</span><br><span class="number">jgjg</span></div></div></div></div><div class="rt-tr-group" role="rowgroup"><div class="rt-tr -even" role="row"><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;">test</div><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;"><div><span class="number">18</span><br><span class="number">jggkhkg</span></div></div></div></div><div class="rt-tr-group" role="rowgroup"><div class="rt-tr -odd" role="row"><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;">naveen</div><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;"><div><span class="number">14</span><br><span class="number">jgjg</span></div></div></div></div><div class="rt-tr-group" role="rowgroup"><div class="rt-tr -even" role="row"><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;">test</div><div class="rt-td" role="gridcell" style="flex: 100 0 auto; width: 100px;"><div><span class="number">18</span><br><span class="number">jggkhkg</span></div></div></div></div></div>

updated sandbox
https://codesandbox.io/s/bu45o?fontsize=14


问:
API call working with `curl` does not work in Swift
I am getting a json file back from a http request:

```<code>[
  {
    "_ref": "Ref0",
    "name": "someName0"
  },
  {
    "_ref": "Ref1",
    "name": "someName1"
  },
  {
    "_ref": "Ref2",
    "name": "someName2"
  }
]
</code>```

Here's my swift code so far:

guard let natRules = try? JSONSerialization.jsonObject(
  with: data, options: []) as? [Any]
  else { return }
```

<p>How can I get the array's item's content as a <code>[String:String]</code> dictionary? When I print <code>natRules</code>, the result looks like this:</p>

```[
  {
    "_ref" = "Ref0";
    "name" = "someName0"
  },
  {
    "_ref" = "Ref1";
    "name" = "someName1"
  },
  {
    "_ref" = "Ref2";
    "name" = "someName2"
  }
]
```

I would expect the entries to look like "_ref": "Ref0" ... though...
What am I missing here?

Edit (and message to future me):

Seems as though with the above sample I gave, I didn't account for non-string values (which are present in the code I am trying to handle) -- so basically, if there are non-string values present, a cast to [[String:Any]] is necessary.
So that's my TIL I guess...

答:
First of all if the result is supposed to be [[String:String]] cast is accordingly

```<code>guard let natRules = try? JSONSerialization.jsonObject(
  with: data) as? [[String:String]]
  else { return }
</code>```

To iterate over an array use a loop

```<code>for rule in natRules {
     print(rule)
}
</code>```

Body:
I am getting a json file back from a http request:

[
  {
    "_ref": "Ref0",
    "name": "someName0"
  },
  {
    "_ref": "Ref1",
    "name": "someName1"
  },
  {
    "_ref": "Ref2",
    "name": "someName2"
  }
]

Here's my swift code so far:

guard let natRules = try? JSONSerialization.jsonObject(
  with: data, options: []) as? [Any]
  else { return }

How can I get the array's item's content as a [String:String] dictionary? When I print natRules, the result looks like this:

[
  {
    "_ref" = "Ref0";
    "name" = "someName0"
  },
  {
    "_ref" = "Ref1";
    "name" = "someName1"
  },
  {
    "_ref" = "Ref2";
    "name" = "someName2"
  }
]

I would expect the entries to look like "_ref": "Ref0" ... though...
What am I missing here?

Edit (and message to future me):

Seems as though with the above sample I gave, I didn't account for non-string values (which are present in the code I am trying to handle) -- so basically, if there are non-string values present, a cast to [[String:Any]] is necessary.
So that's my TIL I guess...

Body:
First of all if the result is supposed to be [[String:String]] cast is accordingly

guard let natRules = try? JSONSerialization.jsonObject(
  with: data) as? [[String:String]]
  else { return }

To iterate over an array use a loop

for rule in natRules {
     print(rule)
}


问:
How to generate a random sample of points from a 3-D ellipsoid using Python?
I am trying to sample around 1000 points from a 3-D ellipsoid, uniformly. Is there some way to code it such that we can get points starting from the equation of the ellipsoid?

I want points on the surface of the ellipsoid.

答:
Consider using Monte-Carlo simulation: generate a random 3D point; check if the point is inside the ellipsoid; if it is, keep it. Repeat until you get 1,000 points.

P.S. Since the OP changed their question, this answer is no longer valid.


问:
How to write a new row in an existing csv file without appending it in the last line?
I want to add a new row to an existing .csv file in python.

I tried by the following by appending a line to the csv file in spyder IDE in windows.

```<code>def write_to_file():

file = open('E:/Python/Sample//Dataset.csv','a')
file.write(",".join([str(newID),request.form['username'],request.form['age']]))

file.close()
</code>```

I expect the new values in a new row. But it is appending the new values in the last row.

If i add name "Erick" and Age "60", the output looks like the below image.

But I expect something like the below.

答:
A simpler version would be:

```<code>import csv

row =['Eric', '60']

with open('people.csv','a') as csvFile:   #a to append to existing csv file
    writer = csv.writer(csvFile)
    csvFile.write("\n")    #write your data to new line
    writer.writerow(row)
csvFile.close()
</code>```

Output (assuming your csv Doesn't end on new line):

Please be warned (If your csv ends on a newline) the output will have additional space:

Body:
I want to add a new row to an existing .csv file in python.

I tried by the following by appending a line to the csv file in spyder IDE in windows.

def write_to_file():

file = open('E:/Python/Sample//Dataset.csv','a')
file.write(",".join([str(newID),request.form['username'],request.form['age']]))

file.close()

I expect the new values in a new row. But it is appending the new values in the last row.

If i add name "Erick" and Age "60", the output looks like the below image.

But I expect something like the below.

Body:
A simpler version would be:

import csv

row =['Eric', '60']

with open('people.csv','a') as csvFile:   #a to append to existing csv file
    writer = csv.writer(csvFile)
    csvFile.write("\n")    #write your data to new line
    writer.writerow(row)
csvFile.close()

Output (assuming your csv Doesn't end on new line):

Please be warned (If your csv ends on a newline) the output will have additional space: