问:
How can I change date format for formGroups input element with Angular 7?
When input is of type 'Date', date format is dd/MM/yyyy.
I want to change date format from MM/dd/yyyy to dd/MM/yyyy (Turkish Format and Turkish Calender).

Here is the code.

```<code><form [formGroup]="opportunityForm" (ngSubmit)="updateData(opportunityForm.value)">
 <div class="form-group">
          <label>Oluşturulma Tarihi</label>
          <input  type="date"  class="form-control"  formControlName="createDate" required>
          <div class="alert-danger" *ngIf="!opportunityForm.controls['createDate'].valid && (opportunityForm.controls['createDate'].touched)">
            <div [hidden]="!opportunityForm.controls['createDate'].errors.required">
              Tarih alanı gerekli
            </div>
          </div>
        </div>
 <button type="submit" class="btn btn-primary" [disabled]="!opportunityForm.valid">Güncelle</button>
</form>

constructor(private http: HttpClient,private fb: FormBuilder,private router: Router,private actRoute: ActivatedRoute, private service:OpportunityService) {
    this.opportunityForm=this.fb.group({
      title:['',Validators.required],
      description:['',Validators.required],
      createDate:['',Validators.required],
      expirationDate:['',Validators.required],
      file: new FormControl(null)
    });
</code>```

Suggestions and solutions will be appreciated.

答:
There are multiple way to do this, But can you explain if you want to change the format looks even in the html? if not i'd suggest you to use formatDate instead of datePipe which is lot easier in my opinion.

in your .ts file do this.

```<code>import { formatDate } from '@angular/common';
 this.opportunityForm.value.createDate = formatDate(this.opportunityForm.value.createDate, 'yyyy/MM/dd', 'en');
 // 'yyyy/MM/dd' format can be replaced with however you want to
</code>```

Body:
When input is of type 'Date', date format is dd/MM/yyyy.
I want to change date format from MM/dd/yyyy to dd/MM/yyyy (Turkish Format and Turkish Calender).

Here is the code.

<form [formGroup]="opportunityForm" (ngSubmit)="updateData(opportunityForm.value)">

          Oluşturulma Tarihi
          <input  type="date"  class="form-control"  formControlName="createDate" required>

              Tarih alanı gerekli

 <button type="submit" class="btn btn-primary" [disabled]="!opportunityForm.valid">Güncelle</button>
</form>

constructor(private http: HttpClient,private fb: FormBuilder,private router: Router,private actRoute: ActivatedRoute, private service:OpportunityService) {
    this.opportunityForm=this.fb.group({
      title:['',Validators.required],
      description:['',Validators.required],
      createDate:['',Validators.required],
      expirationDate:['',Validators.required],
      file: new FormControl(null)
    });

Suggestions and solutions will be appreciated.

Body:
There are multiple way to do this, But can you explain if you want to change the format looks even in the html? if not i'd suggest you to use formatDate instead of datePipe which is lot easier in my opinion.

in your .ts file do this.

import { formatDate } from '@angular/common';
 this.opportunityForm.value.createDate = formatDate(this.opportunityForm.value.createDate, 'yyyy/MM/dd', 'en');
 // 'yyyy/MM/dd' format can be replaced with however you want to


来源: stackexchange

问:
How do I copy from one BigQuery Table to another when the target contains REPEATED fields?
I have two tables which have similar schema, but one has a subset of fields which have Mode set to REPEATED. For example:

Schema 1:

```<code>[
    {"name": "id", "type": "NUMERIC", "mode": "REQUIRED"},
    {"name": "name", "type": "STRING", "mode": "REQUIRED"},
    {"name": "created", "type": "TIMESTAMP", "mode": "REQUIRED"},
    {"name": "valid", "type": "BOOLEAN", "mode": "REQUIRED"},
    {"name": "parameter1", "type": "STRING", "mode": "REQUIRED"},
    {"name": "parameter2", "type": "FLOAT", "mode": "REQUIRED"},
    {"name": "parameter3", "type": "BOOLEAN", "mode": "REQUIRED"}
]
</code>```

Schema 2:

```<code>[
    {"name": "id", "type": "NUMERIC", "mode": "REQUIRED"},
    {"name": "name", "type": "STRING", "mode": "REQUIRED"},
    {"name": "created", "type": "TIMESTAMP", "mode": "REQUIRED"},
    {"name": "valid", "type": "BOOLEAN", "mode": "REQUIRED"},
    {"name": "parameters", "type": "RECORD", "mode": "REPEATED", "fields":
        [
            {"name": "parameter1", "type": "STRING", "mode": "REQUIRED"},
            {"name": "parameter2", "type": "FLOAT", "mode": "REQUIRED"},
            {"name": "parameter3", "type": "BOOLEAN", "mode": "REQUIRED"}
        ]
    }
]
</code>```

I've created Table1 and Table2 using these schemas. Table1 has been written to, Table2 is empty. I'd like to copy the contents of Table1 to Table2, where Table1.parameter1, Table1.parameter2 and Table1.parameter3 are written to an array of Table2.parameters of exactly one element each. I'm assuming a SQL command like INSERT INTO TABLE2 (id, name, created ...) SELECT id, name, created FROM TABLE1; should do the job, but I can't find the correct syntax.

(In future Table 2 will have data with multiple lines of parameters written to it, hence the need for the copy)

I've seen the documentation at https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax and none of the suggestions seem to fit my use case. Can you point me in the right direction?

Thanks!

答:
This can be done by grouping the parameter columns of the first table into a STRUCT and an ARRAY when inserting them into the second table:

```<code>INSERT INTO table2 (id, name, created, valid, parameters)
SELECT id, name, created, valid, [(parameter1, parameter2, parameter3)]
FROM table1
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two tables which have similar schema, but one has a subset of fields which have Mode set to REPEATED. For example:

Schema 1:

[
    {"name": "id", "type": "NUMERIC", "mode": "REQUIRED"},
    {"name": "name", "type": "STRING", "mode": "REQUIRED"},
    {"name": "created", "type": "TIMESTAMP", "mode": "REQUIRED"},
    {"name": "valid", "type": "BOOLEAN", "mode": "REQUIRED"},
    {"name": "parameter1", "type": "STRING", "mode": "REQUIRED"},
    {"name": "parameter2", "type": "FLOAT", "mode": "REQUIRED"},
    {"name": "parameter3", "type": "BOOLEAN", "mode": "REQUIRED"}
]

Schema 2:

[
    {"name": "id", "type": "NUMERIC", "mode": "REQUIRED"},
    {"name": "name", "type": "STRING", "mode": "REQUIRED"},
    {"name": "created", "type": "TIMESTAMP", "mode": "REQUIRED"},
    {"name": "valid", "type": "BOOLEAN", "mode": "REQUIRED"},
    {"name": "parameters", "type": "RECORD", "mode": "REPEATED", "fields":
        [
            {"name": "parameter1", "type": "STRING", "mode": "REQUIRED"},
            {"name": "parameter2", "type": "FLOAT", "mode": "REQUIRED"},
            {"name": "parameter3", "type": "BOOLEAN", "mode": "REQUIRED"}
        ]
    }
]

I've created Table1 and Table2 using these schemas. Table1 has been written to, Table2 is empty. I'd like to copy the contents of Table1 to Table2, where Table1.parameter1, Table1.parameter2 and Table1.parameter3 are written to an array of Table2.parameters of exactly one element each. I'm assuming a SQL command like INSERT INTO TABLE2 (id, name, created ...) SELECT id, name, created FROM TABLE1; should do the job, but I can't find the correct syntax.

(In future Table 2 will have data with multiple lines of parameters written to it, hence the need for the copy)

I've seen the documentation at https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax and none of the suggestions seem to fit my use case. Can you point me in the right direction?

Thanks!

Body:
This can be done by grouping the parameter columns of the first table into a STRUCT and an ARRAY when inserting them into the second table:

INSERT INTO table2 (id, name, created, valid, parameters)
SELECT id, name, created, valid, [(parameter1, parameter2, parameter3)]
FROM table1


问:
How do I upload file to Azure function while publishing the code from Visual Studio?
I have created a Azure Function, which is having a dependency on ini file.

```<code> public class DataProcessingFunction
 {
    FunctionName("DataProcessingFunction")]
    public async Task Run([EventGridTrigger]EventGridEvent eventGridEvent,ILogger log)
    {
        string iniFolderPath = $@"{Directory.GetCurrentDirectory()}\Ini\";
        string iniFileName = "Sample.ini";
        var iniConfig = FileManager.ReadFile(iniFolderPath, iniFileName);
    }
 }
</code>```

I have selected Copy if never option in Visual Studio while publishing the code to Azure function
Also, I have tried selecting Embedded Resource. But I am not able to find the file

I get an exception

File not found.

Add/Upload option in Azure portal is disabled because I am publishing the function from Visual studio

Question: Do I need to upload file to blob and then refer it in a code?

答:
Here is the way to do it.

ExecutionContext context; // You can modify your function method to take an additional parameter of type ExecutionContext

public static async Task Run(<.... Other parameters>, ILogger log, ExecutionContext context)

Then build the path by combining function directory, "templates" is the directory I have in the function app project which is deployed along with other code, emails.html is file within templates (For each of these files you have to set, copy-always or copy-if-newer in the properties.). Instead of templates you can have your .ini file.

string templatePath = Path.Combine(context.FunctionAppDirectory, "Templates", "emails.html");

Body:
I have created a Azure Function, which is having a dependency on ini file.

 public class DataProcessingFunction
 {
    FunctionName("DataProcessingFunction")]
    public async Task Run([EventGridTrigger]EventGridEvent eventGridEvent,ILogger log)
    {
        string iniFolderPath = $@"{Directory.GetCurrentDirectory()}\Ini\";
        string iniFileName = "Sample.ini";
        var iniConfig = FileManager.ReadFile(iniFolderPath, iniFileName);
    }
 }

I have selected Copy if never option in Visual Studio while publishing the code to Azure function
Also, I have tried selecting Embedded Resource. But I am not able to find the file

I get an exception

File not found.

Add/Upload option in Azure portal is disabled because I am publishing the function from Visual studio

Question: Do I need to upload file to blob and then refer it in a code?


问:
How to change color of every Even values element in RecyclerView in Kotlin?
In kotlin I'm fresher please let me know about it

```<code>//In onBindViewHolder method :
        val context = holder.itemView.context
//Here I want to change background colour so please tell me or comment
        if (position % 2 == 0) {
           holder.binding.root.setBackgroundColor(ContextCompat.getColor(context,R.color.colorAccent))
        } else {
            holder.binding.root.setBackgroundColor(ContextCompat.getColor(context,R.color.colorPrimary))
        }

</code>```

Thanks in advance.!

答:
Please use this one :

```<code> if (position % 2 == 1) {
           holder.binding.root.setBackgroundColor(ContextCompat.getColor(context,R.color.colorAccent))
        } else {
            holder.binding.root.setBackgroundColor(ContextCompat.getColor(context,R.color.colorPrimary))
        }
</code>```

It will be executed.

Body:
In kotlin I'm fresher please let me know about it

//In onBindViewHolder method :
        val context = holder.itemView.context
//Here I want to change background colour so please tell me or comment
        if (position % 2 == 0) {
           holder.binding.root.setBackgroundColor(ContextCompat.getColor(context,R.color.colorAccent))
        } else {
            holder.binding.root.setBackgroundColor(ContextCompat.getColor(context,R.color.colorPrimary))
        }

Thanks in advance.!

Body:
Please use this one :

 if (position % 2 == 1) {
           holder.binding.root.setBackgroundColor(ContextCompat.getColor(context,R.color.colorAccent))
        } else {
            holder.binding.root.setBackgroundColor(ContextCompat.getColor(context,R.color.colorPrimary))
        }

It will be executed.


问:
Limitation on document count for azure search S3 HD pricing tier
When I read the article I see below info

"For S3 High Density services created after late 2017, the 200 million document per partition has been removed but the 1 million document per index limit remains."

I wanted to confirm if 1 million document limit still exists for S3 HD index or this limit has also been removed recently?

答:
Same issues I have faced then I'm converting data into batches.

Please modify the code as per your requirement.

```<code>for (int i = 0; i < result.Items.Count; i = i + 31500)
{
    searchItems = result.Items.Skip(i).Take(31500);
    actionList = new List<IndexAction<AzureSearchItem>>();
    foreach (var item in searchItems)
    {
        actionList.Add(IndexAction.MergeOrUpload(AzureHelper.FormatSearchItem(item)));
    }
    PostBulkAssortmentDocuments(actionList.AsEnumerable());
}

public virtual void PostBulkAssortmentDocuments(IEnumerable<IndexAction<AzureSearchItem>> actions)
{
    if (actions.Count() == 0)
        return;

    var batch = IndexBatch.New(actions);

    try
    {
        var data = GetIndexClient(IndexName).Documents.Index(batch);

        var passResultCount = data.Results.Where(x => x.Succeeded).Count();
        var failResultCount = data.Results.Where(x => x.Succeeded == false).Count();
        var MessageResult = data.Results.Where(x => !string.IsNullOrEmpty(x.ErrorMessage));
        var keyResult = data.Results.Where(x => !string.IsNullOrEmpty(x.Key)).Select(x => x.Key).ToList();
        var unikKey = keyResult.Distinct().ToList();
        string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
    }
    catch (IndexBatchException e)
    {
        // Sometimes when your Search service is under load, indexing will fail for some of the documents in
        // the batch. Depending on your application, you can take compensating actions like delaying and
        // retrying. For this simple demo, we just log the failed document keys and continue.
        Console.WriteLine(
            "Failed to index some of the documents: {0}",
            String.Join(", ", e.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key)));

        this.WriteToFile("Error - PostBulkAssortmentDocuments -" + e.Message);
    }
}
</code>```

Body:
Same issues I have faced then I'm converting data into batches.

Please modify the code as per your requirement.

for (int i = 0; i < result.Items.Count; i = i + 31500)
{
    searchItems = result.Items.Skip(i).Take(31500);
    actionList = new List<IndexAction<AzureSearchItem>>();
    foreach (var item in searchItems)
    {
        actionList.Add(IndexAction.MergeOrUpload(AzureHelper.FormatSearchItem(item)));
    }
    PostBulkAssortmentDocuments(actionList.AsEnumerable());
}

public virtual void PostBulkAssortmentDocuments(IEnumerable<IndexAction<AzureSearchItem>> actions)
{
    if (actions.Count() == 0)
        return;

    var batch = IndexBatch.New(actions);

    try
    {
        var data = GetIndexClient(IndexName).Documents.Index(batch);

        var passResultCount = data.Results.Where(x => x.Succeeded).Count();
        var failResultCount = data.Results.Where(x => x.Succeeded == false).Count();
        var MessageResult = data.Results.Where(x => !string.IsNullOrEmpty(x.ErrorMessage));
        var keyResult = data.Results.Where(x => !string.IsNullOrEmpty(x.Key)).Select(x => x.Key).ToList();
        var unikKey = keyResult.Distinct().ToList();
        string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
    }
    catch (IndexBatchException e)
    {
        // Sometimes when your Search service is under load, indexing will fail for some of the documents in
        // the batch. Depending on your application, you can take compensating actions like delaying and
        // retrying. For this simple demo, we just log the failed document keys and continue.
        Console.WriteLine(
            "Failed to index some of the documents: {0}",
            String.Join(", ", e.IndexingResults.Where(r => !r.Succeeded).Select(r => r.Key)));

        this.WriteToFile("Error - PostBulkAssortmentDocuments -" + e.Message);
    }
}


问:
JVM property -Dfile.encoding=UTF8 or UTF-8?
I would like to know what is the value of the Java Virtual Machine (JVM) property to set my file encoding to UTF-8.

Do I put -Dfile.encoding=UTF8 or -Dfile.encoding=UTF-8?

答:
It will be:

```<code>UTF8
</code>```

See here for the definitions.

ContentLicense: CC BY-SA 3.0

Body:
It will be:

UTF8

See here for the definitions.


问:
How should i catch and handle 406 error in VUEJS
I have a route where i send to the api the day and h to verify in database if there is an opening in a schedule, if is not the api is sending 406. And i'm getting in console 406 error.
How should i handle that error to have a clean console? </p>

答:
you can wrap your call in a try{} catch(e) {} to handle what happens after the error happens

but it is impossible to prevent the browser from showing the error in the console programmatically because of the potential risk that a script might misuse the errored requests to hide its activities from the user.


问:
How to get Double from String based on locale?
I'm looking for a short and elegance solution, such as some method.

If it's possible to use method like this:

public Double getDoubleFromString(String string); (inside this method it's needed to get current locale because of different GroupingSeparator and DecimalSeparator in different locales)

答:
You should be avoiding double precision by using BigDecimal. Would this work in your case (kotlin) ?

```<code>        val formatter: NumberFormat = DecimalFormat.getInstance()
        (formatter as DecimalFormat).isParseBigDecimal = true

        Log.d("test","${formatter.parse("value to parse")?.toDouble()}" )
</code>```

Some results:

```<code>en-us: "123,56.2498" -> 12356.2498
en-us: "123abc" -> 123.0
ua-uk: "123,56.2498" -> 123.56
</code>```

Body:
You should be avoiding double precision by using BigDecimal. Would this work in your case (kotlin) ?

        val formatter: NumberFormat = DecimalFormat.getInstance()
        (formatter as DecimalFormat).isParseBigDecimal = true

        Log.d("test","${formatter.parse("value to parse")?.toDouble()}" )

Some results:

en-us: "123,56.2498" -> 12356.2498
en-us: "123abc" -> 123.0
ua-uk: "123,56.2498" -> 123.56


问:
How to extract the heatmap of from a set of gene interest from main heatmap?
I have made a heatmap based on following script.

```<code>#load the library
library(pheatmap)

#set label font
par(cex.lab=1.5) # is for y-axis
par(cex.axis=1.5) # is for x-axis

#Set the working directory
setwd("F:\\User\\OneDrive\\data\\final\\Rcode")

#hedge
#read the expression matrix
hedge <- read.table("hedge.txt",sep="\t",header = TRUE)

#Group the data in the frame
group_df = data.frame(Groups=rep(c("AP","CP","BP"),c(6,42,28)))

#Assign the col name to the matrix
rownames(group_df) = colnames(hedge)[2:ncol(hedge)]

#Assign the rownames
rownames(hedge) = hedge[,1]

#plot the heatmap with specific split
pheatmap(hedge[,-1],cluster_cols=FALSE,
         annotation_col=group_df, gaps_col = cumsum(c(6,42,28)))
</code>```

I got following heatmap from the code:

Now I want to extract and replot a subplot from the main heatmap using gene set of my interest (CD34, CD117, CD38, SHH, GLI1, GLI2, GLI3, BCL2, PTCH1, PTCH2, SMO). How can I do this?

答:
You can do something like this, define the genes of interest:

```<code>genes_of_interest = c("CD34","CD117","CD38","SHH",
"GLI1","GLI2","GLI3","BCL2","PTCH1","PTCH2","SMO")
</code>```

If some of them are not in the matrix, do:

```<code>pheatmap(hedge[rownames(hedge) %in% genes_of_interest,-1],cluster_cols=FALSE,
         annotation_col=group_df, gaps_col = cumsum(c(6,42,28)))
</code>```

If you are sure all of them are in there:

```<code>pheatmap(hedge[genes_of_interest,-1],cluster_cols=FALSE,
         annotation_col=group_df, gaps_col = cumsum(c(6,42,28)))
</code>```

The rows will be clustered again so if you don't want that, you need to turn the cluster_rows to FALSE.

Body:
I have made a heatmap based on following script.

#load the library
library(pheatmap)

#set label font
par(cex.lab=1.5) # is for y-axis
par(cex.axis=1.5) # is for x-axis

#Set the working directory
setwd("F:\\User\\OneDrive\\data\\final\\Rcode")

#hedge
#read the expression matrix
hedge <- read.table("hedge.txt",sep="\t",header = TRUE)

#Group the data in the frame
group_df = data.frame(Groups=rep(c("AP","CP","BP"),c(6,42,28)))

#Assign the col name to the matrix
rownames(group_df) = colnames(hedge)[2:ncol(hedge)]

#Assign the rownames
rownames(hedge) = hedge[,1]

#plot the heatmap with specific split
pheatmap(hedge[,-1],cluster_cols=FALSE,
         annotation_col=group_df, gaps_col = cumsum(c(6,42,28)))

I got following heatmap from the code:

Now I want to extract and replot a subplot from the main heatmap using gene set of my interest (CD34, CD117, CD38, SHH, GLI1, GLI2, GLI3, BCL2, PTCH1, PTCH2, SMO). How can I do this?

Body:
You can do something like this, define the genes of interest:

genes_of_interest = c("CD34","CD117","CD38","SHH",
"GLI1","GLI2","GLI3","BCL2","PTCH1","PTCH2","SMO")

If some of them are not in the matrix, do:

pheatmap(hedge[rownames(hedge) %in% genes_of_interest,-1],cluster_cols=FALSE,
         annotation_col=group_df, gaps_col = cumsum(c(6,42,28)))

If you are sure all of them are in there:

pheatmap(hedge[genes_of_interest,-1],cluster_cols=FALSE,
         annotation_col=group_df, gaps_col = cumsum(c(6,42,28)))

The rows will be clustered again so if you don't want that, you need to turn the cluster_rows to FALSE.


答:
I would use not exists with a correlated subquery:

```<code>select t.name, t.paid
from mytable t
where not exists (
    select 1 from mytable t1 where t1.name = t.name and t1.paid = 'Yes'
)
</code>```

For performance with this query, you want an index on (name, paid).

Title: Postgresql - How to get record from the same table that doesn't occur specific data

Body:
In PostgreSQL, if i have this kind of record :

|---------------------|------------------|
|      Name           |     Paid         |
|---------------------|------------------|
|        Teddy        |        No        |
|---------------------|------------------|
|        Andy         |        No        |
|---------------------|------------------|
|        Andy         |        Yes       |
|---------------------|------------------|
|        Sarah        |        Yes       |
|---------------------|------------------|
|        Michael      |        No        |
|---------------------|------------------|
|        Michael      |        Yes       |
|---------------------|------------------|

How do i get Names that don't have 'Yes' occurence in the table?

In this example the result should be : Teddy.

Thanks !

Body:
I would use not exists with a correlated subquery:

select t.name, t.paid
from mytable t
where not exists (
    select 1 from mytable t1 where t1.name = t.name and t1.paid = 'Yes'
)

For performance with this query, you want an index on (name, paid).


问:
Access multipartProperties in SpringBoot JSP Page
i have defined

```<code>spring.servlet.multipart.max-file-size=20MB
</code>```

in my application.properties

This configuration is read by

```<code>package org.springframework.boot.autoconfigure.web.servlet;
@ConfigurationProperties(prefix = "spring.servlet.multipart", ignoreUnknownFields = false)
public class MultipartProperties {
</code>```

How can i access the MultipartProperties Bean?

I tried

```<code><spring:eval expression="@multipartProperties.maxFileSize" />
</code>```

but only get

```<code>org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'multipartProperties' available
</code>```

答:
Ok i found the correct bean

```<code><spring:eval expression="@multipartConfigElement.maxFileSize" />
</code>```

i saw it in MultipartAutoConfiguration

```<code>@Bean
@ConditionalOnMissingBean({ MultipartConfigElement.class, CommonsMultipartResolver.class })
public MultipartConfigElement multipartConfigElement() {
    return this.multipartProperties.createMultipartConfig();
}
</code>```

Body:
i have defined

spring.servlet.multipart.max-file-size=20MB

in my application.properties

This configuration is read by

package org.springframework.boot.autoconfigure.web.servlet;
@ConfigurationProperties(prefix = "spring.servlet.multipart", ignoreUnknownFields = false)
public class MultipartProperties {

How can i access the MultipartProperties Bean?

I tried

<spring:eval expression="@multipartProperties.maxFileSize" />

but only get

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'multipartProperties' available

Body:
Ok i found the correct bean

<spring:eval expression="@multipartConfigElement.maxFileSize" />

i saw it in MultipartAutoConfiguration

@Bean
@ConditionalOnMissingBean({ MultipartConfigElement.class, CommonsMultipartResolver.class })
public MultipartConfigElement multipartConfigElement() {
    return this.multipartProperties.createMultipartConfig();
}


问:
What is the difference between Array.from() and Array.apply()?
I got "Maximum call stack size exceeded." error when using Array.apply() to convert a large Uint8Array to an Array.

I found that apply() passes my parameter array as arguments in Array's constructor and function's arguments are stored in stack. Therefore, if I pass a large array to apply(), it'll exceed the stack.

After some searching, I changed to use Array.from() and it solved my issue.

I read the algorithm in ECMAScript but I can't understand it. So, could someone tell me the difference between apply() and from()?

答:
Array.apply calls Function.prototype.apply with a calling context (a this value) of Array. If the second parameter is an array-like object, it will call the Array constructor with all of the elements of that array-like object as arguments. Eg:

```<code>Array.apply(null, [1, 2, 3, 4])
</code>```

results in, and is equivalent to

```<code>Array(1, 2, 3, 4)
</code>```

But argument lists have a size limit. It depends on the engine, but it looks like you probably shouldn't try to pass more than 10,000 arguments or so.

In contrast, Array.from invokes the iterator of the array-like object. If the iterator doesn't exist, but the object has a length property, it will iterate from 0 up to the value of the length - 1 and create an array from those values. Here, since a Uint8Array has an iterator, that iterator is what gets invoked when you use Array.from.

Iterators don't have the same sort of size limit that argument lists have (unless they're spread into an argument list, or something similar). The iterator's .next method is called, returning a value to put into the array, until the iterator is exhausted. It's pretty similar to the following:

const arr = [0, 1, 2];

// Create a new array by iterating through arr's iterator
// just like Array.from is doing:
const newArr = [];
const iterator = arr[Symbol.iterator]();
let iterObj = iterator.next();
while (!iterObj.done) {
  newArr.push(iterObj.value);
  iterObj = iterator.next();
}
console.log(newArr);```

There are no limits on how long the iterator may be, either in the above code, or in Array.from.

So, if the iterable or array-like object you have is very large, constructing an array from it with Array.apply (or by spreading into the Array constructor) may throw an error, whereas using Array.from will not.

Body:
Array.apply calls Function.prototype.apply with a calling context (a this value) of Array. If the second parameter is an array-like object, it will call the Array constructor with all of the elements of that array-like object as arguments. Eg:

Array.apply(null, [1, 2, 3, 4])

results in, and is equivalent to

Array(1, 2, 3, 4)

But argument lists have a size limit. It depends on the engine, but it looks like you probably shouldn't try to pass more than 10,000 arguments or so.

In contrast, Array.from invokes the iterator of the array-like object. If the iterator doesn't exist, but the object has a length property, it will iterate from 0 up to the value of the length - 1 and create an array from those values. Here, since a Uint8Array has an iterator, that iterator is what gets invoked when you use Array.from.

Iterators don't have the same sort of size limit that argument lists have (unless they're spread into an argument list, or something similar). The iterator's .next method is called, returning a value to put into the array, until the iterator is exhausted. It's pretty similar to the following:

const arr = [0, 1, 2];

// Create a new array by iterating through arr's iterator
// just like Array.from is doing:
const newArr = [];
const iterator = arr[Symbol.iterator]();
let iterObj = iterator.next();
while (!iterObj.done) {
  newArr.push(iterObj.value);
  iterObj = iterator.next();
}
console.log(newArr);

There are no limits on how long the iterator may be, either in the above code, or in Array.from.

So, if the iterable or array-like object you have is very large, constructing an array from it with Array.apply (or by spreading into the Array constructor) may throw an error, whereas using Array.from will not.


问:
Determine gcc-toolchain version in clang++ preprocessor
According to cppreference, the gcc libstdc++ supports the parallelism TS. In layperson terms and for what's relevant for me that means #include <execution> works in g++ 9 and doesn't work in g++ 8 or before. In my source code I can handle this with

#if ( defined( __GNUC__ ) && __GNUC__ > 8 )
#  define can_use_std_execution
#  include <execution>
#endif
```

<p>For my clang++ builds, the availability of <code><execution></code> depends on the <code>--gcc-toolchain</code> that I use. So instead of checking the <code>__clang_major__</code>, I'd like to check the gcc libstdc++ version in the preprocessor.</p>

<p>As far as I see in this compiler-explorer example, <code>__GNUC__</code> is defined in clang but the compilation command is</p>

```-g -o /tmp/compiler-explorer-compiler120120-1672-4ffux6.smufm/output.s -mllvm --x86-asm-syntax=intel -S --gcc-toolchain=/opt/compiler-explorer/gcc-8.3.0 -fcolor-diagnostics -fno-crash-diagnostics /tmp/compiler-explorer-compiler120120-1672-4ffux6.smufm/example.cpp
```

i.e. the gcc toolchain is from gcc 8.3.0, but the value of __GNUC__ is 4.

What's a good way to query the gcc toolchain version in the preprocessor with clang? Ideally a way that checks the libstdc++ version in a way that's compatible for g++ and clang++ such that I don't have write a spaghetti if that checks the compiler first.

答:
Grepping for ^#.*define.*9 in the compiler headers of gcc 9 it seems that

#include <bits/c++config.h>
#if _GLIBCXX_RELEASE > 8
#  include <execution>
#endif
```

can do the job. From this conformance view this variable was introduced with the toolchain of gcc 7.

Body:
According to cppreference, the gcc libstdc++ supports the parallelism TS. In layperson terms and for what's relevant for me that means #include <execution> works in g++ 9 and doesn't work in g++ 8 or before. In my source code I can handle this with

#if ( defined( __GNUC__ ) && __GNUC__ > 8 )
#  define can_use_std_execution
#  include <execution>
#endif

For my clang++ builds, the availability of <execution> depends on the --gcc-toolchain that I use. So instead of checking the __clang_major__, I'd like to check the gcc libstdc++ version in the preprocessor.

As far as I see in this compiler-explorer example, __GNUC__ is defined in clang but the compilation command is

-g -o /tmp/compiler-explorer-compiler120120-1672-4ffux6.smufm/output.s -mllvm --x86-asm-syntax=intel -S --gcc-toolchain=/opt/compiler-explorer/gcc-8.3.0 -fcolor-diagnostics -fno-crash-diagnostics /tmp/compiler-explorer-compiler120120-1672-4ffux6.smufm/example.cpp

i.e. the gcc toolchain is from gcc 8.3.0, but the value of __GNUC__ is 4.

What's a good way to query the gcc toolchain version in the preprocessor with clang? Ideally a way that checks the libstdc++ version in a way that's compatible for g++ and clang++ such that I don't have write a spaghetti if that checks the compiler first.

Body:
Grepping for ^#.*define.*9 in the compiler headers of gcc 9 it seems that

#include <bits/c++config.h>
#if _GLIBCXX_RELEASE > 8
#  include <execution>
#endif

can do the job. From this conformance view this variable was introduced with the toolchain of gcc 7.


问:
Node JS Proper Content-Type for responses
Is there a reason that I should not be sending my content-type as binary for everything? I am a bit naive about proper http but it seems to work for everything. What are some of the pitfalls I will run into working this way?</p>

答:
If you send a stylesheet as Content Type binary, IE9 won't render it. It refuses to render any stylesheet that isn't text/css. That's probably enough to keep people from not visiting your site with IE9.

Not to mention the other benefits like the browser handling specific content types differently based on user preferences.

http://blogs.msdn.com/b/ieinternals/archive/2011/03/27/http-406-not-acceptable-php-ie9-standards-mode-accepts-only-text_2f00_css-for-stylesheets.aspx

Edit
Here, you can use this, it will make it easier to determine the content type. The module will have two methods. getExt and getContentType. If you pass the extension to getContentType it will return the Content-Type for that file. I'm not the one that compiled all the content types, unfortunately I forgot where I found it...

https://gist.github.com/976610


问:
Count and summation of positive and negative number sequences
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]
</code>```

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))
</code>```

result

```<code>        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046
</code>```

Body:
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)

python

x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}

python

sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))

result

        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046

Body:
In R, you could also do:

# DATA
set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)

library(data.table)
dt <- data.table(x = x)

# Create Positive or Negative variable
dt$x_logical <- ifelse(dt$x > 0, "P", "N")

# Create a reference data.frame/table to keep continuous counts
seq_dt <- data.frame(val = rle(x = dt$x_logical)$lengths)
seq_dt$id <- 1:nrow(seq_dt)

# Map id in the main data.table and get cumulative sum
dt$id <- rep(seq_dt$id, seq_dt$val)
dt[, csum := cumsum(x), by = "id"]

        x x_logical id   csum
 1: -0.010         N  1 -0.010
 2:  0.003         P  2  0.003
 3: -0.002         N  3 -0.002
 4:  0.018         P  4  0.018
 5:  0.002         P  4  0.020
 6:  0.006         P  4  0.026
 7: -0.012         N  5 -0.012
 8:  0.014         P  6  0.014
 9: -0.017         N  7 -0.017
10: -0.007         N  7 -0.024
11:  0.002         P  8  0.002
12:  0.002         P  8  0.004
13: -0.004         N  9 -0.004
14:  0.015         P 10  0.015
15:  0.002         P 10  0.017
16: -0.001         N 11 -0.001
17: -0.008         N 11 -0.009
18:  0.010         P 12  0.010
19: -0.018         N 13 -0.018
20:  0.046         P 14  0.046


问:
How to trigger CKEditor 5 image file system dialog from code?
How do you trigger the CKEditor 5 insert image file dialog/picker from code? I have the "imageUpload" toolbar button in place and it works, but it's the balloon editor so it's not visible until they select something. I'd like to create my own button that's always visible to make it easier.</p>

答:
It's impossible to trigger it from code at any given time. The event must be user-originated (e.g. by a click listener).

If you, however, want to have a button outside the editor which will trigger this logic, you can use the button delivered by CKEditor 5 in ImageUploadUI. Just do this:

```<code>const imageUploadButton = editor.ui.componentFactory.create( 'imageUpload', editor.locale );
imageUploadButton.render();
imageUploadButton.element; // The element that you can insert somewhere in your view.
</code>```

Body:
It's impossible to trigger it from code at any given time. The event must be user-originated (e.g. by a click listener).

If you, however, want to have a button outside the editor which will trigger this logic, you can use the button delivered by CKEditor 5 in ImageUploadUI. Just do this:

const imageUploadButton = editor.ui.componentFactory.create( 'imageUpload', editor.locale );
imageUploadButton.render();
imageUploadButton.element; // The element that you can insert somewhere in your view.


问:
Test with many variables: I looking for quick method to introduce each variable in the test
I have some data and I need to compare the average but I am looking for quick method to introduce each sample in the test.

```<code>from scipy import stats

my_variables = ["a","b","c"]
my_variables[0] = [1,2,3]
my_variables[1] = [0,1,2]
my_variables[2] = [2,3,4]

Kruskal_Wallis_test= stats.kruskal(my_variables[0], my_variables[1], my_variables[2])
</code>```

Would be it possible doing something like this?

```<code>Kruskal_Wallis_test= stats.kruskal(my_variables)
</code>```

答:
The * is used to unpack the argument list when the function is called, in this case it upacks your my_variables list.

Here is how you should use * operator in your code,

```<code>Kruskal_Wallis_test = stats.kruskal(*my_variables)
</code>```

which is identical to calling,

```<code>Kruskal_Wallis_test= stats.kruskal(my_variables[0], my_variables[1], my_variables[2])
</code>```

Body:
I have some data and I need to compare the average but I am looking for quick method to introduce each sample in the test.

from scipy import stats

my_variables = ["a","b","c"]
my_variables[0] = [1,2,3]
my_variables[1] = [0,1,2]
my_variables[2] = [2,3,4]

Kruskal_Wallis_test= stats.kruskal(my_variables[0], my_variables[1], my_variables[2])

Would be it possible doing something like this?

Kruskal_Wallis_test= stats.kruskal(my_variables)

Body:
The * is used to unpack the argument list when the function is called, in this case it upacks your my_variables list.

Here is how you should use * operator in your code,

Kruskal_Wallis_test = stats.kruskal(*my_variables)

which is identical to calling,

Kruskal_Wallis_test= stats.kruskal(my_variables[0], my_variables[1], my_variables[2])


问:
Joomla Random image module with recursive search for images
I'd love to have a random image module which uses recursion while searching for images so that the random image would be from the directory I've chosen or its subdirectiories. I have found Random Image Plus but it's for Joomla 1.5 not 1.6 which I'm using. Could you tell me if there are other modules for Joomla 1.6 or if the Random Image Plus module could be easily upgraded to be 1.6 compatible?</p>

答:
There are so many image plugins, recursive perhaps not but i guess you will find quite many. Perhaps its good to know that 16native is the search query in the extension diretory for joomla 1.6 plugins. Try

http://extensions.joomla.org/search?q=random+image+16native

(66 hits)


问:
Better way to dynamically access values in nested array
I need a way to dynamically access values in a nested array using an index map. What i want to achieve is looping over an array with data and extract some values that can be in any level of the nesting and save it to a bi-dimensional array.
So far I've come up with the following code, which works quite well, but I was wondering if there is a more efficient way to do this.

```<code><?php
// Sample data
$array = array();
$array[0]['code'] = "ABC123";
$array[0]['ship'] = array("name" => "Fortune", "code" => 'FA');
$array[0]['departure'] = array("port" => "Amsterdam", "code" => "AMS");
$array[0]['document'] = array("type" => "Passport", "data" => array("valid" => '2022-03-18', 'number' => 'AX123456') );
$array[1]['code'] = "QWERT67";
$array[1]['ship'] = array("name" => "Dream", "code" => 'DR');
$array[1]['departure'] = array("port" => "Barcelona", "code" => "BRC");
$array[1]['document'] = array("type" => "Passport", "data" => array("valid" => '2024-12-09', 'number' => 'DF908978') );

// map of indexes of $array I need in my final result array. The levels of the nested indexes is subdivided by ":"
$map = array("code", "ship:name", "departure:port", "document:type", "document:data:number");

$result = array();

// loop array for rows of data
foreach($array as $i => $row){
    // loop map for indexes
    foreach($map as $index){
        // extract specific nested values from $row and save them in 2-dim array $result
        $result[$i][$index] = xpath_array($index, $row);
    }
}

// print out result
print_r($result);

// takes path to value in $array and returns given value
function xpath_array($xpath, $array){
    $tmp = array();
    // path is subdivded by ":"
    $elems = explode(":", $xpath);
    foreach($elems as $i => $elem){
        // if first (or ony) iteration take root value from array and put it in $tmp
        if($i == 0){
            $tmp = $array[$elem];
        }else{
            // other iterations (if any) dig in deeper into the nested array until last item is reached
            $tmp = $tmp[$elem];
        }
    }
    // return found item (can be value or array)
    return $tmp;
}
</code>```

Any suggestion?

答:
This was quite tricky for me, i used Recursive function, first we normalize array keys to obtain key as you want like this document:type, then we normalize array to obtain all at same level :

```<code>/**
 * @param array $array
 * @param string|null $key
 *
 * @return array
 */
function normalizeKey(array $array, ?string $key = ''): array
{
    $result = [];
    foreach ($array as $k => $v) {
        $index = !empty($key) && !\is_numeric($key) ? $key.':'.$k : $k;
        if (true === \is_array($v)) {
            $result[$k] = normalizeKey($v, $index);
            continue;
        }

        $result[$index] = $v;
    }

    return $result;
}

/**
 * @param array $item
 * @param int $level
 *
 * @return array
 */
function normalizeStructure(array $item, int $level = 0): array
{
    foreach ($item as $k => $v) {
        $level = isset($v['code']) ? 0 : $level;
        if (true === \is_array($v) && 0 === $level) {
            $item[$k] = normalizeStructure($v, ++$level);
            continue;
        }

        if (true === \is_array($v) && 0 < $level) {
            $item = \array_merge($item, normalizeStructure($v, ++$level));
            unset($item[$k]);
            continue;
        }
    }

    return $item;
}

$data = normalizeStructure(normalizeKey($array));
</code>```

I edited your data set to add more nests:

```<code>// Sample data
$array = array();
$array[0]['code'] = "ABC123";
$array[0]['ship'] = array("name" => "Fortune", "code" => 'FA');
$array[0]['departure'] = array("port" => "Amsterdam", "code" => "AMS");
$array[0]['document'] = array("type" => "Passport", "data" => array("valid" => '2022-03-18', 'number' => 'AX123456'));
$array[1]['code'] = "QWERT67";
$array[1]['ship'] = array("name" => "Dream", "code" => 'DR');
$array[1]['departure'] = array("port" => "Barcelona", "code" => "BRC");
$array[1]['document'] = array("type" => "Passport", "data" => array("valid" => '2024-12-09', 'number' => 'DF908978', 'check' => ['number' => '998', 'code' => 'itsWell', 'inception' => ['border' => 'finalInception']]));
</code>```

With these data, you should finally receive this result:

```<code>/*
Array
(
    [0] => Array
        (
            [code] => ABC123
            [ship:name] => Fortune
            [ship:code] => FA
            [departure:port] => Amsterdam
            [departure:code] => AMS
            [document:type] => Passport
            [document:data:valid] => 2022-03-18
            [document:data:number] => AX123456
        )

    [1] => Array
        (
            [code] => QWERT67
            [ship:name] => Dream
            [ship:code] => DR
            [departure:port] => Barcelona
            [departure:code] => BRC
            [document:type] => Passport
            [document:data:valid] => 2024-12-09
            [document:data:number] => DF908978
            [document:data:check:number] => 998
            [document:data:check:code] => itsWell
            [document:data:check:inception:border] => finalInception
        )

)
*/
</code>```

Recursivity seems to be like Inception, everything is nested and you can lose your mind in , mine was already lost in.

Body:
I need a way to dynamically access values in a nested array using an index map. What i want to achieve is looping over an array with data and extract some values that can be in any level of the nesting and save it to a bi-dimensional array.
So far I've come up with the following code, which works quite well, but I was wondering if there is a more efficient way to do this.

<?php
// Sample data
$array = array();
$array[0]['code'] = "ABC123";
$array[0]['ship'] = array("name" => "Fortune", "code" => 'FA');
$array[0]['departure'] = array("port" => "Amsterdam", "code" => "AMS");
$array[0]['document'] = array("type" => "Passport", "data" => array("valid" => '2022-03-18', 'number' => 'AX123456') );
$array[1]['code'] = "QWERT67";
$array[1]['ship'] = array("name" => "Dream", "code" => 'DR');
$array[1]['departure'] = array("port" => "Barcelona", "code" => "BRC");
$array[1]['document'] = array("type" => "Passport", "data" => array("valid" => '2024-12-09', 'number' => 'DF908978') );

// map of indexes of $array I need in my final result array. The levels of the nested indexes is subdivided by ":"
$map = array("code", "ship:name", "departure:port", "document:type", "document:data:number");

$result = array();

// loop array for rows of data
foreach($array as $i => $row){
    // loop map for indexes
    foreach($map as $index){
        // extract specific nested values from $row and save them in 2-dim array $result
        $result[$i][$index] = xpath_array($index, $row);
    }
}

// print out result
print_r($result);

// takes path to value in $array and returns given value
function xpath_array($xpath, $array){
    $tmp = array();
    // path is subdivded by ":"
    $elems = explode(":", $xpath);
    foreach($elems as $i => $elem){
        // if first (or ony) iteration take root value from array and put it in $tmp
        if($i == 0){
            $tmp = $array[$elem];
        }else{
            // other iterations (if any) dig in deeper into the nested array until last item is reached
            $tmp = $tmp[$elem];
        }
    }
    // return found item (can be value or array)
    return $tmp;
}

Any suggestion?

Body:
This was quite tricky for me, i used Recursive function, first we normalize array keys to obtain key as you want like this document:type, then we normalize array to obtain all at same level :

/**
 * @param array $array
 * @param string|null $key
 *
 * @return array
 */
function normalizeKey(array $array, ?string $key = ''): array
{
    $result = [];
    foreach ($array as $k => $v) {
        $index = !empty($key) && !\is_numeric($key) ? $key.':'.$k : $k;
        if (true === \is_array($v)) {
            $result[$k] = normalizeKey($v, $index);
            continue;
        }

        $result[$index] = $v;
    }

    return $result;
}

/**
 * @param array $item
 * @param int $level
 *
 * @return array
 */
function normalizeStructure(array $item, int $level = 0): array
{
    foreach ($item as $k => $v) {
        $level = isset($v['code']) ? 0 : $level;
        if (true === \is_array($v) && 0 === $level) {
            $item[$k] = normalizeStructure($v, ++$level);
            continue;
        }

        if (true === \is_array($v) && 0 < $level) {
            $item = \array_merge($item, normalizeStructure($v, ++$level));
            unset($item[$k]);
            continue;
        }
    }

    return $item;
}

$data = normalizeStructure(normalizeKey($array));

I edited your data set to add more nests:

// Sample data
$array = array();
$array[0]['code'] = "ABC123";
$array[0]['ship'] = array("name" => "Fortune", "code" => 'FA');
$array[0]['departure'] = array("port" => "Amsterdam", "code" => "AMS");
$array[0]['document'] = array("type" => "Passport", "data" => array("valid" => '2022-03-18', 'number' => 'AX123456'));
$array[1]['code'] = "QWERT67";
$array[1]['ship'] = array("name" => "Dream", "code" => 'DR');
$array[1]['departure'] = array("port" => "Barcelona", "code" => "BRC");
$array[1]['document'] = array("type" => "Passport", "data" => array("valid" => '2024-12-09', 'number' => 'DF908978', 'check' => ['number' => '998', 'code' => 'itsWell', 'inception' => ['border' => 'finalInception']]));

With these data, you should finally receive this result:

/*
Array
(
    [0] => Array
        (
            [code] => ABC123
            [ship:name] => Fortune
            [ship:code] => FA
            [departure:port] => Amsterdam
            [departure:code] => AMS
            [document:type] => Passport
            [document:data:valid] => 2022-03-18
            [document:data:number] => AX123456
        )

    [1] => Array
        (
            [code] => QWERT67
            [ship:name] => Dream
            [ship:code] => DR
            [departure:port] => Barcelona
            [departure:code] => BRC
            [document:type] => Passport
            [document:data:valid] => 2024-12-09
            [document:data:number] => DF908978
            [document:data:check:number] => 998
            [document:data:check:code] => itsWell
            [document:data:check:inception:border] => finalInception
        )

)
*/

Recursivity seems to be like Inception, everything is nested and you can lose your mind in , mine was already lost in.


问:
Using v-for in laravel + vue.js, am trying to display a table containing information of the user but nothing shows
```<code><script>
    export default {
        name: "OutPatient",
        data(){
            return{
                out_patients: {}
            }
        },
        methods: {
                index(){
                        axios.get('/data/out_patient').then(({data}) =>
                                (this.out_patients = data.data));

                },
                update(){}
        },
        created(){
                this.index();
        }

    }
</script>

<tr v-for="out_patient in out_patients" v-bind:key="out_patient.id">
    <td>{{out_patient.id}}</td>
    <td>{{out_patient.first_name}}</td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td>
      <a href="#"><i class="fa fa-edit blue"></i></a>
      |
      <a href="#"><i class="fa fa-trash red"></i></a>
    </td>
</tr>

</code>```

This is my code but the data is not showing in the table even though in the XHR the data shows there.

In the inspect element I can see the data but the v-for loop is unable to display the data.

答:
```<code><script>
export default {
    name: "OutPatient",
    data(){
        return{
            out_patients: {},
            out_patient:'',
        }
    },
    methods: {
           index(){
                 axios.get('/data/out_patient')
                     .then(({data}) =>
                         (this.out_patients = data.data));

           },
            update(){

            }
        },
    created(){
        this.index();
    }
}
</script>

<tr v-for="out_patient in out_patients" v-bind:key="out_patient.id">
    <td>{{out_patient.id}}</td>
    <td>{{out_patient.first_name}}</td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td>
        <a href="#">
            <i class="fa fa-edit blue"></i>
        </a>
        |
        <a href="#">
            <i class="fa fa-trash red"></i>
        </a>
    </td>
</tr>
</code>```

Just declare out_patient in data. I hope this solves your issue.
And also check if out_patients is returning data.

Body:
    {{out_patient.id}}
    {{out_patient.first_name}}

      |

This is my code but the data is not showing in the table even though in the XHR the data shows there.

In the inspect element I can see the data but the v-for loop is unable to display the data.

Body:
<script>
export default {
    name: "OutPatient",
    data(){
        return{
            out_patients: {},
            out_patient:'',
        }
    },
    methods: {
           index(){
                 axios.get('/data/out_patient')
                     .then(({data}) =>
                         (this.out_patients = data.data));

           },
            update(){

            }
        },
    created(){
        this.index();
    }
}
</script>

<tr v-for="out_patient in out_patients" v-bind:key="out_patient.id">
    <td>{{out_patient.id}}</td>
    <td>{{out_patient.first_name}}</td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td>
        <a href="#">
            <i class="fa fa-edit blue"></i>
        </a>
        |
        <a href="#">
            <i class="fa fa-trash red"></i>
        </a>
    </td>
</tr>

Just declare out_patient in data. I hope this solves your issue.
And also check if out_patients is returning data.


问:
How to list all producers of a kafka cluster?
I am able to list all Kafka Consumer with KafkaAdminClient:

```<code>AdminClient client = AdminClient.create(conf);
ListTopicsResult ltr = client.listTopics();
KafkaFuture<Set<String>> names = ltr.names();

ArrayList<ConsumerGroupListing> consumerGroups = new ArrayList<>(client.listConsumerGroups().all().get());
ConsumerGroupListing consumerGroup = consumerGroups.get(0);
</code>```

Is it possible to list all registrated producers in a similar way?

答: In contrast to consumers, it is not possible to retrieve such information since Kafka brokers don't store any kind of information about the producers connected to them.

Body:
I am able to list all Kafka Consumer with KafkaAdminClient:

AdminClient client = AdminClient.create(conf);
ListTopicsResult ltr = client.listTopics();
KafkaFuture<Set<String>> names = ltr.names();

ArrayList<ConsumerGroupListing> consumerGroups = new ArrayList<>(client.listConsumerGroups().all().get());
ConsumerGroupListing consumerGroup = consumerGroups.get(0);

Is it possible to list all registrated producers in a similar way?


问:
How do I search results from jquery GET
I'm having a bit of a problem investigating the result from my get in my script. I got the following code to check if a user is still logged in:

```<code>$.get("nowhereGet", function(result){
    if($(result).find('[id="loginInput"]'))
    {
        //HTML is in the response then we have been logged out and the user needs to go to
        window.location.href = "login";
    }
    });
</code>```

Now if the user is logged in Struts will return one html-page in result from my get. If the user has been logged out different page will be returned one with and element id="loginInput"in it.

I thought the above would do the trick but no love. What am I doing wrong?

Is there a better way to do this than to ping the server with a random get? I need a method that performes this check using ajax and any get or post done while logged out will get intercepted and the result will be the login-page instead of the intended page

答:
$('#result').get(......); ???

UPDATE
so the element #result would have what ever the #loginInput has

$('#result').load('login.php #loginInput');

Otherwise look for a json option because the way you are doing it, its kinda messy

Unless you are looking for this

```<code>$.get("nowhereGet", function(result){
    if(result && $(result).find('#loginInput').length)
    {
        //HTML is in the response then we have been logged out and the user needs to go to
        window.location.href = "login";
    }
    });
</code>```

Title: How do I search results from jquery GET

Body:
I'm having a bit of a problem investigating the result from my get in my script. I got the following code to check if a user is still logged in:

$.get("nowhereGet", function(result){
    if($(result).find('[id="loginInput"]'))
    {
        //HTML is in the response then we have been logged out and the user needs to go to
        window.location.href = "login";
    }
    });

Now if the user is logged in Struts will return one html-page in result from my get. If the user has been logged out different page will be returned one with and element id="loginInput"in it.

I thought the above would do the trick but no love. What am I doing wrong?

Is there a better way to do this than to ping the server with a random get? I need a method that performes this check using ajax and any get or post done while logged out will get intercepted and the result will be the login-page instead of the intended page

Body:
$('#result').get(......); ???

UPDATE
so the element #result would have what ever the #loginInput has

$('#result').load('login.php #loginInput');

Otherwise look for a json option because the way you are doing it, its kinda messy

Unless you are looking for this

$.get("nowhereGet", function(result){
    if(result && $(result).find('#loginInput').length)
    {
        //HTML is in the response then we have been logged out and the user needs to go to
        window.location.href = "login";
    }
    });


问:
Pass some instructions to a function
I'm trying to deduplicate a js code of major of form that do an ajax request, I initially do a php function that generate any form onsubmit function passing the different code as parameters but don't seems good.
After I tried to a javascript function instead, for simple variables I did it working, for example:

```<code>// <script> inside of the page generate by php (and in some cases in html received by other ajax request)
$('#f_man-marker_edit-marker').on('submit', function(e){
    TM.editMarker(e, $(this), 'man-marker_edit-marker');
});

...
// in other js file
TM.editMarker = function (e, form, ajax_request) {
    // stop browser from submitting form!
    e.preventDefault();

    // Abort any pending request
    if (request) request.abort();

    // Let's select and cache all the fields
    let inputs = form.find("input, select, button, textarea");

    // Serialize the data in the form
    let serializedData = form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    inputs.prop("disabled", true);

    request = $.ajax({
        url: "ajax.php?req=" + ajax_request,
        type: "post",
        data: serializedData,
        dataType: "html"
    });

    request.done(function (response) {
        $("#ajaxoutput2").empty().append(response);
        $("#ResultModal2").modal("show");
    });

    request.fail(function (jqXHR, textStatus, errorThrown) {
        console.error(
            "Ajax " + ajax_request + " request failed. The following error occurred: " +
            textStatus, errorThrown
        );
    });

    request.always(function () {
        inputs.prop("disabled", false);
    });

};
</code>```

Now is missed pass request.done instructions as parameter but I not found a good and working way to do it.
Put them in a function gave me the variable response not defined, also adding it as parameter.
More exactly I tried:

```<code>$('#f_man-marker_edit-marker').on('submit', function(e){
                    let req_done = function (response) {
                        $("#ajaxoutput2").empty().append(response);
                        $("#ResultModal2").modal("show");
                    };
                    TM.editMarker(e, $(this), 'man-marker_edit-marker', req_done());
                });

...
// in other js file
TM.editMarker = function (e, form, ajax_request, req_done()) {
...
    request.done(function (response) {
        req_done(response);
    });
...
};

</code>```

Thas is not working.
Is possible to pass the instructions as they are and have them working or must be in a function? If must be in a function what is the right way to do it? Probably is possibile with eval() but seems highly discouraged and I not tried it for now.

EDIT:
I try to explain better: what I try to do is have a php or js function to call and pass as parameters the only things that changes, for example on on hundreds of similar forms that I will do on the project it will be fine there will be thousands or tens of thousands of lines of duplicate code avoided and a possible refactor or future improvements much simpler and faster.
I started with a generation from php, for example:

```<code>...
// "f_man-marker_add-marker" is the id of the form, "man-marker_add-marker" is the id of the ajax request, $man_marker_jap1 contain that instructions printed inside of request.done function (they can be different on any form)

TM\UI\JSHelper::jqueryAjaxPost(
            "f_man-marker_add-marker", "man-marker_add-marker", $man_marker_jap1);

.....
// in the file of TM\UI\JSHelper:

...
/**
     * Generate a jquery ajax of type post and datatype html
     * will call the url ajax.php?req=$request_name
     * and request.done will do what define in $done_content
     *
     * @param string $form_id Id of the form
     * @param string $request_name Name of the ajax request parameter
     * @param string $done_content Content of request.done
     */
    public static function jqueryAjaxPost(string $form_id, string $request_name, string $done_content){
        echo <<<HTML

$("#$form_id").submit(function(event){

    // Prevent default posting of form - put here to work in case of errors
    event.preventDefault();

    // Abort any pending request
    if (request) { request.abort(); }

    let form = $(this);

    // Let's select and cache all the fields
    let inputs = form.find("input, select, button, textarea");

    // Serialize the data in the form
    let serializedData = form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    inputs.prop("disabled", true);

    request = $.ajax({
        url: "ajax.php?req=$request_name",
        type: "post",
        data: serializedData,
        dataType: "html"
    });

    request.done(function (response){
        $done_content
    });

    request.fail(function (jqXHR, textStatus, errorThrown){
        console.error(
            "Ajax $request_name request failed. The following error occurred: "+
            textStatus, errorThrown
        );
    });

    request.always(function () {
        inputs.prop("disabled", false);
    });

});

HTML;
    }
</code>```

but not have js "issue" (if done correctly) because the generated code is specific per form and "full js" without call to other external functions.
I then thinked to do it mainly in js only file (which to logic would seem more correct rather generate all the js from php) and was ok except of the content of request.done that must change, so I open this post to aswer what is the best and correct way to do it.
If instead there is no better method to do what I need mainly in js and the less worst seems to remain in the php generation tell me.

EDIT2:
I did other tests and found a working solution without using eval (I don't know if good):

```<code>// inside a <script> of part of page generated by php or html code received from ajax request
$('#f_man-marker_edit-marker').on('submit', function(e){
    let req_done = function (response) {
        $("#ajaxoutput2").empty().append(response);
        $("#ResultModal2").modal("show");
    };
    TM.jqueryAjaxPost(e, $(this), 'man-marker_edit-marker', req_done);
});

...
// in other js-only file
/**
 * Basic jquery ajax request of type post from form
 * where changes only request.done content
 * @param e Event received from onsubmit of the form
 * @param form Receive the element with $(this)
 * @param ajax_request Name of the ajax request send to php
 * @param req_done Instruction to do on request.done
 */
TM.jqueryAjaxPost = function (e, form, ajax_request, req_done) {

    // stop browser from submitting form!
    e.preventDefault();

    // Abort any pending request
    if (request) request.abort();

    // Let's select and cache all the fields
    let inputs = form.find("input, select, button, textarea");

    // Serialize the data in the form
    let serializedData = form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    inputs.prop("disabled", true);

    request = $.ajax({
        url: "ajax.php?req=" + ajax_request,
        type: "post",
        data: serializedData,
        dataType: "html"
    });

    request.done(function (response) {
        req_done(response);
    });

    request.fail(function (jqXHR, textStatus, errorThrown) {
        console.error(
            "Ajax " + ajax_request + " request failed. The following error occurred: " +
            textStatus, errorThrown
        );
    });

    request.always(function () {
        inputs.prop("disabled", false);
    });

};
</code>```

Is this good or is there a better way to do it and/or possible improvement?

EDIT3:
I tried also to do something working with additional parameters:

```<code>TM.deleteMarker = function (id) {
    let req_done = function (response, parArray) {
        $("#ajaxoutput").empty().append(response);
        $('#link_open-marker' + parArray[id]).remove();
    };
    TM.jqueryAjaxGet('man-marker_delete-marker&id=' + id, req_done, {id: id});
};

/**
 * Basic jquery ajax request of method get and datatype html
 * @param ajax_request Name of the ajax request send to php and get parameters, it will be
 * will be added to the end of the url
 * @param req_done Instruction to do on request.done
 * @param parArray Additional parameters used in req_done
 */
TM.jqueryAjaxGet = function (ajax_request, req_done, parArray = {}) {
    // Abort any pending request
    if (request) {
        request.abort();
    }

    request = $.ajax({
        url: "ajax.php?req=" + ajax_request,
        method: "get",
        dataType: "html"
    });

    request.done(function (response) {
        req_done(response, parArray);
    });

    request.fail(function (jqXHR, textStatus, errorThrown) {
        console.error(
            "Ajax " + ajax_request + " request failed. The following error occurred: " +
            textStatus, errorThrown
        );
    });
};
</code>```

don't gave errors or warning and work all except

```<code>$('#link_open-marker' + parArray[id]).remove();
</code>```

so I suppose I did something wrong about parArray but I not undestand what, Can someone help me to solve (or do in a different way if not good this) please?

Thanks for any reply and sorry for my bad english.

答:
I'm not quite sure if i understood your question right, but if its about getting a done callback outside of your method you have two possible ways of doing that.

Use closures:

```<code>TM.editMarker = function (e, form, ajax_request, doneHandler) {
   ...

   request.done(function (response) {
        $("#ajaxoutput2").empty().append(response);
        $("#ResultModal2").modal("show");

        if(doneHandler !== undefined)
             doneHandler();
    });
}

TM.editMarker(e, $(this), 'man-marker_edit-marker', function() {
   console.log("done");
});
</code>```

Use promises:

```<code>TM.editMarker = function (e, form, ajax_request) {
   ...

   var prom= jQuery.Deferred();
   request.done(function (response) {
        $("#ajaxoutput2").empty().append(response);
        $("#ResultModal2").modal("show");

        prom.resolve();
    });

    return prom.promise();
}

TM.editMarker(e, $(this), 'man-marker_edit-marker').then(function() {
   console.log("done");
});
</code>```

Answer on edit:

Ok, so what you are trying to do is executing a javascript function through the ajax response. You could achieve this by doing something like this:

```<code>$.ajax({
    url: "somejs.js",
    context: document.body,
    success: function(responseText) {
        eval(responseText);
    }
});
</code>```

However this is really dirty and not good practice because javascript is usually UI manipulating commands. Keep the UI stuff in the frontend and only return raw data / json from your backend. Can you give me an example of what the response looks like then I can give you an example of how I would solve it.

Title: Pass some instructions to a function

Body:
I'm trying to deduplicate a js code of major of form that do an ajax request, I initially do a php function that generate any form onsubmit function passing the different code as parameters but don't seems good.
After I tried to a javascript function instead, for simple variables I did it working, for example:

//

Body:
I'm not quite sure if i understood your question right, but if its about getting a done callback outside of your method you have two possible ways of doing that.

Use closures:

TM.editMarker = function (e, form, ajax_request, doneHandler) {
   ...

   request.done(function (response) {
        $("#ajaxoutput2").empty().append(response);
        $("#ResultModal2").modal("show");

        if(doneHandler !== undefined)
             doneHandler();
    });
}

TM.editMarker(e, $(this), 'man-marker_edit-marker', function() {
   console.log("done");
});

Use promises:

TM.editMarker = function (e, form, ajax_request) {
   ...

   var prom= jQuery.Deferred();
   request.done(function (response) {
        $("#ajaxoutput2").empty().append(response);
        $("#ResultModal2").modal("show");

        prom.resolve();
    });

    return prom.promise();
}

TM.editMarker(e, $(this), 'man-marker_edit-marker').then(function() {
   console.log("done");
});

Answer on edit:

Ok, so what you are trying to do is executing a javascript function through the ajax response. You could achieve this by doing something like this:

$.ajax({
    url: "somejs.js",
    context: document.body,
    success: function(responseText) {
        eval(responseText);
    }
});

However this is really dirty and not good practice because javascript is usually UI manipulating commands. Keep the UI stuff in the frontend and only return raw data / json from your backend. Can you give me an example of what the response looks like then I can give you an example of how I would solve it.


问:
How to create the Tables2 class dynamically
In the tables.py in the example dir there is:

```<code>class Bootstrap4Table(tables.Table):
    country = tables.Column(linkify=True)
    continent = tables.Column(accessor="country__continent", linkify=True)
    class Meta:
        model = Person
        template_name = "django_tables2/bootstrap4.html"
        attrs = {"class": "table table-hover"}
        exclude = ("friendly",)
</code>```

I am trying to create a table class dynamically, so I did:
Override the get_table method like so:

```<code>def get_table(self, **kwargs):
    """
    Return a table object to use. The table has automatic support for
    sorting and pagination.
    """
    table_class, table_data = type('QueryTable', (tables.Table), myTableCol), mylist
    table_class = table_class
    print(table_class, table_data)
    table = table_class(data=table_data, **kwargs)
    return RequestConfig(self.request, paginate=self.get_table_pagination(table)).configure(table)
</code>```

Where the table_class, table_data is where I am creating the class. myTableCol provides the columns and mylist provides the data for each column. My problem is I dont know how to include the template_name = "django_tables2/bootstrap4.html" when I am dynamically creating the table class.
Also, when i do it this way, the tables dont show any borders.

I am pulling data from a rdf graph and I don't know the name or number of columns, so I want to dynamically create the columns along with having the Meta class with template_name = "django_tables2/bootstrap4.html.

答:
I figured it out by going through the /django_tables2/tables.py.

So, I first created a Meta class to serve as the inner class to the class that I wanted to create:

```<code>Meta = type('Meta', (object,), {'template_name':"django_tables2/bootstrap4.html", 'attrs':{"class": "paleblue"},})
</code>```

I then append this class to the myTableCol (I need to change the name) dictionary like myTableCol.update({'Meta':Meta}).

Next, I created the class that I wanted:

```<code>QueryTable2=type('QueryTable', (tables.Table,), myTableCol)
</code>```

The reason why I had to update the dictionary of the column names is that lines 34-39 in /django_tables2/tables.py of the DeclarativeColumnsMetaclass class loops over the attributes of the class and checks if the items in the myTableCol are instances of a Column. If true the key and value are appended to a list of dictionaries, if not they are added to a another dictionary as key/value pairs.

So, I updated my get_table like:

```<code>def get_table(self, **kwargs):
    """
    Return a table object to use. The table has automatic support for
    sorting and pagination.
    """
    ....
    other processing
    ....

    Meta = type('Meta', (object,), {'template_name':"django_tables2/bootstrap4.html", 'attrs':{"class": "paleblue"},})
    myTableCol.update({'Meta':Meta})
    QueryTable2=type('QueryTable', (tables.Table,), myTableCol)
    table_class, table_data =  QueryTable2, mylist
    table_class = table_class
    print(table_class, table_data)
    table = table_class(data=table_data, **kwargs)
    return RequestConfig(self.request, paginate=self.get_table_pagination(table)).configure(table)
</code>```

Body:
In the tables.py in the example dir there is:

class Bootstrap4Table(tables.Table):
    country = tables.Column(linkify=True)
    continent = tables.Column(accessor="country__continent", linkify=True)
    class Meta:
        model = Person
        template_name = "django_tables2/bootstrap4.html"
        attrs = {"class": "table table-hover"}
        exclude = ("friendly",)

I am trying to create a table class dynamically, so I did:
Override the get_table method like so:

def get_table(self, **kwargs):
    """
    Return a table object to use. The table has automatic support for
    sorting and pagination.
    """
    table_class, table_data = type('QueryTable', (tables.Table), myTableCol), mylist
    table_class = table_class
    print(table_class, table_data)
    table = table_class(data=table_data, **kwargs)
    return RequestConfig(self.request, paginate=self.get_table_pagination(table)).configure(table)

Where the table_class, table_data is where I am creating the class. myTableCol provides the columns and mylist provides the data for each column. My problem is I dont know how to include the template_name = "django_tables2/bootstrap4.html" when I am dynamically creating the table class.
Also, when i do it this way, the tables dont show any borders.

I am pulling data from a rdf graph and I don't know the name or number of columns, so I want to dynamically create the columns along with having the Meta class with template_name = "django_tables2/bootstrap4.html.

Body:
I figured it out by going through the /django_tables2/tables.py.

So, I first created a Meta class to serve as the inner class to the class that I wanted to create:

Meta = type('Meta', (object,), {'template_name':"django_tables2/bootstrap4.html", 'attrs':{"class": "paleblue"},})

I then append this class to the myTableCol (I need to change the name) dictionary like myTableCol.update({'Meta':Meta}).

Next, I created the class that I wanted:

QueryTable2=type('QueryTable', (tables.Table,), myTableCol)

The reason why I had to update the dictionary of the column names is that lines 34-39 in /django_tables2/tables.py of the DeclarativeColumnsMetaclass class loops over the attributes of the class and checks if the items in the myTableCol are instances of a Column. If true the key and value are appended to a list of dictionaries, if not they are added to a another dictionary as key/value pairs.

So, I updated my get_table like:

def get_table(self, **kwargs):
    """
    Return a table object to use. The table has automatic support for
    sorting and pagination.
    """
    ....
    other processing
    ....

    Meta = type('Meta', (object,), {'template_name':"django_tables2/bootstrap4.html", 'attrs':{"class": "paleblue"},})
    myTableCol.update({'Meta':Meta})
    QueryTable2=type('QueryTable', (tables.Table,), myTableCol)
    table_class, table_data =  QueryTable2, mylist
    table_class = table_class
    print(table_class, table_data)
    table = table_class(data=table_data, **kwargs)
    return RequestConfig(self.request, paginate=self.get_table_pagination(table)).configure(table)


问:
Merging Errors: Error: Attribute application@appComponentFactory in android 28.0.3
Merging Errors: Error: Attribute application@appComponentFactory value=(androidx.core.app.CoreComponentFactory) from AndroidManifest.xml:22:18-86 is also present at AndroidManifest.xml:22:18-91 value=(android.support.v4.app.CoreComponentFactory). Suggestion: add 'tools:replace="android:appComponentFactory"' to  element at AndroidManifest.xml:39:5-738:19 to override.

in android 28.0.3  i want solution without migrating androidx. thanks in advance.

答:
As it's suggested why you don't add

```<code>android:appComponentFactory="android.support.v4.app.CoreComponentFactory"
tools:replace="android:appComponentFactory"
</code>```

to mainfest application tag.and if you want to use suport library rather than androidx please don't try to use libraries that use androidx.

Body:
As it's suggested why you don't add

android:appComponentFactory="android.support.v4.app.CoreComponentFactory"
tools:replace="android:appComponentFactory"

to mainfest application tag.and if you want to use suport library rather than androidx please don't try to use libraries that use androidx.


问:
unable to apply css styles to an svg image embedded in a div tag.?
Hi I am having an angular 5 project . I am drawing an bar graph using d3js library. In my bar graph there are vertical bars to which I would like to apply styles. However it is not working as the bars are displayed with default black colour as show below.

The following is my component html code, where i have a div tag named "histogramHolder" to which i will append the svg from my component ts file.

```<code>performance.component.html

    <div class="row">

      <div class="col-1"></div>
      <div class="col-10"  id="histogramHolder">
      </div>
      <div class="col-2">  </div>
     </div>
</code>```

the following is my component scss file.

```<code>performance.component.scss

    .bar {
        fill: steelblue;
    }
</code>```

the following is the code snippet where i create an svg image and append to the div tag named "histogramHolder"

```<code>import * as d3 from "d3";
@Component({
  selector: 'pc-performance',
  templateUrl: './performance.component.html',
  styleUrls: ['./performance.component.scss']
})
export class PerformanceComponent implements OnInit {

  ngOnInit() {

  const data=[{"key":"2019-09-11","documentCount":149002},{"key":"2019-09-12","documentCount":0},{"key":"2019-09-13","documentCount":80000},{"key":"2019-09-14","documentCount":0},{"key":"2019-09-15","documentCount":0},{"key":"2019-09-16","documentCount":0},{"key":"2019-09-17","documentCount":0},{"key":"2019-09-18","documentCount":270204},{"key":"2019-09-19","documentCount":0},{"key":"2019-09-20","documentCount":1},{"key":"2019-09-21","documentCount":0},{"key":"2019-09-22","documentCount":0},{"key":"2019-09-23","documentCount":269836},{"key":"2019-09-24","documentCount":0},{"key":"2019-09-25","documentCount":0},{"key":"2020-01-15","documentCount":0},{"key":"2020-01-16","documentCount":0},{"key":"2020-01-17","documentCount":0},{"key":"2020-01-18","documentCount":0},{"key":"2020-01-19","documentCount":0},{"key":"2020-01-20","documentCount":0},{"key":"2020-01-21","documentCount":0},{"key":"2020-01-22","documentCount":0},{"key":"2020-01-23","documentCount":0},{"key":"2020-01-24","documentCount":0},{"key":"2020-01-25","documentCount":0},{"key":"2020-01-26","documentCount":0},{"key":"2020-01-27","documentCount":0},{"key":"2020-01-28","documentCount":0},{"key":"2020-02-09","documentCount":0},{"key":"2020-02-10","documentCount":56000},{"key":"2020-02-11","documentCount":500}];

    const margin = {top: 20, right: 20, bottom: 60, left: 60},
          width = 960 - margin.left - margin.right,
          height = 500 - margin.top - margin.bottom;

const x = d3.scaleBand().range([0, width]).paddingInner(0.1).paddingOuter(0.5);

    const y = d3.scaleLinear().range([height, 0]);

          const svg = d3.select("div#histogramHolder").append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .append("g")
              .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    x.domain(data.map(function(d) { return d.key; }));
    y.domain([0, d3.max(data, function(d) { return d.documentCount; })]);

    // append the rectangles for the bar chart
    svg.selectAll(".bar")
    .data(data)
    .enter().append("rect")
    .attr("class", "bar")
    .attr("x", function(d) { return x(d.key); })
    .attr("width", x.bandwidth())
    .attr("y", function(d) { return y(d.documentCount); })
    .attr("height", function(d) { return height - y(d.documentCount); });

    svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))
    .selectAll("text")
        .attr("y", 0)
        .attr("x", 9)
        .attr("dy", ".35em")
        .attr("transform", "rotate(60)")
        .style("text-anchor", "start");

     // add the y Axis
     svg.append("g").call(d3.axisLeft(y));
  }
}
</code>```

I would expect the bars to be displayed in steelblue colour as i am setting it ( .attr("class", "bar") ) in the code . however it is not happening
appreciate any help

答:
Any content that is added in DOM by library then customized css of dynamically added element will not applied if it is in component's css. So it's necessary to add customized css in Global style.

Try to put style of svg in your globle style styles.scss

Body:
Hi I am having an angular 5 project . I am drawing an bar graph using d3js library. In my bar graph there are vertical bars to which I would like to apply styles. However it is not working as the bars are displayed with default black colour as show below.

The following is my component html code, where i have a div tag named "histogramHolder" to which i will append the svg from my component ts file.

performance.component.html

the following is my component scss file.

performance.component.scss

    .bar {
        fill: steelblue;
    }

the following is the code snippet where i create an svg image and append to the div tag named "histogramHolder"

import * as d3 from "d3";
@Component({
  selector: 'pc-performance',
  templateUrl: './performance.component.html',
  styleUrls: ['./performance.component.scss']
})
export class PerformanceComponent implements OnInit {

  ngOnInit() {

  const data=[{"key":"2019-09-11","documentCount":149002},{"key":"2019-09-12","documentCount":0},{"key":"2019-09-13","documentCount":80000},{"key":"2019-09-14","documentCount":0},{"key":"2019-09-15","documentCount":0},{"key":"2019-09-16","documentCount":0},{"key":"2019-09-17","documentCount":0},{"key":"2019-09-18","documentCount":270204},{"key":"2019-09-19","documentCount":0},{"key":"2019-09-20","documentCount":1},{"key":"2019-09-21","documentCount":0},{"key":"2019-09-22","documentCount":0},{"key":"2019-09-23","documentCount":269836},{"key":"2019-09-24","documentCount":0},{"key":"2019-09-25","documentCount":0},{"key":"2020-01-15","documentCount":0},{"key":"2020-01-16","documentCount":0},{"key":"2020-01-17","documentCount":0},{"key":"2020-01-18","documentCount":0},{"key":"2020-01-19","documentCount":0},{"key":"2020-01-20","documentCount":0},{"key":"2020-01-21","documentCount":0},{"key":"2020-01-22","documentCount":0},{"key":"2020-01-23","documentCount":0},{"key":"2020-01-24","documentCount":0},{"key":"2020-01-25","documentCount":0},{"key":"2020-01-26","documentCount":0},{"key":"2020-01-27","documentCount":0},{"key":"2020-01-28","documentCount":0},{"key":"2020-02-09","documentCount":0},{"key":"2020-02-10","documentCount":56000},{"key":"2020-02-11","documentCount":500}];

    const margin = {top: 20, right: 20, bottom: 60, left: 60},
          width = 960 - margin.left - margin.right,
          height = 500 - margin.top - margin.bottom;

const x = d3.scaleBand().range([0, width]).paddingInner(0.1).paddingOuter(0.5);

    const y = d3.scaleLinear().range([height, 0]);

          const svg = d3.select("div#histogramHolder").append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .append("g")
              .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    x.domain(data.map(function(d) { return d.key; }));
    y.domain([0, d3.max(data, function(d) { return d.documentCount; })]);

    // append the rectangles for the bar chart
    svg.selectAll(".bar")
    .data(data)
    .enter().append("rect")
    .attr("class", "bar")
    .attr("x", function(d) { return x(d.key); })
    .attr("width", x.bandwidth())
    .attr("y", function(d) { return y(d.documentCount); })
    .attr("height", function(d) { return height - y(d.documentCount); });

    svg.append("g")
    .attr("transform", "translate(0," + height + ")")
    .call(d3.axisBottom(x))
    .selectAll("text")
        .attr("y", 0)
        .attr("x", 9)
        .attr("dy", ".35em")
        .attr("transform", "rotate(60)")
        .style("text-anchor", "start");

     // add the y Axis
     svg.append("g").call(d3.axisLeft(y));
  }
}

I would expect the bars to be displayed in steelblue colour as i am setting it ( .attr("class", "bar") ) in the code . however it is not happening
appreciate any help


问:
What is the good way of writing Cucumber Framework
I am new to Cucumber and I am designing the framework.What is the good way of writing framework.

As of now I have designed the framework like this (Page Object Model)

```<code>Feature File
Given User is on home screen

Step Definition file
@Given("^User is on home screen$")
public void User_is_on_home_screen(String Username,String Pwd)
{
     lp.enterDetails(Username,Pwd)
}

Page related java files (Includes all Methods by page wise,which is called by respective step definition files).
public class login{
/**
Locators
**/
public void enterDetails(String Username,String Pwd){
/**
steps
**/
}
</code>```

My question is Can we include the methods in the respective page definition file instead of creating separate java file and store all page locators in one java file

```<code>Feature File
Given User is on home screen

Step Definition file
@Given("^User is on home screen$")
public void User_is_on_home_screen(String Username,String Pwd)
{
 public void enterDetails(String Username,String Pwd){
/**
steps
**/
}

Page Locators java file (Includes all page locators
public class Locators{
     /**
  All Locators
**/
}
</code>```

Which one is standard and efficient?

答:
Yes, you can use dependency injection in the cucumber and inject page object classes to you step definition using dependency

```<code>        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
</code>```

That would look like that:

```<code>public class BaseStep {

    private DeviceServiceImpl deviceService;
    private DashboardScreen dashboardScreen;
    public BaseStep() {
        this.deviceService = new DeviceServiceImpl(Hooks.driver);
        this.dashboardScreen = new DashboardScreen(Hooks.driver);
    }

    @Then("^I install application$")
    public void iInstallApplication() {
        dashboardScreen.scroll();
    }

    @Given("^I enable all network activity$")
    public void iEnableAllNetworkActivity() {

    }
}
</code>```

In that time you have located all elements on the pages:

```<code>/**
 * @author Tomash Gombosh
 */
public class DashboardScreen extends AbstractScreen {
    private static final AppElement SIGN_IN_BUTTON = new AppElement(
            "Sign in button",
            By.id(String.format("%s:%s", ApplicationProperties.ANDROID_APP_PACKAGE, "id/right_link")),
            ScrollTo.NO,
            true);
    private static final AppElement SIGN_UP_BUTTON = new AppElement(
            "Sign Up Button",
            By.id(String.format("%s:%s", ApplicationProperties.ANDROID_APP_PACKAGE, "id/sign_button")),
            ScrollTo.NO,
            true);

    public DashboardScreen(final AppiumDriver<MobileElement> driver) {
        super(driver);
    }

    @Override
    public boolean isDisplayed() {
        waitToBeVisible(SIGN_IN_BUTTON);
        scrollService.scrollDown();
        return allRequiredElementDisplayed();
    }

    public void tapLogin() {
        isDisplayed();
        tap(SIGN_IN_BUTTON);
    }

    public void tapSignIn() {
        tap(SIGN_UP_BUTTON);
    }

    public void scroll() {
        scrollService.scrollDown();
    }
}

</code>```

Would that helpful for you? Or need more explanation?

Body:
I am new to Cucumber and I am designing the framework.What is the good way of writing framework.

As of now I have designed the framework like this (Page Object Model)

Feature File
Given User is on home screen

Step Definition file
@Given("^User is on home screen$")
public void User_is_on_home_screen(String Username,String Pwd)
{
     lp.enterDetails(Username,Pwd)
}

Page related java files (Includes all Methods by page wise,which is called by respective step definition files).
public class login{
/**
Locators
**/
public void enterDetails(String Username,String Pwd){
/**
steps
**/
}

My question is Can we include the methods in the respective page definition file instead of creating separate java file and store all page locators in one java file

Feature File
Given User is on home screen

Step Definition file
@Given("^User is on home screen$")
public void User_is_on_home_screen(String Username,String Pwd)
{
 public void enterDetails(String Username,String Pwd){
/**
steps
**/
}

Page Locators java file (Includes all page locators
public class Locators{
     /**
  All Locators
**/
}

Which one is standard and efficient?

Body:
Yes, you can use dependency injection in the cucumber and inject page object classes to you step definition using dependency

        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-core</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>${cucumber.version}</version>
            <scope>test</scope>
        </dependency>

That would look like that:

public class BaseStep {

    private DeviceServiceImpl deviceService;
    private DashboardScreen dashboardScreen;
    public BaseStep() {
        this.deviceService = new DeviceServiceImpl(Hooks.driver);
        this.dashboardScreen = new DashboardScreen(Hooks.driver);
    }

    @Then("^I install application$")
    public void iInstallApplication() {
        dashboardScreen.scroll();
    }

    @Given("^I enable all network activity$")
    public void iEnableAllNetworkActivity() {

    }
}

In that time you have located all elements on the pages:

/**
 * @author Tomash Gombosh
 */
public class DashboardScreen extends AbstractScreen {
    private static final AppElement SIGN_IN_BUTTON = new AppElement(
            "Sign in button",
            By.id(String.format("%s:%s", ApplicationProperties.ANDROID_APP_PACKAGE, "id/right_link")),
            ScrollTo.NO,
            true);
    private static final AppElement SIGN_UP_BUTTON = new AppElement(
            "Sign Up Button",
            By.id(String.format("%s:%s", ApplicationProperties.ANDROID_APP_PACKAGE, "id/sign_button")),
            ScrollTo.NO,
            true);

    public DashboardScreen(final AppiumDriver<MobileElement> driver) {
        super(driver);
    }

    @Override
    public boolean isDisplayed() {
        waitToBeVisible(SIGN_IN_BUTTON);
        scrollService.scrollDown();
        return allRequiredElementDisplayed();
    }

    public void tapLogin() {
        isDisplayed();
        tap(SIGN_IN_BUTTON);
    }

    public void tapSignIn() {
        tap(SIGN_UP_BUTTON);
    }

    public void scroll() {
        scrollService.scrollDown();
    }
}

Would that helpful for you? Or need more explanation?