问:
Unable to map and unmarshal yaml array to golang struct
I want to unmarshal my ~/.kube/config file into a go struct.

I am using the following approach

```<code>func ListContexts(pathToKubeConfig string) ([]string, error) {
    type Contexts struct {
        Ctx []string `yaml:"contexts"`
        //ApiVersion string              `yaml:"apiVersion"`
    }
    var ctx []string
    var c Contexts

    file, err := ioutil.ReadFile(pathToKubeConfig)
    if err != nil {
        return nil, err
    }

    err = yaml.Unmarshal(file, &c)
    fmt.Printf("%#v\n", c.Ctx)
    return ctx, nil
}
}
</code>```

As is widely known, a kubeconfig file has the following struct:

```<code>apiVersion: v1
. . .
contexts:
- context:
    cluster: cluster1
    user: user1
  name: context1
- context:
    cluster: cluster2
    user: user2
  name: context2
</code>```

My approach is printing:

```<code>[]string(nil)
</code>```

Since context is a yaml array, why my mapping into a string array not working?

When I uncomment the ApiVersion field of my struct and try to print it, it works.

答:
context is an array, but not a string array. Either use []map[string]interface{} for context, or define the context as a struct, and use its array:

```<code>type context struct {
   Cluster string `yaml:"cluster"`
   ...
}

type contexts struct {
   Contexts []context `yaml:"contexts"`
}
</code>```

Body:
I want to unmarshal my ~/.kube/config file into a go struct.

I am using the following approach

func ListContexts(pathToKubeConfig string) ([]string, error) {
    type Contexts struct {
        Ctx []string `yaml:"contexts"`
        //ApiVersion string              `yaml:"apiVersion"`
    }
    var ctx []string
    var c Contexts

    file, err := ioutil.ReadFile(pathToKubeConfig)
    if err != nil {
        return nil, err
    }

    err = yaml.Unmarshal(file, &c)
    fmt.Printf("%#v\n", c.Ctx)
    return ctx, nil
}
}

As is widely known, a kubeconfig file has the following struct:

apiVersion: v1
. . .
contexts:
- context:
    cluster: cluster1
    user: user1
  name: context1
- context:
    cluster: cluster2
    user: user2
  name: context2

My approach is printing:

[]string(nil)

Since context is a yaml array, why my mapping into a string array not working?

When I uncomment the ApiVersion field of my struct and try to print it, it works.

Body:
context is an array, but not a string array. Either use []map[string]interface{} for context, or define the context as a struct, and use its array:

type context struct {
   Cluster string `yaml:"cluster"`
   ...
}

type contexts struct {
   Contexts []context `yaml:"contexts"`
}


来源: stackexchange

问:
How to get CatBoost model's coefficients?
I need to get the parameters to use the model in another program.

I tried  cat_model.coef_, cat_model.intercept_ or what I think. is that possible to catch the params ?

I totally solved this problem, what i was tryna do is named 'saving model'.

```<code> cat_model.save_model('cat_model.cbm')
</code>```

答:
For catboost, your model has something called feature importances, given that it's a gradient boosting tree model what you get back is how heavy certain features are in splitting the tree up.

```<code>cat_model.feature_importances_
</code>```

will tell you that. Though you should do more research into how the model works and what it will give you back because interpreting these features can be somewhat deceptive.

ContentLicense: CC BY-SA 4.0

Body:
I need to get the parameters to use the model in another program.

I tried  cat_model.coef_, cat_model.intercept_ or what I think. is that possible to catch the params ?

I totally solved this problem, what i was tryna do is named 'saving model'.

 cat_model.save_model('cat_model.cbm')

Body:
For catboost, your model has something called feature importances, given that it's a gradient boosting tree model what you get back is how heavy certain features are in splitting the tree up.

cat_model.feature_importances_

will tell you that. Though you should do more research into how the model works and what it will give you back because interpreting these features can be somewhat deceptive.


问:
How to store drawable in an array
I want to download a bunch of images and would like to store it as drawable in an array. So I tried declaring a drawable array.But it returns me nullPointer exception when I access that array.

My question is, how to declare an array type as drawable ?

答:
an array of drawables would be declared like:

```<code>int numDrawables = 10;
Drawable[] drawableArray = new Drawable[numDrawables];
</code>```

to fill the array:

```<code>for(int i = 0; i < numDrawables; i++){
    // get a drawable from somewhere
    Drawable drawable = new Drawable();
    drawableArray[i] = drawable;
}
</code>```

to access the array:

```<code>Drawable aDrawable = drawableArray[0];
</code>```

This is basic java, If you are getting null pointer exceptions, you are doing something wrong.

ContentLicense: CC BY-SA 3.0

Title: How to store drawable in an array

Body:
an array of drawables would be declared like:

int numDrawables = 10;
Drawable[] drawableArray = new Drawable[numDrawables];

to fill the array:

for(int i = 0; i < numDrawables; i++){
    // get a drawable from somewhere
    Drawable drawable = new Drawable();
    drawableArray[i] = drawable;
}

to access the array:

Drawable aDrawable = drawableArray[0];

This is basic java, If you are getting null pointer exceptions, you are doing something wrong.


问:
Get same nth day of the month in x number of months
I am needing some help converting a function from access vba to vb.net.
The script generates a new date, based on the date entered, and the number of months to be added.
“If today is the second Tuesday in March, what will be the second Tuesday in 4 months?”

```<code>Public Function NdNwk(dType As String, _
        dtSpan As Integer, sDate As Date) As Variant
'  This Function RETURNS the DAY of WHICH WEEK
'  (e.g. Second Tuesday of the Month).
'  FUNCTIONS to be passed to Variables:
'  gtDoW: Day of the WEEK of the START DATE.
'  (1 for Sunday, 2 for Monday, etc.)
'  gtWoM: WEEK of the MONTH of the START DATE.
'  (1 for First, 2 for Second, etc.)
'  gtDSTdt: Desired DATE
'  (generated by the [DateAdd] Function).

'  CALL EXAMPLE: If TODAY is Tuesday, March 10, 2020,
‘  (second Tuesday of March), then using
'  NdNwk(m, 2, #5/21/2020#)
'  Would generate the DATE 5/12/2020,
'  As the SECOND TUESDAY of MAY.

    Dim gtDSTdt As Date, gtWoM As Integer, gtDoW As Integer
    Dim iLoop As Integer, iPick As Integer, dstDTdom As Date

    gtDoW = Weekday(sDate)
    gtWoM = (Int((Day(sDate) - 1) / 7) + 1)
    gtDSTdt = DateAdd(dType, dtSpan, sDate)

    For iLoop = 1 To Day(DateSerial(Year(gtDSTdt), _
                    Month(gtDSTdt) + 1, 0))

        dstDTdom = DateSerial(Year(gtDSTdt), _
                Month(gtDSTdt), iLoop)

        If Weekday(dstDTdom, 1) = gtDoW Then
            iPick = iPick + 1
            If iPick = gtWoM Then
                NdNwk = dstDTdom
                Exit Function
            End If

        End If
    Next
End Function
</code>```

Any and all help is appreciated here.

答:
First of all, thanks for all the feedback.
The solution that I was able to parse together is as follows:

A text box to show the number of months.

A text box to show the new date.

A button click action to run the following code:

```<code>    Private Sub BtnMonth_Click(sender As Object, e As EventArgs) Handles BtnMonth.Click
        Dim WrkDt As Date = Now

        Dim QtyMnths As Integer = CType(TxtMntCount.Text, Int32)
        Dim newFoM = New Date(WrkDt.Year, WrkDt.Month, 1).AddMonths(QtyMnths)
        Dim DoWDt As Integer = WrkDt.DayOfWeek
        Dim newMntdate = newFoM.AddDays(Enumerable.Range(0,
                         Date.DaysInMonth(newFoM.Year, newFoM.Month) - 1).Where(Function(i) newFoM.AddDays(i).DayOfWeek = DoWDt).Skip(1).First())
        TxtNewDate.Text = Format(newMntdate, "MMMM dd, yyyy (ddd)")
    End Sub
</code>```

This works perfectly fine for me!

Mary's solution looks great, and I will give it a shot in the future when I need a modular input.

Thanks again for all the help!

Body:
I am needing some help converting a function from access vba to vb.net.
The script generates a new date, based on the date entered, and the number of months to be added.
“If today is the second Tuesday in March, what will be the second Tuesday in 4 months?”

Public Function NdNwk(dType As String, _
        dtSpan As Integer, sDate As Date) As Variant
'  This Function RETURNS the DAY of WHICH WEEK
'  (e.g. Second Tuesday of the Month).
'  FUNCTIONS to be passed to Variables:
'  gtDoW: Day of the WEEK of the START DATE.
'  (1 for Sunday, 2 for Monday, etc.)
'  gtWoM: WEEK of the MONTH of the START DATE.
'  (1 for First, 2 for Second, etc.)
'  gtDSTdt: Desired DATE
'  (generated by the [DateAdd] Function).

'  CALL EXAMPLE: If TODAY is Tuesday, March 10, 2020,
‘  (second Tuesday of March), then using
'  NdNwk(m, 2, #5/21/2020#)
'  Would generate the DATE 5/12/2020,
'  As the SECOND TUESDAY of MAY.

    Dim gtDSTdt As Date, gtWoM As Integer, gtDoW As Integer
    Dim iLoop As Integer, iPick As Integer, dstDTdom As Date

    gtDoW = Weekday(sDate)
    gtWoM = (Int((Day(sDate) - 1) / 7) + 1)
    gtDSTdt = DateAdd(dType, dtSpan, sDate)

    For iLoop = 1 To Day(DateSerial(Year(gtDSTdt), _
                    Month(gtDSTdt) + 1, 0))

        dstDTdom = DateSerial(Year(gtDSTdt), _
                Month(gtDSTdt), iLoop)

        If Weekday(dstDTdom, 1) = gtDoW Then
            iPick = iPick + 1
            If iPick = gtWoM Then
                NdNwk = dstDTdom
                Exit Function
            End If

        End If
    Next
End Function

Any and all help is appreciated here.

Body:
First of all, thanks for all the feedback.
The solution that I was able to parse together is as follows:

A text box to show the number of months.

A text box to show the new date.

A button click action to run the following code:

    Private Sub BtnMonth_Click(sender As Object, e As EventArgs) Handles BtnMonth.Click
        Dim WrkDt As Date = Now

        Dim QtyMnths As Integer = CType(TxtMntCount.Text, Int32)
        Dim newFoM = New Date(WrkDt.Year, WrkDt.Month, 1).AddMonths(QtyMnths)
        Dim DoWDt As Integer = WrkDt.DayOfWeek
        Dim newMntdate = newFoM.AddDays(Enumerable.Range(0,
                         Date.DaysInMonth(newFoM.Year, newFoM.Month) - 1).Where(Function(i) newFoM.AddDays(i).DayOfWeek = DoWDt).Skip(1).First())
        TxtNewDate.Text = Format(newMntdate, "MMMM dd, yyyy (ddd)")
    End Sub

This works perfectly fine for me!

Mary's solution looks great, and I will give it a shot in the future when I need a modular input.

Thanks again for all the help!


问:
Is there a way to combine CSR and SSR for the same Angular app?
My Team is looking to build something like a Medium clone. The posts created by users are not expected to change much, so SSR/SSG seems like a good option, especially if there's some incremental build feature available. However, things like 'upvotes' on posts can change very frequently, so we are unsure how to accommodate that.

Also a part of the app that will lie beyond a login, like Dashboard, or an editor to create a new post... etc, doesn't need SEO, so we were thinking if that could be done via CSR, while other parts remained SSG or SSR.

Can such a combination be done with Angular Universal? We have been making CSR Angular SPA-s only till now, so apologies if the questions are a bit dumb :(

答:
I've been looking into this issue myself. It looks like there is no way to mix both CSR and SSR in the same application out of the box.

There are few articles online that mention Dynamic SSR in Angular applications but I couldn't find any code snippets.

This article shows how to do it with nginx service, however.


问:
Create TLS connection using mbed TLS without TCP in iOS
The project I am working on involves connecting to a MFI (Made for iPhone) device using EAF (External Accessory Framework) and passing data back and forth via a USB cable.  I want to use TLS to encrypt the traffic but I am having trouble getting it to work because TCP is not available on the device.  </p>

<p>I am using the following code to test a TLS handshake with a web server. It works fine.  My problem is that I don't know how to create a connection to the device since TCP is unavailable.  Any advice?  Thanks. </p>

```<code>bool tlsHandshake( id param )
{

mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;

mbedtls_ssl_config conf;
mbedtls_ssl_context m_ssl;
mbedtls_net_context server_fd;
mbedtls_x509_crt cacert;

//initialise an SSL/TLS context
mbedtls_net_init( &server_fd );
mbedtls_ssl_init(&m_ssl);
mbedtls_ssl_config_init( &conf );

mbedtls_entropy_init( &entropy );
const char *pers = "BYOM2Plus";

mbedtls_debug_set_threshold( DEBUG_LEVEL );
int ret = 0;
ret = mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, &entropy, (const unsigned char *)pers, strlen(pers));

if( ret != 0 ) {

    [param LogEvent:[NSString stringWithFormat:@"%@%@", @"failed!! mbedtls_ctr_drbg_seed returned 0x%x", [@(ret) stringValue]]];
    return false;
}
else{
    [param LogEvent:@"mbedtls_ctr_drbg_seed OK"];
}

//-------------------------- Initialize certificates --------------------------

[param LogEvent:@"Loading the CA root certificate"];
int ret2 = 0;
ret2 = mbedtls_x509_crt_parse( &cacert, (const unsigned char *) mbedtls_test_cas_pem, mbedtls_test_cas_pem_len );
if( ret2 < 0 )
{
     [param LogEvent:[NSString stringWithFormat:@"%@%@", @" failed\n  !  mbedtls_x509_crt_parse returned -", [@(ret2) stringValue] ]];
     return false;
}

[param LogEvent:[NSString stringWithFormat:@"%@%@", @"x509 cert ok ", [@(ret2) stringValue]]];

//---------------------------- Start the connection -----------------------------
[param LogEvent:[NSString stringWithFormat:@"%@%s%@%s",@"Connecting to tcp ", SERVER_NAME, @":", SERVER_PORT]];

int ret3 = mbedtls_net_connect( &server_fd, SERVER_NAME, SERVER_PORT, MBEDTLS_NET_PROTO_TCP );
if( ret3 != 0 )
{
    [param LogEvent:[NSString stringWithFormat:@"%@%@", @"Failed ! mbedtls_net_connect returned -", [@(ret3) stringValue]]];
    return false;
}

[param LogEvent:[NSString stringWithFormat:@"%@%@", @"Connection started: ", [@(ret3) stringValue]]];

//---------------------------- SSL setup ----------------------------
int ret4 = 0;
ret4 = mbedtls_ssl_config_defaults( &conf,
                                           MBEDTLS_SSL_IS_CLIENT,
                                           MBEDTLS_SSL_TRANSPORT_STREAM,
                                       MBEDTLS_SSL_PRESET_DEFAULT );
if( ret4 != 0 ) {
    [param LogEvent:[NSString stringWithFormat:@"%@%@", @"failed!! mbedtls_ssl_config_defaults returned 0x%0x", [@(ret4) stringValue]]];
    return false;
}
else{
    [param LogEvent:@"mbedtls_ssl_config_defaults OK"];
}

mbedtls_ssl_conf_authmode( &conf, MBEDTLS_SSL_VERIFY_NONE );
mbedtls_ssl_conf_ca_chain( &conf, &cacert, NULL );
mbedtls_ssl_conf_rng( &conf, mbedtls_ctr_drbg_random, &ctr_drbg );
mbedtls_ssl_conf_dbg( &conf, my_debug, stdout );

int ret5 = 0;
ret5 = mbedtls_ssl_setup( &m_ssl, &conf );
if( ret5 != 0 ) {
    [param LogEvent:[NSString stringWithFormat:@"%@%@", @"failed!! mbedtls_ssl_setup returned -", [@(ret5) stringValue]]];
    return false;
}

int ret6 = 0;
ret6 = mbedtls_ssl_set_hostname( &m_ssl, "mbed TLS Server 1" );
if( ret6 != 0 )
{
    [param LogEvent:[NSString stringWithFormat:@"%@%@", @" failed ! mbedtls_ssl_set_hostname returned -", [@(ret6) stringValue]]];
    return false;
}

mbedtls_ssl_set_bio( &m_ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL );

[param LogEvent:@"Performing the SSL/TLS handshake"];
[param LogEvent:@"Waiting for Handshake"];

//#ifdef HANDSHAKING_TEST
//perform an SSL/TLS handshake
int ret7 = -1;
while(( ret7 = mbedtls_ssl_handshake( &m_ssl )) != 0 ) {
    if( ret7 != MBEDTLS_ERR_SSL_WANT_READ && ret7 != MBEDTLS_ERR_SSL_WANT_WRITE ) {
        [param LogEvent:[NSString stringWithFormat:@"%@%@", @"failed!! mbedtls_ssl_handshake returned ", [@(ret7) stringValue]]];
        return false;
    }
    else{
        [param LogEvent:@"SSL/TLS handshake succeeded"];
    }
}

[param LogEvent:[NSString stringWithFormat:@"%@%@", @"Handshake return value: ", [@(ret7) stringValue]]];

return true;
}
</code>```

答:
Even if this is an old question I'll give some hints.

The struct mbedtls_ssl_context has besides many members the following interesting members:

p_bio which refers to an mbedtls_net_context (which is actually a wrapper for a socket / a file descriptor)

f_send which is a callback method for network send

f_recv which is a callback method for network receive

These members are usually set via mbedtls_ssl_set_bio(). One solution for you could be to provide your own set_bio() function or simply set the struct members directly.

File references:

include/mbedtls/ssl.h

library/ssl_tls.c

Version used to check this: mbedtls-2.16.6

Body:
The project I am working on involves connecting to a MFI (Made for iPhone) device using EAF (External Accessory Framework) and passing data back and forth via a USB cable.  I want to use TLS to encrypt the traffic but I am having trouble getting it to work because TCP is not available on the device.

I am using the following code to test a TLS handshake with a web server. It works fine.  My problem is that I don't know how to create a connection to the device since TCP is unavailable.  Any advice?  Thanks.

bool tlsHandshake( id param )
{

mbedtls_entropy_context entropy;
mbedtls_ctr_drbg_context ctr_drbg;

mbedtls_ssl_config conf;
mbedtls_ssl_context m_ssl;
mbedtls_net_context server_fd;
mbedtls_x509_crt cacert;

//initialise an SSL/TLS context
mbedtls_net_init( &server_fd );
mbedtls_ssl_init(&m_ssl);
mbedtls_ssl_config_init( &conf );

mbedtls_entropy_init( &entropy );
const char *pers = "BYOM2Plus";

mbedtls_debug_set_threshold( DEBUG_LEVEL );
int ret = 0;
ret = mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, &entropy, (const unsigned char *)pers, strlen(pers));

if( ret != 0 ) {

    [param LogEvent:[NSString stringWithFormat:@"%@%@", @"failed!! mbedtls_ctr_drbg_seed returned 0x%x", [@(ret) stringValue]]];
    return false;
}
else{
    [param LogEvent:@"mbedtls_ctr_drbg_seed OK"];
}

//-------------------------- Initialize certificates --------------------------

[param LogEvent:@"Loading the CA root certificate"];
int ret2 = 0;
ret2 = mbedtls_x509_crt_parse( &cacert, (const unsigned char *) mbedtls_test_cas_pem, mbedtls_test_cas_pem_len );
if( ret2 < 0 )
{
     [param LogEvent:[NSString stringWithFormat:@"%@%@", @" failed\n  !  mbedtls_x509_crt_parse returned -", [@(ret2) stringValue] ]];
     return false;
}

[param LogEvent:[NSString stringWithFormat:@"%@%@", @"x509 cert ok ", [@(ret2) stringValue]]];

//---------------------------- Start the connection -----------------------------
[param LogEvent:[NSString stringWithFormat:@"%@%s%@%s",@"Connecting to tcp ", SERVER_NAME, @":", SERVER_PORT]];

int ret3 = mbedtls_net_connect( &server_fd, SERVER_NAME, SERVER_PORT, MBEDTLS_NET_PROTO_TCP );
if( ret3 != 0 )
{
    [param LogEvent:[NSString stringWithFormat:@"%@%@", @"Failed ! mbedtls_net_connect returned -", [@(ret3) stringValue]]];
    return false;
}

[param LogEvent:[NSString stringWithFormat:@"%@%@", @"Connection started: ", [@(ret3) stringValue]]];

//---------------------------- SSL setup ----------------------------
int ret4 = 0;
ret4 = mbedtls_ssl_config_defaults( &conf,
                                           MBEDTLS_SSL_IS_CLIENT,
                                           MBEDTLS_SSL_TRANSPORT_STREAM,
                                       MBEDTLS_SSL_PRESET_DEFAULT );
if( ret4 != 0 ) {
    [param LogEvent:[NSString stringWithFormat:@"%@%@", @"failed!! mbedtls_ssl_config_defaults returned 0x%0x", [@(ret4) stringValue]]];
    return false;
}
else{
    [param LogEvent:@"mbedtls_ssl_config_defaults OK"];
}

mbedtls_ssl_conf_authmode( &conf, MBEDTLS_SSL_VERIFY_NONE );
mbedtls_ssl_conf_ca_chain( &conf, &cacert, NULL );
mbedtls_ssl_conf_rng( &conf, mbedtls_ctr_drbg_random, &ctr_drbg );
mbedtls_ssl_conf_dbg( &conf, my_debug, stdout );

int ret5 = 0;
ret5 = mbedtls_ssl_setup( &m_ssl, &conf );
if( ret5 != 0 ) {
    [param LogEvent:[NSString stringWithFormat:@"%@%@", @"failed!! mbedtls_ssl_setup returned -", [@(ret5) stringValue]]];
    return false;
}

int ret6 = 0;
ret6 = mbedtls_ssl_set_hostname( &m_ssl, "mbed TLS Server 1" );
if( ret6 != 0 )
{
    [param LogEvent:[NSString stringWithFormat:@"%@%@", @" failed ! mbedtls_ssl_set_hostname returned -", [@(ret6) stringValue]]];
    return false;
}

mbedtls_ssl_set_bio( &m_ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL );

[param LogEvent:@"Performing the SSL/TLS handshake"];
[param LogEvent:@"Waiting for Handshake"];

//#ifdef HANDSHAKING_TEST
//perform an SSL/TLS handshake
int ret7 = -1;
while(( ret7 = mbedtls_ssl_handshake( &m_ssl )) != 0 ) {
    if( ret7 != MBEDTLS_ERR_SSL_WANT_READ && ret7 != MBEDTLS_ERR_SSL_WANT_WRITE ) {
        [param LogEvent:[NSString stringWithFormat:@"%@%@", @"failed!! mbedtls_ssl_handshake returned ", [@(ret7) stringValue]]];
        return false;
    }
    else{
        [param LogEvent:@"SSL/TLS handshake succeeded"];
    }
}

[param LogEvent:[NSString stringWithFormat:@"%@%@", @"Handshake return value: ", [@(ret7) stringValue]]];

return true;
}


问:
scripting with C#?
I have used Python extensively for doing various adhoc data munging and ancillary tasks. Since I am learning C#, I figure it would be fun to see if I can rewrite some of these scripts in C#.

Is there an executable available that takes a .cs file and runs it ala python?

答:
You can do something like this (Create a Console app with code similar to this one)

```<code>...
using System.Reflection;
using System.CodeDom.Compiler;
...

namespace YourNameSpace
{
  public interface IRunner
  {
    void Run();
  }

  public class Program
  {
    static Main(string[] args)
    {
      if(args.Length == 1)
      {
        Assembly compiledScript = CompileCode(args[0]);
        if(compiledScript != null)
          RunScript(compiledScript);
      }
    }

    private Assembly CompileCode(string code)
    {
      Microsoft.CSharp.CSharpCodeProvider csProvider = new
Microsoft.CSharp.CSharpCodeProvider();

      CompilerParameters options = new CompilerParameters();
      options.GenerateExecutable = false;
      options.GenerateInMemory = true;

      // Add the namespaces needed for your code
      options.ReferencedAssemblies.Add("System");
      options.ReferencedAssemblies.Add("System.IO");
      options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);

      // Compile the code
      CompilerResults result;
      result = csProvider.CompileAssemblyFromSource(options, code);

      if (result.Errors.HasErrors)
      {
        // TODO: Output the errors
        return null;
      }

      if (result.Errors.HasWarnings)
      {
        // TODO: output warnings
      }

      return result.CompiledAssembly;
    }

    private void RunScript(Assembly script)
    {
      foreach (Type type in script.GetExportedTypes())
      {
        foreach (Type iface in type.GetInterfaces())
        {
          if (iface == typeof(YourNameSpace.Runner))
          {
            ConstructorInfo constructor = type.GetConstructor(System.Type.EmptyTypes);
              if (constructor != null && constructor.IsPublic)
              {
                YourNameSpace.IRunner scriptObject = constructor.Invoke(null) as
YourNameSpace.IRunner;

                if (scriptObject != null)
                {
                  scriptObject.Run();
                }
                else
                {
                  // TODO: Unable to create the object
                }
              }
              else
              {
                // TODO: Not implementing IRunner
              }
            }
          }
        }
      }
  }
}
</code>```

After creating this console app you can start this like this at a command prompt:

```<code>YourPath:\> YourAppName.exe "public class Test : IRunnder { public void Run() {
Console.WriteLine("woot"); } }"
</code>```

You can easily change the Main method to accept file instead of inline code, so your console app would have a simillar behaviour as the python or ruby interpreter. Simply pass a filename to your application and read it with a StreamReader in the main function and pass the content to the CompileCode method. Something like this:

```<code>static void Main(string[] args)
{
  if(args.Length == 1 && File.Exists(args[0]))
  {
    var assambly = CompileCode(File.ReadAllText(args[0]));
    ...
  }
}
</code>```

And on the command line:

```<code>YourPath:\> YourApp.exe c:\script.cs
</code>```

You have to implement the IRunner interface, you could as well simply call a hard-coded Start method without inheriting the interface, that was just to show the concept of compiling class on the fly and executing it.

Hope it help.

Title: scripting with C#?

Body:
You can do something like this (Create a Console app with code similar to this one)

...
using System.Reflection;
using System.CodeDom.Compiler;
...

namespace YourNameSpace
{
  public interface IRunner
  {
    void Run();
  }

  public class Program
  {
    static Main(string[] args)
    {
      if(args.Length == 1)
      {
        Assembly compiledScript = CompileCode(args[0]);
        if(compiledScript != null)
          RunScript(compiledScript);
      }
    }

    private Assembly CompileCode(string code)
    {
      Microsoft.CSharp.CSharpCodeProvider csProvider = new
Microsoft.CSharp.CSharpCodeProvider();

      CompilerParameters options = new CompilerParameters();
      options.GenerateExecutable = false;
      options.GenerateInMemory = true;

      // Add the namespaces needed for your code
      options.ReferencedAssemblies.Add("System");
      options.ReferencedAssemblies.Add("System.IO");
      options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);

      // Compile the code
      CompilerResults result;
      result = csProvider.CompileAssemblyFromSource(options, code);

      if (result.Errors.HasErrors)
      {
        // TODO: Output the errors
        return null;
      }

      if (result.Errors.HasWarnings)
      {
        // TODO: output warnings
      }

      return result.CompiledAssembly;
    }

    private void RunScript(Assembly script)
    {
      foreach (Type type in script.GetExportedTypes())
      {
        foreach (Type iface in type.GetInterfaces())
        {
          if (iface == typeof(YourNameSpace.Runner))
          {
            ConstructorInfo constructor = type.GetConstructor(System.Type.EmptyTypes);
              if (constructor != null && constructor.IsPublic)
              {
                YourNameSpace.IRunner scriptObject = constructor.Invoke(null) as
YourNameSpace.IRunner;

                if (scriptObject != null)
                {
                  scriptObject.Run();
                }
                else
                {
                  // TODO: Unable to create the object
                }
              }
              else
              {
                // TODO: Not implementing IRunner
              }
            }
          }
        }
      }
  }
}

After creating this console app you can start this like this at a command prompt:

YourPath:\> YourAppName.exe "public class Test : IRunnder { public void Run() {
Console.WriteLine("woot"); } }"

You can easily change the Main method to accept file instead of inline code, so your console app would have a simillar behaviour as the python or ruby interpreter. Simply pass a filename to your application and read it with a StreamReader in the main function and pass the content to the CompileCode method. Something like this:

static void Main(string[] args)
{
  if(args.Length == 1 && File.Exists(args[0]))
  {
    var assambly = CompileCode(File.ReadAllText(args[0]));
    ...
  }
}

And on the command line:

YourPath:\> YourApp.exe c:\script.cs

You have to implement the IRunner interface, you could as well simply call a hard-coded Start method without inheriting the interface, that was just to show the concept of compiling class on the fly and executing it.

Hope it help.


问:
How to assign an ID to identify duplicate array elements?
I have a multi-dimensional array which contains a string and another array for each element.

```<code>duplicates =
[["link_A", [247936, 672212, 248156, 671720]],
 ["link_B", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["link_C", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["link_D", [247471, 671767, 247567, 671846]],
 ["link_E", [247471, 671767, 247567, 671846]],    # Same coordinates as previous line
 ["link_F", [247567, 671846, 247775, 671680]],
 ["link_G", [247567, 671846, 247775, 671680]]]    # Same coordinates as previous line
</code>```

I have my data in a format that I want in order to go through the "duplicates" array using "each" and export the data to .csv.

The only thing I want at this point is for an assigned ID/number for every duplicate that has the same coordinates. Happy to have it as an element in the array, such as:

Desired Output:

```<code>duplicates =
[["1", "link_A", [247936, 672212, 248156, 671720]],
 ["1", "link_B", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["1", "link_C", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["2", "link_D", [247471, 671767, 247567, 671846]],
 ["2", "link_E", [247471, 671767, 247567, 671846]],    # Same coordinates as previous line
 ["3", "link_F", [247567, 671846, 247775, 671680]],
 ["3", "link_G", [247567, 671846, 247775, 671680]]]    # Same coordinates as previous line
</code>```

What's the best way of going about this?

Many thanks.

Edit:

Thank you for the responses. The current 3 answers (from 1. Siim Liiser, 2. Cary Swoveland and 3. iGian) all work well for me with slight variation (I believe - correct me if I'm wrong!):

Doesn't mutate "duplicates" // Doesn't assume in order

Doesn't mutate "duplicates" // Assumes duplicates in order

Mutates "duplicates" // Doesn't assume in order

I didn't mention it in the question but I was okay with duplicates itself being mutated. I had previously used "group_by" (little bit more info below) to create duplicates so the order shouldn't really matter either. Thanks again.

Original array (seen as 'segment_store' below) at very start holds the link name (e.g. "link_A") and an array of coords (two XY coords) - these represent link segments. As I was looking to find duplicates, I used:

```<code>duplicates = segment_store.group_by{|i| i[1]}.select{|k,v| v.length > 1}.values.flatten(1)
</code>```

to get duplicates as seen in original question (pre-edit).

答:
Let's suppose you have this dataset (I used a Symbol instead of the array of coordinates for simplicity), note the last (H) element having the same coordinates as the first:

```<code>duplicates =
  [["link_A", :coords_a],
   ["link_B", :coords_a],
   ["link_C", :coords_a],
   ["link_D", :coords_d],
   ["link_E", :coords_d],
   ["link_F", :coords_f],
   ["link_G", :coords_f],
   ["link_H", :coords_a]]
</code>```

Consider to use the Enumerable#group_by method to get an output like this:

```<code>duplicates.group_by(&:last)

#   {:coords_a=>[["link_A", :coords_a], ["link_B", :coords_a], ["link_C", :coords_a], ["link_H", :coords_a]],
#    :coords_d=>[["link_D", :coords_d], ["link_E", :coords_d]],
#    :coords_f=>[["link_F", :coords_f], ["link_G", :coords_f]]}
</code>```

Then, use the values of the hash (duplicates.group_by(&:last).values), which are groups and map them adding the index, using Enumerable#with_index.

The final result is the one liner:

```<code>duplicates.group_by(&:last).values
          .flat_map.with_index(1) { |val, id| val.map { |e| e.unshift id } }

#   [[1, "link_A", :coords_a], [1, "link_B", :coords_a], [1, "link_C", :coords_a], [1, "link_H", :coords_a],
#    [2, "link_D", :coords_d], [2, "link_E", :coords_d],
#    [3, "link_F", :coords_f], [3, "link_G", :coords_f]]
</code>```

If you could mutate the duplicate array, you could also do something similar but using Enumerable#each, instead of Enumerable#flat_map:

```<code>duplicates.group_by(&:last).values
          .each.with_index(1) { |val, id| val.map { |e| e.unshift id } }
duplicates

# [[1, "link_A", :coords_a],
#  [1, "link_B", :coords_a],
#  [1, "link_C", :coords_a],
#  [2, "link_D", :coords_d],
#  [2, "link_E", :coords_d],
#  [3, "link_F", :coords_f],
#  [3, "link_G", :coords_f],
#  [1, "link_H", :coords_a]]
</code>```

Maybe you want to convert the index to String.

Body:
I have a multi-dimensional array which contains a string and another array for each element.

duplicates =
[["link_A", [247936, 672212, 248156, 671720]],
 ["link_B", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["link_C", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["link_D", [247471, 671767, 247567, 671846]],
 ["link_E", [247471, 671767, 247567, 671846]],    # Same coordinates as previous line
 ["link_F", [247567, 671846, 247775, 671680]],
 ["link_G", [247567, 671846, 247775, 671680]]]    # Same coordinates as previous line

I have my data in a format that I want in order to go through the "duplicates" array using "each" and export the data to .csv.

The only thing I want at this point is for an assigned ID/number for every duplicate that has the same coordinates. Happy to have it as an element in the array, such as:

Desired Output:

duplicates =
[["1", "link_A", [247936, 672212, 248156, 671720]],
 ["1", "link_B", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["1", "link_C", [247936, 672212, 248156, 671720]],    # Same coordinates as previous line
 ["2", "link_D", [247471, 671767, 247567, 671846]],
 ["2", "link_E", [247471, 671767, 247567, 671846]],    # Same coordinates as previous line
 ["3", "link_F", [247567, 671846, 247775, 671680]],
 ["3", "link_G", [247567, 671846, 247775, 671680]]]    # Same coordinates as previous line

What's the best way of going about this?

Many thanks.

Edit:

Thank you for the responses. The current 3 answers (from 1. Siim Liiser, 2. Cary Swoveland and 3. iGian) all work well for me with slight variation (I believe - correct me if I'm wrong!):

Doesn't mutate "duplicates" // Doesn't assume in order

Doesn't mutate "duplicates" // Assumes duplicates in order

Mutates "duplicates" // Doesn't assume in order

I didn't mention it in the question but I was okay with duplicates itself being mutated. I had previously used "group_by" (little bit more info below) to create duplicates so the order shouldn't really matter either. Thanks again.

Original array (seen as 'segment_store' below) at very start holds the link name (e.g. "link_A") and an array of coords (two XY coords) - these represent link segments. As I was looking to find duplicates, I used:

duplicates = segment_store.group_by{|i| i[1]}.select{|k,v| v.length > 1}.values.flatten(1)

to get duplicates as seen in original question (pre-edit).

Body:
Let's suppose you have this dataset (I used a Symbol instead of the array of coordinates for simplicity), note the last (H) element having the same coordinates as the first:

duplicates =
  [["link_A", :coords_a],
   ["link_B", :coords_a],
   ["link_C", :coords_a],
   ["link_D", :coords_d],
   ["link_E", :coords_d],
   ["link_F", :coords_f],
   ["link_G", :coords_f],
   ["link_H", :coords_a]]

Consider to use the Enumerable#group_by method to get an output like this:

duplicates.group_by(&:last)

#   {:coords_a=>[["link_A", :coords_a], ["link_B", :coords_a], ["link_C", :coords_a], ["link_H", :coords_a]],
#    :coords_d=>[["link_D", :coords_d], ["link_E", :coords_d]],
#    :coords_f=>[["link_F", :coords_f], ["link_G", :coords_f]]}

Then, use the values of the hash (duplicates.group_by(&:last).values), which are groups and map them adding the index, using Enumerable#with_index.

The final result is the one liner:

duplicates.group_by(&:last).values
          .flat_map.with_index(1) { |val, id| val.map { |e| e.unshift id } }

#   [[1, "link_A", :coords_a], [1, "link_B", :coords_a], [1, "link_C", :coords_a], [1, "link_H", :coords_a],
#    [2, "link_D", :coords_d], [2, "link_E", :coords_d],
#    [3, "link_F", :coords_f], [3, "link_G", :coords_f]]

If you could mutate the duplicate array, you could also do something similar but using Enumerable#each, instead of Enumerable#flat_map:

duplicates.group_by(&:last).values
          .each.with_index(1) { |val, id| val.map { |e| e.unshift id } }
duplicates

# [[1, "link_A", :coords_a],
#  [1, "link_B", :coords_a],
#  [1, "link_C", :coords_a],
#  [2, "link_D", :coords_d],
#  [2, "link_E", :coords_d],
#  [3, "link_F", :coords_f],
#  [3, "link_G", :coords_f],
#  [1, "link_H", :coords_a]]

Maybe you want to convert the index to String.


问:
Javascript how to make text 10% larger
I am making a website and it is nearly finished and while testing someone mentioned a setting for text size. Now I know I can just go through and make the font to a set value that is set by something else. But I want to see if I can do it with Javascript.

On my settings page I have a range input from 80% to 120%, but how it will work is it will make the text size bigger depending on the current value it is. For example, the size setting was set to 100%, then I increased it to 110% I want all text to get 10% bigger than before, but I don't have a clue on how to do it, even if it's possible. If anyone has a different method to changing font size based on a setting that would be useful.

Or can I do this:

```<code>font-size: {{setting}};
</code>```

for the whole document after I have loaded the rest of the CSS, meaning would this set all text to this size or make it bigger/smaller depending on if its over 100%?

答:
Other way:</p>

```<code>$root-font-size: 16px;

@function rem($size) {
  @return $size / $root-font-size * 1rem;
}

html {
  font-size: ($root-font-size / 16px) * 100%;
}

.some-block {
  font-size: rem(24px);
}
</code>```

Title: Javascript how to make text 10% larger

Body:
I am making a website and it is nearly finished and while testing someone mentioned a setting for text size. Now I know I can just go through and make the font to a set value that is set by something else. But I want to see if I can do it with Javascript.

On my settings page I have a range input from 80% to 120%, but how it will work is it will make the text size bigger depending on the current value it is. For example, the size setting was set to 100%, then I increased it to 110% I want all text to get 10% bigger than before, but I don't have a clue on how to do it, even if it's possible. If anyone has a different method to changing font size based on a setting that would be useful.

Or can I do this:

font-size: {{setting}};

for the whole document after I have loaded the rest of the CSS, meaning would this set all text to this size or make it bigger/smaller depending on if its over 100%?

Body:
Other way:

$root-font-size: 16px;

@function rem($size) {
  @return $size / $root-font-size * 1rem;
}

html {
  font-size: ($root-font-size / 16px) * 100%;
}

.some-block {
  font-size: rem(24px);
}


问:
Set background color to matplotlib chart
I'm generating an orderbook chart using Matplotlib, the chart is generated but i'm having an hard time figuring how to set a background color to it. On the chart, i'm plotting 2 orderbooks for every side, to do this i'm using a simple loop on my data:

```<code>fig = plt.figure(facecolor='#131722',dpi=135, figsize=(5, 3))
ax1 = plt.subplot2grid((2,1), (0,0), rowspan=6, colspan=4, facecolor='#131722')

Colors = [['#2BBB2B', '#FF0000'], ['#09ff00', '#ff8c00']]

for x in List:

    Index = List.index(x)

    print(Index)

    rate_buy = []
    total_buy = []
    rate_sell = []
    total_sell = []

    for y in x['data']['asks']:
        rate_sell.append(y[0])
        total_sell.append(y[1])

    for y in x['data']['bids']:
        rate_buy.append(y[0])
        total_buy.append(y[1])

    rBuys = pd.DataFrame({'buy': rate_buy})
    rSells = pd.DataFrame({'sell': rate_sell})
    tBuys = pd.DataFrame({'total': total_buy})
    tSells = pd.DataFrame({'total': total_sell})

    plt.plot(rBuys.buy, tBuys.total, color=Colors[Index][0], linewidth=0.9, alpha=0.9)
    plt.plot(rSells.sell, tSells.total, color=Colors[Index][1],alpha=0.3, linewidth=0.9)
</code>```

The output is the following:

So basically, what i want to do, is set the area INSIDE the chart with the same color of the value Color. How can i do that?

答:
You can use a np.vstack function to create an array of x and y coordinates for the area, then plot it trhough the Polygon function, as this:

```<code>import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Polygon

x = np.linspace(0, 10, 11)
y1 = np.array([4, 5, 6, 9, 11, 7, 6, 2, 4, 4, 5])
y2 = np.array([4, 3, 2, 1, 1, 6, 5, 7, 7, 6, 5])

# here I concatenate the x and y arrays for the border of the area
# two times x for back and forth
# y1 and y2 for the top and bottom part of the area
area = np.vstack((np.concatenate((x, x[::-1])),
                  np.concatenate((y1, y2[::-1])))).T

fig, ax = plt.subplots(1, 1, figsize = (8, 8))

ax.plot(x, y1, 'r-', lw = 2, label = 'y1')
ax.plot(x, y2, 'b-', lw = 2, label = 'y2')

# here I add the area to the plot
ax.add_patch(Polygon(area, facecolor = 'g', alpha = 0.5))

ax.grid()
ax.legend()

plt.show()
</code>```

which gives you this:

In your chart there are 4 curves, which I call light-green, dark-green, red and brown.
If you want to color the part of the graph between light-green and dark-green you should fill in the vstack vector in the following way:

```<code>area_1 = np.vstack((np.concatenate((x_of_light-green, x_of_dark-green[::-1])),
                    np.concatenate((y_of_light-green, y_of_dark-green[::-1])))).T
</code>```

The [::-1] after the arrays is necessary in order to reverse the order of the element: with the x_of_light-green and y_of_light-green you define the forth (the bottom border of the colored area), while with the x_of_dark-green[::-1] and y_of_dark-green[::-1] you define the back (the top border of the colored area).

While for the region between the red and brown curves:

```<code>area_2 = np.vstack((np.concatenate((x_of_red, x_of_brown[::-1])),
                    np.concatenate((y_of_red, y_of_brown[::-1])))).T
</code>```

Replace x_of_... and y_of_... with the data of the dataframe you are considering.

Once you have defined these area, you can add them to your graph with the ax1.add_path(Polygon(area_1)) and ax1.add_path(Polygon(area_2)).

Body:
I'm generating an orderbook chart using Matplotlib, the chart is generated but i'm having an hard time figuring how to set a background color to it. On the chart, i'm plotting 2 orderbooks for every side, to do this i'm using a simple loop on my data:

fig = plt.figure(facecolor='#131722',dpi=135, figsize=(5, 3))
ax1 = plt.subplot2grid((2,1), (0,0), rowspan=6, colspan=4, facecolor='#131722')

Colors = [['#2BBB2B', '#FF0000'], ['#09ff00', '#ff8c00']]

for x in List:

    Index = List.index(x)

    print(Index)

    rate_buy = []
    total_buy = []
    rate_sell = []
    total_sell = []

    for y in x['data']['asks']:
        rate_sell.append(y[0])
        total_sell.append(y[1])

    for y in x['data']['bids']:
        rate_buy.append(y[0])
        total_buy.append(y[1])

    rBuys = pd.DataFrame({'buy': rate_buy})
    rSells = pd.DataFrame({'sell': rate_sell})
    tBuys = pd.DataFrame({'total': total_buy})
    tSells = pd.DataFrame({'total': total_sell})

    plt.plot(rBuys.buy, tBuys.total, color=Colors[Index][0], linewidth=0.9, alpha=0.9)
    plt.plot(rSells.sell, tSells.total, color=Colors[Index][1],alpha=0.3, linewidth=0.9)

The output is the following:

So basically, what i want to do, is set the area INSIDE the chart with the same color of the value Color. How can i do that?

Body:
You can use a np.vstack function to create an array of x and y coordinates for the area, then plot it trhough the Polygon function, as this:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Polygon

x = np.linspace(0, 10, 11)
y1 = np.array([4, 5, 6, 9, 11, 7, 6, 2, 4, 4, 5])
y2 = np.array([4, 3, 2, 1, 1, 6, 5, 7, 7, 6, 5])

# here I concatenate the x and y arrays for the border of the area
# two times x for back and forth
# y1 and y2 for the top and bottom part of the area
area = np.vstack((np.concatenate((x, x[::-1])),
                  np.concatenate((y1, y2[::-1])))).T

fig, ax = plt.subplots(1, 1, figsize = (8, 8))

ax.plot(x, y1, 'r-', lw = 2, label = 'y1')
ax.plot(x, y2, 'b-', lw = 2, label = 'y2')

# here I add the area to the plot
ax.add_patch(Polygon(area, facecolor = 'g', alpha = 0.5))

ax.grid()
ax.legend()

plt.show()

which gives you this:

In your chart there are 4 curves, which I call light-green, dark-green, red and brown.
If you want to color the part of the graph between light-green and dark-green you should fill in the vstack vector in the following way:

area_1 = np.vstack((np.concatenate((x_of_light-green, x_of_dark-green[::-1])),
                    np.concatenate((y_of_light-green, y_of_dark-green[::-1])))).T

The [::-1] after the arrays is necessary in order to reverse the order of the element: with the x_of_light-green and y_of_light-green you define the forth (the bottom border of the colored area), while with the x_of_dark-green[::-1] and y_of_dark-green[::-1] you define the back (the top border of the colored area).

While for the region between the red and brown curves:

area_2 = np.vstack((np.concatenate((x_of_red, x_of_brown[::-1])),
                    np.concatenate((y_of_red, y_of_brown[::-1])))).T

Replace x_of_... and y_of_... with the data of the dataframe you are considering.

Once you have defined these area, you can add them to your graph with the ax1.add_path(Polygon(area_1)) and ax1.add_path(Polygon(area_2)).


问:
Flask File Uploads to Unique Directory
I've built an application following the file upload process (more or less) along the lines of the Flask file upload documentation found here, https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/.

In this portion of the code, UPLOAD_FOLDER = '/path/to/the/uploads', this points to one, single directory where file uploads will live. The problem I'm trying to solve is when I deploy my app to a server there will be multiple, simultaneous users. With a single upload directory, users will collide when they upload files with the same names--a situation that will occur in my app.

What I want to do is create a unique temp directory that is unique to each browser session. So, user 1 would have their own unique temp directory and user 2 would have their own unique temp directory and so on.

In this case, I think there would not be any user collision. Can anyone please suggest how I would create such unique temp directories associated with each browser session in the file upload process? Something along the lines of UPLOAD_FOLDER = '/path/to/the/uploads/user1_session', etc for each unique user?

答:
Ok, so lacking further information and any sort of view on what your code/program looks like this is the what I would recommend at the moment.

I am relatively new to programming as well so this might not be the best answer. But in my experience you really,really do not want to be creating multiple directories per user/per session. That is a bad idea. This is where databases comes in handy.

Now in regards to your problem the easiest/fastest way to resolve this issue is to look into how password salt and hashing is done.

Just hash and salt your filenames.

Here is a link that provides a simple yet through explanation on how it is done.

Title: Flask File Uploads to Unique Directory


问:
Laravel relations in multiple model with belongsToMany and hasMany
I am working on an eCommerce application.

I have 3 models. Product, Color, ProductImage.

The relation between Product and Color is: belongsToMany

<?php

namespace App\Entities\Product;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    /**
     * A product has many colors.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function colors()
    {
        return $this->belongsToMany(Color::class);
    }
}
```
<p>The relation between <code>Color</code> and <code>ProductImage</code> is: <strong>hasMany</strong></p>
<pre class="lang-php prettyprint-override"><code><?php

namespace App\Entities\Product;

use Illuminate\Database\Eloquent\Model;

class Color extends Model
{
    /**
     * A color has many images.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function images()
    {
        return $this->hasMany(ProductImage::class);
    }
}
</code>```

Question is how to make a relation between the Product and ProductImage model?

How to design the product_images table?

id, color_id, image

like this?

my use case is, I will make a slider on a single product page. There will be a Color select option. If a user selects a color, need to load product images associate with that selected color.

Appreciate your help :)

答:
I am also working on an e-commerce project and I have designed my database like below.

A product has multiple product colors but a product color belongs to only one product. product id and color together a compound key(unique) of the product_colors table.

If you have a product T-shirt which id is 101 which product color is red then together 101 and red are a unique product_color.

Product_image belongs to the product and product_colors table. Together product_id and product_color_id are composite key. In case if you have multiple images for the same product id and color then you can save the image as JSON data. which I did for my application.

Although I have designed my database like fig 01. But if we want to separate the colors table then we could design the database like this.

Body:
I am working on an eCommerce application.

I have 3 models. Product, Color, ProductImage.

The relation between Product and Color is: belongsToMany

<?php

namespace App\Entities\Product;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    /**
     * A product has many colors.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function colors()
    {
        return $this->belongsToMany(Color::class);
    }
}

The relation between Color and ProductImage is: hasMany

<?php

namespace App\Entities\Product;

use Illuminate\Database\Eloquent\Model;

class Color extends Model
{
    /**
     * A color has many images.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function images()
    {
        return $this->hasMany(ProductImage::class);
    }
}

Question is how to make a relation between the Product and ProductImage model?

How to design the product_images table?

id, color_id, image

like this?

my use case is, I will make a slider on a single product page. There will be a Color select option. If a user selects a color, need to load product images associate with that selected color.

Appreciate your help :)


问:
python's selenium "send_keys" with chrome driver drops characters
I am using selenium package with Python (https://pypi.python.org/pypi/selenium) with Windows 7.
When I try to login to my facebook account I use the send_keys command, e.g.

```<code>elem = browser.find_element_by_name("email")
elem.send_keys(email);
elem = browser.find_element_by_name("pass")
elem.send_keys(password);
</code>```

Login fails apparently because the second send_keys drops the first character of the password (I found this by directly sending the password characters to the email field.

What's going on? Why can't selenium do something so simple as sending keys to an input field?
Is this some kind of a protection measure coded by Facebook to reject automatic scripting?

Tried to send the whole alphabet and got this:

```<code>abcdefghijklmnopqrstuvwxyzBCDFGIKLNOQSTWX
</code>```

Notice how many characters are missing...

Update

Apparently the problem has nothing to do with facebook but to the chrome driver.

If I send the following simple code

```<code>browser = webdriver.Chrome()
browser.get("https://www.google.com") # Load page
elem = browser.find_element_by_name("q") # Find the query box
query= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
elem.send_keys(query)
</code>```

With chrome driver I get
    BCDFGIKLNOQSTWX
Notice how A, E, H ... Y, Z are missing
With firefox driver (replacing browser = webdriver.Chrome() with browser = webdriver.Firefox() I get:
    ABCDEFGHIJKLMNOPQRSTUVWXYZ

答:
I ran into a similar problem as OP and was satisfied with none of the answers written here nor anywhere else on this site that I could find.
Since I read during my research that the issue was at some point in time fixed, I have to assume that it re-appeared nowadays.

As P.T. mentioned, if you run into similar problems, chances are the chromedrivers/firefoxdrivers are buggy again.

Since none of the solutions I found helped alleviate the issue, I instead opted for just circumventing selenium and its drivers altogether. So I used javascript to first find the element (through its absolute Xpath), then write to it / set it.

```<code>from selenium import webdriver

def write_to_element(driver, element_xpath, input_string),
        js_command = f'document.evaluate(\'{xpath}\', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.value = \'{input_string}\';'
        driver.execute_script(js_command)

driver = webdriver.Chrome()
driver.get('WebPage/With/Element/You/Want/To/Write/To')
xpath = 'Xpath/Of/Element/You/Want/To/Write/To'
write_to_element(driver, xpath, 'SomeRandomInput')
</code>```

document.evaluate(\'{xpath}\', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null) evaluates the xpath to an element, so essentially finds your element on the webpage.

.singleNodeValue.value = \'{input_string}\';' sets the value of that element to input_string

Body:
I am using selenium package with Python (https://pypi.python.org/pypi/selenium) with Windows 7.
When I try to login to my facebook account I use the send_keys command, e.g.

elem = browser.find_element_by_name("email")
elem.send_keys(email);
elem = browser.find_element_by_name("pass")
elem.send_keys(password);

Login fails apparently because the second send_keys drops the first character of the password (I found this by directly sending the password characters to the email field.

What's going on? Why can't selenium do something so simple as sending keys to an input field?
Is this some kind of a protection measure coded by Facebook to reject automatic scripting?

Tried to send the whole alphabet and got this:

abcdefghijklmnopqrstuvwxyzBCDFGIKLNOQSTWX

Notice how many characters are missing...

Update

Apparently the problem has nothing to do with facebook but to the chrome driver.

If I send the following simple code

browser = webdriver.Chrome()
browser.get("https://www.google.com") # Load page
elem = browser.find_element_by_name("q") # Find the query box
query= "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
elem.send_keys(query)

With chrome driver I get
    BCDFGIKLNOQSTWX
Notice how A, E, H ... Y, Z are missing
With firefox driver (replacing browser = webdriver.Chrome() with browser = webdriver.Firefox() I get:
    ABCDEFGHIJKLMNOPQRSTUVWXYZ

Body:
I ran into a similar problem as OP and was satisfied with none of the answers written here nor anywhere else on this site that I could find.
Since I read during my research that the issue was at some point in time fixed, I have to assume that it re-appeared nowadays.

As P.T. mentioned, if you run into similar problems, chances are the chromedrivers/firefoxdrivers are buggy again.

Since none of the solutions I found helped alleviate the issue, I instead opted for just circumventing selenium and its drivers altogether. So I used javascript to first find the element (through its absolute Xpath), then write to it / set it.

from selenium import webdriver

def write_to_element(driver, element_xpath, input_string),
        js_command = f'document.evaluate(\'{xpath}\', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.value = \'{input_string}\';'
        driver.execute_script(js_command)

driver = webdriver.Chrome()
driver.get('WebPage/With/Element/You/Want/To/Write/To')
xpath = 'Xpath/Of/Element/You/Want/To/Write/To'
write_to_element(driver, xpath, 'SomeRandomInput')

document.evaluate(\'{xpath}\', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null) evaluates the xpath to an element, so essentially finds your element on the webpage.

.singleNodeValue.value = \'{input_string}\';' sets the value of that element to input_string


问:
Writing a normal python code into function called computepay()
How can I write the following program to prompt the user for hours and rate per hour using input to compute gross pay in a function called computepay() and use the function to do the computation. I want the function to return a value. In short, I want function to do it for me so that I can reduce the manual work from my side. Any help would be appreciated. Thanks.</p>

```<code>
sh = input("Enter hours:")
try:
    fh = float(sh)
except:
    print("Error, please enter numeric input")
    quit() # Commenting this line out will yield different result
sr = input("Enter Rate:")
try:
    fr = float(sr)
except:
    print("Error, please enter numeric input")
    quit() # Commenting this line out will yield different result

if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)

</code>```

答:
tell me if this is what you are looking for:</p>

```<code>def computepay(sh, sr):
    """
    compute pay

    :param sh: float, hours
    :param sr: float, rate
    :return:
    """

    # reference object change
    fh = sh
    fr = sr

    if fh > 40:
        reg = fr * fh
        otp = (fh - 40.0) * (fr * 0.5)
        xp = reg + otp
    else:
        xp = fh * fr

    print("Pay:", xp)
    return xp

</code>```

Body:
How can I write the following program to prompt the user for hours and rate per hour using input to compute gross pay in a function called computepay() and use the function to do the computation. I want the function to return a value. In short, I want function to do it for me so that I can reduce the manual work from my side. Any help would be appreciated. Thanks.

sh = input("Enter hours:")
try:
    fh = float(sh)
except:
    print("Error, please enter numeric input")
    quit() # Commenting this line out will yield different result
sr = input("Enter Rate:")
try:
    fr = float(sr)
except:
    print("Error, please enter numeric input")
    quit() # Commenting this line out will yield different result

if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)

Body:
tell me if this is what you are looking for:

def computepay(sh, sr):
    """
    compute pay

    :param sh: float, hours
    :param sr: float, rate
    :return:
    """

    # reference object change
    fh = sh
    fr = sr

    if fh > 40:
        reg = fr * fh
        otp = (fh - 40.0) * (fr * 0.5)
        xp = reg + otp
    else:
        xp = fh * fr

    print("Pay:", xp)
    return xp


问:
Unable to login Spring Security - always redirects me back to login page
Could you please advise what is wrong in configuration. I can't login with correct credentials, it always redirects me back to login page (code 302). When type http://localhost:8080 - Spring Security redirects to /login, after form submitting redirects back to /login.</p>

```<code>protected void configure (AuthenticationManagerBuilder builder) throws Exception {
    builder.inMemoryAuthentication().withUser("user").password("{noop}12345").roles("USER");
}

protected void configure (HttpSecurity http) throws Exception {

    http.authorizeRequests().anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login").permitAll().defaultSuccessUrl("/start.html").loginProcessingUrl("/authenticateMe");
</code>```

```<code>@GetMapping("/login")
    public String showLogin () {
        return "index";
    }

    @PostMapping("/authenticateMe")
    public String login () {
        return "start";
    }
</code>```

```<code><body>

  <form method="post" th:action="@{/authenticateMe}"  class="login">
    <p>
        <label th:for="username">Username: </label>
        <input type="text" th:name="username" id="username"/>
    </p>

    <p>
        <label th:for="password">Password: </label>
        <input type="password" th:name="password" id="password"/>
    </p>

</code>```

答:
You're overriding the url that processes the login attempt. Your code

```<code>@PostMapping("/authenticateMe")
public String login () {
    return "start";
}
</code>```

Is responding to the login request, but not actually doing any processing of the login information (e.g. setting the Authentication object on the SecurityContext). You've configured an authentication manager, so remove the code from your controller and that should allow your authentication to be processed correctly.

Body:
Could you please advise what is wrong in configuration. I can't login with correct credentials, it always redirects me back to login page (code 302). When type http://localhost:8080 - Spring Security redirects to /login, after form submitting redirects back to /login.

protected void configure (AuthenticationManagerBuilder builder) throws Exception {
    builder.inMemoryAuthentication().withUser("user").password("{noop}12345").roles("USER");
}

protected void configure (HttpSecurity http) throws Exception {

    http.authorizeRequests().anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login").permitAll().defaultSuccessUrl("/start.html").loginProcessingUrl("/authenticateMe");

@GetMapping("/login")
    public String showLogin () {
        return "index";
    }

    @PostMapping("/authenticateMe")
    public String login () {
        return "start";
    }

  <form method="post" th:action="@{/authenticateMe}"  class="login">

        Username:
        <input type="text" th:name="username" id="username"/>

        Password:
        <input type="password" th:name="password" id="password"/>

Body:
You're overriding the url that processes the login attempt. Your code

@PostMapping("/authenticateMe")
public String login () {
    return "start";
}

Is responding to the login request, but not actually doing any processing of the login information (e.g. setting the Authentication object on the SecurityContext). You've configured an authentication manager, so remove the code from your controller and that should allow your authentication to be processed correctly.


问:
How to slice a list from an element n to the end in python?
I'm having some trouble figuring out how to slice python lists, it is illustrated as follows:

```<code>>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</code>```

To my understanding, python slice means lst[start:end], and including start, excluding end. So how would i go about finding the "rest" of a list starting from an element n?

Thanks a lot for all your help!

答:
You can leave one end of the slice open by not specifying the value.</p>

```<code>test[3:] = [3, 4, 5, 6, 7, 8, 9]
test[:3] = [0, 1, 2]
</code>```

OwnerDisplayName: FurtiveFelon

ContentLicense: CC BY-SA 2.5

Body:
I'm having some trouble figuring out how to slice python lists, it is illustrated as follows:

>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

To my understanding, python slice means lst[start:end], and including start, excluding end. So how would i go about finding the "rest" of a list starting from an element n?

Thanks a lot for all your help!

Body:
You can leave one end of the slice open by not specifying the value.

test[3:] = [3, 4, 5, 6, 7, 8, 9]
test[:3] = [0, 1, 2]

OwnerDisplayName: Angela

LastEditorDisplayName: Angela


问:
How to pass rich params to jsf for i18n?
I am using jsf to render my html pages and I am using the nifty resource bundle loading to add i18n to the various pages. The problem I am having is that with outputFormat you can not pass in any "rich" parameters. For instance this sentance:

This my favorite search engine, you should check it out.

It would be nice to do something like this:

```<code> <h:outputFormat value="#{bundle.favItemLineWithParam}>
      <f:param>
           <h:outputFormat value="#{bundle.searchEngine}>
                <f:param>
                     <h:link value="http://google.com">
                </f:param>
           </h:outputFormat>
      </f:param>
 </h:outputFormat>
</code>```

but that is not allowed, it would seem like the only option is to render the links in java with a backing bean or something. Any Ideas?

答:
That's not possible. You need to use plain HTML in the bundle value and set escape="false".

favItem = This is my favourite {0}, you should check it out.
```

<p>with</p>

```<h:outputFormat value="#{bundle.favItem}" escape="false">
    <f:param value="search engine" />
    <f:param value="http://google.com" />
</h:outputFormat>
```

<hr>

<p><strong>Update</strong>: </p>

<p>Since version 1.5, it's possible with <code><o:param></code> of JSF utility library OmniFaces:</p>

<pre class="lang-none prettyprint-override"><code>favItem = This is my favourite {0}, you should check it out.
searchEngine = search engine
</code>```

with

```<code><h:outputFormat value="#{bundle.favItem}" escape="false">
    <o:param><a href="http://google.com">#{bundle.searchEngine}</a></o:param>
</h:outputFormat>
</code>```

Body:
I am using jsf to render my html pages and I am using the nifty resource bundle loading to add i18n to the various pages. The problem I am having is that with outputFormat you can not pass in any "rich" parameters. For instance this sentance:

This my favorite search engine, you should check it out.

It would be nice to do something like this:

 <h:outputFormat value="#{bundle.favItemLineWithParam}>
      <f:param>
           <h:outputFormat value="#{bundle.searchEngine}>
                <f:param>
                     <h:link value="http://google.com">
                </f:param>
           </h:outputFormat>
      </f:param>
 </h:outputFormat>

but that is not allowed, it would seem like the only option is to render the links in java with a backing bean or something. Any Ideas?

Body:
That's not possible. You need to use plain HTML in the bundle value and set escape="false".

favItem = This is my favourite <a href="{1}">{0}</a>, you should check it out.

with

<h:outputFormat value="#{bundle.favItem}" escape="false">
    <f:param value="search engine" />
    <f:param value="http://google.com" />
</h:outputFormat>

Update:

Since version 1.5, it's possible with <o:param> of JSF utility library OmniFaces:

favItem = This is my favourite {0}, you should check it out.
searchEngine = search engine

with

<h:outputFormat value="#{bundle.favItem}" escape="false">
    <o:param><a href="http://google.com">#{bundle.searchEngine}</a></o:param>
</h:outputFormat>


问:
make_shared and abstract polymorphism
Is there any way I can use make_shared instead of shared_ptr for abstract types?

Example:

```<code>#include <memory>
#include <vector>

class Foo
{
public:
    virtual void fooFunc() = 0;
};

class Bar : public Foo
{
public:
    void fooFunc() {};
};

int main()
{
    std::vector< std::shared_ptr<Foo> > vec;

    vec.push_back(std::shared_ptr<Foo>(new Bar()));
    //vec.push_back(std::make_shared<Foo>(new Bar())); //doesn't work because Foo is abstract

    return 0;
}
</code>```

答:
I ended up here because I didn't specify my inheritance as public. So I had:

class Bar : Foo
```

<p>instead of:</p>

<pre class="lang-cpp prettyprint-override"><code>class Bar : public Foo
</code>```

Adding the public made shared_ptr<Foo> foo = make_shared<Bar>(...) work as expected

Title: make_shared and abstract polymorphism

Body:
Is there any way I can use make_shared instead of shared_ptr for abstract types?

Example:

#include <memory>
#include <vector>

class Foo
{
public:
    virtual void fooFunc() = 0;
};

class Bar : public Foo
{
public:
    void fooFunc() {};
};

int main()
{
    std::vector< std::shared_ptr<Foo> > vec;

    vec.push_back(std::shared_ptr<Foo>(new Bar()));
    //vec.push_back(std::make_shared<Foo>(new Bar())); //doesn't work because Foo is abstract

    return 0;
}

Body:
I ended up here because I didn't specify my inheritance as public. So I had:

class Bar : Foo

instead of:

class Bar : public Foo

Adding the public made shared_ptr<Foo> foo = make_shared<Bar>(...) work as expected


问:
I edit the style sheet of my css in wordpress but the changes do not apply on the blog
I'm breaking my head, to change the size of my wordpress blog logo, because they say it is for the css style sheet, but any changes I make to the style sheet do not apply to my blog, even if I delete all style sheet my blog does not change, can anyone help me?</p>

答:
There are several things to consider:

If the changes you want to make are minor, just use theme editors css and js injection mechanics.

Second most common thing is syntax, to counter that just edit your current active themes style file and enter something like body background-color:{ red !important} to check if the changes are being made. Then check with your browsers developer tools to check if the changes are being made in the style file.

If you are using some caching plugin, turn it off until you are done working on the site changes.

Check if you are editing the right theme. You should check what theme is active in your themes section of the wordpress.

In the case where you are using a child theme and you are editing child themes style.css file, you should first enqueue the file. More info on that here

If you are hosting your website not on the shared hosting, but on private server, you should check your file permissions.

Hope this helps.


Title: Subtracting fix date from whole panda data frame - python

Body:
I have data

    customer_id purchase_amount date_of_purchase
0   760       25.0  06-11-2009
1   860      50.0   09-28-2012
2   1200    100.0   10-25-2005
3   1420    50.0    09-07-2009
4   1940    70.0    01-25-2013
5   1960    40.0    10-29-2013
6   2620    30.0    09-03-2006
7   3050    50.0    12-04-2007
8   3120    150.0   08-11-2006
9   3260    45.0    10-20-2010
10  3510    35.0    04-05-2013
11  3970    30.0    07-06-2007
12  4000    20.0    11-25-2005
13  4180    20.0    09-22-2010
14  4390    30.0    04-15-2011
15  4750    60.0    02-12-2013
16  4840    30.0    10-14-2005
17  4910    15.0    12-13-2006
18  4950    50.0    05-19-2010
19  4970    30.0    01-12-2006
20  5250    50.0    12-20-2005

Now I want to subtract 01-01-2016 from each row of date_of_purchase

I tried the following so I should have a new column days_since with a number of days.

NOW = pd.to_datetime('01/01/2016').strftime('%m-%d-%Y')
gb = customer_purchases_df.groupby('customer_id')
df2 = gb.agg({'date_of_purchase': lambda x: (NOW - x.max()).days})

any suggestion. how I can achieve this

Thanks in advance

Body:
pd.to_datetime(df['date_of_purchase']).rsub(pd.to_datetime('2016-01-01')).dt.days

0     2395
1     1190
2     3720
3     2307
4     1071
5      794
6     3407
7     2950
8     3430
9     1899
10    1001
11    3101
12    3689
13    1927
14    1722
15    1053
16    3731
17    3306
18    2053
19    3641
20    3664
Name: date_of_purchase, dtype: int64


问:
Intellij disable new line before annotated field for Kotlin
IntelliJ autoformat keeps adding a blank lines between class field declarations having annotations.
Do you know how to disable it?
This happens for kotlin files since does not work like that for java files.

Example, between each var intellij adds a blank line each time I execute autoformat.

```<code>class Resign : UnitTest() {
    @InjectMocks
    private lateinit var resignService: ResignServiceImpl

    @Mock
    private lateinit var actionAccess: ActionAccess

    @Mock
    private lateinit var userReportConverter: UserReportConverter

    ....
}
</code>```

答:
The problem was fixed in KT-37891. The option to disable this behavior should be available in the next plugin version.

You may also consider voting for KT-32185: 'More code style options for minimum blank lines'

Body:
IntelliJ autoformat keeps adding a blank lines between class field declarations having annotations.
Do you know how to disable it?
This happens for kotlin files since does not work like that for java files.

Example, between each var intellij adds a blank line each time I execute autoformat.

class Resign : UnitTest() {
    @InjectMocks
    private lateinit var resignService: ResignServiceImpl

    @Mock
    private lateinit var actionAccess: ActionAccess

    @Mock
    private lateinit var userReportConverter: UserReportConverter

    ....
}


问:
Format 2 dates in 1 cell
I'm displaying 2 dates in 1 cell and I want to change the format of the 2 dates. I could do it with only one date but when it comes to 2 I struggle. here is a screenshot of my ag-grid:

I tried to create new function dateFormatterr which takes 2 parameters and use it in columnDefs but it didn't work. Here is my code:

```<code>import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Grid, GridApi } from 'ag-grid-community';
import { AgGridAngular } from 'ag-grid-angular';
import { DealsService } from './services/deals.service';
import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {
  title = 'app';
  gridOptions = {
    rowHeight: 70
  }
  columnDefs = [{
      headerName: "Block \n Deal",
      cellRenderer: function(params) {
        return params.data.BLOCKID + '<br/>' + params.data.DEALID
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Class \n Type',
      cellRenderer: function(params) {
        return params.data.DEALCLASS + '<br/>' + params.data.DEALTYPE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Trade \n Start',
      cellRenderer: function(params) {
        return params.data.TRADEDATE + '<br/>' + params.data.STARTDATE
      },
      valueFormatter: this.dateFormatterr('TRADEDATE', 'STARTDATE'),
      width: 150,
      resizable: true,
      filter: true,
    },
    {
      headerName: 'Folder \n Cpty',
      cellRenderer: function(params) {
        return params.data.FOLDERSHORTNAME + '<br/>' + params.data.CPTYSHORTNAME
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'ShortName \n Name',
      cellRenderer: function(params) {
        return params.data.INSTRSHORTNAME + '<br/>' + params.data.INSTRNAME
      },
      width: 150,
      resizable: true,
      filter: true,
    },
    {
      headerName: 'Quantity \n Settl.Amt',
      cellRenderer: function(params) {
        return params.data.QUANTITY + '<br/>' + params.data.SETTLEAMT
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Rate \n Fees',
      cellRenderer: function(params) {
        return params.data.FLOATINGRATESSHORTNAME + '<br/>' + params.data.RENTSPREADFIXEDRATE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Category \n Status',
      cellRenderer: function(params) {
        return params.data.DEALCAT + '<br/>' + params.data.WORKFLOWSTATE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'End',
      field: 'ENDDATE',
      valueFormatter: this.dateFormatter,
      width: 140,
      resizable: true,
      filter: true
    },
  ];
  rowData: any;
  constructor(private service: DealsService) {}
  dateFormatter(params) {
    return moment(params.value).format('DD/MM/YYYY');
  }
  dateFormatterr(params1, params2) {
    return moment(params1.value + params2.value).format('DD/MM/YYYY');
  }
  ngOnInit() {
    this.service.getDealsList().subscribe(data => {
      this.rowData = data;
    });
  }
}
</code>```

I hope to get your help.

答:
the dateFormatterr function must take one parameter not two, inside the function :

You have to separate the two dates String into two String using regex/pattern or a custom function.

Parse each string to a date format

Finally sum the two dates using moment and return it

I cannot give you the code; because your screenshot dont show all the date.

Title: Format 2 dates in 1 cell

Body:
I'm displaying 2 dates in 1 cell and I want to change the format of the 2 dates. I could do it with only one date but when it comes to 2 I struggle. here is a screenshot of my ag-grid:

I tried to create new function dateFormatterr which takes 2 parameters and use it in columnDefs but it didn't work. Here is my code:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Grid, GridApi } from 'ag-grid-community';
import { AgGridAngular } from 'ag-grid-angular';
import { DealsService } from './services/deals.service';
import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent implements OnInit {
  title = 'app';
  gridOptions = {
    rowHeight: 70
  }
  columnDefs = [{
      headerName: "Block \n Deal",
      cellRenderer: function(params) {
        return params.data.BLOCKID + '
' + params.data.DEALID
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Class \n Type',
      cellRenderer: function(params) {
        return params.data.DEALCLASS + '
' + params.data.DEALTYPE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Trade \n Start',
      cellRenderer: function(params) {
        return params.data.TRADEDATE + '
' + params.data.STARTDATE
      },
      valueFormatter: this.dateFormatterr('TRADEDATE', 'STARTDATE'),
      width: 150,
      resizable: true,
      filter: true,
    },
    {
      headerName: 'Folder \n Cpty',
      cellRenderer: function(params) {
        return params.data.FOLDERSHORTNAME + '
' + params.data.CPTYSHORTNAME
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'ShortName \n Name',
      cellRenderer: function(params) {
        return params.data.INSTRSHORTNAME + '
' + params.data.INSTRNAME
      },
      width: 150,
      resizable: true,
      filter: true,
    },
    {
      headerName: 'Quantity \n Settl.Amt',
      cellRenderer: function(params) {
        return params.data.QUANTITY + '
' + params.data.SETTLEAMT
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Rate \n Fees',
      cellRenderer: function(params) {
        return params.data.FLOATINGRATESSHORTNAME + '
' + params.data.RENTSPREADFIXEDRATE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'Category \n Status',
      cellRenderer: function(params) {
        return params.data.DEALCAT + '
' + params.data.WORKFLOWSTATE
      },
      width: 150,
      resizable: true,
      filter: true
    },
    {
      headerName: 'End',
      field: 'ENDDATE',
      valueFormatter: this.dateFormatter,
      width: 140,
      resizable: true,
      filter: true
    },
  ];
  rowData: any;
  constructor(private service: DealsService) {}
  dateFormatter(params) {
    return moment(params.value).format('DD/MM/YYYY');
  }
  dateFormatterr(params1, params2) {
    return moment(params1.value + params2.value).format('DD/MM/YYYY');
  }
  ngOnInit() {
    this.service.getDealsList().subscribe(data => {
      this.rowData = data;
    });
  }
}

I hope to get your help.


问:
How could I evaluate multiple lines for loop in a Java assert statement?
I am looking to sum the values of an array and make a quick calculation using the result of that sum, then use the result of that calculation to compare to an already existing number so the comparison forms the condition of the assert. Can I place the for loop and calculations next to the assert keyword, or must I create a function separately that contains the for loop call it from the assert statement? </p>

答:
assert takes an expression; a for loop is a statement.  You could sum the array in an expression using a streams operation:

```<code>assert Arrays.stream(array).sum() == expectedSum;
</code>```

or, as you suggested, call out to a function that does something similar.

Body:
assert takes an expression; a for loop is a statement.  You could sum the array in an expression using a streams operation:

assert Arrays.stream(array).sum() == expectedSum;

or, as you suggested, call out to a function that does something similar.


问:
how to arrange output dfs on a single worksheet
I have 3 data frames  I want all thee df output on one worksheet  1st df  should start from C2 cell,  2ND df should start from H2 cell, 3rd df should start from C8 cell.
Image of output df arrangement is attached.</p>

答:
Have you tried mode = 'a' which means append mode?
ex. open the file in 'a', use to_csv() to write the first dataframe. Repeat for the other dataframes.

Or pass mode = 'a' to to_csv when you writing to the csv file.


问:
Access dom element with vuejs and vuetify in v-tabs
I have a div tag with an 'id="meet"' into v-tabs.

I need to access the node of this tag after I click a tab. I am using

```<code>let node=document.querySelector("#meet").
</code>```

My problem is that it always returns "null". Here is the codepen: https://codepen.io/luizalves/pen/WNrepxz

What is wrong here?

答:
Of course, according to vuetify docs, you may add eager prop to v-tab-item component, and that's it, but...possibly you are doing something wrong.

It's not a good idea to always add this prop because you are losing one of the vuetify 2.X advantages - lazy loading. This may lead to big performance problems if there are many elements on the tab.

Maybe it would be better if you will work directly with reactive variables (like variables in v-model directive), not DOM objects.

Body:
I have a div tag with an 'id="meet"' into v-tabs.

I need to access the node of this tag after I click a tab. I am using

let node=document.querySelector("#meet").

My problem is that it always returns "null". Here is the codepen: https://codepen.io/luizalves/pen/WNrepxz

What is wrong here?


问:
How to send back json data with status(204).send() without refreshing the page in nodejs?
I am working in nodejs project with handlebars. I am a beginner in nodejs. I just want to send back some data(it could be a json object) to handlebars template after POST request on the same page without refreshing the page. But I don't know how to do this.

This is the part of code but not the entire code:

```<code>router.post('/post/team', (req, res)=>{
    const newTeamPostQuery = newteampost({
        totalOvers: req.body.totalOvers,
        currentMatch: true,
        teamOne: [
            {
                name: req.body.teamOne,
                over: 0
            }
        ],
        teamTwo: [
            {
                name: req.body.teamTwo,
                over: 0
            }
        ]
    });

    newTeamPostQuery.save().then(savedPost=>{
        res.status(204).send({data: savedPost});
    }).catch(error=>{
        console.log(error);
    });
});
</code>```

I don't want to refresh the page. When I use this res.json({data: newTeamPostQuery}); then it refreshes the page to this /post/team route and show the json data on the page.

I am using handlebars to show data like this:
{{#if data.currentMatch}} data.totalOvers {{else}} Overs {{/if}}

I am using mongodb.

答:
Alright so as I am thinking you are getting this Data from your HTML

let's suppose you have <input type=text id='username>
after that you have the submit button, now you don't need to make a submit form
just include js file at the end of your html file
inside main.js

```<code>document.getElementById('buttonID).addEventListener('click,()=>{
    let username = document.detElementById('buttonID')
    // make post request with ajax to send that data
})
</code>```

inside your post request do whatever you like with that data you got back
you could have empty HTML element and just change their values with that data

Body:
I am working in nodejs project with handlebars. I am a beginner in nodejs. I just want to send back some data(it could be a json object) to handlebars template after POST request on the same page without refreshing the page. But I don't know how to do this.

This is the part of code but not the entire code:

router.post('/post/team', (req, res)=>{
    const newTeamPostQuery = newteampost({
        totalOvers: req.body.totalOvers,
        currentMatch: true,
        teamOne: [
            {
                name: req.body.teamOne,
                over: 0
            }
        ],
        teamTwo: [
            {
                name: req.body.teamTwo,
                over: 0
            }
        ]
    });

    newTeamPostQuery.save().then(savedPost=>{
        res.status(204).send({data: savedPost});
    }).catch(error=>{
        console.log(error);
    });
});

I don't want to refresh the page. When I use this res.json({data: newTeamPostQuery}); then it refreshes the page to this /post/team route and show the json data on the page.

I am using handlebars to show data like this:
{{#if data.currentMatch}} data.totalOvers {{else}} Overs {{/if}}

I am using mongodb.

Body:
Alright so as I am thinking you are getting this Data from your HTML

let's suppose you have <input type=text id='username>
after that you have the submit button, now you don't need to make a submit form
just include js file at the end of your html file <script src='main.js'></script>
inside main.js

document.getElementById('buttonID).addEventListener('click,()=>{
    let username = document.detElementById('buttonID')
    // make post request with ajax to send that data
})

inside your post request do whatever you like with that data you got back
you could have empty HTML element and just change their values with that data


问:
How to fix auto-fixable problems on VSCode with Flutter?
I've updated pedantic package and ended up 1K+ problems. Many of them are prefer_single_quotes or unnecessary this etc. They are one click away to fix. I think eslint or some other tools can do that within the VSCode.

Is there a way to do it with Flutter projects?  I find dartfix package but says “No recommended changes” after running it. What I want to do is fix all the auto-fixable problems on the problems tab.

dartfix on pub.dev

答: I'm not sure how many of these problems dartfmt can cover, but it's definitely worth trying! To run dartfmt with idiomatic fixing, overwriting and link-following, please run dartfmt --fix --overwrite --follow-links . in your project folder.


问:
Calculate Next Acceptable Notification Time in C#
Good evening!

I am trying to figure out a way to calculate the next time it's acceptable to notify someone based upon their previously stored preferences - basically, they specify what days of the week they wish to be notified along with a time range. For instance, someone might want to be notified Monday - Friday between the hours of 9 AM and 5 PM. In other words, only notify them during the work week and only during normal business hours.

If I generate an alert at, say Saturday morning at 4 AM, I want to arrive at the following Monday at 9 AM. On the other hand, if I generate an alert at 2:30 PM on Wednesday, the function should return the current date and time - Wednesday at 2:30 PM. I'm not worried about holidays and I'm absolutely fine with a single time frame for all seven days of the week.

It really feels like this should be straightforward, but I have as of yet not been able to figure out a way to do so. Anyone ever solve this problem?

Thanks in advance!
Marshall

答:
Not sure I understood Jerome's comment, but it probably indicates that I did not explain my question too terribly well. Hopefully, my answer will help that!

I spent some time this morning and believe I have a solution worked out - feels a bit on the sloppy side, but every test I throw at it comes out as expected.

A few notes - mon1, tue1, etc. are all check boxes on my test UI. If mon1 is checked, that indicates the recipient is willing to receive an alert on Monday between the hours of start1 and stop 1, which are datetimepicker controls on the test UI, allowing for indicating time of day.

```<code>    internal class ADOW
    {
        public DayOfWeek dow;
        public bool allowed;

        public ADOW(DayOfWeek dw, bool allw)
        {
            dow = dw;
            allowed = allw;
        }
    }

    private void calculate_Click(object sender, EventArgs e)
    {
        List<ADOW> allowedDOW = new List<ADOW>();
        allowedDOW.Add(new ADOW(DayOfWeek.Monday, mon1.Checked));
        allowedDOW.Add(new ADOW(DayOfWeek.Tuesday, tue1.Checked));
        allowedDOW.Add(new ADOW(DayOfWeek.Wednesday, wed1.Checked));
        allowedDOW.Add(new ADOW(DayOfWeek.Thursday, thu1.Checked));
        allowedDOW.Add(new ADOW(DayOfWeek.Friday, fri1.Checked));
        allowedDOW.Add(new ADOW(DayOfWeek.Saturday, sat1.Checked));
        allowedDOW.Add(new ADOW(DayOfWeek.Sunday, sun1.Checked));

        DateTime cdt = currentDT.Value;
        DayOfWeek cdow = cdt.DayOfWeek;
        bool todayOK = allowedDOW.Find(x => x.dow == cdow).allowed;

        if (todayOK)
        {
            // Check to see if the current time is inside the acceptable range
            double secondsStart = start1.Value.TimeOfDay.TotalSeconds;
            double secondsStop = stop1.Value.TimeOfDay.TotalSeconds;

            double secondsNow = cdt.TimeOfDay.TotalSeconds;

            if (secondsNow>=secondsStart)
            {
                if (secondsNow<=secondsStop)
                {
                    // Now is ok, send the alert immediately
                    SendIt(cdt);
                }
                else
                {
                    // Too late in the day - find the next valid day
                    cdt = LookAhead(cdt, allowedDOW);
                    SendIt(cdt);
                }
            }
            else
            {
                // The day is right, but it's too early - schedule the send for the now + (secondsStart-now)
                SendIt(cdt.AddSeconds(secondsStart - secondsNow));
            }
        }
        else
        {
            // This particular day is no good - find an acceptable one
            cdt = LookAhead(cdt, allowedDOW);
            SendIt(cdt);
        }

    }

    private DateTime LookAhead(DateTime cdt, List<ADOW> adow)
    {
        DateTime response = DateTime.MinValue;

        bool acceptable = false;
        while (!acceptable)
        {
            // First, add 24 hours to the current time to push the day by one.
            cdt = cdt.AddHours(24);

            // Now, we need to set the right time of day, which is start1.
            double secondsOver = cdt.TimeOfDay.TotalSeconds - start1.Value.TimeOfDay.TotalSeconds;
            cdt = cdt.Subtract(new TimeSpan(0, 0, (int)secondsOver));

            // Finally, check to see if the new day of the week is valid - if not, keep looking!
            acceptable = adow.Find(x => x.dow == cdt.DayOfWeek).allowed;

            if (acceptable)
            {
                response = cdt;
            }
        }

        return response;
    }
</code>```

Thanks for reading! Looking forward to anyone pointing out any flaws or improvements.

Marshall

Body:
Not sure I understood Jerome's comment, but it probably indicates that I did not explain my question too terribly well. Hopefully, my answer will help that!

I spent some time this morning and believe I have a solution worked out - feels a bit on the sloppy side, but every test I throw at it comes out as expected.

A few notes - mon1, tue1, etc. are all check boxes on my test UI. If mon1 is checked, that indicates the recipient is willing to receive an alert on Monday between the hours of start1 and stop 1, which are datetimepicker controls on the test UI, allowing for indicating time of day.

    internal class ADOW
    {
        public DayOfWeek dow;
        public bool allowed;

        public ADOW(DayOfWeek dw, bool allw)
        {
            dow = dw;
            allowed = allw;
        }
    }

    private void calculate_Click(object sender, EventArgs e)
    {
        List<ADOW> allowedDOW = new List<ADOW>();
        allowedDOW.Add(new ADOW(DayOfWeek.Monday, mon1.Checked));
        allowedDOW.Add(new ADOW(DayOfWeek.Tuesday, tue1.Checked));
        allowedDOW.Add(new ADOW(DayOfWeek.Wednesday, wed1.Checked));
        allowedDOW.Add(new ADOW(DayOfWeek.Thursday, thu1.Checked));
        allowedDOW.Add(new ADOW(DayOfWeek.Friday, fri1.Checked));
        allowedDOW.Add(new ADOW(DayOfWeek.Saturday, sat1.Checked));
        allowedDOW.Add(new ADOW(DayOfWeek.Sunday, sun1.Checked));

        DateTime cdt = currentDT.Value;
        DayOfWeek cdow = cdt.DayOfWeek;
        bool todayOK = allowedDOW.Find(x => x.dow == cdow).allowed;

        if (todayOK)
        {
            // Check to see if the current time is inside the acceptable range
            double secondsStart = start1.Value.TimeOfDay.TotalSeconds;
            double secondsStop = stop1.Value.TimeOfDay.TotalSeconds;

            double secondsNow = cdt.TimeOfDay.TotalSeconds;

            if (secondsNow>=secondsStart)
            {
                if (secondsNow<=secondsStop)
                {
                    // Now is ok, send the alert immediately
                    SendIt(cdt);
                }
                else
                {
                    // Too late in the day - find the next valid day
                    cdt = LookAhead(cdt, allowedDOW);
                    SendIt(cdt);
                }
            }
            else
            {
                // The day is right, but it's too early - schedule the send for the now + (secondsStart-now)
                SendIt(cdt.AddSeconds(secondsStart - secondsNow));
            }
        }
        else
        {
            // This particular day is no good - find an acceptable one
            cdt = LookAhead(cdt, allowedDOW);
            SendIt(cdt);
        }

    }

    private DateTime LookAhead(DateTime cdt, List<ADOW> adow)
    {
        DateTime response = DateTime.MinValue;

        bool acceptable = false;
        while (!acceptable)
        {
            // First, add 24 hours to the current time to push the day by one.
            cdt = cdt.AddHours(24);

            // Now, we need to set the right time of day, which is start1.
            double secondsOver = cdt.TimeOfDay.TotalSeconds - start1.Value.TimeOfDay.TotalSeconds;
            cdt = cdt.Subtract(new TimeSpan(0, 0, (int)secondsOver));

            // Finally, check to see if the new day of the week is valid - if not, keep looking!
            acceptable = adow.Find(x => x.dow == cdt.DayOfWeek).allowed;

            if (acceptable)
            {
                response = cdt;
            }
        }

        return response;
    }

Thanks for reading! Looking forward to anyone pointing out any flaws or improvements.

Marshall


问:
Configuring Multiple Build Configurations from Shared VCS Root in TeamCity
I have a single SVN repository containing multiple projects, e.g.

/molindo/trunk/foo

/molindo/trunk/bar

/molindo/trunk/baz

Currently, I've configured 3 projects, all using the shared VCS root /molindo.

By default, every commit would trigger build of all 3 projects (although trunk/foo doesn't care about changes in trunk/bar or trunk/baz). As I've seen, it's possible to configure VCS triggers (e.g. +:/trunk/foo/** for project foo). While this works for build triggering, it still shows pending changes for other projects.

So what are my options now. I could think of

accept unrelated changes shown as pending on UI

go back and create VCS roots for each project

Both options are suboptimal. The first because it's ugly, the second because it's cumbersome. Is there another option I don't know of? Or is there another (preferred) to build multiple projects from a shared SVN repository?

答:
Please, try to use the following VCS Trigger rules

VCS Trigger rules for project "foo":

```<code>+:/trunk/foo/**
-:/trunk/bar/**
-:/trunk/baz/**
</code>```

VCS Trigger rules for project "bar":

```<code>+:/trunk/bar/**
-:/trunk/foo/**
-:/trunk/baz/**
</code>```

VCS Trigger rules for project "baz":

```<code>+:/trunk/baz/**
-:/trunk/foo/**
-:/trunk/bar/**
</code>```

Body:
Please, try to use the following VCS Trigger rules

VCS Trigger rules for project "foo":

+:/trunk/foo/**
-:/trunk/bar/**
-:/trunk/baz/**

VCS Trigger rules for project "bar":

+:/trunk/bar/**
-:/trunk/foo/**
-:/trunk/baz/**

VCS Trigger rules for project "baz":

+:/trunk/baz/**
-:/trunk/foo/**
-:/trunk/bar/**