问:
get the URL for NSData saved in CoreData
I'm saving a UIImage to Core Data. So first, I convert it to NSData, then save it.

I need to get the URL for the image after it's saved. I'm doing this because I want to schedule a local notification with an attachment, and the only way to do it, AFAIK, is to with a URL.

Here is my code:

```<code>//my image:
var myImage: UIImage?
var imageData: NSData?
    if let image = myImage {
    imageData = UIImageJPEGRepresentation(image, 0.5)! as NSData
}
myEntity.setValue(imageData, forKey: "image")
</code>```

And that's how I should add an attachment to the notification:

UNNotificationAttachment.init(identifier: String, url: URL>, options: [AnyHashable : Any]?)

I'm saving the image and scheduling the notification manually when the user taps on a button to save the image.

Please let me know if you need extra info.

答:
And an implementation of how I saved it and then got the URL in practice when I had the same challenge:

Swift 5:

```<code> func getImageURL(for image: UIImage?) -> URL {
            let documentsDirectoryPath:NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
            let tempImageName = "tempImage.jpg"
            var imageURL: URL?

            if let image = image {

                let imageData:Data = image.jpegData(compressionQuality: 1.0)!
                let path:String = documentsDirectoryPath.appendingPathComponent(tempImageName)
                try? image.jpegData(compressionQuality: 1.0)!.write(to: URL(fileURLWithPath: path), options: [.atomic])
                imageURL = URL(fileURLWithPath: path)
                try? imageData.write(to: imageURL!, options: [.atomic])
            }
            return imageURL!
        }
</code>```

Body:
I'm saving a UIImage to Core Data. So first, I convert it to NSData, then save it.

I need to get the URL for the image after it's saved. I'm doing this because I want to schedule a local notification with an attachment, and the only way to do it, AFAIK, is to with a URL.

Here is my code:

//my image:
var myImage: UIImage?
var imageData: NSData?
    if let image = myImage {
    imageData = UIImageJPEGRepresentation(image, 0.5)! as NSData
}
myEntity.setValue(imageData, forKey: "image")

And that's how I should add an attachment to the notification:

UNNotificationAttachment.init(identifier: String, url: URL>, options: [AnyHashable : Any]?)

I'm saving the image and scheduling the notification manually when the user taps on a button to save the image.

Please let me know if you need extra info.

Body:
And an implementation of how I saved it and then got the URL in practice when I had the same challenge:

Swift 5:

 func getImageURL(for image: UIImage?) -> URL {
            let documentsDirectoryPath:NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
            let tempImageName = "tempImage.jpg"
            var imageURL: URL?

            if let image = image {

                let imageData:Data = image.jpegData(compressionQuality: 1.0)!
                let path:String = documentsDirectoryPath.appendingPathComponent(tempImageName)
                try? image.jpegData(compressionQuality: 1.0)!.write(to: URL(fileURLWithPath: path), options: [.atomic])
                imageURL = URL(fileURLWithPath: path)
                try? imageData.write(to: imageURL!, options: [.atomic])
            }
            return imageURL!
        }


来源: stackexchange

问:
Excel file not being downloaded when function is called via ajax method
Situation

I am working on an application where I can have a grid with X items, and each item has a print button. Clicking this print button allows me to call an ajax function which passes the ID of the grid item to a controller. I retrieve the relevant data based on that ID and then download it in an excel file. (The retrieving of the specific item is not yet done)

What I have so far

So far, I have the basic code that downloads an excel file, along with my grid .

Problem

The problem I am facing is, if I click the "Print" button...nothing happens, even with a breakpoint in my exporttoexcel  functions shows me that the function is entered and I can step thru it and despite no errors, nothing occurs. However, I added  random button that called the same function and when i clicked that button, the excel file was downloaded. As a result, I believe the issue has something to do with aJax.

Code

<input type="button" value="Test" onclick="location.href='@Url.Action("ExportToExcel", "Profile")'" />
```

<p>This is the code which downloads the file. It was a simple button I added.</p>

<pre class="lang-js prettyprint-override"><code>function ExportToExcel(id) {
    $.ajax({
        type: "POST",
        url: "@Url.Action("ExportToExcel", "Profile")",
        data: { "id": id },
        dataType: "json"

    });
}
</code>```

This is the function that I want to work, but it does not work and I cannot see what i've got wrong.

Export to Excel Code

public void ExportToExcelx()
{
    var products = new System.Data.DataTable("teste");
    products.Columns.Add("col1", typeof(int));
    products.Columns.Add("col2", typeof(string));

    products.Rows.Add(1, "product 1");
    products.Rows.Add(2, "product 2");
    products.Rows.Add(3, "product 3");
    products.Rows.Add(4, "product 4");
    products.Rows.Add(5, "product 5");
    products.Rows.Add(6, "product 6");
    products.Rows.Add(7, "product 7");

    var grid = new GridView();
    grid.DataSource = products;
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
    Response.ContentType = "application/ms-excel";

    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    //Response.Output.Write(sw.ToString());
    //Response.Flush();
    //Response.End();
    // =============

    //Open a memory stream that you can use to write back to the response
    byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
    MemoryStream s = new MemoryStream(byteArray);
    StreamReader sr = new StreamReader(s, Encoding.ASCII);

    //Write the stream back to the response
    Response.Write(sr.ReadToEnd());
    Response.End();

    //  return View("MyView");
}
```

Theory

I believe the error is somehow tied in to aJax, I am also creating the button in the controller like this.
"<button type='button' class='btn btn-warning' onclick='ExportToExcel(" + c.id + ");'>Print</button>",

Since location.href='@Url.Action works, I was wondering if attempting to redo my dynamic button would solve my issue.

Appreciate any insight that could be offered.

答:
File cannot be downloaded until full post back is triggered. Here is how you can do it:
Your ExportToExcelx function will hold file in TempData object as following:

```<code>TempData["fileHandle"] = s.ToArray();
</code>```

Rather than returning view return temp data identifier "fileHandle" and file name as shown below:

```<code> return Json(new { fileHandle = "fileHandle", FileName = "file.xls" }, JsonRequestBehavior.AllowGet);
</code>```

So your modified function will be like this:

```<code>public JsonResult ExportToExcelx()
{
    var products = new System.Data.DataTable("teste");
    products.Columns.Add("col1", typeof(int));
    products.Columns.Add("col2", typeof(string));

    products.Rows.Add(1, "product 1");
    products.Rows.Add(2, "product 2");
    products.Rows.Add(3, "product 3");
    products.Rows.Add(4, "product 4");
    products.Rows.Add(5, "product 5");
    products.Rows.Add(6, "product 6");
    products.Rows.Add(7, "product 7");

    var grid = new GridView();
    grid.DataSource = products;
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
    Response.ContentType = "application/ms-excel";

    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    //Response.Output.Write(sw.ToString());
    //Response.Flush();
    //Response.End();
    // =============

    //Open a memory stream that you can use to write back to the response
    byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
    MemoryStream s = new MemoryStream(byteArray);

    TempData["fileHandle"] = s.ToArray();

    //StreamReader sr = new StreamReader(s, Encoding.ASCII);

    //Write the stream back to the response
    Response.Write(sr.ReadToEnd());
    Response.End();

    return Json(new { fileHandle = "fileHandle", FileName = "file.xls" }, JsonRequestBehavior.AllowGet);
    //  return View("MyView");
}
</code>```

Now you need another function in your controller to download file like following:

```<code>    [HttpGet]
    public virtual ActionResult Download(string fileHandle, string fileName)
    {
        if (TempData[fileHandle] != null)
        {
            byte[] data = TempData[fileHandle] as byte[];
            return File(data, "application/vnd.ms-excel", fileName);
        }
        else
        {

            return new EmptyResult();
        }
    }
</code>```

On successful call to ExportToExcelx function your ajax call will call download function as following:

```<code>    $.ajax({
    type: 'GET',
    cache: false,
    url: '/url',
    success: function (data) {
        window.location = '/url/Download?fileHandle=' + data.fileHandle
            + '&filename=' + data.FileName; //call download function
    },
    error: function (e) {
        //handle error
    }
</code>```

Download function then will return the file.

Hope this helps.

ContentLicense: CC BY-SA 4.0

Body:
Situation

I am working on an application where I can have a grid with X items, and each item has a print button. Clicking this print button allows me to call an ajax function which passes the ID of the grid item to a controller. I retrieve the relevant data based on that ID and then download it in an excel file. (The retrieving of the specific item is not yet done)

What I have so far

So far, I have the basic code that downloads an excel file, along with my grid .

Problem

The problem I am facing is, if I click the "Print" button...nothing happens, even with a breakpoint in my exporttoexcel  functions shows me that the function is entered and I can step thru it and despite no errors, nothing occurs. However, I added  random button that called the same function and when i clicked that button, the excel file was downloaded. As a result, I believe the issue has something to do with aJax.

Code

<input type="button" value="Test" onclick="location.href='@Url.Action("ExportToExcel", "Profile")'" />

This is the code which downloads the file. It was a simple button I added.

function ExportToExcel(id) {
    $.ajax({
        type: "POST",
        url: "@Url.Action("ExportToExcel", "Profile")",
        data: { "id": id },
        dataType: "json"

    });
}

This is the function that I want to work, but it does not work and I cannot see what i've got wrong.

Export to Excel Code

public void ExportToExcelx()
{
    var products = new System.Data.DataTable("teste");
    products.Columns.Add("col1", typeof(int));
    products.Columns.Add("col2", typeof(string));

    products.Rows.Add(1, "product 1");
    products.Rows.Add(2, "product 2");
    products.Rows.Add(3, "product 3");
    products.Rows.Add(4, "product 4");
    products.Rows.Add(5, "product 5");
    products.Rows.Add(6, "product 6");
    products.Rows.Add(7, "product 7");

    var grid = new GridView();
    grid.DataSource = products;
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
    Response.ContentType = "application/ms-excel";

    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    //Response.Output.Write(sw.ToString());
    //Response.Flush();
    //Response.End();
    // =============

    //Open a memory stream that you can use to write back to the response
    byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
    MemoryStream s = new MemoryStream(byteArray);
    StreamReader sr = new StreamReader(s, Encoding.ASCII);

    //Write the stream back to the response
    Response.Write(sr.ReadToEnd());
    Response.End();

    //  return View("MyView");
}

Theory

I believe the error is somehow tied in to aJax, I am also creating the button in the controller like this.
"<button type='button' class='btn btn-warning' onclick='ExportToExcel(" + c.id + ");'>Print</button>",

Since location.href='@Url.Action works, I was wondering if attempting to redo my dynamic button would solve my issue.

Appreciate any insight that could be offered.

Body:
File cannot be downloaded until full post back is triggered. Here is how you can do it:
Your ExportToExcelx function will hold file in TempData object as following:

TempData["fileHandle"] = s.ToArray();

Rather than returning view return temp data identifier "fileHandle" and file name as shown below:

 return Json(new { fileHandle = "fileHandle", FileName = "file.xls" }, JsonRequestBehavior.AllowGet);

So your modified function will be like this:

public JsonResult ExportToExcelx()
{
    var products = new System.Data.DataTable("teste");
    products.Columns.Add("col1", typeof(int));
    products.Columns.Add("col2", typeof(string));

    products.Rows.Add(1, "product 1");
    products.Rows.Add(2, "product 2");
    products.Rows.Add(3, "product 3");
    products.Rows.Add(4, "product 4");
    products.Rows.Add(5, "product 5");
    products.Rows.Add(6, "product 6");
    products.Rows.Add(7, "product 7");

    var grid = new GridView();
    grid.DataSource = products;
    grid.DataBind();

    Response.ClearContent();
    Response.Buffer = true;
    Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
    Response.ContentType = "application/ms-excel";

    Response.Charset = "";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);

    grid.RenderControl(htw);

    //Response.Output.Write(sw.ToString());
    //Response.Flush();
    //Response.End();
    // =============

    //Open a memory stream that you can use to write back to the response
    byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
    MemoryStream s = new MemoryStream(byteArray);

    TempData["fileHandle"] = s.ToArray();

    //StreamReader sr = new StreamReader(s, Encoding.ASCII);

    //Write the stream back to the response
    Response.Write(sr.ReadToEnd());
    Response.End();

    return Json(new { fileHandle = "fileHandle", FileName = "file.xls" }, JsonRequestBehavior.AllowGet);
    //  return View("MyView");
}

Now you need another function in your controller to download file like following:

    [HttpGet]
    public virtual ActionResult Download(string fileHandle, string fileName)
    {
        if (TempData[fileHandle] != null)
        {
            byte[] data = TempData[fileHandle] as byte[];
            return File(data, "application/vnd.ms-excel", fileName);
        }
        else
        {

            return new EmptyResult();
        }
    }

On successful call to ExportToExcelx function your ajax call will call download function as following:

    $.ajax({
    type: 'GET',
    cache: false,
    url: '/url',
    success: function (data) {
        window.location = '/url/Download?fileHandle=' + data.fileHandle
            + '&filename=' + data.FileName; //call download function
    },
    error: function (e) {
        //handle error
    }

Download function then will return the file.

Hope this helps.


问:
Trouble with makefile when installing PyLucene
I am trying to build PyLucene on my Windows 10 machine. Here are the details I am currently providing on the Makefile:

```<code>PREFIX_PYTHON=C:\\Users\\Charlie\\Anaconda3
ANT=C:\\Program Files\\apache-ant-1.10.5\\bin\\ant
JAVA_HOME=C:\\Program Files\\Java\\jdk-11.0.2
PYTHON=$(PREFIX_PYTHON)\python.exe
JCC = $(PYTHON) -m jcc
NUM_FILES = 8
</code>```

When I run  'make' from the command line, I encounter the following error:

```<code>process_begin: CreateProcess(NULL, pwd, ...) failed.
process_begin: CreateProcess(NULL, which icupkg, ...) failed.
process_begin: CreateProcess(NULL, uname, ...) failed.
process_begin: CreateProcess(NULL, uname, ...) failed.
cd lucene-java-7.6.0/lucene; (C:\\Program Files\\apache-ant-1.10.5\\bin\\ant ivy-availability-check || C:\\Program Files\\apache-ant-1.10.5\\bin\\ant ivy-bootstrap)
process_begin: CreateProcess(NULL, uname, ...) failed.
The filename, directory name, or volume label syntax is incorrect.
'C:\\Program' is not recognized as an internal or external command,
operable program or batch file.
make: *** [ivy] Error 1
</code>```

Can someone provide any insight as to what is going wrong? Thanks.

答:
Try this.</p>

```<code>JAVA_HOME="C:\\"Program Files"\\Java\\jdk-11.0.2"
</code>```

Body:
I am trying to build PyLucene on my Windows 10 machine. Here are the details I am currently providing on the Makefile:

PREFIX_PYTHON=C:\\Users\\Charlie\\Anaconda3
ANT=C:\\Program Files\\apache-ant-1.10.5\\bin\\ant
JAVA_HOME=C:\\Program Files\\Java\\jdk-11.0.2
PYTHON=$(PREFIX_PYTHON)\python.exe
JCC = $(PYTHON) -m jcc
NUM_FILES = 8

When I run  'make' from the command line, I encounter the following error:

process_begin: CreateProcess(NULL, pwd, ...) failed.
process_begin: CreateProcess(NULL, which icupkg, ...) failed.
process_begin: CreateProcess(NULL, uname, ...) failed.
process_begin: CreateProcess(NULL, uname, ...) failed.
cd lucene-java-7.6.0/lucene; (C:\\Program Files\\apache-ant-1.10.5\\bin\\ant ivy-availability-check || C:\\Program Files\\apache-ant-1.10.5\\bin\\ant ivy-bootstrap)
process_begin: CreateProcess(NULL, uname, ...) failed.
The filename, directory name, or volume label syntax is incorrect.
'C:\\Program' is not recognized as an internal or external command,
operable program or batch file.
make: *** [ivy] Error 1

Can someone provide any insight as to what is going wrong? Thanks.

Body:
Try this.

JAVA_HOME="C:\\"Program Files"\\Java\\jdk-11.0.2"


问:
No specs found when looping tests on Protractor
I'm using Protractor on Selenium, MacOS and Chrome.
I'm trying to run the same test using an array of elements to provide the test data:

As I read here: Looping on a protractor test with parameters

I was trying that solution but when I run it, my test is not even found:

```<code> for(var i = 0; casos.length; i++){

            (function(cotizacion){
                it('obtener $1,230.00 de la cotizacion', function(){
                    browser.get('https://mifel-danielarias.c9users.io');
                    login(user,pass);
                    fillVidaCotizadorForm(formData);
                    //browser.sleep(5000);
                    var primaTotal = element(by.binding('vida.primaTotal'));
                    browser.wait(EC.visibilityOf(primaTotal),4000);
                    expect(primaTotal.getText()).toBe(cotizacion);
                });
            })(casos[i].Fallecimiento);
        }
</code>```

Output message:

```<code>> [14:13:01] I/hosted - Using the selenium server at
> http://localhost:4444/wd/hub [14:13:01] I/launcher - Running 1
> instances of WebDriver Started
>
>
> No specs found Finished in 0.003 seconds
</code>```

This loop is inside my describe function and if I run the test normally without any loop, it runs flawlessly.

答: As @OptimWorks mentioned in his comment, Data Driven Approach was exactly what I was looking for, and this question provided several good answers.</p>

Body:
I'm using Protractor on Selenium, MacOS and Chrome.
I'm trying to run the same test using an array of elements to provide the test data:

As I read here: Looping on a protractor test with parameters

I was trying that solution but when I run it, my test is not even found:

 for(var i = 0; casos.length; i++){

            (function(cotizacion){
                it('obtener $1,230.00 de la cotizacion', function(){
                    browser.get('https://mifel-danielarias.c9users.io');
                    login(user,pass);
                    fillVidaCotizadorForm(formData);
                    //browser.sleep(5000);
                    var primaTotal = element(by.binding('vida.primaTotal'));
                    browser.wait(EC.visibilityOf(primaTotal),4000);
                    expect(primaTotal.getText()).toBe(cotizacion);
                });
            })(casos[i].Fallecimiento);
        }

Output message:

> [14:13:01] I/hosted - Using the selenium server at
> http://localhost:4444/wd/hub [14:13:01] I/launcher - Running 1
> instances of WebDriver Started
>
>
> No specs found Finished in 0.003 seconds

This loop is inside my describe function and if I run the test normally without any loop, it runs flawlessly.


问:
Cube.js: Can't find join path to join
I'm taking over a website. I could not reach the previous developer anymore. He decided to use cube.js and once showed me a working KPI page with charts. Now, I'm trying to make the page work on my side, and understand what he did.

I have installed cube.js on my machine. The collections in our database are comments, folders, logs, posts, sessions, subscribers, users. I used cubejs generate -t users and cubejs generate -t logs to generate Users.js and Logs.js. For example, here is the generated Users.js:

```<code>cube(`Users`, {
  sql: `SELECT * FROM news.users`,

  joins: {

  },

  measures: {
    count: {
      type: `count`,
      drillMembers: [currentname, currentprovider, googleJsonDisplayname, googleJsonId, googleJsonNameFamilyname, googleJsonNameGivenname, googleDisplayname, googleId, googleNameFamilyname, googleNameGivenname, googleProvider, localId, localProvider, firstdate]
    },

    googleJsonCircledbycount: {
      sql: `${CUBE}.\`google._json.circledByCount\``,
      type: `sum`,
      title: `Google. Json.circledbycount`
    }
  },

  dimensions: {
    currentname: {
      sql: `${CUBE}.\`currentName\``,
      type: `string`
    },

    currentprovider: {
      sql: `${CUBE}.\`currentProvider\``,
      type: `string`
    },

    firstapp: {
      sql: `${CUBE}.\`firstApp\``,
      type: `string`
    },

    googleJsonDisplayname: {
      sql: `${CUBE}.\`google._json.displayName\``,
      type: `string`,
      title: `Google. Json.displayname`
    },

    googleJsonEtag: {
      sql: `${CUBE}.\`google._json.etag\``,
      type: `string`,
      title: `Google. Json.etag`
    },

    googleJsonGender: {
      sql: `${CUBE}.\`google._json.gender\``,
      type: `string`,
      title: `Google. Json.gender`
    },

    googleJsonId: {
      sql: `${CUBE}.\`google._json.id\``,
      type: `string`,
      title: `Google. Json.id`
    },

    googleJsonImageUrl: {
      sql: `${CUBE}.\`google._json.image.url\``,
      type: `string`,
      title: `Google. Json.image.url`
    },

    googleJsonKind: {
      sql: `${CUBE}.\`google._json.kind\``,
      type: `string`,
      title: `Google. Json.kind`
    },

    googleJsonLanguage: {
      sql: `${CUBE}.\`google._json.language\``,
      type: `string`,
      title: `Google. Json.language`
    },

    googleJsonNameFamilyname: {
      sql: `${CUBE}.\`google._json.name.familyName\``,
      type: `string`,
      title: `Google. Json.name.familyname`
    },

    googleJsonNameGivenname: {
      sql: `${CUBE}.\`google._json.name.givenName\``,
      type: `string`,
      title: `Google. Json.name.givenname`
    },

    googleJsonObjecttype: {
      sql: `${CUBE}.\`google._json.objectType\``,
      type: `string`,
      title: `Google. Json.objecttype`
    },

    googleJsonUrl: {
      sql: `${CUBE}.\`google._json.url\``,
      type: `string`,
      title: `Google. Json.url`
    },

    googleRaw: {
      sql: `${CUBE}.\`google._raw\``,
      type: `string`,
      title: `Google. Raw`
    },

    googleDisplayname: {
      sql: `${CUBE}.\`google.displayName\``,
      type: `string`,
      title: `Google.displayname`
    },

    googleGender: {
      sql: `${CUBE}.\`google.gender\``,
      type: `string`,
      title: `Google.gender`
    },

    googleId: {
      sql: `${CUBE}.\`google.id\``,
      type: `string`,
      title: `Google.id`
    },

    googleNameFamilyname: {
      sql: `${CUBE}.\`google.name.familyName\``,
      type: `string`,
      title: `Google.name.familyname`
    },

    googleNameGivenname: {
      sql: `${CUBE}.\`google.name.givenName\``,
      type: `string`,
      title: `Google.name.givenname`
    },

    googleProvider: {
      sql: `${CUBE}.\`google.provider\``,
      type: `string`,
      title: `Google.provider`
    },

    localExpired: {
      sql: `${CUBE}.\`local.expired\``,
      type: `string`,
      title: `Local.expired`
    },

    localFirstapp: {
      sql: `${CUBE}.\`local.firstApp\``,
      type: `string`,
      title: `Local.firstapp`
    },

    localHash: {
      sql: `${CUBE}.\`local.hash\``,
      type: `string`,
      title: `Local.hash`
    },

    localId: {
      sql: `${CUBE}.\`local.id\``,
      type: `string`,
      title: `Local.id`
    },

    localProvider: {
      sql: `${CUBE}.\`local.provider\``,
      type: `string`,
      title: `Local.provider`
    },

    localSalt: {
      sql: `${CUBE}.\`local.salt\``,
      type: `string`,
      title: `Local.salt`
    },

    localType: {
      sql: `${CUBE}.\`local.type\``,
      type: `string`,
      title: `Local.type`
    },

    localVerificationcode: {
      sql: `${CUBE}.\`local.verificationCode\``,
      type: `string`,
      title: `Local.verificationcode`
    },

    localVerified: {
      sql: `${CUBE}.\`local.verified\``,
      type: `string`,
      title: `Local.verified`
    },

    firstdate: {
      sql: `${CUBE}.\`firstDate\``,
      type: `time`
    }
  }
});
</code>```

Then, I launched cube.js backend and his page localhost:8000/kpi on my machine. There are errors like Error: Error: Cube 'Customs' not found for path 'Customs.count', Error: Error: Cube 'Customs' not found for path 'Customs.count' and Error: Error: Can't find join path to join 'Users', 'Logs':

Here is how the previous developer defined his query.ts:

```<code>export const getQueryUserByType = (dateRange: any, granularity: any) => ({
  measures: ['Users.count'],
  dimensions: ['Users.localType'],
  timeDimensions: dateRange
    ? [
        {
          dimension: 'Logs.date',
          dateRange: dateRange,
          granularity,
        },
      ]
    : [
        {
          dimension: 'Logs.date',
          granularity,
        },
      ],
});

export const getQueryUserPageVist = (dateRange: any, granularity: any) => ({
  measures: ['Users.count'],
  dimensions: ['Logs.url'],
  timeDimensions: dateRange
    ? [
        {
          dimension: 'Logs.date',
          dateRange: dateRange,
          granularity,
        },
      ]
    : [
        {
          dimension: 'Logs.date',
          granularity,
        },
      ],
  filters: [
    {
      member: 'Logs.actionThetype',
      operator: 'equals',
      values: ['VisitPage'],
    },
  ],
});

export const getQueryCustomByApp = (dateRange: any, granularity: any) => ({
  measures: ['Customs.count'],
  dimensions: ['Customs.offerdisplayname'],
  timeDimensions: dateRange
    ? [
        {
          dimension: 'Customs.timestamp',
          dateRange: dateRange,
          granularity,
        },
      ]
    : [
        {
          dimension: 'Customs.timestamp',
          granularity,
        },
      ],
});
</code>```

Could anyone tell What errors like Error: Error: Cube 'Customs' not found for path 'Customs.count', Error: Error: Cube 'Customs' not found for path 'Customs.count' and Error: Error: Can't find join path to join 'Users', 'Logs' mean? How could I fix them?

答:
Your application is missing Cube.js schema which is essential part of Cube.js deployment. You either should try to find this missing source code or redevelop it based on your dashboard ui application.

As errors state you're missing Customs cube definition as well as join definition between Users and Logs. You can learn more about joins here: https://cube.dev/docs/joins

Title: Cube.js: Can't find join path to join

Body:
I'm taking over a website. I could not reach the previous developer anymore. He decided to use cube.js and once showed me a working KPI page with charts. Now, I'm trying to make the page work on my side, and understand what he did.

I have installed cube.js on my machine. The collections in our database are comments, folders, logs, posts, sessions, subscribers, users. I used cubejs generate -t users and cubejs generate -t logs to generate Users.js and Logs.js. For example, here is the generated Users.js:

cube(`Users`, {
  sql: `SELECT * FROM news.users`,

  joins: {

  },

  measures: {
    count: {
      type: `count`,
      drillMembers: [currentname, currentprovider, googleJsonDisplayname, googleJsonId, googleJsonNameFamilyname, googleJsonNameGivenname, googleDisplayname, googleId, googleNameFamilyname, googleNameGivenname, googleProvider, localId, localProvider, firstdate]
    },

    googleJsonCircledbycount: {
      sql: `${CUBE}.\`google._json.circledByCount\``,
      type: `sum`,
      title: `Google. Json.circledbycount`
    }
  },

  dimensions: {
    currentname: {
      sql: `${CUBE}.\`currentName\``,
      type: `string`
    },

    currentprovider: {
      sql: `${CUBE}.\`currentProvider\``,
      type: `string`
    },

    firstapp: {
      sql: `${CUBE}.\`firstApp\``,
      type: `string`
    },

    googleJsonDisplayname: {
      sql: `${CUBE}.\`google._json.displayName\``,
      type: `string`,
      title: `Google. Json.displayname`
    },

    googleJsonEtag: {
      sql: `${CUBE}.\`google._json.etag\``,
      type: `string`,
      title: `Google. Json.etag`
    },

    googleJsonGender: {
      sql: `${CUBE}.\`google._json.gender\``,
      type: `string`,
      title: `Google. Json.gender`
    },

    googleJsonId: {
      sql: `${CUBE}.\`google._json.id\``,
      type: `string`,
      title: `Google. Json.id`
    },

    googleJsonImageUrl: {
      sql: `${CUBE}.\`google._json.image.url\``,
      type: `string`,
      title: `Google. Json.image.url`
    },

    googleJsonKind: {
      sql: `${CUBE}.\`google._json.kind\``,
      type: `string`,
      title: `Google. Json.kind`
    },

    googleJsonLanguage: {
      sql: `${CUBE}.\`google._json.language\``,
      type: `string`,
      title: `Google. Json.language`
    },

    googleJsonNameFamilyname: {
      sql: `${CUBE}.\`google._json.name.familyName\``,
      type: `string`,
      title: `Google. Json.name.familyname`
    },

    googleJsonNameGivenname: {
      sql: `${CUBE}.\`google._json.name.givenName\``,
      type: `string`,
      title: `Google. Json.name.givenname`
    },

    googleJsonObjecttype: {
      sql: `${CUBE}.\`google._json.objectType\``,
      type: `string`,
      title: `Google. Json.objecttype`
    },

    googleJsonUrl: {
      sql: `${CUBE}.\`google._json.url\``,
      type: `string`,
      title: `Google. Json.url`
    },

    googleRaw: {
      sql: `${CUBE}.\`google._raw\``,
      type: `string`,
      title: `Google. Raw`
    },

    googleDisplayname: {
      sql: `${CUBE}.\`google.displayName\``,
      type: `string`,
      title: `Google.displayname`
    },

    googleGender: {
      sql: `${CUBE}.\`google.gender\``,
      type: `string`,
      title: `Google.gender`
    },

    googleId: {
      sql: `${CUBE}.\`google.id\``,
      type: `string`,
      title: `Google.id`
    },

    googleNameFamilyname: {
      sql: `${CUBE}.\`google.name.familyName\``,
      type: `string`,
      title: `Google.name.familyname`
    },

    googleNameGivenname: {
      sql: `${CUBE}.\`google.name.givenName\``,
      type: `string`,
      title: `Google.name.givenname`
    },

    googleProvider: {
      sql: `${CUBE}.\`google.provider\``,
      type: `string`,
      title: `Google.provider`
    },

    localExpired: {
      sql: `${CUBE}.\`local.expired\``,
      type: `string`,
      title: `Local.expired`
    },

    localFirstapp: {
      sql: `${CUBE}.\`local.firstApp\``,
      type: `string`,
      title: `Local.firstapp`
    },

    localHash: {
      sql: `${CUBE}.\`local.hash\``,
      type: `string`,
      title: `Local.hash`
    },

    localId: {
      sql: `${CUBE}.\`local.id\``,
      type: `string`,
      title: `Local.id`
    },

    localProvider: {
      sql: `${CUBE}.\`local.provider\``,
      type: `string`,
      title: `Local.provider`
    },

    localSalt: {
      sql: `${CUBE}.\`local.salt\``,
      type: `string`,
      title: `Local.salt`
    },

    localType: {
      sql: `${CUBE}.\`local.type\``,
      type: `string`,
      title: `Local.type`
    },

    localVerificationcode: {
      sql: `${CUBE}.\`local.verificationCode\``,
      type: `string`,
      title: `Local.verificationcode`
    },

    localVerified: {
      sql: `${CUBE}.\`local.verified\``,
      type: `string`,
      title: `Local.verified`
    },

    firstdate: {
      sql: `${CUBE}.\`firstDate\``,
      type: `time`
    }
  }
});

Then, I launched cube.js backend and his page localhost:8000/kpi on my machine. There are errors like Error: Error: Cube 'Customs' not found for path 'Customs.count', Error: Error: Cube 'Customs' not found for path 'Customs.count' and Error: Error: Can't find join path to join 'Users', 'Logs':

Here is how the previous developer defined his query.ts:

export const getQueryUserByType = (dateRange: any, granularity: any) => ({
  measures: ['Users.count'],
  dimensions: ['Users.localType'],
  timeDimensions: dateRange
    ? [
        {
          dimension: 'Logs.date',
          dateRange: dateRange,
          granularity,
        },
      ]
    : [
        {
          dimension: 'Logs.date',
          granularity,
        },
      ],
});

export const getQueryUserPageVist = (dateRange: any, granularity: any) => ({
  measures: ['Users.count'],
  dimensions: ['Logs.url'],
  timeDimensions: dateRange
    ? [
        {
          dimension: 'Logs.date',
          dateRange: dateRange,
          granularity,
        },
      ]
    : [
        {
          dimension: 'Logs.date',
          granularity,
        },
      ],
  filters: [
    {
      member: 'Logs.actionThetype',
      operator: 'equals',
      values: ['VisitPage'],
    },
  ],
});

export const getQueryCustomByApp = (dateRange: any, granularity: any) => ({
  measures: ['Customs.count'],
  dimensions: ['Customs.offerdisplayname'],
  timeDimensions: dateRange
    ? [
        {
          dimension: 'Customs.timestamp',
          dateRange: dateRange,
          granularity,
        },
      ]
    : [
        {
          dimension: 'Customs.timestamp',
          granularity,
        },
      ],
});

Could anyone tell What errors like Error: Error: Cube 'Customs' not found for path 'Customs.count', Error: Error: Cube 'Customs' not found for path 'Customs.count' and Error: Error: Can't find join path to join 'Users', 'Logs' mean? How could I fix them?


问:
How to add attribute to all documents in a collection, with same data of another attribute in MongoDB?
I've seen this question and it could be useful, but I need some extra steps.

I have a collection of Sites filled with name, data and a field called infoBox that is an object.

```<code>infoBox: {
    coordX: {
      type: Number,
    },
    coordY: {
      type: Number,
    },
    type: {
      type: Number,
      enum: [InfoBoxType.line, InfoBoxType.horizontal, InfoBoxType.vertical],
    },
    midPoint: {
      coordX: {
        type: Number,
      },
      coordY: {
        type: Number,
      },
    },
</code>```

So, I need to add another attibute to all infoboxes of the sites called "levels" that is an array, and this field must contains two objects like InfoBox, with the same values, but with empty 'levels'. (both infobox 1 & 2 with same values).This is to initialize the DB, later these values will be editted by the users.

Trying to be clear, I actually have:

```<code>Site
    data
    name
    infobox
        coordx
        coordy
        midpoint
            coordx
            coordy
</code>```

and I need

```<code>Site
    data
    name
    infobox
        coordx
        coordy
        midpoint
            coordx
            coordy
        levels
            infobox1
                coordx
                coordy
                midpoint
                    coordx
                    coordy
                levels(empty)
            infobox2
                coordx
                coordy
                midpoint
                    coordx
                    coordy
                levels(empty)
</code>```

How can I accomplish this?

Extra info:
Mongo version 4.2

EDIT

I am trying to make it with something like this, but with no luck yet:

```<code>let sites = await this.siteModel.find({});
 const firstZoom = site.infoBox;
 const secondZoom =  site.infoBox;

  const levelss = [
    firstZoom,
    secondZoom,
  ];

await this.siteModel.update({ _id: site._id }, { $set: { 'infoBox.levels.$': levelss } });
</code>```

答:
On MongoDB v4.2 which supports aggregation pipeline in update operations, you can try this (you can use .updateMany() as well) :

```<code>this.siteModel.update({},
    [{
        $set: {
            'infobox.levels': [{ infobox1: { $mergeObjects: ['$infobox', { 'levels': [] }] } },
            { infobox2: { $mergeObjects: ['$infobox', { 'levels': [] }] } }]
        }
    }], { multi: true })
</code>```

Ref : .update()

Collection Data :

```<code>/* 1 */
{
    "_id" : ObjectId("5e4dba9e7f8bc30a75c658fc"),
    "data" : 1,
    "name" : "noName",
    "infobox" : {
        "coordx" : 2,
        "coordy" : 2,
        "midpoint" : {
            "coordx" : 1,
            "coordy" : 1
        }
    }
}

/* 2 */
{
    "_id" : ObjectId("5e4dbab07f8bc30a75c65ab1"),
    "data" : 2,
    "name" : "yesName",
    "infobox" : {
        "coordx" : 4,
        "coordy" : 4,
        "midpoint" : {
            "coordx" : 2,
            "coordy" : 2
        }
    }
}
</code>```

Docs in DB after update operation :

```<code>/* 1 */
{
    "_id" : ObjectId("5e4dba9e7f8bc30a75c658fc"),
    "data" : 1,
    "name" : "noName",
    "infobox" : {
        "coordx" : 2,
        "coordy" : 2,
        "midpoint" : {
            "coordx" : 1,
            "coordy" : 1
        },
        "levels" : [
            {
                "infobox1" : {
                    "coordx" : 2,
                    "coordy" : 2,
                    "midpoint" : {
                        "coordx" : 1,
                        "coordy" : 1
                    },
                    "levels" : []
                }
            },
            {
                "infobox2" : {
                    "coordx" : 2,
                    "coordy" : 2,
                    "midpoint" : {
                        "coordx" : 1,
                        "coordy" : 1
                    },
                    "levels" : []
                }
            }
        ]
    }
}

/* 2 */
{
    "_id" : ObjectId("5e4dbab07f8bc30a75c65ab1"),
    "data" : 2,
    "name" : "yesName",
    "infobox" : {
        "coordx" : 4,
        "coordy" : 4,
        "midpoint" : {
            "coordx" : 2,
            "coordy" : 2
        },
        "levels" : [
            {
                "infobox1" : {
                    "coordx" : 4,
                    "coordy" : 4,
                    "midpoint" : {
                        "coordx" : 2,
                        "coordy" : 2
                    },
                    "levels" : []
                }
            },
            {
                "infobox2" : {
                    "coordx" : 4,
                    "coordy" : 4,
                    "midpoint" : {
                        "coordx" : 2,
                        "coordy" : 2
                    },
                    "levels" : []
                }
            }
        ]
    }
}
</code>```

Body:
I've seen this question and it could be useful, but I need some extra steps.

I have a collection of Sites filled with name, data and a field called infoBox that is an object.

infoBox: {
    coordX: {
      type: Number,
    },
    coordY: {
      type: Number,
    },
    type: {
      type: Number,
      enum: [InfoBoxType.line, InfoBoxType.horizontal, InfoBoxType.vertical],
    },
    midPoint: {
      coordX: {
        type: Number,
      },
      coordY: {
        type: Number,
      },
    },

So, I need to add another attibute to all infoboxes of the sites called "levels" that is an array, and this field must contains two objects like InfoBox, with the same values, but with empty 'levels'. (both infobox 1 & 2 with same values).This is to initialize the DB, later these values will be editted by the users.

Trying to be clear, I actually have:

Site
    data
    name
    infobox
        coordx
        coordy
        midpoint
            coordx
            coordy

and I need

Site
    data
    name
    infobox
        coordx
        coordy
        midpoint
            coordx
            coordy
        levels
            infobox1
                coordx
                coordy
                midpoint
                    coordx
                    coordy
                levels(empty)
            infobox2
                coordx
                coordy
                midpoint
                    coordx
                    coordy
                levels(empty)

How can I accomplish this?

Extra info:
Mongo version 4.2

EDIT

I am trying to make it with something like this, but with no luck yet:

let sites = await this.siteModel.find({});
 const firstZoom = site.infoBox;
 const secondZoom =  site.infoBox;

  const levelss = [
    firstZoom,
    secondZoom,
  ];

await this.siteModel.update({ _id: site._id }, { $set: { 'infoBox.levels.$': levelss } });

Body:
On MongoDB v4.2 which supports aggregation pipeline in update operations, you can try this (you can use .updateMany() as well) :

this.siteModel.update({},
    [{
        $set: {
            'infobox.levels': [{ infobox1: { $mergeObjects: ['$infobox', { 'levels': [] }] } },
            { infobox2: { $mergeObjects: ['$infobox', { 'levels': [] }] } }]
        }
    }], { multi: true })

Ref : .update()

Collection Data :

/* 1 */
{
    "_id" : ObjectId("5e4dba9e7f8bc30a75c658fc"),
    "data" : 1,
    "name" : "noName",
    "infobox" : {
        "coordx" : 2,
        "coordy" : 2,
        "midpoint" : {
            "coordx" : 1,
            "coordy" : 1
        }
    }
}

/* 2 */
{
    "_id" : ObjectId("5e4dbab07f8bc30a75c65ab1"),
    "data" : 2,
    "name" : "yesName",
    "infobox" : {
        "coordx" : 4,
        "coordy" : 4,
        "midpoint" : {
            "coordx" : 2,
            "coordy" : 2
        }
    }
}

Docs in DB after update operation :

/* 1 */
{
    "_id" : ObjectId("5e4dba9e7f8bc30a75c658fc"),
    "data" : 1,
    "name" : "noName",
    "infobox" : {
        "coordx" : 2,
        "coordy" : 2,
        "midpoint" : {
            "coordx" : 1,
            "coordy" : 1
        },
        "levels" : [
            {
                "infobox1" : {
                    "coordx" : 2,
                    "coordy" : 2,
                    "midpoint" : {
                        "coordx" : 1,
                        "coordy" : 1
                    },
                    "levels" : []
                }
            },
            {
                "infobox2" : {
                    "coordx" : 2,
                    "coordy" : 2,
                    "midpoint" : {
                        "coordx" : 1,
                        "coordy" : 1
                    },
                    "levels" : []
                }
            }
        ]
    }
}

/* 2 */
{
    "_id" : ObjectId("5e4dbab07f8bc30a75c65ab1"),
    "data" : 2,
    "name" : "yesName",
    "infobox" : {
        "coordx" : 4,
        "coordy" : 4,
        "midpoint" : {
            "coordx" : 2,
            "coordy" : 2
        },
        "levels" : [
            {
                "infobox1" : {
                    "coordx" : 4,
                    "coordy" : 4,
                    "midpoint" : {
                        "coordx" : 2,
                        "coordy" : 2
                    },
                    "levels" : []
                }
            },
            {
                "infobox2" : {
                    "coordx" : 4,
                    "coordy" : 4,
                    "midpoint" : {
                        "coordx" : 2,
                        "coordy" : 2
                    },
                    "levels" : []
                }
            }
        ]
    }
}


问:
Boost XML class_id based deserialization
I have an XML serialized reflected type and I can get its serialization like this:

```<code>template <typename Archive>
std::function<void(Archive&,unsigned)> get_serialization_for_type(std::string name);

</code>```

These types all have a GUID set with the boost serialization library, so their class_id attribute in the XML matches a valid name. How do I deserialize these types? Is there a way I can get the attributes of the current node the archive is reading? Suggestions on different approaches are also welcome but I cannot change the format of the XML.

Sample XML:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="17">
   ...
   <container class_id="23" tracking_level="0" version="0">
      <count>2</count>
      <typeA class_id="type_a" tracking_level="0" version="0">
         ...
      </typeA>
      <typeB class_id="type_b" tracking_level="0" version="0">
         ...
      </typeB>
   </container>
   ...
</boost_serialization>
</code>```

答:
That looks like a regular Boost Serialization XML archive. Why don't you read it in exactly the same way as you wrote it?

What I mean is basically this: this code serializes and deserializes a container of polymorphic elements with different types and properties.

It does so using "the same" code for serialization and de-serialization.

You should in principle be able to leverage this pattern if the XML is indeed being generated by Boost Serialization.

Live On Coliru

```<code>#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>

#include <boost/serialization/vector.hpp>
#include <boost/serialization/unique_ptr.hpp>
#include <boost/serialization/assume_abstract.hpp>
#include <boost/serialization/export.hpp>

#include <iostream>
#include <sstream>
#include <boost/core/demangle.hpp>

namespace MyLib {
    struct Base {
        using BaseContainer = std::vector<std::unique_ptr<Base> >;
        virtual ~Base() = default;
        int a, b, c;
    };

    struct A : Base {
        std::string d, e, f;
    };

    struct B : Base {
        float h, i, j;
    };

    template <typename Ar> void serialize(Ar& ar, Base& base, unsigned) {
        ar & BOOST_SERIALIZATION_NVP(base.a)
           & BOOST_SERIALIZATION_NVP(base.b)
           & BOOST_SERIALIZATION_NVP(base.c)
           ;
    }

    template <typename Ar> void serialize(Ar& ar, A& a, unsigned) {
        ar & boost::serialization::make_nvp("Base", boost::serialization::base_object<Base>(a))
           & BOOST_SERIALIZATION_NVP(a.d)
           & BOOST_SERIALIZATION_NVP(a.e)
           & BOOST_SERIALIZATION_NVP(a.f)
           ;
    }

    template <typename Ar> void serialize(Ar& ar, B& b, unsigned) {
        ar & boost::serialization::make_nvp("Base", boost::serialization::base_object<Base>(b))
           & BOOST_SERIALIZATION_NVP(b.h)
           & BOOST_SERIALIZATION_NVP(b.i)
           & BOOST_SERIALIZATION_NVP(b.j)
           ;
    }

    using BaseContainer = std::vector<std::unique_ptr<Base> >;
}

//BOOST_SERIALIZATION_ASSUME_ABSTRACT(MyLib::Base)
BOOST_CLASS_EXPORT(MyLib::Base)
BOOST_CLASS_EXPORT_GUID(MyLib::A, "type_A")
BOOST_CLASS_EXPORT_GUID(MyLib::B, "type_B")

int main() {
    std::stringstream xml;

    {
        MyLib::BaseContainer container;
        container.emplace_back(std::make_unique<MyLib::A>());
        container.emplace_back(std::make_unique<MyLib::B>());
        container.emplace_back(std::make_unique<MyLib::B>());
        container.emplace_back(std::make_unique<MyLib::A>());

        boost::archive::xml_oarchive oa(xml);

        oa << BOOST_SERIALIZATION_NVP(container);
    }

    //std::cout << xml.str();

    {
        boost::archive::xml_iarchive ia(xml);

        MyLib::BaseContainer container;
        ia >> BOOST_SERIALIZATION_NVP(container);

        for (auto& el : container) {
            std::cout << "Element of type " << boost::core::demangle(typeid(*el).name()) << "\n";
        }
    }
}
</code>```

Prints:

```<code>Element of type MyLib::A
Element of type MyLib::B
Element of type MyLib::B
Element of type MyLib::A
</code>```

Body:
I have an XML serialized reflected type and I can get its serialization like this:

template <typename Archive>
std::function<void(Archive&,unsigned)> get_serialization_for_type(std::string name);

These types all have a GUID set with the boost serialization library, so their class_id attribute in the XML matches a valid name. How do I deserialize these types? Is there a way I can get the attributes of the current node the archive is reading? Suggestions on different approaches are also welcome but I cannot change the format of the XML.

Sample XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="17">
   ...
   <container class_id="23" tracking_level="0" version="0">
      <count>2</count>
      <typeA class_id="type_a" tracking_level="0" version="0">
         ...
      </typeA>
      <typeB class_id="type_b" tracking_level="0" version="0">
         ...
      </typeB>
   </container>
   ...
</boost_serialization>

Body:
That looks like a regular Boost Serialization XML archive. Why don't you read it in exactly the same way as you wrote it?

What I mean is basically this: this code serializes and deserializes a container of polymorphic elements with different types and properties.

It does so using "the same" code for serialization and de-serialization.

You should in principle be able to leverage this pattern if the XML is indeed being generated by Boost Serialization.

Live On Coliru

#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>

#include <boost/serialization/vector.hpp>
#include <boost/serialization/unique_ptr.hpp>
#include <boost/serialization/assume_abstract.hpp>
#include <boost/serialization/export.hpp>

#include <iostream>
#include <sstream>
#include <boost/core/demangle.hpp>

namespace MyLib {
    struct Base {
        using BaseContainer = std::vector<std::unique_ptr<Base> >;
        virtual ~Base() = default;
        int a, b, c;
    };

    struct A : Base {
        std::string d, e, f;
    };

    struct B : Base {
        float h, i, j;
    };

    template <typename Ar> void serialize(Ar& ar, Base& base, unsigned) {
        ar & BOOST_SERIALIZATION_NVP(base.a)
           & BOOST_SERIALIZATION_NVP(base.b)
           & BOOST_SERIALIZATION_NVP(base.c)
           ;
    }

    template <typename Ar> void serialize(Ar& ar, A& a, unsigned) {
        ar & boost::serialization::make_nvp("Base", boost::serialization::base_object<Base>(a))
           & BOOST_SERIALIZATION_NVP(a.d)
           & BOOST_SERIALIZATION_NVP(a.e)
           & BOOST_SERIALIZATION_NVP(a.f)
           ;
    }

    template <typename Ar> void serialize(Ar& ar, B& b, unsigned) {
        ar & boost::serialization::make_nvp("Base", boost::serialization::base_object<Base>(b))
           & BOOST_SERIALIZATION_NVP(b.h)
           & BOOST_SERIALIZATION_NVP(b.i)
           & BOOST_SERIALIZATION_NVP(b.j)
           ;
    }

    using BaseContainer = std::vector<std::unique_ptr<Base> >;
}

//BOOST_SERIALIZATION_ASSUME_ABSTRACT(MyLib::Base)
BOOST_CLASS_EXPORT(MyLib::Base)
BOOST_CLASS_EXPORT_GUID(MyLib::A, "type_A")
BOOST_CLASS_EXPORT_GUID(MyLib::B, "type_B")

int main() {
    std::stringstream xml;

    {
        MyLib::BaseContainer container;
        container.emplace_back(std::make_unique<MyLib::A>());
        container.emplace_back(std::make_unique<MyLib::B>());
        container.emplace_back(std::make_unique<MyLib::B>());
        container.emplace_back(std::make_unique<MyLib::A>());

        boost::archive::xml_oarchive oa(xml);

        oa << BOOST_SERIALIZATION_NVP(container);
    }

    //std::cout << xml.str();

    {
        boost::archive::xml_iarchive ia(xml);

        MyLib::BaseContainer container;
        ia >> BOOST_SERIALIZATION_NVP(container);

        for (auto& el : container) {
            std::cout << "Element of type " << boost::core::demangle(typeid(*el).name()) << "\n";
        }
    }
}

Prints:

Element of type MyLib::A
Element of type MyLib::B
Element of type MyLib::B
Element of type MyLib::A


问:
"address of stack memory associated with local variable" error when running user-defined function in C
Recentely I've been taking the CS50 2020 course from Harvard University as an introduction to C programming. I'm not very experienced with the language or with coding as a whole, so I'm struggling a bit to figure out what is wrong with my code.

I wrote this little function which is suposed to take in a string and, by calling another function, encrypt the text using a Caesar cypher, then return it as a string. Problem is, I can't figure out how to return the character array as a string. I tried adding a NUL char at the end of the array after reading a bit about the problem, and it compiled alright, but when I ran the program I got the following error message:

```<code>error: address of stack memory associated with local variable 'result' returned [-Werror,-Wreturn-stack-address]
    return result;
           ^~~~~~
</code>```

My code:

```<code>string encypher(string text)
{
    int length = strlen(text);
    char result[length];
    for(int i = 0; i < length; i++)
    {
        int letter_c = test_char(text[i]);
        result[i] = (char)letter_c;
    }
    result[length + 1] = '\0';
    return result;
}
</code>```

答:
In the line

return result;

the array decays to a pointer to the first element of the array, so it is effectively the following:

return &result[0];

This array is allocated on the stack in the function encypher, so it will no longer exist when the function returns. Therefore, the returned pointer is a dangling pointer, which means that it is pointing to memory which is no longer allocated and may be overwritten by something else. For this reason, such a pointer should not be used.

In order to allocate memory that will still exist after the function returns, you can either:

Use dynamic memory allocation, such as malloc.

Allocate the memory on the stack of the function calling encypher (instead of in the function encypher itself) and change the parameters of the function encypher to accept a pointer to that array.

In my opinion, the second solution is the cleaner solution, as it allows the caller to decide where and how the memory is allocated. Using that solution, your code would look like this:

```<code>void encypher( char *cyphertext, const char *plaintext )
{
    int length = strlen(plaintext);
    //removed: char result[length];
    for(int i = 0; i < length; i++)
    {
        int letter_c = test_char(plaintext[i]);
        cyphertext[i] = (char)letter_c;
    }
    cyphertext[length + 1] = '\0';
}
</code>```

The function could now be called like this:

```<code>int main( void )
{
    char plaintext[23] = "This is the plaintext.";
    char cyphertext[23]; //make sure the buffer is large enough to store the cyphertext including the terminating null character

    encypher( cyphertext, plaintext );

    return 0;
}
</code>```

Body:
Recentely I've been taking the CS50 2020 course from Harvard University as an introduction to C programming. I'm not very experienced with the language or with coding as a whole, so I'm struggling a bit to figure out what is wrong with my code.

I wrote this little function which is suposed to take in a string and, by calling another function, encrypt the text using a Caesar cypher, then return it as a string. Problem is, I can't figure out how to return the character array as a string. I tried adding a NUL char at the end of the array after reading a bit about the problem, and it compiled alright, but when I ran the program I got the following error message:

error: address of stack memory associated with local variable 'result' returned [-Werror,-Wreturn-stack-address]
    return result;
           ^~~~~~

My code:

string encypher(string text)
{
    int length = strlen(text);
    char result[length];
    for(int i = 0; i < length; i++)
    {
        int letter_c = test_char(text[i]);
        result[i] = (char)letter_c;
    }
    result[length + 1] = '\0';
    return result;
}

Body:
In the line

return result;

the array decays to a pointer to the first element of the array, so it is effectively the following:

return &result[0];

This array is allocated on the stack in the function encypher, so it will no longer exist when the function returns. Therefore, the returned pointer is a dangling pointer, which means that it is pointing to memory which is no longer allocated and may be overwritten by something else. For this reason, such a pointer should not be used.

In order to allocate memory that will still exist after the function returns, you can either:

Use dynamic memory allocation, such as malloc.

Allocate the memory on the stack of the function calling encypher (instead of in the function encypher itself) and change the parameters of the function encypher to accept a pointer to that array.

In my opinion, the second solution is the cleaner solution, as it allows the caller to decide where and how the memory is allocated. Using that solution, your code would look like this:

void encypher( char *cyphertext, const char *plaintext )
{
    int length = strlen(plaintext);
    //removed: char result[length];
    for(int i = 0; i < length; i++)
    {
        int letter_c = test_char(plaintext[i]);
        cyphertext[i] = (char)letter_c;
    }
    cyphertext[length + 1] = '\0';
}

The function could now be called like this:

int main( void )
{
    char plaintext[23] = "This is the plaintext.";
    char cyphertext[23]; //make sure the buffer is large enough to store the cyphertext including the terminating null character

    encypher( cyphertext, plaintext );

    return 0;
}


问:
Sorting Array in nodejs by date order (recent to oldest)
I'm trying to sort the following array so that the most recent event_end is first

```<code>{
   "results":[
      {
         "event_start":"2017-11-27T09:00:00Z",
         "event_end":"2017-11-27T09:00:00Z",
         "attendance":0,
         "title":"Administrate Training Session",
         "type":"delegate"
      },
      {
         "event_start":"2018-02-01T09:00:00Z",
         "event_end":"2018-02-01T09:00:00Z",
         "attendance":0,
         "title":"Health and Safety Awareness (HSA)",
         "type":"delegate"
      },
      {
         "event_start":"2018-02-19T09:00:00Z",
         "event_end":"2018-04-30T09:00:00Z",
         "attendance":0,
         "title":"SMSTS",
         "type":"delegate"
      }
   ]
}
</code>```

My current code (and this is after trying almost all the different ways to do this is):

```<code>Array.from(outcome).sort(sortFunction);
      function sortFunction(a, b){
        if(b[3] === a[3]){
          return 0;
        } else {
          return (b[3] < a[3]) ? -1 : 1;
        }
      }
</code>```

And just to give clarity to how the array is being created:

```<code>var history = JSON.parse(body);
      var outcome = {};
      var key = 'results';
      outcome[key] = [];
      history.forEach(delegate => {
          var data = null;
          var sessionKey;
          var attendanceCount = 0;
          var sessionCount = 0;
          var attended = 0;
          Array.from(delegate['session_attendance']).forEach(function(val){
            if(!val.__proto__.__proto__){
              sessionCount++;
            }
          });
          var type;
          for(var k in delegate['session_attendance']){
            sessionKey = k;
            if(k['status'] == true){
              attendanceCount++;
            }
          }
          if(attendanceCount == 0){
            attended = attendanceCount;
          } else {
            (attendanceCount / sessionCount) * 100
          }
          if(delegate['registration']['booking_contact'] !== null){
            if(delegate['registration']['booking_contact']['id'] == delegate['contact']['id']){
              type = 'booking_contact';
            }
          } else{
            type = 'delegate';
          }
          data = {
            'objectId': delegate['id'],
            'title': delegate['event']['title'],
            'event_start': delegate['event']['start'],
            'event_end': delegate['session_attendance'][sessionKey]['start'],
            'attendance': attended,
            'type': type
          }
          outcome[key].push(data);
        })
</code>```

I'm sure its obvious but can anyone point me in the direction of where I am going wrong and how to sort it appropriately?

答:
var obj = {
   "results":[
      {
         "event_start":"2017-11-27T09:00:00Z",
         "event_end":"2017-11-27T09:00:00Z",
         "attendance":0,
         "title":"Administrate Training Session",
         "type":"delegate"
      },
      {
         "event_start":"2018-02-01T09:00:00Z",
         "event_end":"2018-02-01T09:00:00Z",
         "attendance":0,
         "title":"Health and Safety Awareness (HSA)",
         "type":"delegate"
      },
      {
         "event_start":"2018-02-19T09:00:00Z",
         "event_end":"2018-04-30T09:00:00Z",
         "attendance":0,
         "title":"SMSTS",
         "type":"delegate"
      }
   ]
}

obj.results.sort((a, b) => {
  return new Date(b.event_end) - new Date(a.event_end)
})

console.log(obj.results)```

Body:
I'm trying to sort the following array so that the most recent event_end is first

{
   "results":[
      {
         "event_start":"2017-11-27T09:00:00Z",
         "event_end":"2017-11-27T09:00:00Z",
         "attendance":0,
         "title":"Administrate Training Session",
         "type":"delegate"
      },
      {
         "event_start":"2018-02-01T09:00:00Z",
         "event_end":"2018-02-01T09:00:00Z",
         "attendance":0,
         "title":"Health and Safety Awareness (HSA)",
         "type":"delegate"
      },
      {
         "event_start":"2018-02-19T09:00:00Z",
         "event_end":"2018-04-30T09:00:00Z",
         "attendance":0,
         "title":"SMSTS",
         "type":"delegate"
      }
   ]
}

My current code (and this is after trying almost all the different ways to do this is):

Array.from(outcome).sort(sortFunction);
      function sortFunction(a, b){
        if(b[3] === a[3]){
          return 0;
        } else {
          return (b[3] < a[3]) ? -1 : 1;
        }
      }

And just to give clarity to how the array is being created:

var history = JSON.parse(body);
      var outcome = {};
      var key = 'results';
      outcome[key] = [];
      history.forEach(delegate => {
          var data = null;
          var sessionKey;
          var attendanceCount = 0;
          var sessionCount = 0;
          var attended = 0;
          Array.from(delegate['session_attendance']).forEach(function(val){
            if(!val.__proto__.__proto__){
              sessionCount++;
            }
          });
          var type;
          for(var k in delegate['session_attendance']){
            sessionKey = k;
            if(k['status'] == true){
              attendanceCount++;
            }
          }
          if(attendanceCount == 0){
            attended = attendanceCount;
          } else {
            (attendanceCount / sessionCount) * 100
          }
          if(delegate['registration']['booking_contact'] !== null){
            if(delegate['registration']['booking_contact']['id'] == delegate['contact']['id']){
              type = 'booking_contact';
            }
          } else{
            type = 'delegate';
          }
          data = {
            'objectId': delegate['id'],
            'title': delegate['event']['title'],
            'event_start': delegate['event']['start'],
            'event_end': delegate['session_attendance'][sessionKey]['start'],
            'attendance': attended,
            'type': type
          }
          outcome[key].push(data);
        })

I'm sure its obvious but can anyone point me in the direction of where I am going wrong and how to sort it appropriately?


问:
Grails functional test Geb page object module not working No signature of method
This is the page object.

```<code>package myapp.pages
import geb.Page

class LoginPage extends Page {
    static url = "http://localhost:8080/login/auth"
    //static at = {title.contains("Login")}
    static at = {
        waitFor {title.contains("Login")} // Add waitFor here to verify on page
    }
    static content = {
        loginForm { $( 'form') }
        usernameField { $('form').userName }
        passwordField { $('form').password }
        submitButton { $('input#submit' )}
    }

    void  loginSubmit(String email, String password) {
        usernameField = "email@something.com"
        assert $('form').username == "email@something.com"
        passwordField = "secret"
        assert $('form').password == "secret"
        submitButton.click()
    }
}
</code>```

And this is the LoginSpec test file

```<code>package myapp.login

import geb.spock.GebSpec
import grails.testing.mixin.integration.Integration
import grails.transaction.*
import myapp.pages.LoginPage

@Integration
@Rollback
class LoginSpec extends GebSpec {

    def setup() {
    }

    def cleanup() {
    }

    void "user successfully logs in, is redirected to homepage"() {
        given:
        to LoginPage

        when:
        LoginPage.loginSubmit("email@something.com", "secret")

        then:
        title.contains("Dashboard")
    }
}
</code>```

When i run this test, I get the following error:

```<code>groovy.lang.MissingMethodException: No signature of method: static myapp.pages.LoginPage.loginSubmit() is applicable for argument types: (java.lang.String, java.lang.String) values: [email@something.com.com, secret]
</code>```

I basically get the same error when I hardcode the username and password into the login page loginsubmit function. The selectors are fine, when I use the same selectors directly in the LoginSpec test to set the username and password, the test passes. The issue only occurs when I try to use the page object.

答: Geb remembers the current page and automatically dispatches method calls to the page, so you do not need to include the page class name: loginSubmit("email@something.com", "secret") in the test will call the method on the page.

Body:
This is the page object.

package myapp.pages
import geb.Page

class LoginPage extends Page {
    static url = "http://localhost:8080/login/auth"
    //static at = {title.contains("Login")}
    static at = {
        waitFor {title.contains("Login")} // Add waitFor here to verify on page
    }
    static content = {
        loginForm { $( 'form') }
        usernameField { $('form').userName }
        passwordField { $('form').password }
        submitButton { $('input#submit' )}
    }

    void  loginSubmit(String email, String password) {
        usernameField = "email@something.com"
        assert $('form').username == "email@something.com"
        passwordField = "secret"
        assert $('form').password == "secret"
        submitButton.click()
    }
}

And this is the LoginSpec test file

package myapp.login

import geb.spock.GebSpec
import grails.testing.mixin.integration.Integration
import grails.transaction.*
import myapp.pages.LoginPage

@Integration
@Rollback
class LoginSpec extends GebSpec {

    def setup() {
    }

    def cleanup() {
    }

    void "user successfully logs in, is redirected to homepage"() {
        given:
        to LoginPage

        when:
        LoginPage.loginSubmit("email@something.com", "secret")

        then:
        title.contains("Dashboard")
    }
}

When i run this test, I get the following error:

groovy.lang.MissingMethodException: No signature of method: static myapp.pages.LoginPage.loginSubmit() is applicable for argument types: (java.lang.String, java.lang.String) values: [email@something.com.com, secret]

I basically get the same error when I hardcode the username and password into the login page loginsubmit function. The selectors are fine, when I use the same selectors directly in the LoginSpec test to set the username and password, the test passes. The issue only occurs when I try to use the page object.


问:
Styling the UI Fabric Date Picker Callout
How could I modify the style of elements inside the callout of the UI Fabric Date Picker? For example highlight the current month?

According to the documentation, I should be able to use the DatePicker styles property to target sub-components, but I don't know how to reach specific elements:

```<code>styles = {
  callout: {
  ... what goes here?
  }
}
</code>```

I am trying to get this to work without having to rely on yet another third party library like styled-components.

答:
Thanks @Lumpenstein for all the help. I am just posting here an example to showcase the use of the selectors and & notations:

```<code>const dpStyles: IDatePickerStyles = {
    root: { /* styles */ },
    textField: { /* styles */ },
    icon: { /* styles */ },
    callout:
      { selectors:
        { '& button': { backgroundColor: "red" }
      }
 }
};
</code>```

Body:
How could I modify the style of elements inside the callout of the UI Fabric Date Picker? For example highlight the current month?

According to the documentation, I should be able to use the DatePicker styles property to target sub-components, but I don't know how to reach specific elements:

styles = {
  callout: {
  ... what goes here?
  }
}

I am trying to get this to work without having to rely on yet another third party library like styled-components.

Body:
Thanks @Lumpenstein for all the help. I am just posting here an example to showcase the use of the selectors and & notations:

const dpStyles: IDatePickerStyles = {
    root: { /* styles */ },
    textField: { /* styles */ },
    icon: { /* styles */ },
    callout:
      { selectors:
        { '& button': { backgroundColor: "red" }
      }
 }
};


问:
Error: 404008: Resource Not Found While Exporting View into CSV in Python
I'm trying to export data from a dashboard to csv. I found the populate_csv(view_item) function but have a trouble running the script.

This is the error that i receive:
404008: Resource Not Found
        API version '2.7' does not support access to the given resource.

Does anyone know another way to export data into CSV using python. Below is my starter code. Thanks a lot!

```<code>import tableauserverclient as TSC

tableau_auth = TSC.TableauAuth('user', '###########')

server = TSC.Server('xxxxxxxxxx')

# change current api version from 2.3 to 2.7

server.version = '2.7'

with server.auth.sign_in(tableau_auth):

    wconnect = server.workbooks.get_by_id('2ff8366c-8398-4dc0-b810-e648f90208a7')

    vfound = wconnect.views

    view_item = vfound[0]

    print(vars(vfound[0]))

    server.views.populate_csv(view_item)

    with open('view_csv2.csv','wb') as f:

        f.write(b''.join(view_item.csv))
</code>```

Does anyone know why and what i need to do to fix this?

Thanks!

答: I had the same problem with version 2.7 but it worked fine with 2.8</p>

Body:
I'm trying to export data from a dashboard to csv. I found the populate_csv(view_item) function but have a trouble running the script.

This is the error that i receive:
404008: Resource Not Found
        API version '2.7' does not support access to the given resource.

Does anyone know another way to export data into CSV using python. Below is my starter code. Thanks a lot!

import tableauserverclient as TSC

tableau_auth = TSC.TableauAuth('user', '###########')

server = TSC.Server('xxxxxxxxxx')

# change current api version from 2.3 to 2.7

server.version = '2.7'

with server.auth.sign_in(tableau_auth):

    wconnect = server.workbooks.get_by_id('2ff8366c-8398-4dc0-b810-e648f90208a7')

    vfound = wconnect.views

    view_item = vfound[0]

    print(vars(vfound[0]))

    server.views.populate_csv(view_item)

    with open('view_csv2.csv','wb') as f:

        f.write(b''.join(view_item.csv))

Does anyone know why and what i need to do to fix this?

Thanks!


问:
What is difference between creating HTML by innerHTML and document.createElement?
I wonder what is the difference between creating HTML by innerHTML and document.createElement?

For example, I want to create a new DIV inside of parent DIV.

Let's assume parent DIV has no content.

One option is parent.innerHTML = '

';

Another option is parent.append(document.createElement('div'));

I was asked this during an interview.

Personally, I think that creating an HTML object gives us the flexibility to add more elements later on compared to using innerHTML.

Wondering if there is a better reason.

答:
In addition to your answer If you use 1st option:
1. Adding innerHTML will trigger DOM update immediately
2. If you need to update content of newly created element you should either select it from DOM or update parent’s innerHTML again (will cause rerender, and potential lost of event listeners, if there any on a child element)</p>


问:
Where to store images in Android
I have moved all my images from the folder mipmap to drawable because here it was said that the mipmap folder is only for app icons to lanch the app Mipmaps vs. drawable folders (the answer got 841 likes). However, when I now want to start my app I get an error message

```<code> FATAL EXCEPTION: main
    Process: com.example.td.barapp, PID: 4331
    java.lang.RuntimeException: Canvas: trying to draw too large(188394348bytes) bitmap.
        at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)
</code>```

In several realted questions people tell to store the pictures in different drawable folders (see Android : Understanding drawable folder) like drawable-xxhdpi or drawable-xxxhdpi.

Update: I was told by someone in this post (who later deleted his answers) to store the image (which has a size of 1,7 MB) in the folder drawable-anydpi. I did as he said but the outcome on the Emulator looks quite bad for an imageview (see screenshot):

Then I moved the same file  back into the folder mipmap-xxxhdpi and now it looks good again. So my question now is, whether it is also okay to have the image in the mipmap-xxxhdpi folder instead of the drawable folder? I'd be happy for every advice because I am quite confused now.

答:
java.lang.RuntimeException: Canvas: trying to draw too
  large(188394348bytes) bitmap

This exception mainly because you are trying to display a big image ~ 188MB which will have a high resolution, and android puts limitation on that, This also reported here.

One of the reasons is to save device resources; for instance you might get java.lang.OutOfMemory, so the system save device memory from that.

1, 2, 3 may guide you thoroughly on that.

Normally you can use a few mega bytes image in your app ~0-3MBs.
Third party libraries like Glide & Picasso offer disk, network, & memory management techniques while displaying images on your ImageViews.

One of the options you may consider is to resize images before loading them, so can have look on this question.

Keep in mind that android puts limitaion on your apk file on the app store, so you need to minimize images for that reason, or load them from a back-end server.

As you mentioned, you can only put app icons in res\mipmap. And if you decide to put the images on your app, it's efficient to create them in different densities (hdpi, xhdpi, xxhdpi, xxxhdpi...), so they can match all the variety of device resolutions, and lets you avoid distorted images or high processing by android OS to match your image to the device resolution before displaying them.

Title: Where to store images in Android

Body:
I have moved all my images from the folder mipmap to drawable because here it was said that the mipmap folder is only for app icons to lanch the app Mipmaps vs. drawable folders (the answer got 841 likes). However, when I now want to start my app I get an error message

 FATAL EXCEPTION: main
    Process: com.example.td.barapp, PID: 4331
    java.lang.RuntimeException: Canvas: trying to draw too large(188394348bytes) bitmap.
        at android.view.DisplayListCanvas.throwIfCannotDraw(DisplayListCanvas.java:260)

In several realted questions people tell to store the pictures in different drawable folders (see Android : Understanding drawable folder) like drawable-xxhdpi or drawable-xxxhdpi.

Update: I was told by someone in this post (who later deleted his answers) to store the image (which has a size of 1,7 MB) in the folder drawable-anydpi. I did as he said but the outcome on the Emulator looks quite bad for an imageview (see screenshot):

Then I moved the same file  back into the folder mipmap-xxxhdpi and now it looks good again. So my question now is, whether it is also okay to have the image in the mipmap-xxxhdpi folder instead of the drawable folder? I'd be happy for every advice because I am quite confused now.


问:
Ionic v4 - how do I autofocus on a Input?
I have a view with an input <ion-input #codigobarras></ion-input>

How can I auto focus on this input?

What have I tried

```<code>@ViewChild('codigobarras') input_codigobarras: Input;

...

ionViewDidEnter() {
    this.input_codigobarras.focus(); // didn't work = temp2.focus is not a function
    this.input_codigobarras.focus.emit(); // didn't work = do nothing, just returns undefined
    this.input_codigobarras.getElementRef().nativeElement.focus() // didn't work = do nothing, just returns undefined
    this.input_codigobarras.setFocus(); // didn't work = do nothing, just returns undefined
}
</code>```
```<code><ion-input [autofocus]></ion-input> <!-- Didn't work -->
</code>```

答:
A more generic solution to do this when and where you want could be:

```<code><ion-input ... #inputId></ion-input>
</code>```

So with a ViewChild in your controller you can easily set the focus on:

```<code>@ViewChild('inputId', {static: false}) ionInput: { setFocus: () => void; };
...
setFocusOnInput() {
   this.ionInput.setFocus();
}
</code>```

Body:
I have a view with an input <ion-input #codigobarras></ion-input>

How can I auto focus on this input?

What have I tried

@ViewChild('codigobarras') input_codigobarras: Input;

...

ionViewDidEnter() {
    this.input_codigobarras.focus(); // didn't work = temp2.focus is not a function
    this.input_codigobarras.focus.emit(); // didn't work = do nothing, just returns undefined
    this.input_codigobarras.getElementRef().nativeElement.focus() // didn't work = do nothing, just returns undefined
    this.input_codigobarras.setFocus(); // didn't work = do nothing, just returns undefined
}

<ion-input [autofocus]></ion-input>

Body:
A more generic solution to do this when and where you want could be:

<ion-input ... #inputId></ion-input>

So with a ViewChild in your controller you can easily set the focus on:

@ViewChild('inputId', {static: false}) ionInput: { setFocus: () => void; };
...
setFocusOnInput() {
   this.ionInput.setFocus();
}


答:
Few differences:

innerHTML works with htmlString where as createElement() method creates the HTML element specified by tagName. And clearly string differs to HTML element.

Events attached with innerHTML are removed if use =+ as this redraws the full html but events attached to the element created bycreateElement() are not lost.

Demo:

document.body.innerHTML += '
Clicking on this will not show alert as this is created with innerHTML
';
document.getElementById('first').addEventListener('click', function (){
  alert('hi'); // will not work
});
document.body.innerHTML += '
Created again with innerHTML
';

var newDiv = document.createElement("div");
newDiv.id = "second";
newDiv.textContent = 'Clicking on this will show alert as this is created with createElement()';
document.body.append(newDiv);
document.getElementById('second').addEventListener('click', function (){
  alert('Hi...'); // will not work
});
var newDiv2 = document.createElement("div");
newDiv2.textContent = 'Created with createElement() again';
document.body.append(newDiv2);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{
  padding: 5px 10px;
  border: 2px solid gray;
  background-color: lightblue
}</code>```

Title: What is difference between creating HTML by innerHTML and document.createElement?

Body:
I wonder what is the difference between creating HTML by innerHTML and document.createElement?

For example, I want to create a new DIV inside of parent DIV.

Let's assume parent DIV has no content.

One option is parent.innerHTML = '

';

Another option is parent.append(document.createElement('div'));

I was asked this during an interview.

Personally, I think that creating an HTML object gives us the flexibility to add more elements later on compared to using innerHTML.

Wondering if there is a better reason.

Body:
Few differences:

innerHTML works with htmlString where as createElement() method creates the HTML element specified by tagName. And clearly string differs to HTML element.

Events attached with innerHTML are removed if use =+ as this redraws the full html but events attached to the element created bycreateElement() are not lost.

Demo:

document.body.innerHTML += '<div id="first">Clicking on this will not show alert as this is created with innerHTML</div>';
document.getElementById('first').addEventListener('click', function (){
  alert('hi'); // will not work
});
document.body.innerHTML += '<div>Created again with innerHTML</div>';

var newDiv = document.createElement("div");
newDiv.id = "second";
newDiv.textContent = 'Clicking on this will show alert as this is created with createElement()';
document.body.append(newDiv);
document.getElementById('second').addEventListener('click', function (){
  alert('Hi...'); // will not work
});
var newDiv2 = document.createElement("div");
newDiv2.textContent = 'Created with createElement() again';
document.body.append(newDiv2);

div{
  padding: 5px 10px;
  border: 2px solid gray;
  background-color: lightblue
}


问:
Python GAE: raised ValueError(Unpaired high surrogate) with json.loads only on production server
On GAE with Python, I'm using urlfetch to fetch a json string from Flickr. When I try to load that string with json.loads on the production server the exception "raised ValueError(Unpaired high surrogate)" is thrown.

When I try to json.loads the string in the development console, it loads into a dict as expected (see below). I have successfully loaded several other json strings from Flickr with the same code. There is something about the json string below that throws the ValueError exception ONLY on the production server.

```<code>import json

s = """{"photo":{"id":"191019103", "secret":"d7a8bb95bc", "server":"72", "farm":1, "dateuploaded":"1153079847", "isfavorite":0, "license":"1", "safety_level":"0", "rotation":0, "originalsecret":"d7a8bb95bc", "originalformat":"jpg", "owner":{"nsid":"13968020@N00", "username":"\ud800dc80 jgraham", "realname":"", "location":"", "iconserver":"38", "iconfarm":1}, "title":{"_content":"By the Year 2000 All Our Food Will be in the Form of Tiny Pills"}, "description":{"_content":""}, "visibility":{"ispublic":1, "isfriend":0, "isfamily":0}, "dates":{"posted":"1153079847", "taken":"2006-07-15 14:31:16", "takengranularity":"0", "lastupdate":"1282690106"}, "views":"984", "editability":{"cancomment":0, "canaddmeta":0}, "publiceditability":{"cancomment":1, "canaddmeta":0}, "usage":{"candownload":1, "canblog":0, "canprint":0, "canshare":1}, "comments":{"_content":"18"}, "notes":{"note":[]}, "people":{"haspeople":0}, "tags":{"tag":[{"id":"1207251-191019103-2909", "author":"13968020@N00", "raw":"Birmingham", "_content":"birmingham", "machine_tag":0}, {"id":"1207251-191019103-77552", "author":"13968020@N00", "raw":"Bullring", "_content":"bullring", "machine_tag":0}, {"id":"1207251-191019103-463", "author":"13968020@N00", "raw":"Abstract", "_content":"abstract", "machine_tag":0}, {"id":"1207251-191019103-1174", "author":"13968020@N00", "raw":"Architecture", "_content":"architecture", "machine_tag":0}, {"id":"1207251-191019103-141", "author":"13968020@N00", "raw":"Blue", "_content":"blue", "machine_tag":0}, {"id":"1207251-191019103-2194948", "author":"13968020@N00", "raw":"i500", "_content":"i500", "machine_tag":0}, {"id":"1207251-191019103-11820", "author":"13968020@N00", "raw":"Explore", "_content":"explore", "machine_tag":0}, {"id":"1207251-191019103-3254511", "author":"13968020@N00", "raw":"utata_feature", "_content":"utatafeature", "machine_tag":0}]}, "urls":{"url":[{"type":"photopage", "_content":"http:\/\/www.flickr.com\/photos\/jgraham\/191019103\/"}]}, "media":"photo"}, "stat":"ok"}"""

print json.loads(s) #prints dict
</code>```

答:
If you have a big json file with one record per line and don't mind missing some lines, you can just ignore those lines.</p>

```<code>grep -v "\\\\ud" file.json > file2.json
</code>```

ContentLicense: CC BY-SA 3.0

Body:
On GAE with Python, I'm using urlfetch to fetch a json string from Flickr. When I try to load that string with json.loads on the production server the exception "raised ValueError(Unpaired high surrogate)" is thrown.

When I try to json.loads the string in the development console, it loads into a dict as expected (see below). I have successfully loaded several other json strings from Flickr with the same code. There is something about the json string below that throws the ValueError exception ONLY on the production server.

import json

s = """{"photo":{"id":"191019103", "secret":"d7a8bb95bc", "server":"72", "farm":1, "dateuploaded":"1153079847", "isfavorite":0, "license":"1", "safety_level":"0", "rotation":0, "originalsecret":"d7a8bb95bc", "originalformat":"jpg", "owner":{"nsid":"13968020@N00", "username":"\ud800dc80 jgraham", "realname":"", "location":"", "iconserver":"38", "iconfarm":1}, "title":{"_content":"By the Year 2000 All Our Food Will be in the Form of Tiny Pills"}, "description":{"_content":""}, "visibility":{"ispublic":1, "isfriend":0, "isfamily":0}, "dates":{"posted":"1153079847", "taken":"2006-07-15 14:31:16", "takengranularity":"0", "lastupdate":"1282690106"}, "views":"984", "editability":{"cancomment":0, "canaddmeta":0}, "publiceditability":{"cancomment":1, "canaddmeta":0}, "usage":{"candownload":1, "canblog":0, "canprint":0, "canshare":1}, "comments":{"_content":"18"}, "notes":{"note":[]}, "people":{"haspeople":0}, "tags":{"tag":[{"id":"1207251-191019103-2909", "author":"13968020@N00", "raw":"Birmingham", "_content":"birmingham", "machine_tag":0}, {"id":"1207251-191019103-77552", "author":"13968020@N00", "raw":"Bullring", "_content":"bullring", "machine_tag":0}, {"id":"1207251-191019103-463", "author":"13968020@N00", "raw":"Abstract", "_content":"abstract", "machine_tag":0}, {"id":"1207251-191019103-1174", "author":"13968020@N00", "raw":"Architecture", "_content":"architecture", "machine_tag":0}, {"id":"1207251-191019103-141", "author":"13968020@N00", "raw":"Blue", "_content":"blue", "machine_tag":0}, {"id":"1207251-191019103-2194948", "author":"13968020@N00", "raw":"i500", "_content":"i500", "machine_tag":0}, {"id":"1207251-191019103-11820", "author":"13968020@N00", "raw":"Explore", "_content":"explore", "machine_tag":0}, {"id":"1207251-191019103-3254511", "author":"13968020@N00", "raw":"utata_feature", "_content":"utatafeature", "machine_tag":0}]}, "urls":{"url":[{"type":"photopage", "_content":"http:\/\/www.flickr.com\/photos\/jgraham\/191019103\/"}]}, "media":"photo"}, "stat":"ok"}"""

print json.loads(s) #prints dict

Body:
If you have a big json file with one record per line and don't mind missing some lines, you can just ignore those lines.

grep -v "\\\\ud" file.json > file2.json


问:
How do I set up a PayPal checkout
I'm wanting to set up a PayPal checkout button so my customers can buy goods using PayPal.
I want a solution that relies on the server and it just the client side.

I have been to the PayPal website and I have found all kinds of methods to enable the setting up of the API but I don't know which one to choose and the site does not explain much so I'm hopping you could tell me which method I should use to set it up?

Thanks

答:
If you need a Checkout button, one of these demo patterns should get you started

Option #1: No server-side code needed.

Option #2: Requires server-side code for payment setup and capture.

Title: How do I set up a PayPal checkout


问:
How could i change the msgbox title "The page at http://.... says:"
I am opening the msgbox in asp.net by following code..

```<code>if (ds.Tables[0].Rows[0][12].ToString() == "0" )
   Page.ClientScript.RegisterStartupScript(this.GetType(), "Window", "alert('This ID is not yet approved to create a case. ');", true);
else if(ds.Tables[0].Rows[0][12].ToString() == "2")
   Page.ClientScript.RegisterStartupScript(this.GetType(), "Window", "alert('Your ID is rejected to create a case. ');", true);
else
   Page.ClientScript.RegisterStartupScript(this.GetType(), "Window", "alert('Please enter a valid ID.');", true);
</code>```

When its running on mozilla browser Message Box title showing The page at http://.... says:

I want to change this title and show my custom title a part from The page at http://.... says:

Any open help me soon.

答:
Use custom alert message box, for changing the title else you can't change the title

for more details check this link

http://javascript.internet.com/miscellaneous/custom-alert-box.html

Body:
I am opening the msgbox in asp.net by following code..

if (ds.Tables[0].Rows[0][12].ToString() == "0" )
   Page.ClientScript.RegisterStartupScript(this.GetType(), "Window", "alert('This ID is not yet approved to create a case. ');", true);
else if(ds.Tables[0].Rows[0][12].ToString() == "2")
   Page.ClientScript.RegisterStartupScript(this.GetType(), "Window", "alert('Your ID is rejected to create a case. ');", true);
else
   Page.ClientScript.RegisterStartupScript(this.GetType(), "Window", "alert('Please enter a valid ID.');", true);

When its running on mozilla browser Message Box title showing The page at http://.... says:

I want to change this title and show my custom title a part from The page at http://.... says:

Any open help me soon.


问:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY
I am trying to parse the incoming Json (given below) to Java object using Gson. The Json request seems to be a valid one, but I am getting the following exception while parsing it.

```<code>com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 5 column 19 path $.metadata.
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226) ~[gson-2.8.5.jar:?]
        at com.google.gson.Gson.fromJson(Gson.java:927) ~[gson-2.8.5.jar:?]
</code>```

Incoming Json request :

```<code>{
    "metadata": {
        "salesId": "123",
        "promoCode": "2010",
        "items": [
            {
                "0": {
                    "productCode": "1234",
                    "total": 169900
                },
                "1": {
                    "productCode": "4567",
                    "total": 19900
                }
            }
        ]
    }
}
</code>```

Parsing logic :

```<code>protected <T extends GenericModel> Optional<T> convertFromJson(final String json, final Class<T> clazz) {
        if (StringUtils.isEmpty(json)) {
            return Optional.empty();
        }
        return Optional.of(new Gson().fromJson(json, clazz));
    }
</code>```

Java class :

```<code>public class Metadata {
    private String salesId;
    private String promoCode;
    private ArrayList<Object> items = new ArrayList<Object>();

    public String getSalesId() {
        return salesId;
    }

    public void setSalesId(String salesId) {
        this.salesId = salesId;
    }

    public String getPromoCode() {
        return promoCode;
    }

    public void setPromoCode(String promoCode) {
        this.promoCode = promoCode;
    }

    public ArrayList<Object> getItems() {
        return items;
    }

    public void setItems(ArrayList<Object> items) {
        this.items = items;
    }

    @Override
    public String toString() {
        return "Metadata{" +
                "salesId=" + getSalesId() +
                "promoCode=" + getPromoCode() +
                "items=" + getItems() +
                '}';
    }
}
</code>```

Please note that Metadata.java is an inner class.

Have been trying to resolve the issue, but no luck. Could anyone let me know how to solve it? TIA.

答: I found out the issue and thought I'l post it here incase someone comes across the same issue. I cleaned the project and rebuild again and it worked fine. The issue was not with the code afterall. I read it on a thread regarding gson libraries and tried it. And it worked for me.</p>

Body:
I am trying to parse the incoming Json (given below) to Java object using Gson. The Json request seems to be a valid one, but I am getting the following exception while parsing it.

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 5 column 19 path $.metadata.
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:226) ~[gson-2.8.5.jar:?]
        at com.google.gson.Gson.fromJson(Gson.java:927) ~[gson-2.8.5.jar:?]

Incoming Json request :

{
    "metadata": {
        "salesId": "123",
        "promoCode": "2010",
        "items": [
            {
                "0": {
                    "productCode": "1234",
                    "total": 169900
                },
                "1": {
                    "productCode": "4567",
                    "total": 19900
                }
            }
        ]
    }
}

Parsing logic :

protected <T extends GenericModel> Optional<T> convertFromJson(final String json, final Class<T> clazz) {
        if (StringUtils.isEmpty(json)) {
            return Optional.empty();
        }
        return Optional.of(new Gson().fromJson(json, clazz));
    }

Java class :

public class Metadata {
    private String salesId;
    private String promoCode;
    private ArrayList<Object> items = new ArrayList<Object>();

    public String getSalesId() {
        return salesId;
    }

    public void setSalesId(String salesId) {
        this.salesId = salesId;
    }

    public String getPromoCode() {
        return promoCode;
    }

    public void setPromoCode(String promoCode) {
        this.promoCode = promoCode;
    }

    public ArrayList<Object> getItems() {
        return items;
    }

    public void setItems(ArrayList<Object> items) {
        this.items = items;
    }

    @Override
    public String toString() {
        return "Metadata{" +
                "salesId=" + getSalesId() +
                "promoCode=" + getPromoCode() +
                "items=" + getItems() +
                '}';
    }
}

Please note that Metadata.java is an inner class.

Have been trying to resolve the issue, but no luck. Could anyone let me know how to solve it? TIA.


问:
Where to store files for user in Android?
I have to export files from my application and looking for a solution, where I can save files, to give the user the possibility to open them.

I tried already getFilesDir().getPath() which worked well, until I realized that the folder can't open from a real device (/data/user/0/com.myapplication.example/files) since the /data path is just a storage area for the application.

What are the alternatives?

答:
You should have a look here https://developer.android.com/training/data-storage
I'm not sure what file type you are trying to store however what you have tried stores the file withing the applications directory and not the devices. To combat this I would look under either Media or Documents and other files again in the above link. I would be able to be of further assistance if I knew what file type you are trying to store. Hope this helps you in some way.</p>


问:
HSQLDBs 'ON DUPLICATE KEY UPDATE'-feature does not behave as in MYSQL?
I am using MYSQLs ON DUPLICATE KEY UPDATE-feature, and it works as I expect when running on a MYSQL database. But when I try to write tests running against a in-memory HSQLDB, I experience different behaviour.

Given the following table:

```<code>CREATE TABLE foo (id INT PRIMARY KEY NOT NULL, counter INT);
</code>```

With the following insert statement:

```<code>INSERT INTO foo(id, counter) VALUES (1, 1) ON DUPLICATE KEY UPDATE counter=counter+1
</code>```

After the first run, counter is 1.

After the second run, counter is 2.

After the third run, counter is still 2. Here I expected the counter to be 3. (It is 3 if I run the same queries against MYSQL).

Is this a bug, or have I misunderstood how ON DUPLICATE KEY UPDATE should work?

For a running example, see the following github-repository: https://github.com/mortenberg80/hsqldbtest

答: The initial HSQLDB implementation of ON DUPLICATE UPDATE used the VALUES list as the source of the update in all cases where col_name was encounterd. It has been enhanced for version 2.5.1 to use the existing table row values as the source for col_name, and use the VALUES list as the source for VALUES(col_name). This corresponds with MySQL usage.

Body:
I am using MYSQLs ON DUPLICATE KEY UPDATE-feature, and it works as I expect when running on a MYSQL database. But when I try to write tests running against a in-memory HSQLDB, I experience different behaviour.

Given the following table:

CREATE TABLE foo (id INT PRIMARY KEY NOT NULL, counter INT);

With the following insert statement:

INSERT INTO foo(id, counter) VALUES (1, 1) ON DUPLICATE KEY UPDATE counter=counter+1

After the first run, counter is 1.

After the second run, counter is 2.

After the third run, counter is still 2. Here I expected the counter to be 3. (It is 3 if I run the same queries against MYSQL).

Is this a bug, or have I misunderstood how ON DUPLICATE KEY UPDATE should work?

For a running example, see the following github-repository: https://github.com/mortenberg80/hsqldbtest