问:
Expect (fail-at-end)
Can somebody show me a complete minimal example for fail at end behaviour?

The docs I found says just:

```<code>expect.that(actual).isEqualTo(expected); // supplied by @Rule
</code>```

Use case: I would like to have one test, multiple asserts (assertions on the same object, but I would like to see all assert failures, because the test itself is a long-running process).

答:
Expect is intended to be used as a JUnit @Rule. You'll see in the source code that the AssertionError is thrown after the test finishes, in the rule's apply() method. Here's a simplified version of what it does:

```<code>public void evaluate() throws Throwable {
  // this invokes the test, collecting failures in gatherer
  base.evaluate();
  // after the test finishes the failures are collected and thrown
  if (!gatherer.getMessages().isEmpty()) {
    throw new AssertionError(gatherer.toString());
  }
}
</code>```

There's an example usage of Expect in the unit tests (which isn't to say it shouldn't be better-documented elsewhere). Essentially, just add a line like:

```<code>@Rule public final Expect expect = Expect.create();
</code>```

Then use expect.that(foo).... to make assertions about foo that don't cause the test to fail-fast, instead failing once the test is complete.

Title: Expect (fail-at-end)

Body:
Can somebody show me a complete minimal example for fail at end behaviour?

The docs I found says just:

expect.that(actual).isEqualTo(expected); // supplied by @Rule

Use case: I would like to have one test, multiple asserts (assertions on the same object, but I would like to see all assert failures, because the test itself is a long-running process).

Body:
Expect is intended to be used as a JUnit @Rule. You'll see in the source code that the AssertionError is thrown after the test finishes, in the rule's apply() method. Here's a simplified version of what it does:

public void evaluate() throws Throwable {
  // this invokes the test, collecting failures in gatherer
  base.evaluate();
  // after the test finishes the failures are collected and thrown
  if (!gatherer.getMessages().isEmpty()) {
    throw new AssertionError(gatherer.toString());
  }
}

There's an example usage of Expect in the unit tests (which isn't to say it shouldn't be better-documented elsewhere). Essentially, just add a line like:

@Rule public final Expect expect = Expect.create();

Then use expect.that(foo).... to make assertions about foo that don't cause the test to fail-fast, instead failing once the test is complete.


来源: stackexchange

问:
Eclipse - Failed to create the java virtual machine
I'm having issue with running my Eclipse with the following config:

eclipse.ini

```<code>-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20110502
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256M
--launcher.defaultAction
openFile
-vm
jdk1.7.0_02/bin
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms256M
-Xmx1024M

# Adding this line, I get "Failed to create virtual machine"

-XX:PermSize=512M
-XX:MaxPermSize=512M
-XX:+UseParallelOldGC
-XX:ParallelGCThreads=2
-XX:ThreadPriorityPolicy=1
-Xverify:none
-XX:-UseSplitVerifier
</code>```

The above configuration works except when I add the lines I specified above. What could be the problem?

I am running eclipse from a Windows 7 (64-bit) machine with 4GB ram, although the JDK I specified in the path is 32-bit which works just fine. The only problem is if I add those additional config parameters.

答: It works for me after removing -XX:+UseParallelOldGC option from file.

ContentLicense: CC BY-SA 3.0

Body:
I'm having issue with running my Eclipse with the following config:

eclipse.ini

-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.100.v20110502
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256M
--launcher.defaultAction
openFile
-vm
jdk1.7.0_02/bin
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms256M
-Xmx1024M

# Adding this line, I get "Failed to create virtual machine"

-XX:PermSize=512M
-XX:MaxPermSize=512M
-XX:+UseParallelOldGC
-XX:ParallelGCThreads=2
-XX:ThreadPriorityPolicy=1
-Xverify:none
-XX:-UseSplitVerifier

The above configuration works except when I add the lines I specified above. What could be the problem?

I am running eclipse from a Windows 7 (64-bit) machine with 4GB ram, although the JDK I specified in the path is 32-bit which works just fine. The only problem is if I add those additional config parameters.


问:
Having exact movement distances and orientation changes how to fill in OpenCV perspective transformation matrix (disparity-to-depth)?
Say we have a robot\car\NPC\iPhone with a camera view. We controll all of its moves in a 3d space. Here is the algorithm we perform: capture a frame; move\rotate camera (save position and rotation diff: X, Y, Z; aX, aY aZ); capture new frame; do StereoBM. Now We want to perform opencv reprojectImageTo3D on a StereoBM result. It requieres a Q – 4 \times 4 perspective transformation matrix.
I wonder how having translation and rotation diff (6 float values) can we get that 4 \times 4 perspective transformation matrix with out any image processing?

答:
As shown in the documentation for reprojectImageTo3D, you can obtain the 4x4 perspective transform Q from stereoRectify.

However, if you want to create your own matrix, have a look here to see how 3D transformations can be written in a 4x4 matrix (though note that they're using the usual mathematical form, which is transposed from what is typical in computer vision), and here for an OpenCV example with the correct transposition in C++.

Basically you'll need to write the three separate rotation matrices and the translational matrix, and combine them all (via multiplication) to get your final 4x4 transformation matrix.


问:
How to upload multiple files(each file contains max 1 file) on clicking on submit button?
Hi i am developing file upload module using Angularjs and api. I am following https://jsfiddle.net/JeJenny/vtqavfhf/. I have one list which contains document names such as passport,visa etc and so on. I am binding this list to array and looping inside ng-repeat. So based on the number of documents it generates file upload controls as below.

```<code><div class="upload-button" ng-repeat="file in files">
                <div class="upload-button-icon">
                    <img src="images/folder-small.png">
                    <div class="upload-text">{{file}}</div>
                    <input type="file" id="file1" name="file1" file-model="{{file}}"  />
                </div>
</div>
</code>```

Note: we can upload obly one document on one upload.
So clearly if i have 4 documents in files array then 4 file upload controls will generate.

Finally i have one button which should save all the above files on click.

```<code>   <input type="submit" value="{{ 'NEXT' | translate }}" class="blue-button" ng-click="uploadFile(files)">
</code>```

I have this function to save file(Taken from fiddler)

```<code>$scope.uploadFile = function(filename){
       //Here i want to save all the files. For example if there are three documents in array files then 3 documents at a time i want to send it to server.
    };
</code>```

As you can see, fiddler will be having separate functions to save each file individually. I am trying to send all the files at a time.

May i get some help here? I am not sure what should be written inside  $scope.uploadFile function? How can i collect here all files data? Thank you.

答:
add multiple attribute to your input tag file
<input type="file" multiple>
this will allow multiple select of files

Body:
Hi i am developing file upload module using Angularjs and api. I am following https://jsfiddle.net/JeJenny/vtqavfhf/. I have one list which contains document names such as passport,visa etc and so on. I am binding this list to array and looping inside ng-repeat. So based on the number of documents it generates file upload controls as below.

{{file}}

                    <input type="file" id="file1" name="file1" file-model="{{file}}"  />

Note: we can upload obly one document on one upload.
So clearly if i have 4 documents in files array then 4 file upload controls will generate.

Finally i have one button which should save all the above files on click.

   <input type="submit" value="{{ 'NEXT' | translate }}" class="blue-button" ng-click="uploadFile(files)">

I have this function to save file(Taken from fiddler)

$scope.uploadFile = function(filename){
       //Here i want to save all the files. For example if there are three documents in array files then 3 documents at a time i want to send it to server.
    };

As you can see, fiddler will be having separate functions to save each file individually. I am trying to send all the files at a time.

May i get some help here? I am not sure what should be written inside  $scope.uploadFile function? How can i collect here all files data? Thank you.


问:
vector<string> or vector<shared_ptr<string>> in c++ 14
In old c++ style, I always used vector < shared_ptr < string> > or vector < string* > to avoid memory copy when constructing a big vector which holds many string objects.

Since c++11, c++ has rvalue and move semantics; can I use vector < string > now?

I am using gcc 7.1.0 and clang 3.6 with the c++ 14 option.

答:
There are several situations where using vector<shared_ptr<string>> or vector<string*> could help to optimize performance before C++11:

When you add elements to a vector, e.g. calling push_back().

Old behaviour: If vector capacity isn't large enough, the internal
memory buffer will be reallocated and all the old objects will be
copied to a new buffer.

C++11 behaviour: If vector element type has non-throwing move constructor, then it is called instead of copy constructor. std::string has non-throwing move constructor, so in push_back() for std::vector<string> should be not slower then for std::vector<std::shared_ptr<string>>.

When returning a vector that is a local variable from a function

Old behaviour: in case of returning a local variable from a function or method the result is copied. In some limited number of cases compiler is allowed to perform Return Value Optimisation - allocate the object directly on the stack on the caller.

C++11 behaviour: if the return value is rvalue, the move constructor of the vector is called. This operation is actually very cheap (just swapping two pointers). So for int this case using std::vector<string> is appropriate too.

Sharing strings between different vectors

If your intention is to return copy of the collection but not to copy the elements - that is the only way where std::vector<shared_ptr<string>> can still help. But in this case my advice is to share immutable objects between collections, i.e. use std::vector<shared_ptr<const string>>.


问:
Android project broken after Blue Screen on Windows 10
I re-opened my Android Project after blue screen on my machine running Windows 10, all classes and components are unfound. Anybody any idea? I tried re-build and re-start my machines n times.</p>

答:
Just check your project at its path in Windows File Explorer. If the project exists -with all its files (java, layouts, manifests, gradles and other project files)- just go to Android Studio--> File --> Open --> Your project root directory.
It will rebuild the project as new
Hope it helps </p>


问:
Android - Best and safe way to stop thread
I want to know which is the best way to stop a thread in Android. I know I can use AsyncTask instead of it and that there is a cancel() method. I have to use Threads in my situation. Here is how I'm using Thread:

```<code>Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //doing some work
        }
    };
new Thread(runnable).start();
</code>```

So, does anyone have any idea of which is the best way to stop a thread?

答:
The thing is you need to check whether the thread is running or not !?

Field:

```<code>private boolean runningThread = false;
</code>```

In the thread:

```<code>new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep((long) Math.floor(speed));
                        if (!runningThread) {
                            return;
                        }
                        yourWork();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
</code>```

If you want to stop the thread you should make the below field

```<code>private boolean runningThread = false;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to know which is the best way to stop a thread in Android. I know I can use AsyncTask instead of it and that there is a cancel() method. I have to use Threads in my situation. Here is how I'm using Thread:

Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //doing some work
        }
    };
new Thread(runnable).start();

So, does anyone have any idea of which is the best way to stop a thread?

Body:
The thing is you need to check whether the thread is running or not !?

Field:

private boolean runningThread = false;

In the thread:

new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep((long) Math.floor(speed));
                        if (!runningThread) {
                            return;
                        }
                        yourWork();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

If you want to stop the thread you should make the below field

private boolean runningThread = false;


问:
factorial of a number
I have the following code but it is not giving perfect result for factorial can u find it out plz</p>

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript">
 function fact(num)
 {
    var x=parseInt(num);
    //alert(x+1);
    if(x>0)
        x=x* fact(x-1);
    alert(x);
 }
  </script>
 </head>

 <body>
 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1"><br>
  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>
 </body>
</html>
</code>```

答:
Use loop its easy to implement </p>

```<code>function fact(num)
{
    if(num<0)
     return "Undefined";
    var fact=1;
    for(var i=num;i>1;i--)
      fact*=i;
    return fact;
 }

<input type="button" value="Find factiorial" onclick="alert(fact(6))">
</code>```

ContentLicense: CC BY-SA 2.5

Title: factorial of a number

Body:
I have the following code but it is not giving perfect result for factorial can u find it out plz

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <title> New Document </title>

 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1">

  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>

Body:
Use loop its easy to implement

function fact(num)
{
    if(num<0)
     return "Undefined";
    var fact=1;
    for(var i=num;i>1;i--)
      fact*=i;
    return fact;
 }

<input type="button" value="Find factiorial" onclick="alert(fact(6))">


问:
ajax & load are not working togeher
I want to check each time user access when page loading, sessions.php is working and return true or false but load is not working with ajax...

```<code>var section = $("#header a");
section.on('click', function() {
    $.ajax({
        type: "POST",
        url: "/particley/global/post/sessions.php",

        success: function(html) {
            if (html == 'true') {

                $('#load').load(section.id + ' #load');
                window.history.pushState(this.id, this.id, this.id);

                if (this.id == '/p/sign-out') {
                    window.location.assign("/p");
                }

            } else {
                window.location.assign("/p/sign-out");
            }
        }
    });
});
</code>```

答:
for this line

```<code> $('#load').load(section.id + ' #load');
</code>```

did you mean:

```<code> $('#load').load(section.attr("id")  + ' #load');
</code>```

to retrieve the attribute id ?

2 cents ;)

Title: ajax & load are not working togeher

Body:
I want to check each time user access when page loading, sessions.php is working and return true or false but load is not working with ajax...

var section = $("#header a");
section.on('click', function() {
    $.ajax({
        type: "POST",
        url: "/particley/global/post/sessions.php",

        success: function(html) {
            if (html == 'true') {

                $('#load').load(section.id + ' #load');
                window.history.pushState(this.id, this.id, this.id);

                if (this.id == '/p/sign-out') {
                    window.location.assign("/p");
                }

            } else {
                window.location.assign("/p/sign-out");
            }
        }
    });
});

Body:
for this line

 $('#load').load(section.id + ' #load');

did you mean:

 $('#load').load(section.attr("id")  + ' #load');

to retrieve the attribute id ?

2 cents ;)


问:
How to total value of checkbox when I check and update value immediately after unchek it using jquery?

$('#r4').change(function() {
  var sum = 0;
  $('#r4:checked').each(function() {
    sum += parseInt($(this).val());
  })

  $(".totcheck").val(sum);

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-sm-12" style="background: whitesmoke; margin-bottom: 10px;">
    <h3 style="text-align: left">Row 4</h3>
    <div class="row">
      <div class="col-sm-12" id="Spirit" style="text-align: left;">
        <li>
          <label class="control control--checkbox">Content A
            <input type="checkbox" id="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
        <li>
          <label class="control control--checkbox"> Content B
            <input type="checkbox" id="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
        <li>
          <label class="control control--checkbox"> Content C
            <input type="checkbox" id="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
        <li>
          <label class="control control--checkbox"> Content D
            <input type="checkbox" id="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
      </div>
    </div>
  </div>
</div>

<div class="row">
  <div class="col-sm-12" style="background: #ffdcdc; margin-bottom: 10px;">
    <h3 style="text-align: left;">Result</h3>
    <div class="row">
      <div class="col-sm-12" style="text-align: left;">
        <p>Total number of statements checked: <input type="number" name="total" disabled class="totcheck" style="float:none; margin-left: 10px;" />
        </p>
      </div>
    </div>
  </div>
</div></code>```

I have a several div with different id of checkbox. I want to accumulate the value of checkbox when I check,and re-update the value if I uncheck a box.

For example:
If I checked content A and content B, it will update total value to 2, when I unchecked content B, it automatic update total value to 1.

答:
You should use class instead of id in chack box..see below code.</p>

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {
    $('.r4').change(function() {
  var sum = 0;
  $('.r4:checked').each(function() {
    sum += parseInt($(this).val());
  })

  $(".totcheck").val(sum);

});
    });
</script>
<div class="row">
  <div class="col-sm-12" style="background: whitesmoke; margin-bottom: 10px;">
    <h3 style="text-align: left">Row 4</h3>
    <div class="row">
      <div class="col-sm-12" id="Spirit" style="text-align: left;">
        <li>
          <label class="control control--checkbox">Content A
            <input type="checkbox" class="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
        <li>
          <label class="control control--checkbox"> Content B
            <input type="checkbox" class="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
        <li>
          <label class="control control--checkbox"> Content C
            <input type="checkbox" class="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
        <li>
          <label class="control control--checkbox"> Content D
            <input type="checkbox" class="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
      </div>
    </div>
  </div>
</div>
</code>```

Body:
$('#r4').change(function() {
  var sum = 0;
  $('#r4:checked').each(function() {
    sum += parseInt($(this).val());
  })

  $(".totcheck").val(sum);

});

Row 4

          Content A
            <input type="checkbox" id="r4" value="1"/>

           Content B
            <input type="checkbox" id="r4" value="1"/>

           Content C
            <input type="checkbox" id="r4" value="1"/>

           Content D
            <input type="checkbox" id="r4" value="1"/>

Result

Total number of statements checked: <input type="number" name="total" disabled class="totcheck" style="float:none; margin-left: 10px;" />

I have a several div with different id of checkbox. I want to accumulate the value of checkbox when I check,and re-update the value if I uncheck a box.

For example:
If I checked content A and content B, it will update total value to 2, when I unchecked content B, it automatic update total value to 1.

Body:
You should use class instead of id in chack box..see below code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {
    $('.r4').change(function() {
  var sum = 0;
  $('.r4:checked').each(function() {
    sum += parseInt($(this).val());
  })

  $(".totcheck").val(sum);

});
    });
</script>
<div class="row">
  <div class="col-sm-12" style="background: whitesmoke; margin-bottom: 10px;">
    <h3 style="text-align: left">Row 4</h3>
    <div class="row">
      <div class="col-sm-12" id="Spirit" style="text-align: left;">
        <li>
          <label class="control control--checkbox">Content A
            <input type="checkbox" class="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
        <li>
          <label class="control control--checkbox"> Content B
            <input type="checkbox" class="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
        <li>
          <label class="control control--checkbox"> Content C
            <input type="checkbox" class="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
        <li>
          <label class="control control--checkbox"> Content D
            <input type="checkbox" class="r4" value="1"/>
            <div class="control__indicator"></div>
          </label>
        </li>
      </div>
    </div>
  </div>
</div>


问:
Hangfire with horizontal scaling
I want to make use of the hangfire library to run recurring tasks. For the simplicity of this question.

I simply want to run 1 task every 5 minutes.

I have setup hangfire normally. It points to my database. I then push my web project to my azure web app. And all runs happily. Every 5 minutes my task gets run.

But now in the case when my demand increases, and I go and auto or manually scale my web servers, to 3 instances.

Will this task get executed on ALL 3 server instances?

How can I design it so that the task only gets executed ONCE, regardless of which server or instance created that task.

答:
From the docs:

It is possible to run multiple server instances inside a process,
  machine, or on several machines at the same time. Each server use
  distributed locks to perform the coordination logic.

I.e. you will have 3 instances of Hangfire but the individual job will only get executed by one of them, however, this may not be on the same server each time. In order to do this, you can follow this StackOverflow answer which involves assigning the job to a queue that is specific to the server you want the processing to happen on: hangfire recurring job on every server

Title: Hangfire with horizontal scaling


问:
Orchard Widget for front end DB Access
I'm new to Orchard development, C# and MVC, so forgive me if this is actually simple...

I used Orchard CMS in my profession so I understand the widgets, layer zones, content parts etc... however, I have tasked my self with improving one of the processes that is quite common, and I decided the best way would to be to create a module for this purpose.

The basic outline of the process using widgets would be as follows:

Customer navigates to a page and is presented with three sections, Submit and View

The "submit" section is a widget which is a form (most likely a custom form) which posts to a controller, and submits that data to a DB, I think I have this figured out.. but to make sure I am going to use something like the following to do this:

```<code>    [HttpPost]
public ActionResult Index(string fName, string lName) {
    // var post values
    string fName = Request.Form["fName"];
    string lName = Request.Form["lName"];

    System.Data.SqlClient.SqlConnection sqlConnection1 =
        new System.Data.SqlClient.SqlConnection(@"[CONNECTION STRING]");

    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.CommandText = "INSERT INTO Persons (FirstName, LastName) VALUES ('" + fName + "','" + lName +"')";
    cmd.Connection = sqlConnection1;

    sqlConnection1.Open();
    cmd.ExecuteNonQuery();
    sqlConnection1.Close();

    return View();
}
</code>```

However, I am not sure this is the correct way to go about it, and I'm sure there is some better way I can do this, tutorials have recommended I use contentParts and contentPart records to submit data to the db however, this is only useful when submitting data from the admin side, this has to be able to be submitted from the front end by an end-user

The second section is a table which would get a list of records from the database and display them to the user, however, for this I have no idea how to go about this at all, could anyone point me to a tutorial, example source code, or even code snippets where this is achieved?

It is worth noting, I have gone through the documentation for creating modules and widgets on Orchard's site, however, they are all updating the DB via the backend...

Odatia

答:
Though your solution seems to work, I would implement it completely different.

First of all, you are connecting to the orchard db so you can just use Orchard's mechanisms to access the database. Assuming you created the table with a migration, you can access it with the IRepository interface.

Note that your port model must be in the /Models directory!:

/Models/Port.cs:

```<code>public class Port {
    public virtual int Id { get; set; }
    public virtual string MBN { get; set; }
    public virtual string Partner { get; set; }
}
</code>```

Migrations.cs:

```<code>public int Create() {
    SchemaBuilder.CreateTable("Port",
        table => table
            .Column<int>("Id", column => column.PrimaryKey().Identity())
            .Column<string>("MDN", column => column.NotNull().WithDefault(""))
            .Column<string>("Partner", column => column.NotNull().WithDefault(""))
        );
    return 1;
}
</code>```

/Controllers/PortingController.cs:

```<code>[Themed]
public class PortingController : Controller

    private readonly IRepository<Port> _repository;

    public PortingController(IRepository<Port> repository) {
        _repository = repository;
    }

    [HttpGet]
    public ActionResult Index() {
        // query the table
        var ports = _repository.Table.ToList();
        return View(ports);
    }

    [HttpPost]
    public ActionResult AddRequest(port item) {
        if (ModelState.IsValid) {
            _repository.Create(item);
        }

        return RedirectToAction("Index");
    }

}
</code>```

And then in your Views/Porting/Index.cshtml:

```<code>@using Porting.Models
@model IEnumerable<Port>

@* display the models.. *@

@* display a form for creating a new one *@

@using (Html.BeginFormAntiForgeryPost(Url.Action("CreateRequest", "Port", new { area = "YourAreaName" }))) {
    // the form
}
</code>```

For reference see this post

Title: Orchard Widget for front end DB Access

Body:
I'm new to Orchard development, C# and MVC, so forgive me if this is actually simple...

I used Orchard CMS in my profession so I understand the widgets, layer zones, content parts etc... however, I have tasked my self with improving one of the processes that is quite common, and I decided the best way would to be to create a module for this purpose.

The basic outline of the process using widgets would be as follows:

Customer navigates to a page and is presented with three sections, Submit and View

The "submit" section is a widget which is a form (most likely a custom form) which posts to a controller, and submits that data to a DB, I think I have this figured out.. but to make sure I am going to use something like the following to do this:

    [HttpPost]
public ActionResult Index(string fName, string lName) {
    // var post values
    string fName = Request.Form["fName"];
    string lName = Request.Form["lName"];

    System.Data.SqlClient.SqlConnection sqlConnection1 =
        new System.Data.SqlClient.SqlConnection(@"[CONNECTION STRING]");

    System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.CommandText = "INSERT INTO Persons (FirstName, LastName) VALUES ('" + fName + "','" + lName +"')";
    cmd.Connection = sqlConnection1;

    sqlConnection1.Open();
    cmd.ExecuteNonQuery();
    sqlConnection1.Close();

    return View();
}

However, I am not sure this is the correct way to go about it, and I'm sure there is some better way I can do this, tutorials have recommended I use contentParts and contentPart records to submit data to the db however, this is only useful when submitting data from the admin side, this has to be able to be submitted from the front end by an end-user

The second section is a table which would get a list of records from the database and display them to the user, however, for this I have no idea how to go about this at all, could anyone point me to a tutorial, example source code, or even code snippets where this is achieved?

It is worth noting, I have gone through the documentation for creating modules and widgets on Orchard's site, however, they are all updating the DB via the backend...

Odatia

Body:
Though your solution seems to work, I would implement it completely different.

First of all, you are connecting to the orchard db so you can just use Orchard's mechanisms to access the database. Assuming you created the table with a migration, you can access it with the IRepository interface.

Note that your port model must be in the /Models directory!:

/Models/Port.cs:

public class Port {
    public virtual int Id { get; set; }
    public virtual string MBN { get; set; }
    public virtual string Partner { get; set; }
}

Migrations.cs:

public int Create() {
    SchemaBuilder.CreateTable("Port",
        table => table
            .Column<int>("Id", column => column.PrimaryKey().Identity())
            .Column<string>("MDN", column => column.NotNull().WithDefault(""))
            .Column<string>("Partner", column => column.NotNull().WithDefault(""))
        );
    return 1;
}

/Controllers/PortingController.cs:

[Themed]
public class PortingController : Controller

    private readonly IRepository<Port> _repository;

    public PortingController(IRepository<Port> repository) {
        _repository = repository;
    }

    [HttpGet]
    public ActionResult Index() {
        // query the table
        var ports = _repository.Table.ToList();
        return View(ports);
    }

    [HttpPost]
    public ActionResult AddRequest(port item) {
        if (ModelState.IsValid) {
            _repository.Create(item);
        }

        return RedirectToAction("Index");
    }

}

And then in your Views/Porting/Index.cshtml:

@using Porting.Models
@model IEnumerable<Port>

@* display the models.. *@

@* display a form for creating a new one *@

@using (Html.BeginFormAntiForgeryPost(Url.Action("CreateRequest", "Port", new { area = "YourAreaName" }))) {
    // the form
}

For reference see this post


问:
Fetching data to table from array
I'm new to programming and codeigniter,

I'm passing an array to view from controller and when i use print_r function i can view the array data in view
but i want them to show in a table but gives error as "Message: Undefined index: pid....."

my codes are below:

Controller:

```<code>public function bill_data()
{
    $data['data2'] = array(
        'pid' => $this->input->post('pid[]'),
        'proname' => $this->input->post('proname[]'),
        'uprice' => $this->input->post('uprice[]'),
        'qty' => $this->input->post('qty[]'),
        'total' => $this->input->post('total[]'),
        'discount' => $this->input->post('discount'),
        'subtotal' => $this->input->post('subtotal'),
    );

    foreach ($data as $entry) {

        $discount = $entry['discount'];
        $subtotal = $entry['subtotal'];
        $pid = $entry['pid'];
        $proname = $entry['proname'];
        $uprice = $entry['uprice'];
        $qty = $entry['qty'];
        $total = $entry['total'];

    }

    $subtotal = $subtotal - $discount;
    $d['final_result'] = compact("pid", "proname", "uprice", "qty", "total", "discount", "subtotal");

    $this->load->view("invoice", $d);

}
</code>```

my view is like below:

```<code><?php foreach ($final_result as $row) { ?>
<table class="table m-t-30">
   <thead class="bg-faded">
      <tr>
         <th>#</th>
         <th>Product Name</th>
         <th>Unit Price</th>
         <th>Quantity</th>
         <th>Total</th>
      </tr>
   </thead>
   <tbody>
      <tr>
         <td><?php echo $row['pid']; ?></td>
         <td>dsfdfsdf</td>
         <td>upprice</td>
         <td>qty</td>
         <td>Total</td>
      </tr>
   </tbody>
</table>
</code>```

Why it gives me an error? if i use print_r in view i can see the datas perfectly in view

Result:

答: First print_r your $row variable then check what indexes are coming and confirm pid index is exist or not</p>

Title: Fetching data to table from array

Body:
I'm new to programming and codeigniter,

I'm passing an array to view from controller and when i use print_r function i can view the array data in view
but i want them to show in a table but gives error as "Message: Undefined index: pid....."

my codes are below:

Controller:

public function bill_data()
{
    $data['data2'] = array(
        'pid' => $this->input->post('pid[]'),
        'proname' => $this->input->post('proname[]'),
        'uprice' => $this->input->post('uprice[]'),
        'qty' => $this->input->post('qty[]'),
        'total' => $this->input->post('total[]'),
        'discount' => $this->input->post('discount'),
        'subtotal' => $this->input->post('subtotal'),
    );

    foreach ($data as $entry) {

        $discount = $entry['discount'];
        $subtotal = $entry['subtotal'];
        $pid = $entry['pid'];
        $proname = $entry['proname'];
        $uprice = $entry['uprice'];
        $qty = $entry['qty'];
        $total = $entry['total'];

    }

    $subtotal = $subtotal - $discount;
    $d['final_result'] = compact("pid", "proname", "uprice", "qty", "total", "discount", "subtotal");

    $this->load->view("invoice", $d);

}

my view is like below:

<?php foreach ($final_result as $row) { ?>

         #
         Product Name
         Unit Price
         Quantity
         Total

         <?php echo $row['pid']; ?>
         dsfdfsdf
         upprice
         qty
         Total

Why it gives me an error? if i use print_r in view i can see the datas perfectly in view

Result:


问:
How to update camera and marker along with the polyline in Google map?
I am trying a map application like ola. I did drawn a polyline but i cant update the camera while marker is moving. Also i didnt get proper solution for animating the marker along with polyline. Do suggest me a proper solution for both of my problem.

Here is the code:

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener {

```<code>private Context context;
GoogleMap googleMap;
Button btn_start;
Marker marker;
Polyline line;
List<LatLng> list;
LatLng startLatLng = new LatLng(43.182821, -99.292304);
LatLng endLatLng = new LatLng(44.959263, -97.580412);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context = MainActivity.this;

    btn_start = (Button) findViewById(R.id.btn_start);
    String urlTopass = makeURL(startLatLng.latitude,
            startLatLng.longitude, endLatLng.latitude,
            endLatLng.longitude);
    new connectAsyncTask(urlTopass).execute();
    btn_start.setOnClickListener(this);

    SupportMapFragment mapFragment =
            (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap mMap) {
    googleMap = mMap;
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(startLatLng, 9);
    googleMap.animateCamera(cameraUpdate);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_start:
            setAnimation(googleMap, list, ResourceUtils.getBitmap(context, R.drawable.ic_car_yellow_btg));
            break;

        default:
            break;
    }
}

private class connectAsyncTask extends AsyncTask<Void, Void, String> {
    private ProgressDialog progressDialog;
    String url;

    connectAsyncTask(String urlPass) {
        url = urlPass;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Fetching route, Please wait...");
        progressDialog.setIndeterminate(true);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(Void... params) {
        JSONParser jParser = new JSONParser();
        return jParser.getJSONFromUrl(url);
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        progressDialog.hide();
        if (result != null) {
            drawPath(result);
        }
    }
}

public String makeURL(double sourcelat, double sourcelog, double destlat,
                      double destlog) {
    StringBuilder urlString = new StringBuilder();
    urlString.append("http://maps.googleapis.com/maps/api/directions/json");
    urlString.append("?origin=");// from
    urlString.append(Double.toString(sourcelat));
    urlString.append(",");
    urlString.append(Double.toString(sourcelog));
    urlString.append("&destination=");// to
    urlString.append(Double.toString(destlat));
    urlString.append(",");
    urlString.append(Double.toString(destlog));
    urlString.append("&sensor=true&mode=driving&alternatives=true");
    Log.e("url ", " " + urlString);
    return urlString.toString();
}

public class JSONParser {

    InputStream is = null;
    JSONObject jObj = null;
    String json = "";

    public JSONParser() {
    }

    public String getJSONFromUrl(String url) {
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }

            json = sb.toString();
            is.close();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        return json;

    }
}

public void drawPath(String result) {
    if (line != null) {
        googleMap.clear();
    }

    googleMap.addMarker(new MarkerOptions().position(startLatLng).icon(
            BitmapDescriptorFactory.fromBitmap(ResourceUtils.getBitmap(context, R.drawable.ic_car_yellow_btg))));
    /*googleMap.addMarker(new MarkerOptions().position(startLatLng).icon(
            BitmapDescriptorFactory.fromResource(R.drawable.car_red)));*/
    try {
        final JSONObject json = new JSONObject(result);
        JSONArray routeArray = json.getJSONArray("routes");
        JSONObject routes = routeArray.getJSONObject(0);
        JSONObject overviewPolylines = routes
                .getJSONObject("overview_polyline");
        String encodedString = overviewPolylines.getString("points");

        list = decodePoly(encodedString);
        for (int z = 0; z < list.size() - 1; z++) {
            LatLng src = list.get(z);
            LatLng dest = list.get(z + 1);
            line = googleMap.addPolyline(new PolylineOptions()
                    .add(new LatLng(src.latitude, src.longitude),
                            new LatLng(dest.latitude, dest.longitude))
                    .width(10).color(Color.BLUE).geodesic(true));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)), (((double) lng / 1E5)));
        poly.add(p);
        Log.e("coords", "LatLng " + p);
    }
    return poly;
}

public static void setAnimation(GoogleMap myMap, final List<LatLng> directionPoint, final Bitmap bitmap) {
    Marker marker = myMap.addMarker(new MarkerOptions()
            .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
            .position(directionPoint.get(0))
            .flat(true));
    /*PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
    for (int i = 0; i < directionPoint.size(); i++) {
        rectLine.add(directionPoint.get(i));
    }
    myMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 50));*/
    animateMarker(myMap, marker, directionPoint, false);
}

private static void animateMarker(GoogleMap myMap, final Marker marker, final List<LatLng> directionPoint,
                                  final boolean hideMarker) {
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    Projection proj = myMap.getProjection();
    final long duration = 60000;

    final Interpolator interpolator = new LinearInterpolator();

    handler.post(new Runnable() {
        int i = 0;

        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed
                    / duration);
            if (i < directionPoint.size())
                marker.setPosition(directionPoint.get(i));
            i++;

            if (t < 1.0) {
                handler.postDelayed(this, 24);
            } else {
                if (hideMarker) {
                    marker.setVisible(false);
                } else {
                    marker.setVisible(true);
                }
            }
        }
    });
}
</code>```

}

答:
First of all you need this class:

```<code>public interface LatLngInterpolator {
LatLng interpolate(float fraction, LatLng a, LatLng b);

class Linear implements LatLngInterpolator {
    @Override
    public LatLng interpolate(float fraction, LatLng a, LatLng b) {
        double lat = (b.latitude - a.latitude) * fraction + a.latitude;
        double lng = (b.longitude - a.longitude) * fraction + a.longitude;
        return new LatLng(lat, lng);
    }
}

class LinearFixed implements LatLngInterpolator {
    @Override
    public LatLng interpolate(float fraction, LatLng a, LatLng b) {
        double lat = (b.latitude - a.latitude) * fraction + a.latitude;
        double lngDelta = b.longitude - a.longitude;

        // Take the shortest path across the 180th meridian.
        if (Math.abs(lngDelta) > 180) {
            lngDelta -= Math.signum(lngDelta) * 360;
        }
        double lng = lngDelta * fraction + a.longitude;
        return new LatLng(lat, lng);
    }
}

class Spherical implements LatLngInterpolator {

    /* From github.com/googlemaps/android-maps-utils */
    @Override
    public LatLng interpolate(float fraction, LatLng from, LatLng to) {
        // http://en.wikipedia.org/wiki/Slerp
        double fromLat = toRadians(from.latitude);
        double fromLng = toRadians(from.longitude);
        double toLat = toRadians(to.latitude);
        double toLng = toRadians(to.longitude);
        double cosFromLat = cos(fromLat);
        double cosToLat = cos(toLat);

        // Computes Spherical interpolation coefficients.
        double angle = computeAngleBetween(fromLat, fromLng, toLat, toLng);
        double sinAngle = sin(angle);
        if (sinAngle < 1E-6) {
            return from;
        }
        double a = sin((1 - fraction) * angle) / sinAngle;
        double b = sin(fraction * angle) / sinAngle;

        // Converts from polar to vector and interpolate.
        double x = a * cosFromLat * cos(fromLng) + b * cosToLat * cos(toLng);
        double y = a * cosFromLat * sin(fromLng) + b * cosToLat * sin(toLng);
        double z = a * sin(fromLat) + b * sin(toLat);

        // Converts interpolated vector back to polar.
        double lat = atan2(z, sqrt(x * x + y * y));
        double lng = atan2(y, x);
        return new LatLng(toDegrees(lat), toDegrees(lng));
    }

    private double computeAngleBetween(double fromLat, double fromLng, double toLat, double toLng) {
        // Haversine's formula
        double dLat = fromLat - toLat;
        double dLng = fromLng - toLng;
        return 2 * asin(sqrt(pow(sin(dLat / 2), 2) +
                cos(fromLat) * cos(toLat) * pow(sin(dLng / 2), 2)));
    }
}
}
</code>```

Then you can use this class to animate markers:

```<code>public class MarkerAnimation {

private static final String TAG = MarkerAnimation.class.getSimpleName();
public static ArrayList<GetDirectionsAsync> getDirectionsAsyncs = new ArrayList<>();
static boolean isAnimationRunning = false;

public static void animateMarkerToGB(final Marker marker, final LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
    final LatLng startPosition = marker.getPosition();
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    final Interpolator interpolator = new AccelerateDecelerateInterpolator();
    final float durationInMs = 3000;

    handler.post(new Runnable() {
        long elapsed;
        float t;
        float v;

        @Override
        public void run() {
            // Calculate progress using interpolator
            elapsed = SystemClock.uptimeMillis() - start;
            t = elapsed / durationInMs;
            v = interpolator.getInterpolation(t);

            marker.setPosition(latLngInterpolator.interpolate(v, startPosition, finalPosition));

            // Repeat till progress is complete.
            if (t < 1) {
                // Post again 16ms later.
                handler.postDelayed(this, 16);
            }
        }
    });
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void animateMarkerToHC(final Marker marker, final LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
    final LatLng startPosition = marker.getPosition();

    ValueAnimator valueAnimator = new ValueAnimator();
    valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            float v = animation.getAnimatedFraction();
            LatLng newPosition = latLngInterpolator.interpolate(v, startPosition, finalPosition);
            marker.setPosition(newPosition);
        }
    });
    valueAnimator.setFloatValues(0, 1); // Ignored.
    valueAnimator.setDuration(3000);
    valueAnimator.start();
}

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void animateMarkerToICS(Marker marker, LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {

//        List<LatLng> list = new ArrayList<>();
//        list.add(finalPosition);
//        animateMarkerToICSRecursive(marker, list, latLngInterpolator, true);

    try {
        animateMarkerToICSRecursive(marker, finalPosition, latLngInterpolator, true);
//if(MapUtils.distance(marker.getPosition(), finalPosition)
//< 100
//                    || MapUtils.distance(marker.getPosition(),
//finalPosition) > 500){
//                List<LatLng> list = new ArrayList<>();
//                animateMarkerToICSRecursive(marker, finalPosition,
//latLngInterpolator, true);
//            }
//            else{
//                getDirectionsAsyncs.add(new
//GetDirectionsAsync(marker, finalPosition, latLngInterpolator));
//                if(getDirectionsAsyncs.size() == 1){
//                    getDirectionsAsyncs.get(0).execute();
//                }
//            }
    } catch (Exception e) {
        e.printStackTrace();
        try {
            marker.setPosition(finalPosition);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

}

private static void checkAndExecute() {
    if (getDirectionsAsyncs.size() > 0) {
        getDirectionsAsyncs.get(0).execute();
    }
}

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void animateMarkerToICSRecursive(final Marker marker, final List<LatLng> list,
                                               final LatLngInterpolator latLngInterpolator, final boolean rotation) {
    if (list.size() > 0) {
        final LatLng finalPosition = list.remove(0);
        TypeEvaluator<LatLng> typeEvaluator = new TypeEvaluator<LatLng>() {
            @Override
            public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
                return latLngInterpolator.interpolate(fraction, startValue, endValue);
            }
        };
        Property<Marker, LatLng> property = Property.of(Marker.class, LatLng.class, "position");
        ObjectAnimator animator = ObjectAnimator.ofObject(marker, property, typeEvaluator, finalPosition);
        animator.setDuration((long) (10.0d * MapUtils.distance(marker.getPosition(), finalPosition)));
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                isAnimationRunning = true;
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                marker.setPosition(finalPosition);
                isAnimationRunning = false;
                if (list.size() > 0) {
                    animateMarkerToICSRecursive(marker, list, latLngInterpolator, rotation);
                }
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });

        if (rotation) {
            //marker.setRotation((float) MapUtils.getBearing(marker.getPosition(), finalPosition));
            MapUtils.rotateMarker(marker, (float) MapUtils.getBearing(marker.getPosition(), finalPosition));
        }
        if (!isAnimationRunning) {
            animator.start();
        }
    }
}

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void animateMarkerToICSRecursive(final Marker marker, final LatLng finalPosition,
                                               final LatLngInterpolator latLngInterpolator, final boolean rotation) {
    TypeEvaluator<LatLng> typeEvaluator = new TypeEvaluator<LatLng>() {
        @Override
        public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
            return latLngInterpolator.interpolate(fraction, startValue, endValue);
        }
    };
    Property<Marker, LatLng> property = Property.of(Marker.class, LatLng.class, "position");
    ObjectAnimator animator = ObjectAnimator.ofObject(marker, property, typeEvaluator, finalPosition);
    animator.setDuration((long) (1000));
    animator.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animator) {
            isAnimationRunning = true;
        }

        @Override
        public void onAnimationEnd(Animator animator) {
            marker.setPosition(finalPosition);
            isAnimationRunning = false;

        }

        @Override
        public void onAnimationCancel(Animator animator) {

        }

        @Override
        public void onAnimationRepeat(Animator animator) {

        }
    });

    if (rotation) {
        //marker.setRotation((float) MapUtils.getBearing(marker.getPosition(), finalPosition));
        MapUtils.rotateMarker(marker, (float) MapUtils.getBearing(marker.getPosition(), finalPosition));
    }
    if (!isAnimationRunning) {
        animator.start();
    }
}

static class GetDirectionsAsync extends AsyncTask<String, String, String> {

    LatLng source, destination;
    Marker marker;
    LatLngInterpolator latLngInterpolator;

    public GetDirectionsAsync(Marker marker, LatLng destination, LatLngInterpolator latLngInterpolator) {
        this.source = marker.getPosition();
        this.destination = destination;
        this.marker = marker;
        this.latLngInterpolator = latLngInterpolator;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... strings) {
        try {
            Response response = RestClient.getGoogleApiServices().getDirections(source.latitude + "," + source.longitude,
                    destination.latitude + "," + destination.longitude, false, "driving", false);
            String responseStr = new String(((TypedByteArray) response.getBody()).getBytes());
            return responseStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (result != null) {
            final List<LatLng> list = MapUtils.getLatLngListFromPath(result);
            animateMarkerToICSRecursive(marker, list, latLngInterpolator, true);
        }
        getDirectionsAsyncs.remove(0);
        checkAndExecute();

    }
}

}
</code>```

You need to pass the list of all the LatLng's of the path in the above class like this:

```<code> MarkerAnimation.animateMarkerToICS(driverLocationMarker, destinationLatLng, new LatLngInterpolator.Spherical());
</code>```

Hope this helps

EDIT :

This is the code for the marker rotation:
d
        public static void rotateMarker(final Marker marker, final float toRotation) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        final float startRotation = marker.getRotation();
        final long duration = 700;

```<code>    final Interpolator interpolator = new LinearInterpolator();

    handler.post(new Runnable() {
        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);

            float rot = t * toRotation + (1 - t) * startRotation;

            marker.setRotation(-rot > 180 ? rot / 2 : rot);
            if (t < 1.0) {
                // Post again 16ms later.
                handler.postDelayed(this, 16);
            }
        }
    });
}
</code>```

Body:
I am trying a map application like ola. I did drawn a polyline but i cant update the camera while marker is moving. Also i didnt get proper solution for animating the marker along with polyline. Do suggest me a proper solution for both of my problem.

Here is the code:

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, View.OnClickListener {

private Context context;
GoogleMap googleMap;
Button btn_start;
Marker marker;
Polyline line;
List<LatLng> list;
LatLng startLatLng = new LatLng(43.182821, -99.292304);
LatLng endLatLng = new LatLng(44.959263, -97.580412);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context = MainActivity.this;

    btn_start = (Button) findViewById(R.id.btn_start);
    String urlTopass = makeURL(startLatLng.latitude,
            startLatLng.longitude, endLatLng.latitude,
            endLatLng.longitude);
    new connectAsyncTask(urlTopass).execute();
    btn_start.setOnClickListener(this);

    SupportMapFragment mapFragment =
            (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap mMap) {
    googleMap = mMap;
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(startLatLng, 9);
    googleMap.animateCamera(cameraUpdate);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btn_start:
            setAnimation(googleMap, list, ResourceUtils.getBitmap(context, R.drawable.ic_car_yellow_btg));
            break;

        default:
            break;
    }
}

private class connectAsyncTask extends AsyncTask<Void, Void, String> {
    private ProgressDialog progressDialog;
    String url;

    connectAsyncTask(String urlPass) {
        url = urlPass;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Fetching route, Please wait...");
        progressDialog.setIndeterminate(true);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(Void... params) {
        JSONParser jParser = new JSONParser();
        return jParser.getJSONFromUrl(url);
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        progressDialog.hide();
        if (result != null) {
            drawPath(result);
        }
    }
}

public String makeURL(double sourcelat, double sourcelog, double destlat,
                      double destlog) {
    StringBuilder urlString = new StringBuilder();
    urlString.append("http://maps.googleapis.com/maps/api/directions/json");
    urlString.append("?origin=");// from
    urlString.append(Double.toString(sourcelat));
    urlString.append(",");
    urlString.append(Double.toString(sourcelog));
    urlString.append("&destination=");// to
    urlString.append(Double.toString(destlat));
    urlString.append(",");
    urlString.append(Double.toString(destlog));
    urlString.append("&sensor=true&mode=driving&alternatives=true");
    Log.e("url ", " " + urlString);
    return urlString.toString();
}

public class JSONParser {

    InputStream is = null;
    JSONObject jObj = null;
    String json = "";

    public JSONParser() {
    }

    public String getJSONFromUrl(String url) {
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }

            json = sb.toString();
            is.close();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        return json;

    }
}

public void drawPath(String result) {
    if (line != null) {
        googleMap.clear();
    }

    googleMap.addMarker(new MarkerOptions().position(startLatLng).icon(
            BitmapDescriptorFactory.fromBitmap(ResourceUtils.getBitmap(context, R.drawable.ic_car_yellow_btg))));
    /*googleMap.addMarker(new MarkerOptions().position(startLatLng).icon(
            BitmapDescriptorFactory.fromResource(R.drawable.car_red)));*/
    try {
        final JSONObject json = new JSONObject(result);
        JSONArray routeArray = json.getJSONArray("routes");
        JSONObject routes = routeArray.getJSONObject(0);
        JSONObject overviewPolylines = routes
                .getJSONObject("overview_polyline");
        String encodedString = overviewPolylines.getString("points");

        list = decodePoly(encodedString);
        for (int z = 0; z < list.size() - 1; z++) {
            LatLng src = list.get(z);
            LatLng dest = list.get(z + 1);
            line = googleMap.addPolyline(new PolylineOptions()
                    .add(new LatLng(src.latitude, src.longitude),
                            new LatLng(dest.latitude, dest.longitude))
                    .width(10).color(Color.BLUE).geodesic(true));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private List<LatLng> decodePoly(String encoded) {

    List<LatLng> poly = new ArrayList<>();
    int index = 0, len = encoded.length();
    int lat = 0, lng = 0;

    while (index < len) {
        int b, shift = 0, result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lat += dlat;

        shift = 0;
        result = 0;
        do {
            b = encoded.charAt(index++) - 63;
            result |= (b & 0x1f) << shift;
            shift += 5;
        } while (b >= 0x20);
        int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLng p = new LatLng((((double) lat / 1E5)), (((double) lng / 1E5)));
        poly.add(p);
        Log.e("coords", "LatLng " + p);
    }
    return poly;
}

public static void setAnimation(GoogleMap myMap, final List<LatLng> directionPoint, final Bitmap bitmap) {
    Marker marker = myMap.addMarker(new MarkerOptions()
            .icon(BitmapDescriptorFactory.fromBitmap(bitmap))
            .position(directionPoint.get(0))
            .flat(true));
    /*PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);
    for (int i = 0; i < directionPoint.size(); i++) {
        rectLine.add(directionPoint.get(i));
    }
    myMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 50));*/
    animateMarker(myMap, marker, directionPoint, false);
}

private static void animateMarker(GoogleMap myMap, final Marker marker, final List<LatLng> directionPoint,
                                  final boolean hideMarker) {
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    Projection proj = myMap.getProjection();
    final long duration = 60000;

    final Interpolator interpolator = new LinearInterpolator();

    handler.post(new Runnable() {
        int i = 0;

        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed
                    / duration);
            if (i < directionPoint.size())
                marker.setPosition(directionPoint.get(i));
            i++;

            if (t < 1.0) {
                handler.postDelayed(this, 24);
            } else {
                if (hideMarker) {
                    marker.setVisible(false);
                } else {
                    marker.setVisible(true);
                }
            }
        }
    });
}

}

Body:
First of all you need this class:

public interface LatLngInterpolator {
LatLng interpolate(float fraction, LatLng a, LatLng b);

class Linear implements LatLngInterpolator {
    @Override
    public LatLng interpolate(float fraction, LatLng a, LatLng b) {
        double lat = (b.latitude - a.latitude) * fraction + a.latitude;
        double lng = (b.longitude - a.longitude) * fraction + a.longitude;
        return new LatLng(lat, lng);
    }
}

class LinearFixed implements LatLngInterpolator {
    @Override
    public LatLng interpolate(float fraction, LatLng a, LatLng b) {
        double lat = (b.latitude - a.latitude) * fraction + a.latitude;
        double lngDelta = b.longitude - a.longitude;

        // Take the shortest path across the 180th meridian.
        if (Math.abs(lngDelta) > 180) {
            lngDelta -= Math.signum(lngDelta) * 360;
        }
        double lng = lngDelta * fraction + a.longitude;
        return new LatLng(lat, lng);
    }
}

class Spherical implements LatLngInterpolator {

    /* From github.com/googlemaps/android-maps-utils */
    @Override
    public LatLng interpolate(float fraction, LatLng from, LatLng to) {
        // http://en.wikipedia.org/wiki/Slerp
        double fromLat = toRadians(from.latitude);
        double fromLng = toRadians(from.longitude);
        double toLat = toRadians(to.latitude);
        double toLng = toRadians(to.longitude);
        double cosFromLat = cos(fromLat);
        double cosToLat = cos(toLat);

        // Computes Spherical interpolation coefficients.
        double angle = computeAngleBetween(fromLat, fromLng, toLat, toLng);
        double sinAngle = sin(angle);
        if (sinAngle < 1E-6) {
            return from;
        }
        double a = sin((1 - fraction) * angle) / sinAngle;
        double b = sin(fraction * angle) / sinAngle;

        // Converts from polar to vector and interpolate.
        double x = a * cosFromLat * cos(fromLng) + b * cosToLat * cos(toLng);
        double y = a * cosFromLat * sin(fromLng) + b * cosToLat * sin(toLng);
        double z = a * sin(fromLat) + b * sin(toLat);

        // Converts interpolated vector back to polar.
        double lat = atan2(z, sqrt(x * x + y * y));
        double lng = atan2(y, x);
        return new LatLng(toDegrees(lat), toDegrees(lng));
    }

    private double computeAngleBetween(double fromLat, double fromLng, double toLat, double toLng) {
        // Haversine's formula
        double dLat = fromLat - toLat;
        double dLng = fromLng - toLng;
        return 2 * asin(sqrt(pow(sin(dLat / 2), 2) +
                cos(fromLat) * cos(toLat) * pow(sin(dLng / 2), 2)));
    }
}
}

Then you can use this class to animate markers:

public class MarkerAnimation {

private static final String TAG = MarkerAnimation.class.getSimpleName();
public static ArrayList<GetDirectionsAsync> getDirectionsAsyncs = new ArrayList<>();
static boolean isAnimationRunning = false;

public static void animateMarkerToGB(final Marker marker, final LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
    final LatLng startPosition = marker.getPosition();
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    final Interpolator interpolator = new AccelerateDecelerateInterpolator();
    final float durationInMs = 3000;

    handler.post(new Runnable() {
        long elapsed;
        float t;
        float v;

        @Override
        public void run() {
            // Calculate progress using interpolator
            elapsed = SystemClock.uptimeMillis() - start;
            t = elapsed / durationInMs;
            v = interpolator.getInterpolation(t);

            marker.setPosition(latLngInterpolator.interpolate(v, startPosition, finalPosition));

            // Repeat till progress is complete.
            if (t < 1) {
                // Post again 16ms later.
                handler.postDelayed(this, 16);
            }
        }
    });
}

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void animateMarkerToHC(final Marker marker, final LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {
    final LatLng startPosition = marker.getPosition();

    ValueAnimator valueAnimator = new ValueAnimator();
    valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            float v = animation.getAnimatedFraction();
            LatLng newPosition = latLngInterpolator.interpolate(v, startPosition, finalPosition);
            marker.setPosition(newPosition);
        }
    });
    valueAnimator.setFloatValues(0, 1); // Ignored.
    valueAnimator.setDuration(3000);
    valueAnimator.start();
}

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void animateMarkerToICS(Marker marker, LatLng finalPosition, final LatLngInterpolator latLngInterpolator) {

//        List<LatLng> list = new ArrayList<>();
//        list.add(finalPosition);
//        animateMarkerToICSRecursive(marker, list, latLngInterpolator, true);

    try {
        animateMarkerToICSRecursive(marker, finalPosition, latLngInterpolator, true);
//if(MapUtils.distance(marker.getPosition(), finalPosition)
//< 100
//                    || MapUtils.distance(marker.getPosition(),
//finalPosition) > 500){
//                List<LatLng> list = new ArrayList<>();
//                animateMarkerToICSRecursive(marker, finalPosition,
//latLngInterpolator, true);
//            }
//            else{
//                getDirectionsAsyncs.add(new
//GetDirectionsAsync(marker, finalPosition, latLngInterpolator));
//                if(getDirectionsAsyncs.size() == 1){
//                    getDirectionsAsyncs.get(0).execute();
//                }
//            }
    } catch (Exception e) {
        e.printStackTrace();
        try {
            marker.setPosition(finalPosition);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

}

private static void checkAndExecute() {
    if (getDirectionsAsyncs.size() > 0) {
        getDirectionsAsyncs.get(0).execute();
    }
}

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void animateMarkerToICSRecursive(final Marker marker, final List<LatLng> list,
                                               final LatLngInterpolator latLngInterpolator, final boolean rotation) {
    if (list.size() > 0) {
        final LatLng finalPosition = list.remove(0);
        TypeEvaluator<LatLng> typeEvaluator = new TypeEvaluator<LatLng>() {
            @Override
            public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
                return latLngInterpolator.interpolate(fraction, startValue, endValue);
            }
        };
        Property<Marker, LatLng> property = Property.of(Marker.class, LatLng.class, "position");
        ObjectAnimator animator = ObjectAnimator.ofObject(marker, property, typeEvaluator, finalPosition);
        animator.setDuration((long) (10.0d * MapUtils.distance(marker.getPosition(), finalPosition)));
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                isAnimationRunning = true;
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                marker.setPosition(finalPosition);
                isAnimationRunning = false;
                if (list.size() > 0) {
                    animateMarkerToICSRecursive(marker, list, latLngInterpolator, rotation);
                }
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });

        if (rotation) {
            //marker.setRotation((float) MapUtils.getBearing(marker.getPosition(), finalPosition));
            MapUtils.rotateMarker(marker, (float) MapUtils.getBearing(marker.getPosition(), finalPosition));
        }
        if (!isAnimationRunning) {
            animator.start();
        }
    }
}

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void animateMarkerToICSRecursive(final Marker marker, final LatLng finalPosition,
                                               final LatLngInterpolator latLngInterpolator, final boolean rotation) {
    TypeEvaluator<LatLng> typeEvaluator = new TypeEvaluator<LatLng>() {
        @Override
        public LatLng evaluate(float fraction, LatLng startValue, LatLng endValue) {
            return latLngInterpolator.interpolate(fraction, startValue, endValue);
        }
    };
    Property<Marker, LatLng> property = Property.of(Marker.class, LatLng.class, "position");
    ObjectAnimator animator = ObjectAnimator.ofObject(marker, property, typeEvaluator, finalPosition);
    animator.setDuration((long) (1000));
    animator.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animator) {
            isAnimationRunning = true;
        }

        @Override
        public void onAnimationEnd(Animator animator) {
            marker.setPosition(finalPosition);
            isAnimationRunning = false;

        }

        @Override
        public void onAnimationCancel(Animator animator) {

        }

        @Override
        public void onAnimationRepeat(Animator animator) {

        }
    });

    if (rotation) {
        //marker.setRotation((float) MapUtils.getBearing(marker.getPosition(), finalPosition));
        MapUtils.rotateMarker(marker, (float) MapUtils.getBearing(marker.getPosition(), finalPosition));
    }
    if (!isAnimationRunning) {
        animator.start();
    }
}

static class GetDirectionsAsync extends AsyncTask<String, String, String> {

    LatLng source, destination;
    Marker marker;
    LatLngInterpolator latLngInterpolator;

    public GetDirectionsAsync(Marker marker, LatLng destination, LatLngInterpolator latLngInterpolator) {
        this.source = marker.getPosition();
        this.destination = destination;
        this.marker = marker;
        this.latLngInterpolator = latLngInterpolator;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... strings) {
        try {
            Response response = RestClient.getGoogleApiServices().getDirections(source.latitude + "," + source.longitude,
                    destination.latitude + "," + destination.longitude, false, "driving", false);
            String responseStr = new String(((TypedByteArray) response.getBody()).getBytes());
            return responseStr;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (result != null) {
            final List<LatLng> list = MapUtils.getLatLngListFromPath(result);
            animateMarkerToICSRecursive(marker, list, latLngInterpolator, true);
        }
        getDirectionsAsyncs.remove(0);
        checkAndExecute();

    }
}

}

You need to pass the list of all the LatLng's of the path in the above class like this:

 MarkerAnimation.animateMarkerToICS(driverLocationMarker, destinationLatLng, new LatLngInterpolator.Spherical());

Hope this helps

EDIT :

This is the code for the marker rotation:
d
        public static void rotateMarker(final Marker marker, final float toRotation) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        final float startRotation = marker.getRotation();
        final long duration = 700;

    final Interpolator interpolator = new LinearInterpolator();

    handler.post(new Runnable() {
        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed / duration);

            float rot = t * toRotation + (1 - t) * startRotation;

            marker.setRotation(-rot > 180 ? rot / 2 : rot);
            if (t < 1.0) {
                // Post again 16ms later.
                handler.postDelayed(this, 16);
            }
        }
    });
}


问:
Angular Class Default variable type?
In Angular Component I am confused with the title property, please some one clarify this

```<code>export class AppComponent {
  title:string = 'app works!';
}
</code>```

why title is not declared using let or const or var?
What is default type of title Prop?

答:
Default type is any. The following code prints 1</p>

```<code>export class AppComponent { title = 1; }
</code>```

Title: Angular Class Default variable type?

Body:
In Angular Component I am confused with the title property, please some one clarify this

export class AppComponent {
  title:string = 'app works!';
}

why title is not declared using let or const or var?
What is default type of title Prop?

Body:
Default type is any. The following code prints 1

export class AppComponent { title = 1; }


问:
Where can I find a bit shifting guide for C?
I have looked at What are bitwise shift (bit-shift) operators and how do they work?, but I still find the concept of bit shifting difficult to understand.

Can someone point me in the direction of a more basic guide to bit shifting in C? I expect it will be something really long since it will need to cover the whole subject.

I am learning the The C Programming Language (AKA K&R), and that is what this is for, so I can do the exercises. I understand the basics, but I still cannot do correct bit shift operations.

Here are the exercises from K&R that have stumped me

Exercise 2-6: Write a function setbits(x, p, n, y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.

Exercise 2-7: Write a function invert(x, p, n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged.

Exercise 2-8: Write a function rightrot(x, n) that returns the value of the integer x rotated to the right by n bit positions

Exercise 2-9: In a two's complement number system, x &= (x-1) deletes the rightmost 1-bit in x. Explain why, and use this observation to write a faster version of bitcount.

These are exercises from the k&R (the C programming language) book. It's the best C book there is, but I am having trouble understanding bit shifting, so I am having problems with these exercises.

答: Keep in mind that nearly all of those exercises have a straightforward solution that can be written with functions int IsBitSet(int i, int n); int SetBit(int i, int n); and combinations of << and >>.  The straightforward solutions are nearly all worst case, but are far easier to implement and read.  This is kind of like implementing multiplication in terms of addition or addition in terms of  increment.</p>

OwnerDisplayName: angie

LastEditorDisplayName: Rich B

OwnerDisplayName: plinth


问:
UWP RichEditBox: How to enable HyperLinks for loaded RTF files (Document.LoadFromStream)
XAML:

```<code><ScrollViewer x:Name="RtfEulaViewer" Grid.Row="1" VerticalAlignment="Top">
    <RichEditBox x:Name="RtfEula" IsHitTestVisible="False" IsFocusEngagementEnabled="False" IsReadOnly="True"
         Background="{ThemeResource StandardBackground}" BorderThickness="0" TextWrapping="Wrap" />
</ScrollViewer>
</code>```

Code:

```<code>StorageFile file = await StorageFile.GetFileFromPathAsync(filePath);
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
this.RtfEula.Document.LoadFromStream(TextSetOptions.FormatRtf, stream);
</code>```

Absolute or relative HyperLinks in the RTF file that are click-able when it is opened by Word or WordPad, are just shown as normal text.

```<code>{\field{\*\fldinst HYPERLINK "http://www.microsoft.com"}{\fldrslt Microsoft}}
</code>```

from the RTF specification is displayed in blue colour but is also inactive. The mouse pointer does not change if I move over it.

Is there a way to get active HyperLinks in some text box when loading an RTF file?

答:
In your code, you've set IsHitTestVisible="False". This will disable all input interaction. That's why your hyper link is not clickable. Removing this setting or changing its value to True should be able to solve your issue.

```<code><RichEditBox x:Name="RtfEula" IsFocusEngagementEnabled="False" IsReadOnly="True"
     Background="{ThemeResource StandardBackground}" BorderThickness="0" TextWrapping="Wrap" />
</code>```

Body:
XAML:

<ScrollViewer x:Name="RtfEulaViewer" Grid.Row="1" VerticalAlignment="Top">
    <RichEditBox x:Name="RtfEula" IsHitTestVisible="False" IsFocusEngagementEnabled="False" IsReadOnly="True"
         Background="{ThemeResource StandardBackground}" BorderThickness="0" TextWrapping="Wrap" />
</ScrollViewer>

Code:

StorageFile file = await StorageFile.GetFileFromPathAsync(filePath);
IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read);
this.RtfEula.Document.LoadFromStream(TextSetOptions.FormatRtf, stream);

Absolute or relative HyperLinks in the RTF file that are click-able when it is opened by Word or WordPad, are just shown as normal text.

{\field{\*\fldinst HYPERLINK "http://www.microsoft.com"}{\fldrslt Microsoft}}

from the RTF specification is displayed in blue colour but is also inactive. The mouse pointer does not change if I move over it.

Is there a way to get active HyperLinks in some text box when loading an RTF file?

Body:
In your code, you've set IsHitTestVisible="False". This will disable all input interaction. That's why your hyper link is not clickable. Removing this setting or changing its value to True should be able to solve your issue.

<RichEditBox x:Name="RtfEula" IsFocusEngagementEnabled="False" IsReadOnly="True"
     Background="{ThemeResource StandardBackground}" BorderThickness="0" TextWrapping="Wrap" />


问:
Is it possible to see where a .DLL is searching for a file?
I get a "File not found." message from a .DLL I am using, but I am not sure which path it tries to find the file in. It might as well be hard-coded, and I would like to find out.

Is there any method or tool I could use?

Thank you in advance

答:
Process Monitor will do this out-of-the-box for you. Download, unzip and run the exe file. It should immediately show you which processes are trying to access which files.

To apply a filter, hit Ctrl+L (or click the 'Filter' icon in the top menu). Then choose "Process Name is xxx" where xxx is the name of your process. Then click "Add", and then "Ok". This will filter to just your process.

You can also use Find (Ctrl+F) to find things.

Another tip, stop and start capturing by clicking Ctrl+E.


问:
Model is not updating on blur event
I am quite new to Angular2 and I am trying to create a reactive form. E.g. I am trying to create an interactive date input.

My HTML:

```<code><div class="date ui-input">
    <input type="text" name="dateD" [ngModel]="model.date | date:'dd'" (blur)="setDate($event.target.value, 'd')" maxlength="2" />
    <div>.</div>
    <input type="text" name="dateM" [ngModel]="model.date | date:'MM'" (blur)="setDate($event.target.value, 'm')" maxlength="2" />
    <div>.</div>
    <input type="text" name="dateY" [ngModel]="model.date | date:'y'" (blur)="setDate($event.target.value, 'y')" maxlength="4" />
</div>
</code>```

And the corresponding TypeScript for setDate():

```<code>setDate(input:number, type:string[1]) {
    let min = 1;
    let max = 1;
    let fn = null;

    switch(type) {
        case 'd':
            max = 31;
            fn = 'setDate';
            break;
        case 'm':
            input -= 1;
            min = 0;
            max = 11;
            fn = 'setMonth';
            break;
        case 'y':
            min = 1990;
            max = 9999;
            fn = 'setFullYear';
            break;
    }
    if(input < min) {
        input = min;
    }
    else if(input > max) {
        input = max;
    }

    if(fn)
        this.model.date[fn](input);

    console.log(this.model.date);
}
</code>```

The model is updating fine, I am checking that with console.log(). The view is not updating.

I was hoping that the input fields would show the correct date, as per date-pipe, but seems I am wrong. In Angular 1.x everything was much different, I understand, but yet I was able to achieve my goal.

Any suggestions? Is there maybe a function to "manually" update the model?

答:
You are trying to directly manipulate the value property of your form field. This doesn't trigger the update. Instead, use patchValue https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html

```<code>$event.target.patchValue({dateY: value});
</code>```

For example I use it like this in my html:

```<code><form [formGroup]="myForm">
    <input formControlName="myValue" (ionChange)="recalculate($event)">
</form>
</code>```

In my TS code:

```<code>public recalculate(e) {
    let currentValue = this.myForm.controls.get(myValue).value;
    this.myForm.patchValue({ myValue: currentValue / 10 });
}
</code>```

Title: Model is not updating on blur event

Body:
I am quite new to Angular2 and I am trying to create a reactive form. E.g. I am trying to create an interactive date input.

My HTML:

    <input type="text" name="dateD" [ngModel]="model.date | date:'dd'" (blur)="setDate($event.target.value, 'd')" maxlength="2" />

.

    <input type="text" name="dateM" [ngModel]="model.date | date:'MM'" (blur)="setDate($event.target.value, 'm')" maxlength="2" />

.

    <input type="text" name="dateY" [ngModel]="model.date | date:'y'" (blur)="setDate($event.target.value, 'y')" maxlength="4" />

And the corresponding TypeScript for setDate():

setDate(input:number, type:string[1]) {
    let min = 1;
    let max = 1;
    let fn = null;

    switch(type) {
        case 'd':
            max = 31;
            fn = 'setDate';
            break;
        case 'm':
            input -= 1;
            min = 0;
            max = 11;
            fn = 'setMonth';
            break;
        case 'y':
            min = 1990;
            max = 9999;
            fn = 'setFullYear';
            break;
    }
    if(input < min) {
        input = min;
    }
    else if(input > max) {
        input = max;
    }

    if(fn)
        this.model.date[fn](input);

    console.log(this.model.date);
}

The model is updating fine, I am checking that with console.log(). The view is not updating.

I was hoping that the input fields would show the correct date, as per date-pipe, but seems I am wrong. In Angular 1.x everything was much different, I understand, but yet I was able to achieve my goal.

Any suggestions? Is there maybe a function to "manually" update the model?

Body:
You are trying to directly manipulate the value property of your form field. This doesn't trigger the update. Instead, use patchValue https://angular.io/docs/ts/latest/api/forms/index/FormControl-class.html

$event.target.patchValue({dateY: value});

For example I use it like this in my html:

<form [formGroup]="myForm">
    <input formControlName="myValue" (ionChange)="recalculate($event)">
</form>

In my TS code:

public recalculate(e) {
    let currentValue = this.myForm.controls.get(myValue).value;
    this.myForm.patchValue({ myValue: currentValue / 10 });
}


问:
Bazel Checkers Support
What options do Bazel provide for creating new or extending existing targets that call C/C++-code checkers such as

qac

cppcheck

iwyu

?

Do I need to use a genrule or is there some other target rule for that?

Is https://bazel.build/versions/master/docs/be/extra-actions.html my only viable choice here?

In security critical software industries, such as aviation and automotive, it's very common to use the results of these calls to collect so called "metric reports".

In these cases, calls to such linters must have outputs that are further processed by the build actions of these metric report collectors. In such cases, I cannot find a useful way of reusing Bazel's "extra-actions". Ideas any one?

答:
I've written something which uses extra actions to generate a compile_commands.json file used by clang-tidy and other tools, and I'd like to do the same kind of thing for iwyu when I get around to it. I haven't used those other tools, but I assume they fit the same pattern too.

The basic idea is to run an extra action which generates some output for each file (aka C/C++ compilation command), and then find all the output files afterwards (outside of Bazel) and aggregate them. A reasonably complete example is here for reference. Basically, the action listener (written in Python) decodes the extra action proto and extracts the source files, compiler options, etc:

```<code>action = extra_actions_base_pb2.ExtraActionInfo()
with open(argv[1], 'rb') as f:
  action.MergeFromString(f.read())
cpp_compile_info = action.Extensions[extra_actions_base_pb2.CppCompileInfo.cpp_compile_info]
compiler = cpp_compile_info.tool
options = ' '.join(cpp_compile_info.compiler_option)
source = cpp_compile_info.source_file
output = cpp_compile_info.output_file
print('%s %s -c %s -o %s' % (compiler, options, source, output))
</code>```

If you give the extra action an output template, then it can write that output to a file. If you give the output files distinctive names, you can find them all in the output tree and merge them together however you want.

A more sophisticated option is to use bazel query --output=proto and write code to calculate the extra action output filenames of the targets you're interested in from there. That requires writing more code, but you don't have problems with old output files in the output tree that are accidentally included when aggregating.

FWIW, Aspects are another possibility. However, I think extra actions work acceptably for this.

Title: Bazel Checkers Support

Body:
I've written something which uses extra actions to generate a compile_commands.json file used by clang-tidy and other tools, and I'd like to do the same kind of thing for iwyu when I get around to it. I haven't used those other tools, but I assume they fit the same pattern too.

The basic idea is to run an extra action which generates some output for each file (aka C/C++ compilation command), and then find all the output files afterwards (outside of Bazel) and aggregate them. A reasonably complete example is here for reference. Basically, the action listener (written in Python) decodes the extra action proto and extracts the source files, compiler options, etc:

action = extra_actions_base_pb2.ExtraActionInfo()
with open(argv[1], 'rb') as f:
  action.MergeFromString(f.read())
cpp_compile_info = action.Extensions[extra_actions_base_pb2.CppCompileInfo.cpp_compile_info]
compiler = cpp_compile_info.tool
options = ' '.join(cpp_compile_info.compiler_option)
source = cpp_compile_info.source_file
output = cpp_compile_info.output_file
print('%s %s -c %s -o %s' % (compiler, options, source, output))

If you give the extra action an output template, then it can write that output to a file. If you give the output files distinctive names, you can find them all in the output tree and merge them together however you want.

A more sophisticated option is to use bazel query --output=proto and write code to calculate the extra action output filenames of the targets you're interested in from there. That requires writing more code, but you don't have problems with old output files in the output tree that are accidentally included when aggregating.

FWIW, Aspects are another possibility. However, I think extra actions work acceptably for this.