问:
Using Azure Blobs with Azure Website
I'm in the process of making an MVC Windows Azure website which involves users uploading images.
I wanted to store the images in blobs.
I searched for tutorials but most of them deal with Webapps rather than MVC websites.

The only useful tutorial I found was: http://www.codeproject.com/Articles/490178/How-to-Use-Azure-Blob-Storage-with-Azure-Web-Sites

I'm new to the whole MVC/Windows Azure/Visual Studio scene and I got confused at Step 7 where I had to connect to Cloud Storage Account.

```<code>var storageAccount = CloudStorageAccount.Parse(
    ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);
</code>```

I can't figure out where I'm supposed to put that bit of a code.

Same for the code in Step 8: Creating a container

```<code>blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("productimages");
if (container.CreateIfNotExist())
{
    // configure container for public access
    var permissions = container.GetPermissions();
    permissions.PublicAccess = BlobContainerPublicAccessType.Container;
    container.SetPermissions(permissions);
}
</code>```

And Step 9: Save the Image to a BLOB

```<code>string uniqueBlobName = string.Format("productimages/image_{0}{1}",
   Guid.NewGuid().ToString(), Path.GetExtension(image.FileName));
CloudBlockBlob blob = blobStorage.GetBlockBlobReference(uniqueBlobName);
blob.Properties.ContentType = image.ContentType;
blob.UploadFromStream(image.InputStream);
</code>```

Any help will be really appreciated. Any other links to relevant tutorials are also welcome.

Thanks a lot!

答:
Old question but still may help noobs!

Azure Webapps do accept MVC apps. Webapps on Azure are just a container which Im sure can take different types of ASP.NET based applications, Forms or MVC, C# or VB.net.

Assuming you know the basics of an MVC application you can just create the Azure Webapp and publish it to there. It's as straight forward as that.

This code:

```<code>var storageAccount = CloudStorageAccount.Parse(
    ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);
</code>```

And this:

```<code>blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("productimages");
if (container.CreateIfNotExist())
{
    // configure container for public access
    var permissions = container.GetPermissions();
    permissions.PublicAccess = BlobContainerPublicAccessType.Container;
    container.SetPermissions(permissions);
}
</code>```

Can go in a new class specifically for Blob services e.g. call it something like blobServices.cs and save it in the root of your MVC app and it can look like so:

```<code>    var storageAccount = CloudStorageAccount.Parse(
            ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);

    blobStorage = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobStorage.GetContainerReference("productimages");
    if (container.CreateIfNotExist())
    {
        // configure container for public access
        var permissions = container.GetPermissions();
        permissions.PublicAccess = BlobContainerPublicAccessType.Container;
        container.SetPermissions(permissions);
    }
</code>```

Which is probably the best practice. From there on in the Controller/s of your MVC app you can do something like this:

```<code>namespace blabla.cs
{

   public controller myBlobController
    {

      //instantiate the blob service
      BlobProfileImageServices _blobServices = new BlobProfileImageServices();

       public public ActionResult Index()
        {

            //call your blob storage service
            //and loop through each blob
            CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer();
            List<string> blobs = new List<string>();
            foreach (var blobItem in blobContainer.ListBlobs())
            {
                blobs.Add(blobItem.Uri.ToString());

            }

      }

    }
}
</code>```

Title: Using Azure Blobs with Azure Website

Body:
I'm in the process of making an MVC Windows Azure website which involves users uploading images.
I wanted to store the images in blobs.
I searched for tutorials but most of them deal with Webapps rather than MVC websites.

The only useful tutorial I found was: http://www.codeproject.com/Articles/490178/How-to-Use-Azure-Blob-Storage-with-Azure-Web-Sites

I'm new to the whole MVC/Windows Azure/Visual Studio scene and I got confused at Step 7 where I had to connect to Cloud Storage Account.

var storageAccount = CloudStorageAccount.Parse(
    ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);

I can't figure out where I'm supposed to put that bit of a code.

Same for the code in Step 8: Creating a container

blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("productimages");
if (container.CreateIfNotExist())
{
    // configure container for public access
    var permissions = container.GetPermissions();
    permissions.PublicAccess = BlobContainerPublicAccessType.Container;
    container.SetPermissions(permissions);
}

And Step 9: Save the Image to a BLOB

string uniqueBlobName = string.Format("productimages/image_{0}{1}",
   Guid.NewGuid().ToString(), Path.GetExtension(image.FileName));
CloudBlockBlob blob = blobStorage.GetBlockBlobReference(uniqueBlobName);
blob.Properties.ContentType = image.ContentType;
blob.UploadFromStream(image.InputStream);

Any help will be really appreciated. Any other links to relevant tutorials are also welcome.

Thanks a lot!

Body:
Old question but still may help noobs!

Azure Webapps do accept MVC apps. Webapps on Azure are just a container which Im sure can take different types of ASP.NET based applications, Forms or MVC, C# or VB.net.

Assuming you know the basics of an MVC application you can just create the Azure Webapp and publish it to there. It's as straight forward as that.

This code:

var storageAccount = CloudStorageAccount.Parse(
    ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);

And this:

blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("productimages");
if (container.CreateIfNotExist())
{
    // configure container for public access
    var permissions = container.GetPermissions();
    permissions.PublicAccess = BlobContainerPublicAccessType.Container;
    container.SetPermissions(permissions);
}

Can go in a new class specifically for Blob services e.g. call it something like blobServices.cs and save it in the root of your MVC app and it can look like so:

    var storageAccount = CloudStorageAccount.Parse(
            ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);

    blobStorage = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobStorage.GetContainerReference("productimages");
    if (container.CreateIfNotExist())
    {
        // configure container for public access
        var permissions = container.GetPermissions();
        permissions.PublicAccess = BlobContainerPublicAccessType.Container;
        container.SetPermissions(permissions);
    }

Which is probably the best practice. From there on in the Controller/s of your MVC app you can do something like this:

namespace blabla.cs
{

   public controller myBlobController
    {

      //instantiate the blob service
      BlobProfileImageServices _blobServices = new BlobProfileImageServices();

       public public ActionResult Index()
        {

            //call your blob storage service
            //and loop through each blob
            CloudBlobContainer blobContainer = _blobServices.GetCloudBlobContainer();
            List<string> blobs = new List<string>();
            foreach (var blobItem in blobContainer.ListBlobs())
            {
                blobs.Add(blobItem.Uri.ToString());

            }

      }

    }
}


来源: stackexchange

问:
transpose DataTable code gives one extra row indicating the index of the columns
I've to do the transpose of my DataTable and I used the code I found in internet. This code is giving an extra row at the top showing the column index. How can I remove this row?This extra row is at above the header row of my DataTable, and when I use the code dt_.Rows.Remove(dt_.Rows[0]); the header row is removed but not the top row. Reference taken from:
Transpose a datatable

How can I remove the top row?

```<code>DataTable dt_ = new DataTable();

DataTable table = new DataTable();
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
    table.Columns.Add(Convert.ToString(i));
}
DataRow dr;
//get all the columns and make it as rows
for (int j = 0; j < dt.Columns.Count; j++)
{
    dr = table.NewRow();
    dr[0] = dt.Columns[j].ToString();
    for (int k = 1; k <= dt.Rows.Count; k++)
    {
        dr[k] = dt.Rows[k - 1][j];
    }

    table.Rows.Add(dr);
}

dt_ = table;

//dt_.Rows.Remove(dt_.Rows[0]); removes the header row
</code>```

My gridview code

```<code><asp:GridView ID="GridView1"
                        runat="server"
                        CellPadding="3"
                        CellSpacing="2"
                        AutoGenerateColumns="true"
                        ShowFooter="true"
                        FooterStyle-HorizontalAlign="Left"
                        RowStyle-BorderColor="Black" HeaderStyle-BackColor="#0CA3D2">
                        <FooterStyle BackColor="#87CEFA" />
                    </asp:GridView>
</code>```

I've not shown the footer section sum calculation code behind because it is irrelevant here.

snapshot:

答:
I think if you start the loop from 1 it should work</p>

```<code>        DataTable dt = new DataTable();
        DataTable dt_ = new DataTable();

        DataTable table = new DataTable();
        //Get all the rows and change into columns
        for (int i = 0; i <= dt.Rows.Count; i++)
        {
            table.Columns.Add(Convert.ToString(i));
        }
        DataRow dr;
        //get all the columns and make it as rows
        //HERE THE LOOK STARTS FROM ONE
        for (int j = 1; j < dt.Columns.Count; j++)
        {
            dr = table.NewRow();
            dr[0] = dt.Columns[j].ToString();
            for (int k = 1; k <= dt.Rows.Count; k++)
            {
                dr[k] = dt.Rows[k - 1][j];
            }

            table.Rows.Add(dr);
        }

        dt_ = table;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've to do the transpose of my DataTable and I used the code I found in internet. This code is giving an extra row at the top showing the column index. How can I remove this row?This extra row is at above the header row of my DataTable, and when I use the code dt_.Rows.Remove(dt_.Rows[0]); the header row is removed but not the top row. Reference taken from:
Transpose a datatable

How can I remove the top row?

DataTable dt_ = new DataTable();

DataTable table = new DataTable();
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
    table.Columns.Add(Convert.ToString(i));
}
DataRow dr;
//get all the columns and make it as rows
for (int j = 0; j < dt.Columns.Count; j++)
{
    dr = table.NewRow();
    dr[0] = dt.Columns[j].ToString();
    for (int k = 1; k <= dt.Rows.Count; k++)
    {
        dr[k] = dt.Rows[k - 1][j];
    }

    table.Rows.Add(dr);
}

dt_ = table;

//dt_.Rows.Remove(dt_.Rows[0]); removes the header row

My gridview code

<asp:GridView ID="GridView1"
                        runat="server"
                        CellPadding="3"
                        CellSpacing="2"
                        AutoGenerateColumns="true"
                        ShowFooter="true"
                        FooterStyle-HorizontalAlign="Left"
                        RowStyle-BorderColor="Black" HeaderStyle-BackColor="#0CA3D2">
                        <FooterStyle BackColor="#87CEFA" />
                    </asp:GridView>

I've not shown the footer section sum calculation code behind because it is irrelevant here.

snapshot:

Body:
I think if you start the loop from 1 it should work

        DataTable dt = new DataTable();
        DataTable dt_ = new DataTable();

        DataTable table = new DataTable();
        //Get all the rows and change into columns
        for (int i = 0; i <= dt.Rows.Count; i++)
        {
            table.Columns.Add(Convert.ToString(i));
        }
        DataRow dr;
        //get all the columns and make it as rows
        //HERE THE LOOK STARTS FROM ONE
        for (int j = 1; j < dt.Columns.Count; j++)
        {
            dr = table.NewRow();
            dr[0] = dt.Columns[j].ToString();
            for (int k = 1; k <= dt.Rows.Count; k++)
            {
                dr[k] = dt.Rows[k - 1][j];
            }

            table.Rows.Add(dr);
        }

        dt_ = table;


问:
Disable CSS for an element from a specific file
I am working on an existing code base that uses bootstrap. The existing code base has a single large CSS file (apart from bootstrap) that overrides many attributes from bootstrap.

I just want to disable all the CSS values from that large CSS file for a particular element.

```<code>largecss.css
<div disableCSSfromLargeCSS.css> </div>
</code>```

Is this possible? Without manually checking the attributes and overriding them?

答: Try  $('#element *').removeAttr('style') or $('#element').children().removeAttr('style')  to remove all applied css to that div.</p>

Body:
I am working on an existing code base that uses bootstrap. The existing code base has a single large CSS file (apart from bootstrap) that overrides many attributes from bootstrap.

I just want to disable all the CSS values from that large CSS file for a particular element.

largecss.css

Is this possible? Without manually checking the attributes and overriding them?


问:
how to merge and sum frames of images into one in Digital Micrograph?
I tried to use the merge function to sum it together, but the intensity of the Merge Image does not equal to the addition of the two original images. Does anyone know how to do it in DM?</p>

答:
I think the question as asked is maybe a bit under-specified. For simple "intensity adding" of two images of the same size ( pixel dimensions ) you can simply use the label letters and a simple equation like f.e.:

will give you:

I also don't know what the 'merge' function you refer to should be. What script command are you referring to?


问:
Getting "Run-time error '-2147024864 (80070020) which saving outlook attachment on arrival
I run below script to save Outlook attachment on arrival of email. But I frequently get Run-time error '-2147024864 (80070020), which will always stop the inflow of Outlook email. Please advise how to get rid.

```<code>Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "C:\Email\"

     For Each objAtt In itm.Attachments

          objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName

          Set objAtt = Nothing
     Next
End Sub
</code>```

答:
try this code please

it prints the name of each attachment before it saves the attachment

press ctrl-G to see "immediate window" where the printout is sent

check the last file name printed when the program crashes

it may provide some insight

```<code>Sub saveAttachtoDisk(itm As Outlook.MailItem)
    Dim objAtt As Outlook.Attachment
    Dim saveFolder As String
    saveFolder = "C:\Email\"

    For Each objAtt In itm.Attachments

        debug.print objAtt.DisplayName        ' print attachment name to "immediate window"

        objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName

    Next
    Set objAtt = Nothing
End Sub
</code>```

Body:
I run below script to save Outlook attachment on arrival of email. But I frequently get Run-time error '-2147024864 (80070020), which will always stop the inflow of Outlook email. Please advise how to get rid.

Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "C:\Email\"

     For Each objAtt In itm.Attachments

          objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName

          Set objAtt = Nothing
     Next
End Sub

Body:
try this code please

it prints the name of each attachment before it saves the attachment

press ctrl-G to see "immediate window" where the printout is sent

check the last file name printed when the program crashes

it may provide some insight

Sub saveAttachtoDisk(itm As Outlook.MailItem)
    Dim objAtt As Outlook.Attachment
    Dim saveFolder As String
    saveFolder = "C:\Email\"

    For Each objAtt In itm.Attachments

        debug.print objAtt.DisplayName        ' print attachment name to "immediate window"

        objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName

    Next
    Set objAtt = Nothing
End Sub


问:
ReactJs not able to communicate between two components
I am new to react so apologies in advance if my question is silly.

projects is an array Iam getting from App.js

(Project.js)

```<code>import React, { Component } from 'react';
import ProjectItem from './ProjectItem'

class Projects extends Component {
  render() {
    //====== PROJECTS IS AN ARRAY IAM GETTING FROM App.js====
    let projectItems;
    if(this.props.projects){
      projectItems = this.props.projects.map(project => {
        return(
          <ProjectItem key={project.title} project={project} />

        );
      }); // projects map end
    }//==if end
    // ====== RETURN PROJECTS ======
    return (
      <div className="Projects">
          <h1>Projects</h1>
          <p>{this.props.projects[0].title}</p>
      </div>
    );
  }
}

export default Projects;
</code>```

Here I am not able to get the props from Project.js

ProjectItem.js

```<code>import React, { Component } from 'react';

class ProjectItem extends Component {
  render() {
    console.log(this.props);
    return (
      <li className="Project">
        {this.props.project.title}

      </li>
    );
  }
}

export default ProjectItem;
</code>```

Please help and thanks in advance.

答:
Although you would think that you have created the Projects list by mapping over the projects array but unless you return it from the Component, you will not be able to display the props.

You need to add projectItems to your return function like

```<code>import React, { Component } from 'react';
import ProjectItem from './ProjectItem'

class Projects extends Component {
  render() {
    //====== PROJECTS IS AN ARRAY IAM GETTING FROM App.js====
    let projectItems;
    if(this.props.projects){
      projectItems = this.props.projects.map(project => {
        return(
          <ProjectItem key={project.title} project={project} />

        );
      }); // projects map end
    }//==if end
    // ====== RETURN PROJECTS ======
    return (
      <div className="Projects">
          <h1>Projects</h1>
          {projectItems}
      </div>
    );
  }
}

export default Projects;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to react so apologies in advance if my question is silly.

projects is an array Iam getting from App.js

(Project.js)

import React, { Component } from 'react';
import ProjectItem from './ProjectItem'

class Projects extends Component {
  render() {
    //====== PROJECTS IS AN ARRAY IAM GETTING FROM App.js====
    let projectItems;
    if(this.props.projects){
      projectItems = this.props.projects.map(project => {
        return(
          <ProjectItem key={project.title} project={project} />

        );
      }); // projects map end
    }//==if end
    // ====== RETURN PROJECTS ======
    return (

Projects

{this.props.projects[0].title}

    );
  }
}

export default Projects;

Here I am not able to get the props from Project.js

ProjectItem.js

import React, { Component } from 'react';

class ProjectItem extends Component {
  render() {
    console.log(this.props);
    return (

        {this.props.project.title}

    );
  }
}

export default ProjectItem;

Please help and thanks in advance.

Body:
Although you would think that you have created the Projects list by mapping over the projects array but unless you return it from the Component, you will not be able to display the props.

You need to add projectItems to your return function like

import React, { Component } from 'react';
import ProjectItem from './ProjectItem'

class Projects extends Component {
  render() {
    //====== PROJECTS IS AN ARRAY IAM GETTING FROM App.js====
    let projectItems;
    if(this.props.projects){
      projectItems = this.props.projects.map(project => {
        return(
          <ProjectItem key={project.title} project={project} />

        );
      }); // projects map end
    }//==if end
    // ====== RETURN PROJECTS ======
    return (
      <div className="Projects">
          <h1>Projects</h1>
          {projectItems}
      </div>
    );
  }
}

export default Projects;


问:
image blurring, saturation with UISlider movement
hai friends,
   can anyone know the exact functionality to blur our uiimage according to slider control in view based application?
 if yes, means please post your idea with sample code.
 i have some samples about this in openGL only. but i need samples in view based application..

  please help me.. thanks in advance..

答: Jeff Lamarche has an article about how to blur a UIImage. Source is included. </p>

ContentLicense: CC BY-SA 2.5


问:
if error == nil parse swift
I'm trying to check when I save an object to my parse serve if something goes wrong. But I have two options and I have three options and I don't know the difference. I have these three options (if error == nil, or if object != nil, or if error == nil and object != nil). Which one should I use. Thanks

Option #1

```<code>let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if error == nil{
    }
)}
</code>```

Option #2

```<code>let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if object != nil{
    }
)}
</code>```

Option #3

```<code>let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if error == nil && object != nil{
    }
)}
</code>```

答:
I suggest and encourage you to use guard statement, which as made for such situations.</p>

```<code>    //Always safely unwrap optional value:
    if let user = PFUser.current(){

    user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in

        guard success, error == nil else {
        //handle error somehow...(print or whatever...)
        return
         }
       //Continue here as everything is fine...

    )}
}
</code>```

Title: if error == nil parse swift

Body:
I'm trying to check when I save an object to my parse serve if something goes wrong. But I have two options and I have three options and I don't know the difference. I have these three options (if error == nil, or if object != nil, or if error == nil and object != nil). Which one should I use. Thanks

Option #1

let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if error == nil{
    }
)}

Option #2

let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if object != nil{
    }
)}

Option #3

let user = PFUser.current()!
user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in
    if error == nil && object != nil{
    }
)}

Body:
I suggest and encourage you to use guard statement, which as made for such situations.

    //Always safely unwrap optional value:
    if let user = PFUser.current(){

    user.saveInBackground (block: { (success:Bool, error:Error?) -> Void in

        guard success, error == nil else {
        //handle error somehow...(print or whatever...)
        return
         }
       //Continue here as everything is fine...

    )}
}


问:
systemctl error on running systemctl start <application>
faced this error while running my application using systemctl where is actually the problem with?systemctl error on running systemctl start ?</p>

```<code>Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Started <application> Web Interface.
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Main process exited, code=exited, status=203/EXEC
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Unit entered failed state.
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Failed with result 'exit-code'.
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Service hold-off time over, scheduling restart.
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Stopped <application> Web Interface.
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Started <application> Web Interface.
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Main process exited, code=exited, status=203/EXEC
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Unit entered failed state.
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Failed with result 'exit-code'.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Service hold-off time over, scheduling restart.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Stopped <application> Web Interface.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Started <application> Web Interface.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Main process exited, code=exited, status=203/EXEC
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Unit entered failed state.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Failed with result 'exit-code'.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Service hold-off time over, scheduling restart.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Stopped <application> Web Interface.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Started <application> Web Interface.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Main process exited, code=exited, status=203/EXEC
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Unit entered failed state.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Failed with result 'exit-code'.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Service hold-off time over, scheduling restart.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Stopped <application> Web Interface.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Started <application> Web Interface.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Main process exited, code=exited, status=203/EXEC
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Unit entered failed state.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Failed with result 'exit-code'.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Service hold-off time over, scheduling restart.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Stopped <application> Web Interface.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Start request repeated too quickly.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Failed to start <application> Web Interface.
</code>```

答:
The service unit file should set a RestartSec, most developers forget about that.</p>

```<code>Restart=on-failure
RestartSec=3
</code>```

Body:
faced this error while running my application using systemctl where is actually the problem with?systemctl error on running systemctl start ?

Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Started <application> Web Interface.
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Main process exited, code=exited, status=203/EXEC
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Unit entered failed state.
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Failed with result 'exit-code'.
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Service hold-off time over, scheduling restart.
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Stopped <application> Web Interface.
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Started <application> Web Interface.
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Main process exited, code=exited, status=203/EXEC
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Unit entered failed state.
Jul 27 16:20:36 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Failed with result 'exit-code'.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Service hold-off time over, scheduling restart.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Stopped <application> Web Interface.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Started <application> Web Interface.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Main process exited, code=exited, status=203/EXEC
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Unit entered failed state.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Failed with result 'exit-code'.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Service hold-off time over, scheduling restart.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Stopped <application> Web Interface.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Started <application> Web Interface.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Main process exited, code=exited, status=203/EXEC
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Unit entered failed state.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Failed with result 'exit-code'.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Service hold-off time over, scheduling restart.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Stopped <application> Web Interface.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Started <application> Web Interface.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Main process exited, code=exited, status=203/EXEC
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Unit entered failed state.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Failed with result 'exit-code'.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Service hold-off time over, scheduling restart.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Stopped <application> Web Interface.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: <application>.service: Start request repeated too quickly.
Jul 27 16:20:37 nikhil-Lenovo-ideapad-300-15ISK systemd[1]: Failed to start <application> Web Interface.

Body:
The service unit file should set a RestartSec, most developers forget about that.

Restart=on-failure
RestartSec=3


答:
That's because

```<code>//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
    table.Columns.Add(Convert.ToString(i));
}
</code>```

is creating columns named 0, 1, and 2. the problem is with Convert.ToString(i). That, and you will also need to change how you read k.

The code will look like this (not tested):

```<code>DataTable dt_ = new DataTable();

DataTable table = new DataTable();
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
    table.Columns.Add(dt.Rows[i][0]); // the column name is in the first cell
}
DataRow dr;
//get all the columns and make it as rows
for (int j = 0; j < dt.Columns.Count; j++)
{
    dr = table.NewRow();
    dr[0] = dt.Columns[j].ToString();

    // changed the for condition
    for (int k = 1; k < dt.Rows.Count; k++)
    {
        dr[k] = dt.Rows[k][j]; // changed the 'k - 1' to 'k'
    }

    table.Rows.Add(dr);
}

dt_ = table;
</code>```

Title: transpose DataTable code gives one extra row indicating the index of the columns

Body:
That's because

//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
    table.Columns.Add(Convert.ToString(i));
}

is creating columns named 0, 1, and 2. the problem is with Convert.ToString(i). That, and you will also need to change how you read k.

The code will look like this (not tested):

DataTable dt_ = new DataTable();

DataTable table = new DataTable();
//Get all the rows and change into columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
    table.Columns.Add(dt.Rows[i][0]); // the column name is in the first cell
}
DataRow dr;
//get all the columns and make it as rows
for (int j = 0; j < dt.Columns.Count; j++)
{
    dr = table.NewRow();
    dr[0] = dt.Columns[j].ToString();

    // changed the for condition
    for (int k = 1; k < dt.Rows.Count; k++)
    {
        dr[k] = dt.Rows[k][j]; // changed the 'k - 1' to 'k'
    }

    table.Rows.Add(dr);
}

dt_ = table;


问:
Debugging HTML in WebBrowser Control
I need to embed HTML in a Winforms project and call Javascript functions from it. I'm using a webBrowser control in a c# project and calling:

```<code>webBrowser.Navigate("website");
return webBrowser.Document.InvokeScript("myMethod", new object[]{"test"});
</code>```

How can I debug execution of code when the debugger is in "myMethod"?

There's this article on how to debug HTML from IE:
http://www.codeproject.com/Articles/18921/Using-Visual-Studio-to-Debug-JavaScript-in-IE

I don't know how relevant it is though.

答:
In addition to the approach mentioned by Parag, you can also explicitly attach a debugger in Visual Studio and select Attach to: Script code.

Once that's done you get all open scripts to show up in Visual Studio as Script Documents and you can set breakpoints in any of those scripts. You can reuse the same instance for multiple debugging sessions. You also can open a JavaScript Console and DOM Explorer which gives you access to the same tools you'd get in full Internet Explorer.

More detail in a blog post here: https://weblog.west-wind.com/posts/2017/Jul/06/JavaScript-Debugging-in-a-Web-Browser-Control-with-Visual-Studio

Note: Visual Studio 2019 makes script debugging a little harder to set up and unfortunately no longer supports the Console View/Evaluation window. You can still step and debug value, but no real time evaluation or seeing console.log output.

Title: Debugging HTML in WebBrowser Control

Body:
I need to embed HTML in a Winforms project and call Javascript functions from it. I'm using a webBrowser control in a c# project and calling:

webBrowser.Navigate("website");
return webBrowser.Document.InvokeScript("myMethod", new object[]{"test"});

How can I debug execution of code when the debugger is in "myMethod"?

There's this article on how to debug HTML from IE:
http://www.codeproject.com/Articles/18921/Using-Visual-Studio-to-Debug-JavaScript-in-IE

I don't know how relevant it is though.


问:
Printing value of entry box in a dialog in gtk c
I have worked recently with gtk+ in c language.

I have tried to communicate between two callbacks in a dialog and not in the main window (like here). But, unlike the solutions in the link, the program crushes (in the second callback when I try to use the widget I get from the parameters).

This is my code for This:

```<code>#include <gtk/gtk.h>
#include <stdlib.h>
#include <stdio.h>

static void print_text (GtkWidget *widget, gpointer data)
{
    GtkEntry* entry = data;
    printf("%s", gtk_entry_get_text(entry));
}

static void open_dialog (GtkWidget *widget, gpointer data)
{
    GtkWidget *window = data;
    GtkWidget *dialog;
    GtkWidget *content_area;
    GtkWidget *grid;
    GtkWidget *label;
    GtkWidget *button;
    static GtkEntry *textbox;

    dialog = gtk_dialog_new_with_buttons ("Get Text",
                                          window,
                                          GTK_DIALOG_MODAL,
                                          GTK_STOCK_OK,
                                          GTK_RESPONSE_OK,
                                          NULL);
    content_area = gtk_dialog_get_content_area (GTK_DIALOG (dialog));
    grid = gtk_grid_new();
    gtk_container_add (GTK_CONTAINER (content_area), grid);

    label = gtk_label_new("Value: ");
    gtk_grid_attach(GTK_GRID(grid), label, 0, 0, 1, 1);
    textbox = gtk_entry_new();
    gtk_entry_set_text(textbox, "<Value>");
    gtk_grid_attach(GTK_GRID(grid), textbox, 1, 0, 1, 1);

    gtk_widget_show_all (dialog);
    g_signal_connect (GTK_DIALOG (dialog), "response", G_CALLBACK (print_text), textbox);
}

static void activate (GtkApplication *app, gpointer user_data)
{
    GtkWidget *window;
    GtkWidget *button;
    GtkWidget *entry;
    GtkWidget *grid;

    window = gtk_application_window_new (app);
    gtk_window_set_title (GTK_WINDOW (window), "Window");
    gtk_container_set_border_width (GTK_CONTAINER (window), 10);

    grid = gtk_grid_new ();
    gtk_container_add (GTK_CONTAINER (window), grid);

    button = gtk_button_new_with_label ("Print Text");
    g_signal_connect (button, "clicked", G_CALLBACK (open_dialog), window);
    gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 1, 1);

    gtk_widget_show_all (window);
}

int main (int argc, char **argv)
{
    GtkApplication *app;
    int status;

    app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
    status = g_application_run (G_APPLICATION (app), argc, argv);
    g_object_unref (app);

    return status;
}
</code>```

The program should have printed the value of the entry box which in the dialog after closing the dialog. Note: in the main window there is a button that opens the dialog.

Thanks for helping!

答:
Problem is on the print_text function. The prototype for GtkDialog response signal is:

void user_function (GtkDialog *dialog,
                 gint       response_id,
                 gpointer   user_data)

So you must change your function to:

```<code>static void print_text (GtkWidget *widget, gint response_id, gpointer data)
{
    GtkEntry* entry = data;
    printf("%s", gtk_entry_get_text(entry));
    gtk_widget_destroy (widget); // This will close the dialog
}
</code>```

Body:
I have worked recently with gtk+ in c language.

I have tried to communicate between two callbacks in a dialog and not in the main window (like here). But, unlike the solutions in the link, the program crushes (in the second callback when I try to use the widget I get from the parameters).

This is my code for This:

#include <gtk/gtk.h>
#include <stdlib.h>
#include <stdio.h>

static void print_text (GtkWidget *widget, gpointer data)
{
    GtkEntry* entry = data;
    printf("%s", gtk_entry_get_text(entry));
}

static void open_dialog (GtkWidget *widget, gpointer data)
{
    GtkWidget *window = data;
    GtkWidget *dialog;
    GtkWidget *content_area;
    GtkWidget *grid;
    GtkWidget *label;
    GtkWidget *button;
    static GtkEntry *textbox;

    dialog = gtk_dialog_new_with_buttons ("Get Text",
                                          window,
                                          GTK_DIALOG_MODAL,
                                          GTK_STOCK_OK,
                                          GTK_RESPONSE_OK,
                                          NULL);
    content_area = gtk_dialog_get_content_area (GTK_DIALOG (dialog));
    grid = gtk_grid_new();
    gtk_container_add (GTK_CONTAINER (content_area), grid);

    label = gtk_label_new("Value: ");
    gtk_grid_attach(GTK_GRID(grid), label, 0, 0, 1, 1);
    textbox = gtk_entry_new();
    gtk_entry_set_text(textbox, "<Value>");
    gtk_grid_attach(GTK_GRID(grid), textbox, 1, 0, 1, 1);

    gtk_widget_show_all (dialog);
    g_signal_connect (GTK_DIALOG (dialog), "response", G_CALLBACK (print_text), textbox);
}

static void activate (GtkApplication *app, gpointer user_data)
{
    GtkWidget *window;
    GtkWidget *button;
    GtkWidget *entry;
    GtkWidget *grid;

    window = gtk_application_window_new (app);
    gtk_window_set_title (GTK_WINDOW (window), "Window");
    gtk_container_set_border_width (GTK_CONTAINER (window), 10);

    grid = gtk_grid_new ();
    gtk_container_add (GTK_CONTAINER (window), grid);

    button = gtk_button_new_with_label ("Print Text");
    g_signal_connect (button, "clicked", G_CALLBACK (open_dialog), window);
    gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 1, 1);

    gtk_widget_show_all (window);
}

int main (int argc, char **argv)
{
    GtkApplication *app;
    int status;

    app = gtk_application_new ("org.gtk.example", G_APPLICATION_FLAGS_NONE);
    g_signal_connect (app, "activate", G_CALLBACK (activate), NULL);
    status = g_application_run (G_APPLICATION (app), argc, argv);
    g_object_unref (app);

    return status;
}

The program should have printed the value of the entry box which in the dialog after closing the dialog. Note: in the main window there is a button that opens the dialog.

Thanks for helping!

Body:
Problem is on the print_text function. The prototype for GtkDialog response signal is:

void user_function (GtkDialog *dialog,
                 gint       response_id,
                 gpointer   user_data)

So you must change your function to:

static void print_text (GtkWidget *widget, gint response_id, gpointer data)
{
    GtkEntry* entry = data;
    printf("%s", gtk_entry_get_text(entry));
    gtk_widget_destroy (widget); // This will close the dialog
}


问:
Why isn't importNode executing when everything is fine?
I want to use HTML import so I created two files.

File1:

```<code><!DOCTYPE html>
<html>
<head>
    <style>
        div {
            height: 300px;
            width: 300px;
            background-color: yellow;
        }
    </style>
</head>
<body>
    <div></div>
</body>
</html>
</code>```

File2:

```<code><!DOCTYPE html>
<html>
<head>
    <link rel='import' href='test.html' id='LINK'>
    <script>
        var LINK = document.getElementById('LINK');
        var test = LINK.import;
        var content = document.importNode(test.content, true);
        document.body.appendChild(content);

    </script>
</head>
<body>
</body>
</html>
</code>```

I should see a yellow square when I execute File2 but instead I'm getting this error:

Uncaught TypeError: Failed to execute 'importNode' on 'Document': parameter 1 is not of type 'Node'.
    at Import.html:8

When I log the "test" variable to the console, I am getting the document that contains File1 so it's fine there. I just don't get what the error is supposed to mean and why it's not working.

答:
When you write:

```<code>var content = document.importNode(test.content, true);
</code>```

...you suppose that test is a <template> element.

So in the document you import, you should have a <template> element.

test.html:

```<code><html>
<head>
    <style>
        div {
            height: 300px;
            width: 300px;
            background-color: yellow;
        }
    </style>
</head>
<body>
    <template><div></div></template>
</body>
</html>
</code>```

In the main file, use querySelector() (or another selector function) to get the template:

```<code>var LINK = document.getElementById('LINK');
var test = LINK.import.querySelector('template');
var content = document.importNode(test.content, true);
...
</code>```

Body:
I want to use HTML import so I created two files.

File1:

<!DOCTYPE html>

File2:

<!DOCTYPE html>

    <link rel='import' href='test.html' id='LINK'>

I should see a yellow square when I execute File2 but instead I'm getting this error:

Uncaught TypeError: Failed to execute 'importNode' on 'Document': parameter 1 is not of type 'Node'.
    at Import.html:8

When I log the "test" variable to the console, I am getting the document that contains File1 so it's fine there. I just don't get what the error is supposed to mean and why it's not working.

Body:
When you write:

var content = document.importNode(test.content, true);

...you suppose that test is a <template> element.

So in the document you import, you should have a <template> element.

test.html:

<html>
<head>
    <style>
        div {
            height: 300px;
            width: 300px;
            background-color: yellow;
        }
    </style>
</head>
<body>
    <template><div></div></template>
</body>
</html>

In the main file, use querySelector() (or another selector function) to get the template:

var LINK = document.getElementById('LINK');
var test = LINK.import.querySelector('template');
var content = document.importNode(test.content, true);
...


问:
Update List base on another list in JavaScript
How Can I update an Array based on another Array?

This is how I tried to do:

var ref = [
    {
      "name": "Jack",
      "title": "Manager",
      "description": "",
    },
    {
      "name": "Steve",
      "title": "CEO",
      "description": "A test description",
    }
  ];

var elem = [
    {
      "name": "Jack",
      "title": "Manager",
      "description": "",
    },
    {
      "name": "Steve",
      "title": "CEO",
      "description": "A test description",
    }
  ];

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

 ref.indexOf(elem[i]) === -1 ? ref.push(elem[i]) : console.log("This item already exists");

}
console.log(ref);
console.log(elem);```

This Loop caused an error because the length is changing after each iterate.

What I want is, to add each element from elem object if it doesn't exist in arr object and of course stays in JOSN format. In my example, it doesn't have to change.

答:
It would be better to run the loop over elem. Also you can't compare objects like that because references will differ, so you will have to do deep check, something like this should work:

var ref = [
    {
      "name": "Jack",
      "title": "Manager",
      "description": "",
    },
    {
      "name": "Steve",
      "title": "CEO",
      "description": "A test description",
    }
  ];

var elem = [
    {
      "name": "Jack",
      "title": "Manager",
      "description": "",
    },
    {
      "name": "Steve",
      "title": "CEO",
      "description": "A test description",
    }
  ];

for (var i = 0; i < elem.length; i++) {
    var found = false;
    for (var j=0; j<ref.length; j++){
        var count = Object.keys(elem[i]).length;
        for(var key in elem[i]){
            if(ref[j][key] === elem[i][key])
                count--;
        }
        if (count === 0){
           found= true;
           break;
        }
    }
    if (!found)
       ref.push(elem[i]);
 }

console.log(ref);
console.log(elem);```

Body:
How Can I update an Array based on another Array?

This is how I tried to do:

var ref = [
    {
      "name": "Jack",
      "title": "Manager",
      "description": "",
    },
    {
      "name": "Steve",
      "title": "CEO",
      "description": "A test description",
    }
  ];

var elem = [
    {
      "name": "Jack",
      "title": "Manager",
      "description": "",
    },
    {
      "name": "Steve",
      "title": "CEO",
      "description": "A test description",
    }
  ];

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

 ref.indexOf(elem[i]) === -1 ? ref.push(elem[i]) : console.log("This item already exists");

}
console.log(ref);
console.log(elem);

This Loop caused an error because the length is changing after each iterate.

What I want is, to add each element from elem object if it doesn't exist in arr object and of course stays in JOSN format. In my example, it doesn't have to change.


问:
Counting list size resulting from a findall not working in Prolog
I obtain a specific list using findall, and then want to count the number of elements in it.

i.e.

```<code>huntingbreeds(List) :-
   findall(Breedname, breed(Breedname,_,hunting), List).
</code>```

This returns a need list of hunting dogs from my database [beagle, basset].

But now if i try count it using my new predicate:

```<code>list_length([] , 0 ).
list_length([_|Xs] , L ) :-
        list_length(Xs,N) ,
        L is N+1 .
</code>```

with my query
    ?- list_length(huntingbreeds(List), Count).

This just returns false.

I thought I may need to use arg i.e.

```<code>?- list_length(arg(1,huntingbreeds(List),L), Count).
</code>```

but again it returns false.
Anyone know how i can get the list size? I know the function list_length works as if i give it:

```<code>?- list_length([1,2,3], Count).
</code>```

I get
    Count = 3.

But just don't know how to pass it my list from the find result. I have tried putting the full findall statement in place of the huntingbreeds(List) but that still does nothing.

答:
You could  try:</p>

```<code>huntingbreeds(List),list_length(List, Count).
</code>```

Body:
I obtain a specific list using findall, and then want to count the number of elements in it.

i.e.

huntingbreeds(List) :-
   findall(Breedname, breed(Breedname,_,hunting), List).

This returns a need list of hunting dogs from my database [beagle, basset].

But now if i try count it using my new predicate:

list_length([] , 0 ).
list_length([_|Xs] , L ) :-
        list_length(Xs,N) ,
        L is N+1 .

with my query
    ?- list_length(huntingbreeds(List), Count).

This just returns false.

I thought I may need to use arg i.e.

?- list_length(arg(1,huntingbreeds(List),L), Count).

but again it returns false.
Anyone know how i can get the list size? I know the function list_length works as if i give it:

?- list_length([1,2,3], Count).

I get
    Count = 3.

But just don't know how to pass it my list from the find result. I have tried putting the full findall statement in place of the huntingbreeds(List) but that still does nothing.

Body:
You could  try:

huntingbreeds(List),list_length(List, Count).


问:
Set Custom Coordinates to a function, Waze Integration
I'm trying to implement navigation using Waze in my App, using their own API: here.

I want to set in custom coordinates that are set in an array
and then fit them in this code:

```<code>func navigate(toLatitude latitude: Double , longitude: Double) {
                if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
                    // Waze is installed. Launch Waze and start navigation
                    let urlStr: String = "waze://?ll=\(latitude),\(longitude)&navigate=yes"
                    UIApplication.shared.openURL(URL(string: urlStr)!)
                }
                else {
                    // Waze is not installed. Launch AppStore to install Waze app
                    UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
                }
            }
</code>```

i have tried settings up different type of arrays but didn't succeed to make it work . So if you could help me out set custom array holding latitude and longitude that would work properly with the code, that would be awesome

your help will be very much helpful,

Thank you in advance.

答:
Waze app supporting only destination latitude and longitude.

waze://?ll=<lat>,<lon>&navigate=yes

CLLocationCordiates will expect two parameters latitude and longitude, which is CLLocationDegrees type. CLLocationDegrees is nothing but Double value.

```<code>let location =  CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
</code>```

If you have double values then no need to construct as CLLocationCoordinate2D. You can use the same function -> navigate() which you mentioned in your question

Pass the value to a below function to open Waze app.

```<code>func openWaze(location : CLLocationCoordinate2D) {
    if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
        // Waze is installed. Launch Waze and start navigation
        let urlStr: String = "waze://?ll=\(location.latitude),\(location.longitude)&navigate=yes"
        UIApplication.shared.openURL(URL(string: urlStr)!)
    }
    else {
        // Waze is not installed. Launch AppStore to install Waze app
        UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
    }
}
</code>```

Body:
I'm trying to implement navigation using Waze in my App, using their own API: here.

I want to set in custom coordinates that are set in an array
and then fit them in this code:

func navigate(toLatitude latitude: Double , longitude: Double) {
                if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
                    // Waze is installed. Launch Waze and start navigation
                    let urlStr: String = "waze://?ll=\(latitude),\(longitude)&navigate=yes"
                    UIApplication.shared.openURL(URL(string: urlStr)!)
                }
                else {
                    // Waze is not installed. Launch AppStore to install Waze app
                    UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
                }
            }

i have tried settings up different type of arrays but didn't succeed to make it work . So if you could help me out set custom array holding latitude and longitude that would work properly with the code, that would be awesome

your help will be very much helpful,

Thank you in advance.

Body:
Waze app supporting only destination latitude and longitude.

waze://?ll=<lat>,<lon>&navigate=yes

CLLocationCordiates will expect two parameters latitude and longitude, which is CLLocationDegrees type. CLLocationDegrees is nothing but Double value.

let location =  CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

If you have double values then no need to construct as CLLocationCoordinate2D. You can use the same function -> navigate() which you mentioned in your question

Pass the value to a below function to open Waze app.

func openWaze(location : CLLocationCoordinate2D) {
    if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
        // Waze is installed. Launch Waze and start navigation
        let urlStr: String = "waze://?ll=\(location.latitude),\(location.longitude)&navigate=yes"
        UIApplication.shared.openURL(URL(string: urlStr)!)
    }
    else {
        // Waze is not installed. Launch AppStore to install Waze app
        UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
    }
}


问:
JHipster : Generate MongoDB entities with JHipster Domain Language (JDL)
I'm trying JHipster with a MongoDB database. For my example I would like to store Books. To do that I would like to use the JDL format to be able to generate entities, repositories, services, dtos…

This is my actual JDL file:
And it works :

```<code>entity Book {
    name String required
    date LocalDate required
}

dto all with mapstruct
paginate all with pager
service all with serviceImpl
</code>```

Now, I would like to add the notion that a Book can be written by an Author.

I can add an entity Author:

```<code>entity Author {
        firstane String required
        lastname LocalDate required
    }
</code>```

My specific question is: How can I associate an Author and a Book?

The documentation has this example :

```<code>relationship OneToMany {
  Author{book} to Book{writer(name) required}
}
</code>```

But that's not working because NoSQL databases don't support relationships. So, how can I achieve that ?

Thanks.

答:
You haven't said exactly what you want to do with your entities. With NoSQL databases this becomes a more important question. Let's assume you want to return an author and all their books as a single document.

Here are some options:

Have two separate entities with no formal relationship in JHipster. Create a service that looks up an author using the Author Repository and also fetches the books with the same author id using the Book Repository.

Have a single Author entity in JHipster. Model books as an array of embdedded documents for each Author. Unfortunately JHipster does not seem to allow you to define list types as entity fields so you will have to add this to the Java code yourself.

You may be able to use the $lookup feature in mongodb 3.2 to fetch Books for a given Author. The DBRef feature in spring-data-mongo might help in this case.

Body:
I'm trying JHipster with a MongoDB database. For my example I would like to store Books. To do that I would like to use the JDL format to be able to generate entities, repositories, services, dtos…

This is my actual JDL file:
And it works :

entity Book {
    name String required
    date LocalDate required
}

dto all with mapstruct
paginate all with pager
service all with serviceImpl

Now, I would like to add the notion that a Book can be written by an Author.

I can add an entity Author:

entity Author {
        firstane String required
        lastname LocalDate required
    }

My specific question is: How can I associate an Author and a Book?

The documentation has this example :

relationship OneToMany {
  Author{book} to Book{writer(name) required}
}

But that's not working because NoSQL databases don't support relationships. So, how can I achieve that ?

Thanks.


问:
Move a project to an exsisting Repo
I have a project i have been working on for about a year. I kept the project on git, and committed often so it has a lot of history and a lot of previous data but the original local file has been corrupted. I downloaded the latest version of my project from Github. I want to move this new local project to the existing repo and keep all of its history, how could I do this?</p>

答:
I think rebase should help here.

I assuming that, you did the changes on a particular branch(say my-work). Firstly , in your existing local modified repo get the latest from your  remote (say origin).

```<code>git pull -- rebase origin master
</code>```

This will bring all the code from your remote master to your local master.

Now, try to apply your changes on top of master using below command

```<code>git checkout my-work && git rebase master
</code>```

Title: Move a project to an exsisting Repo

Body:
I think rebase should help here.

I assuming that, you did the changes on a particular branch(say my-work). Firstly , in your existing local modified repo get the latest from your  remote (say origin).

git pull -- rebase origin master

This will bring all the code from your remote master to your local master.

Now, try to apply your changes on top of master using below command

git checkout my-work && git rebase master


问:
Python3 - selenium - Chrome : keyword instead of URL
I am exploring Selenium with Chromedriver and Python 3.4. I got curious and tried to do following

```<code>from selenium import webdriver

driver = webdriver.Chrome()
driver.get("Cisco")
</code>```

I gave a search keyword instead of URL to driver. It failed. I thought it will do a keyword search using google search engine. Am I doing something wrong?

I dont want to navigate to google.com and put keyword in search text box.
How can I directly search the keyword?

Any help or guidance will be very helpful.

答:
Just navigate directly to the results page. Use:</p>

```<code>driver.get("https://www.google.com/#q=Cisco")
</code>```

Body:
I am exploring Selenium with Chromedriver and Python 3.4. I got curious and tried to do following

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("Cisco")

I gave a search keyword instead of URL to driver. It failed. I thought it will do a keyword search using google search engine. Am I doing something wrong?

I dont want to navigate to google.com and put keyword in search text box.
How can I directly search the keyword?

Any help or guidance will be very helpful.

Body:
Just navigate directly to the results page. Use:

driver.get("https://www.google.com/#q=Cisco")


问:
Is there a way to timeout a MySql query when using DBI and dbGetQuery?
I realize that

dbGetQuery comes with a default implementation that calls dbSendQuery, then dbFetch, ensuring that the result is always freed by dbClearResult.

and

dbClearResult frees all resources (local and remote) associated with a result set. In some cases (e.g., very large result sets) this can be a critical step to avoid exhausting resources (memory, file descriptors, etc.)

But my team just experienced a locked table that we went into MySQL to kill pid and I'm wondering - is there a way to timeout a query submitted using the DBI package?

I'm looking for and can't find the equivalent of

dbGetQuery(conn = connection, 'select stuff from that_table', timeout = 90)

I tried this, and profiled the function with and without the parameter set and it doesn't appear it does anything; why would it, if dbClearResult is always in play?

答:
If I am reading your question correctly, my sense is you need to rely on your MySQL server to implement your required query timeout. Why? dbQuery is sending a client request to the server you want the server to run the query and timeout.

Proposed Solution:

Include a statement execution hint in the query you submit to your MySQL database.

nb. The query data returned may be too large for you to consume but that is a different problem.

MySql Example:

The MAX_EXECUTION_TIME hint is permitted only for SELECT statements. It places a limit N (a timeout value in milliseconds) on how long an SQL statement is permitted to execute before the server terminates it.

```<code>MAX_EXECUTION_TIME(N)
</code>```

Example with a timeout of 1 second (1000 milliseconds):

```<code>SELECT /*+ MAX_EXECUTION_TIME(1000) */ * FROM t1 INNER JOIN t2 WHERE ...
</code>```

The MAX_EXECUTION_TIME(N) hint sets a statement execution timeout of N milliseconds. If this option is absent or N is 0, the statement timeout established by the max_execution_time system variable applies.

The MAX_EXECUTION_TIME hint is applicable as follows:

For statements with multiple SELECT keywords, such as unions or statements with subqueries, MAX_EXECUTION_TIME applies to the entire statement and must appear after the first SELECT.

It applies to read-only SELECT statements. Statements that are not read-only are those that invoke a stored function that modifies data as a side effect.

It does not apply to SELECT statements in stored programs and is ignored.

I hope the above approach helps move you in the right direction.

Body:
If I am reading your question correctly, my sense is you need to rely on your MySQL server to implement your required query timeout. Why? dbQuery is sending a client request to the server you want the server to run the query and timeout.

Proposed Solution:

Include a statement execution hint in the query you submit to your MySQL database.

nb. The query data returned may be too large for you to consume but that is a different problem.

MySql Example:

The MAX_EXECUTION_TIME hint is permitted only for SELECT statements. It places a limit N (a timeout value in milliseconds) on how long an SQL statement is permitted to execute before the server terminates it.

MAX_EXECUTION_TIME(N)

Example with a timeout of 1 second (1000 milliseconds):

SELECT /*+ MAX_EXECUTION_TIME(1000) */ * FROM t1 INNER JOIN t2 WHERE ...

The MAX_EXECUTION_TIME(N) hint sets a statement execution timeout of N milliseconds. If this option is absent or N is 0, the statement timeout established by the max_execution_time system variable applies.

The MAX_EXECUTION_TIME hint is applicable as follows:

For statements with multiple SELECT keywords, such as unions or statements with subqueries, MAX_EXECUTION_TIME applies to the entire statement and must appear after the first SELECT.

It applies to read-only SELECT statements. Statements that are not read-only are those that invoke a stored function that modifies data as a side effect.

It does not apply to SELECT statements in stored programs and is ignored.

I hope the above approach helps move you in the right direction.


问:
Ruby's instance_eval equivalent in Scala for building DSLs
In Ruby, when you design an embedded DSL a very useful trick is to leverage instance_eval. That way one can offer special statements within a certain block by implementing them as private methods on a special object. This is very nice for contextual stuff.

For an example see: https://robots.thoughtbot.com/writing-a-domain-specific-language-in-ruby

I was wondering what the closest equivalent would be in a Scala EDSL? More specifically how would I offer parts of the syntax only within a certain context that is delimited by a block?

答: If anybody's wondering: It looks like this is gonna be solve by so-called implicit function types. Here's a good write-up of the idea by Martin Odersky himself: https://www.scala-lang.org/blog/2016/12/07/implicit-function-types.html </p>


问:
Accessing Express.js req or session from Jade template
I am wondering if there is an easy way to access Express.js' req or session variables from within a Jade template without passing it in through the normal response.

Or is this the only way?

```<code>res.render('/', {
    session: req.session
});
</code>```

答:
this worked for me

```<code>app.use(function(req,res,next){
   res.locals.user = req.user;
   next();
});
</code>```

in pug or jade view user

```<code>#{user.email}
</code>```

Body:
I am wondering if there is an easy way to access Express.js' req or session variables from within a Jade template without passing it in through the normal response.

Or is this the only way?

res.render('/', {
    session: req.session
});

Body:
this worked for me

app.use(function(req,res,next){
   res.locals.user = req.user;
   next();
});

in pug or jade view user

#{user.email}


问:
Using MPI on Slurm, is there a way to send messages between separate jobs?
I'm new to using MPI (mpi4py) and Slurm. I need to run about 50000 tasks, so to obey the administrator-set limit of about 1000, I've been running them like this:

sbrunner.sh:

```<code>#!/bin/bash
for i in {1..50}
do
   sbatch m2slurm.sh $i
   sleep 0.1
done
</code>```

m2slurm.sh:

```<code>#!/bin/bash
#SBATCH --job-name=mpi
#SBATCH --output=mpi_50000.out
#SBATCH --time=0:10:00
#SBATCH --ntasks=1000

srun --mpi=pmi2 --output=mpi_50k${1}.out python par.py data_50000.pkl ${1} > ${1}py.out 2> ${1}.err
</code>```

par.py (irrelevant stuff omitted):

```<code>offset = (int(sys.argv[2])-1)*1000
comm = MPI.COMM_WORLD
k = comm.Get_rank()
d = data[k+offset]

# ... do something with d ...

allresults = comm.gather(result, root=0)
comm.Barrier()
if k == 0:
    print(allresults)
</code>```

Is this a sensible way to get around the limit of 1000 tasks?

Is there a better way to consolidate results? I now have 50 files I have to concatenate manually. Is there some comm_world that can exist between different jobs?

答:
This looks like a perfect candidate for job arrays. Each job in an array is identical with the exception of a $SLURM_ARRAY_TASK_ID environment variable. You can use this in the same way that you're using the command line variable.

(You'll need to check that MaxArraySize is set high enough by your sysadmin. Check the output of scontrol show config | grep MaxArraySize )

Body:
I'm new to using MPI (mpi4py) and Slurm. I need to run about 50000 tasks, so to obey the administrator-set limit of about 1000, I've been running them like this:

sbrunner.sh:

#!/bin/bash
for i in {1..50}
do
   sbatch m2slurm.sh $i
   sleep 0.1
done

m2slurm.sh:

#!/bin/bash
#SBATCH --job-name=mpi
#SBATCH --output=mpi_50000.out
#SBATCH --time=0:10:00
#SBATCH --ntasks=1000

srun --mpi=pmi2 --output=mpi_50k${1}.out python par.py data_50000.pkl ${1} > ${1}py.out 2> ${1}.err

par.py (irrelevant stuff omitted):

offset = (int(sys.argv[2])-1)*1000
comm = MPI.COMM_WORLD
k = comm.Get_rank()
d = data[k+offset]

# ... do something with d ...

allresults = comm.gather(result, root=0)
comm.Barrier()
if k == 0:
    print(allresults)

Is this a sensible way to get around the limit of 1000 tasks?

Is there a better way to consolidate results? I now have 50 files I have to concatenate manually. Is there some comm_world that can exist between different jobs?


问:
Uncaught exception 'Symfony\Component\Yaml\Exception\ParseException'
this is my first time working a project with symfony 3.3
i installed it and everything is good , now i want to install FOSuserBundle , i followed all steps in symfony site . the last step is to :Update your database schema  ( php bin/console doctrine:schema:update --force )
but i had this exception :
Fatal error: Uncaught exception 'Symfony\Component\Yaml\Exception\ParseException' with message 'Indentation problem at line 34 (near " main:").' in C:\wamp64\www\untitled\vendor\symf
ony\symfony\src\Symfony\Component\Yaml\Parser.php:591
Stack trace:

0 C:\wamp64\www\untitled\vendor\symfony\symfony\src\Symfony\Component\Yaml\Parser.php(320): Symfony\Component\Yaml\Parser->getNextEmbedBlock()

1 C:\wamp64\www\untitled\vendor\symfony\symfony\src\Symfony\Component\Yaml\Parser.php(450): Symfony\Component\Yaml\Parser->doParse('encoders:\n    F...', 2816)

2 C:\wamp64\www\untitled\vendor\symfony\symfony\src\Symfony\Component\Yaml\Parser.php(320): Symfony\Component\Yaml\Parser->parseBlock(7, 'encoders:\n    F...', 2816)

3 C:\wamp64\www\untitled\vendor\symfony\symfony\src\Symfony\Component\Yaml\Parser.php(450): Symfony\Component\Yaml\Parser->doParse('security:\n    e...', 2816)

4 C:\wamp64\www\untitled\vendor\symfony\symfony\src\Symfony\Component\Yaml\Parser.php(320): Symfony\Component\Yaml\Parser->parseBlock(6, 'security:\n    e in C:\wamp64\www\untitled\

vendor\symfony\symfony\src\Symfony\Component\Config\Loader\FileLoader.php on line 179

this is my ..app/config/security.yml

security:

```<code># https://symfony.com/doc/current/security.html#b-configuring-how-users-are-loaded
</code>```

security:
       encoders:
           FOS\UserBundle\Model\UserInterface: bcrypt

```<code>   role_hierarchy:
       ROLE_ADMIN:       ROLE_USER
       ROLE_SUPER_ADMIN: ROLE_ADMIN

   providers:
       fos_userbundle:
           id: fos_user.user_provider.username

   firewalls:
       main:
           pattern: ^/
           form_login:
               provider: fos_userbundle
               csrf_provider: security.csrf.token_manager # Use form.csrf_provider instead for Symfony <2.4
           logout:       true
           anonymous:    true

   access_control:
       - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
       - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
       - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
       - { path: ^/admin/, role: ROLE_ADMIN }

    main:
        anonymous: ~
        # activate different ways to authenticate

        # https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate
        #http_basic: ~

        # https://symfony.com/doc/current/security/form_login_setup.html
        #form_login: ~
</code>```

please help me
thanks :)

答:
This is really tough to notice, but...

There is an extra space before the main: that appears after the access_control: block. Remove the space and you should be good to go.

I found this by copying your file into Netbeans IDE. It's pretty good at identifying YAML file errors.

Good luck.

Body:
this is my first time working a project with symfony 3.3
i installed it and everything is good , now i want to install FOSuserBundle , i followed all steps in symfony site . the last step is to :Update your database schema  ( php bin/console doctrine:schema:update --force )
but i had this exception :
Fatal error: Uncaught exception 'Symfony\Component\Yaml\Exception\ParseException' with message 'Indentation problem at line 34 (near " main:").' in C:\wamp64\www\untitled\vendor\symf
ony\symfony\src\Symfony\Component\Yaml\Parser.php:591
Stack trace:

0 C:\wamp64\www\untitled\vendor\symfony\symfony\src\Symfony\Component\Yaml\Parser.php(320): Symfony\Component\Yaml\Parser->getNextEmbedBlock()

1 C:\wamp64\www\untitled\vendor\symfony\symfony\src\Symfony\Component\Yaml\Parser.php(450): Symfony\Component\Yaml\Parser->doParse('encoders:\n    F...', 2816)

2 C:\wamp64\www\untitled\vendor\symfony\symfony\src\Symfony\Component\Yaml\Parser.php(320): Symfony\Component\Yaml\Parser->parseBlock(7, 'encoders:\n    F...', 2816)

3 C:\wamp64\www\untitled\vendor\symfony\symfony\src\Symfony\Component\Yaml\Parser.php(450): Symfony\Component\Yaml\Parser->doParse('security:\n    e...', 2816)

4 C:\wamp64\www\untitled\vendor\symfony\symfony\src\Symfony\Component\Yaml\Parser.php(320): Symfony\Component\Yaml\Parser->parseBlock(6, 'security:\n    e in C:\wamp64\www\untitled\

vendor\symfony\symfony\src\Symfony\Component\Config\Loader\FileLoader.php on line 179

this is my ..app/config/security.yml

security:

# https://symfony.com/doc/current/security.html#b-configuring-how-users-are-loaded

security:
       encoders:
           FOS\UserBundle\Model\UserInterface: bcrypt

   role_hierarchy:
       ROLE_ADMIN:       ROLE_USER
       ROLE_SUPER_ADMIN: ROLE_ADMIN

   providers:
       fos_userbundle:
           id: fos_user.user_provider.username

   firewalls:
       main:
           pattern: ^/
           form_login:
               provider: fos_userbundle
               csrf_provider: security.csrf.token_manager # Use form.csrf_provider instead for Symfony <2.4
           logout:       true
           anonymous:    true

   access_control:
       - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
       - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
       - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
       - { path: ^/admin/, role: ROLE_ADMIN }

    main:
        anonymous: ~
        # activate different ways to authenticate

        # https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate
        #http_basic: ~

        # https://symfony.com/doc/current/security/form_login_setup.html
        #form_login: ~

please help me
thanks :)


问:
Pascal Triangle in Haskell
I'm new to Haskell and I really need some help!

I have to write a program that includes a recursive function to produce a list of binomial coefficients for the power n=12 using the Pascal's triangle technique.

I have some ideas in my head but because I'm just getting started I have no idea how to implement this to haskell?!

Could someone please help me out??

```<code>first row: (a+b)^0 = 1
second row: (a+b)^1 = 1a+1b
third row: (a+b)^2 = 1a^2+2ab+1b^2
</code>```

and so on...this is my main idea. But I cant even try this out because I have no idea how I put this in Haskell..getting errors all the time

答:
Start out with the triangle itself:

```<code>     1
    1 1
   1 2 1
  1 3 3 1
 1 4 6 4 1
    ...
</code>```

You should notice that to write down the next row, you must apply this rule: sum the previous rows' adjacent elements, using a 0 for the lonely edge elements. Visually:

```<code>    0   1   0
     \+/ \+/
  0   1   1   0
   \+/ \+/ \+/
0   1   2   1   0
 \+/ \+/ \+/ \+/
  1   3   3   1
       ...
</code>```

Operationally, that looks like this:

```<code>For row 0:
[1]  (it's a given; i.e. base case)

For row 1:
[0, 1]   <- row 0 with a zero prepended ([0] ++ row 0)
 +  +
[1, 0]   <- row 0 with a zero appended  (row 0 ++ [0])
 =  =
[1, 1]   <- element-wise addition

For row 2:
[0, 1, 1]
 +  +  +
[1, 1, 0]
 =  =  =
[1, 2, 1]

Generally, for row N:

element-wise addition of:
  [0] ++ row(N-1)
  row(N-1) ++ [0]
</code>```

Remember that element-wise addition of lists in Haskell is zipWith (+).

Thus we arrive at the following Haskell definition:

```<code>pascal 0 = [1]
pascal n = zipWith (+) ([0] ++ pascal (n-1)) (pascal (n-1) ++ [0])
</code>```

Or in a fashion similar to the famous "lazy fibs":

```<code>pascals = [1] : map (\xs -> zipWith (+) ([0] ++ xs) (xs ++ [0])) pascals
</code>```

Title: Pascal Triangle in Haskell

Body:
I'm new to Haskell and I really need some help!

I have to write a program that includes a recursive function to produce a list of binomial coefficients for the power n=12 using the Pascal's triangle technique.

I have some ideas in my head but because I'm just getting started I have no idea how to implement this to haskell?!

Could someone please help me out??

first row: (a+b)^0 = 1
second row: (a+b)^1 = 1a+1b
third row: (a+b)^2 = 1a^2+2ab+1b^2

and so on...this is my main idea. But I cant even try this out because I have no idea how I put this in Haskell..getting errors all the time

Body:
Start out with the triangle itself:

     1
    1 1
   1 2 1
  1 3 3 1
 1 4 6 4 1
    ...

You should notice that to write down the next row, you must apply this rule: sum the previous rows' adjacent elements, using a 0 for the lonely edge elements. Visually:

    0   1   0
     \+/ \+/
  0   1   1   0
   \+/ \+/ \+/
0   1   2   1   0
 \+/ \+/ \+/ \+/
  1   3   3   1
       ...

Operationally, that looks like this:

For row 0:
[1]  (it's a given; i.e. base case)

For row 1:
[0, 1]   <- row 0 with a zero prepended ([0] ++ row 0)
 +  +
[1, 0]   <- row 0 with a zero appended  (row 0 ++ [0])
 =  =
[1, 1]   <- element-wise addition

For row 2:
[0, 1, 1]
 +  +  +
[1, 1, 0]
 =  =  =
[1, 2, 1]

Generally, for row N:

element-wise addition of:
  [0] ++ row(N-1)
  row(N-1) ++ [0]

Remember that element-wise addition of lists in Haskell is zipWith (+).

Thus we arrive at the following Haskell definition:

pascal 0 = [1]
pascal n = zipWith (+) ([0] ++ pascal (n-1)) (pascal (n-1) ++ [0])

Or in a fashion similar to the famous "lazy fibs":

pascals = [1] : map (\xs -> zipWith (+) ([0] ++ xs) (xs ++ [0])) pascals


问:
convert snake_case keyed map to camelCase keyed map in elixir, phoenix before sending stuff as JSON
I want to change keys of maps in elixir from snake case to camel case before sending stuff as JSON. How can I do that? Should it be just a function in which I will wrap every response or should it be done on some lower level, i.e. in Poison?

Thanks

答:
One might use Macro.underscore/1, but that's not correct way to do it. Since the Macro module itself states:

This function was designed to underscore language identifiers/tokens,
    that's why it belongs to the Macro module. Do not use it as a general
    mechanism for underscoring strings as it does not support Unicode or
    characters that are not valid in Elixir identifiers.

So, it is better to use some other library. I would recommend to use recase. It can convert string to any case, not just camelCase.

Since it is a third-party library you need to install it.

add this line to mix.exs into deps: {:recase, "~> 0.6"} Make sure to use the latest version!

run mix deps.get

That's how you use it:

```<code>Recase.to_camel("some-value")
# => "someValue"

Recase.to_camel("Some Value")
# => "someValue"
</code>```

You can find docs here: https://hexdocs.pm/recase/readme.html

And the repo here: https://github.com/sobolevn/recase

Body:
One might use Macro.underscore/1, but that's not correct way to do it. Since the Macro module itself states:

This function was designed to underscore language identifiers/tokens,
    that's why it belongs to the Macro module. Do not use it as a general
    mechanism for underscoring strings as it does not support Unicode or
    characters that are not valid in Elixir identifiers.

So, it is better to use some other library. I would recommend to use recase. It can convert string to any case, not just camelCase.

Since it is a third-party library you need to install it.

add this line to mix.exs into deps: {:recase, "~> 0.6"} Make sure to use the latest version!

run mix deps.get

That's how you use it:

Recase.to_camel("some-value")
# => "someValue"

Recase.to_camel("Some Value")
# => "someValue"

You can find docs here: https://hexdocs.pm/recase/readme.html

And the repo here: https://github.com/sobolevn/recase


问:
Error Working With Paper Onboarding
I've been following this tutorial on Youtube: https://www.youtube.com/watch?v=G5UkS4Mrepo but I continually get the following error at return and can't find the solution:

Cannot convert return expression of type '(String, String, String, String, UIColor, UIColor, UIColor, UIFont, UIFont)' to return type 'OnboardingItemInfo' (aka '(imageName: UiImage, title: String, description: String, iconName: UiImage, color: UIColor, titleColor: UIColor, descriptionColor: UIColor, titleFont: UIFont, descriptionFont: UIFont)')

Around the 15:13 minute mark, he shows a functioning app based on the code he provided, yet mine is throwing an error. Here's my code:

...

```<code>@IBOutlet weak var onboardingView: OnboardingView!

override func viewDidLoad() {
    super.viewDidLoad()
    onboardingView.dataSource = self
}

func onboardingItemsCount() -> Int {
    return 3
}

func onboardingItemAtIndex(_ index: Int) -> OnboardingItemInfo {
    let backgroundColorOne = UIColor(red: 217/255, green: 72/255, blue: 89/255, alpha: 1)
    let backgroundColorTwo = UIColor(red: 106/255, green: 166/255, blue: 211/255, alpha: 1)
    let backgroundColorThree = UIColor(red: 168/255, green: 200/255, blue: 78/255, alpha: 1)

    return[
        ("rocket", "a great rocket start", "text description", "", backgroundColorOne, UIColor.white, UIColor.white, titleFont, descriptionFont)
    ][index]
}
</code>```

...

Docs are found here: https://cdn.rawgit.com/Ramotion/paper-onboarding/master/docs/index.html

答:
Based on the error message, the 1st and 4th values in the tuple being returned need to of type UIImage, not String. Who ever designed this API did a poor job with their naming conventions for those two values.

Also note that you have specified that there are 3 items but your onboardingItemAtIndex only has an array of one value.

Title: Error Working With Paper Onboarding

Body:
I've been following this tutorial on Youtube: https://www.youtube.com/watch?v=G5UkS4Mrepo but I continually get the following error at return and can't find the solution:

Cannot convert return expression of type '(String, String, String, String, UIColor, UIColor, UIColor, UIFont, UIFont)' to return type 'OnboardingItemInfo' (aka '(imageName: UiImage, title: String, description: String, iconName: UiImage, color: UIColor, titleColor: UIColor, descriptionColor: UIColor, titleFont: UIFont, descriptionFont: UIFont)')

Around the 15:13 minute mark, he shows a functioning app based on the code he provided, yet mine is throwing an error. Here's my code:

...

@IBOutlet weak var onboardingView: OnboardingView!

override func viewDidLoad() {
    super.viewDidLoad()
    onboardingView.dataSource = self
}

func onboardingItemsCount() -> Int {
    return 3
}

func onboardingItemAtIndex(_ index: Int) -> OnboardingItemInfo {
    let backgroundColorOne = UIColor(red: 217/255, green: 72/255, blue: 89/255, alpha: 1)
    let backgroundColorTwo = UIColor(red: 106/255, green: 166/255, blue: 211/255, alpha: 1)
    let backgroundColorThree = UIColor(red: 168/255, green: 200/255, blue: 78/255, alpha: 1)

    return[
        ("rocket", "a great rocket start", "text description", "", backgroundColorOne, UIColor.white, UIColor.white, titleFont, descriptionFont)
    ][index]
}

...

Docs are found here: https://cdn.rawgit.com/Ramotion/paper-onboarding/master/docs/index.html


问:
OfficeJS Excel Sample error ( _host_Info=Excel )
I am trying  to use example with shared folder like this
https://github.com/OfficeDev/office-js-docs/blob/master/docs/excel/build-your-first-excel-add-in.md

but got a strange error

cannot find
file://ff/?_host_Info=Excel$Win32$16.01$en-US.
make sure the path or Internet address is correct

Office version 1701 (7066.2092) Desktop Excel32

答:
You should use a web server (local IIS instance, or a node-based dev hosting server, etc.) instead of serving the files off of the file system.

You need the file share for sideloading the manifest on Desktop, but the actual files should be served off of https://localhost:XXXX.

For what it's worth, if you're just starting with playing around with the Excel APIs, might I recommend Script Lab, a playground experience for learning and trying out the APIs.  It actually has that very same "Getting Started" sample (slightly modified and TypeScript-ified):

Hope you find it useful!


问:
Combine to Keras functional models
I am trying to mimic this keras blog about fine tuning image classifiers. I would like to use the Inceptionv3 found on a fchollet repo.

Inception is a Model (functional API), so I can't just do model.add(top_model) which is reserved for Sequential.

How can I add combine two functional Models? Let's say I have

```<code>inputs = Input(shape=input_shape)
x = Flatten()(inputs)
predictions = Dense(4, name='final1')(x)

model1 = Model(input=inputs, output=predictions)
</code>```

for the first model and

```<code>inputs_2 = Input(shape=(4,))
y = Dense(5)(l_inputs)
y = Dense(2, name='final2')(y)
predictions_2 = Dense(29)(y)
model2 = Model(input=inputs2, output=predictions2)
</code>```

for the second. I now want an end-to-end that goes from inputs to predicions_2 and links predictions to inputs_2.

I tried using model1.get_layer('final1').output but I had a mismatch with types and I couldn't make it work.

答:
I ran into this problem as well while fine tuning VGG16. Here's what worked for me and I imagine a similar approach can be taken for Inception V3. Tested on Keras 2.0.5 with Tensorflow 1.2 backend. </p>

```<code># NOTE: define the following variables
#       top_model_weights_path
#       num_classes
#       dense_layer_1 = 4096
#       dense_layer_2 = 4096

vgg16 = applications.VGG16(
    include_top=False,
    weights='imagenet',
    input_shape=(224, 224, 3))

# Inspect the model
vgg16.summary()

# This shape has to match the last layer in VGG16 (without top)
dense_input  = Input(shape=(7, 7, 512))
dense_output = Flatten(name='flatten')(dense_input)
dense_output = Dense(dense_layer_1, activation='relu', name='fc1')(dense_output)
dense_output = Dense(dense_layer_2, activation='relu', name='fc2')(dense_output)
dense_output = Dense(num_classes, activation='softmax', name='predictions')(dense_output)

top_model = Model(inputs=dense_input, outputs=dense_output, name='top_model')

# from: https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html
# note that it is necessary to start with a fully-trained
# classifier, including the top classifier,
# in order to successfully do fine-tuning
top_model.load_weights(top_model_weights_path)

block5_pool = vgg16.get_layer('block5_pool').output

# Now combine the two models
full_output = top_model(block5_pool)
full_model  = Model(inputs=vgg16.input, outputs=full_output)

# set the first 15 layers (up to the last conv block)
# to non-trainable (weights will not be updated)
# WARNING: this may not be applicable for Inception V3
for layer in full_model.layers[:15]:
    layer.trainable = False

# Verify things look as expected
full_model.summary()

# compile the model with a SGD/momentum optimizer
# and a very slow learning rate.
full_model.compile(
    loss='binary_crossentropy',
    optimizer=optimizers.SGD(lr=5e-5, momentum=0.9),
    metrics=['accuracy'])

# Train the model...
</code>```

Title: Combine to Keras functional models

Body:
I am trying to mimic this keras blog about fine tuning image classifiers. I would like to use the Inceptionv3 found on a fchollet repo.

Inception is a Model (functional API), so I can't just do model.add(top_model) which is reserved for Sequential.

How can I add combine two functional Models? Let's say I have

inputs = Input(shape=input_shape)
x = Flatten()(inputs)
predictions = Dense(4, name='final1')(x)

model1 = Model(input=inputs, output=predictions)

for the first model and

inputs_2 = Input(shape=(4,))
y = Dense(5)(l_inputs)
y = Dense(2, name='final2')(y)
predictions_2 = Dense(29)(y)
model2 = Model(input=inputs2, output=predictions2)

for the second. I now want an end-to-end that goes from inputs to predicions_2 and links predictions to inputs_2.

I tried using model1.get_layer('final1').output but I had a mismatch with types and I couldn't make it work.

Body:
I ran into this problem as well while fine tuning VGG16. Here's what worked for me and I imagine a similar approach can be taken for Inception V3. Tested on Keras 2.0.5 with Tensorflow 1.2 backend.

# NOTE: define the following variables
#       top_model_weights_path
#       num_classes
#       dense_layer_1 = 4096
#       dense_layer_2 = 4096

vgg16 = applications.VGG16(
    include_top=False,
    weights='imagenet',
    input_shape=(224, 224, 3))

# Inspect the model
vgg16.summary()

# This shape has to match the last layer in VGG16 (without top)
dense_input  = Input(shape=(7, 7, 512))
dense_output = Flatten(name='flatten')(dense_input)
dense_output = Dense(dense_layer_1, activation='relu', name='fc1')(dense_output)
dense_output = Dense(dense_layer_2, activation='relu', name='fc2')(dense_output)
dense_output = Dense(num_classes, activation='softmax', name='predictions')(dense_output)

top_model = Model(inputs=dense_input, outputs=dense_output, name='top_model')

# from: https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html
# note that it is necessary to start with a fully-trained
# classifier, including the top classifier,
# in order to successfully do fine-tuning
top_model.load_weights(top_model_weights_path)

block5_pool = vgg16.get_layer('block5_pool').output

# Now combine the two models
full_output = top_model(block5_pool)
full_model  = Model(inputs=vgg16.input, outputs=full_output)

# set the first 15 layers (up to the last conv block)
# to non-trainable (weights will not be updated)
# WARNING: this may not be applicable for Inception V3
for layer in full_model.layers[:15]:
    layer.trainable = False

# Verify things look as expected
full_model.summary()

# compile the model with a SGD/momentum optimizer
# and a very slow learning rate.
full_model.compile(
    loss='binary_crossentropy',
    optimizer=optimizers.SGD(lr=5e-5, momentum=0.9),
    metrics=['accuracy'])

# Train the model...


问:
ssl 'module' object has no attribute 'SSLContext'
```<code>In [1]: import ssl

In [2]: context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)

AttributeError  Traceback (most recent call last)
<ipython-input-2-13c9bad66150> in <module>()
----> 1 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)

AttributeError: 'module' object has no attribute 'SSLContext'
</code>```

Python version:  2.7.6

答:
You can use code below for Python 2.7.9:</p>

```<code>ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode=ssl.CERT_NONE
</code>```

Body:
In [1]: import ssl

In [2]: context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)

AttributeError  Traceback (most recent call last)
<ipython-input-2-13c9bad66150> in <module>()
----> 1 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)

AttributeError: 'module' object has no attribute 'SSLContext'

Python version:  2.7.6

Body:
You can use code below for Python 2.7.9:

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode=ssl.CERT_NONE


问:
difference between instruction level parallelism and parallel processing
I do not understand the difference between instruction level parallelism and parallel processing. please help. it would be helpful if anyone gives some example.</p>

答:
ILP

1 . Overlap individual machine operations
(add, mul, load…) so that they execute
 in parallel

2 . Transparent to the user

3 . Goal: speed up execution

Parallel Processing

Having separate processors getting separate chunks of the program ( processors programmed to do so)

Nontransparent to the user

Goal: speed up and quality up


问:
TypeError: Cannot read property of undefined | ReactJS
I want to use fields in my map() function, however I get this TypeError: Cannot read property 'fields' of undefined and I don't understand why. Because when I console.log(this.props.schema.fields) I get data printed out in my console.

Question

Why does is this happening? Is it because inside of the return() there is another scope? Or what..?

```<code>export default class ObjectDisplay extends Component {
  render() {
    console.log(this.props.schema.fields)
    //const { parentDocumentId, value, open, schema } = this.props
    return (
      <table>
        <tbody>
          {this.props.schema.fields.map((schema, i) =>
            <ObjectKeyDisplay
              key={i}
              schema={schema}
              value={(this.props.value || {})[schema.name]}
              parentDocumentId={this.props.parentDocumentId}
            />
          )}
        </tbody>
      </table>
    )
  }
}
</code>```

I am really thankful for all the help.

答:
It is giving you error because when first time it renders it it not able to find the fields property. Try to put condition using ternary operator. </p>

```<code>{
  this.props.schema.fields
       ?
        ... Map function
       : <div></div>
}
</code>```

Body:
I want to use fields in my map() function, however I get this TypeError: Cannot read property 'fields' of undefined and I don't understand why. Because when I console.log(this.props.schema.fields) I get data printed out in my console.

Question

Why does is this happening? Is it because inside of the return() there is another scope? Or what..?

export default class ObjectDisplay extends Component {
  render() {
    console.log(this.props.schema.fields)
    //const { parentDocumentId, value, open, schema } = this.props
    return (

          {this.props.schema.fields.map((schema, i) =>
            <ObjectKeyDisplay
              key={i}
              schema={schema}
              value={(this.props.value || {})[schema.name]}
              parentDocumentId={this.props.parentDocumentId}
            />
          )}

    )
  }
}

I am really thankful for all the help.

Body:
It is giving you error because when first time it renders it it not able to find the fields property. Try to put condition using ternary operator.

{
  this.props.schema.fields
       ?
        ... Map function
       : <div></div>
}


问:
3rd div doesn't touch the top because first and second are under eachother
I don't think the title is a good one but I don't know how to say it in a better way.

I have 3 divs representing an image, user info, user experience.

Due to mobile responsiveness experience must come last, but with the code below the experience div doesn't touch the top.

.one{
 width: 40%;
 height: 50px;
 padding: 5px;
 background-color: #0f0;
}
.two{
 width: 40%;
 height: 70px;
 padding: 5px;
 background-color: #0ff;
 float: left;
}
.three{
 width: 56%;
 height: 100px;
 padding: 5px;
 background-color: #f00;
 float: right;
}
.four{
 width: 500px;
 padding: 5px;
 margin: 5px;
 background-color: #ff0;
 float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="four">
    <div class="one">1 image</div>
    <div class="two">2 info</div>
    <div class="three">3 experience</div>
</div></code>```

How it should look like:

答:
You can wrap the left hand side in a separate div and float that left.

.left {
  float: left;
    width: 40%;
}

.one {
  height: 50px;
  padding: 5px;
  background-color: #0f0;
}

.two {
  height: 70px;
  padding: 5px;
  background-color: #0ff;
}

.three {
 width: 58%;
  height: 100px;
  padding: 5px;
  background-color: #f00;
  float: right;
}

.four {
  width: 500px;
  padding: 5px;
  margin: 5px;
  background-color: #ff0;
  float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="four">
  <div class="left">
    <div class="one">1 image</div>
    <div class="two">2 info</div>
  </div>
  <div class="three">3 experience</div>
</div></code>```

An alternative approach using flexbox:

.left {
  min-width: 40%;
}

.one {
  height: 50px;
  padding: 5px;
  background-color: #0f0;
}

.two {
  height: 70px;
  padding: 5px;
  background-color: #0ff;
}

.three {
  flex: 1;
  height: 100px;
  padding: 5px;
  background-color: #f00;
}

.four {
  width: 500px;
  padding: 5px;
  margin: 5px;
  background-color: #ff0;
  float: left;
  display: flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="four">
  <div class="left">
    <div class="one">1 image</div>
    <div class="two">2 info</div>
  </div>
  <div class="three">3 experience</div>
</div></code>```

Body:
I don't think the title is a good one but I don't know how to say it in a better way.

I have 3 divs representing an image, user info, user experience.

Due to mobile responsiveness experience must come last, but with the code below the experience div doesn't touch the top.

.one{
 width: 40%;
 height: 50px;
 padding: 5px;
 background-color: #0f0;
}
.two{
 width: 40%;
 height: 70px;
 padding: 5px;
 background-color: #0ff;
 float: left;
}
.three{
 width: 56%;
 height: 100px;
 padding: 5px;
 background-color: #f00;
 float: right;
}
.four{
 width: 500px;
 padding: 5px;
 margin: 5px;
 background-color: #ff0;
 float: left;
}

1 image

2 info

3 experience

How it should look like:

Body:
You can wrap the left hand side in a separate div and float that left.

.left {
  float: left;
    width: 40%;
}

.one {
  height: 50px;
  padding: 5px;
  background-color: #0f0;
}

.two {
  height: 70px;
  padding: 5px;
  background-color: #0ff;
}

.three {
 width: 58%;
  height: 100px;
  padding: 5px;
  background-color: #f00;
  float: right;
}

.four {
  width: 500px;
  padding: 5px;
  margin: 5px;
  background-color: #ff0;
  float: left;
}

<div class="four">
  <div class="left">
    <div class="one">1 image</div>
    <div class="two">2 info</div>
  </div>
  <div class="three">3 experience</div>
</div>

An alternative approach using flexbox:

.left {
  min-width: 40%;
}

.one {
  height: 50px;
  padding: 5px;
  background-color: #0f0;
}

.two {
  height: 70px;
  padding: 5px;
  background-color: #0ff;
}

.three {
  flex: 1;
  height: 100px;
  padding: 5px;
  background-color: #f00;
}

.four {
  width: 500px;
  padding: 5px;
  margin: 5px;
  background-color: #ff0;
  float: left;
  display: flex;
}

<div class="four">
  <div class="left">
    <div class="one">1 image</div>
    <div class="two">2 info</div>
  </div>
  <div class="three">3 experience</div>
</div>