问:
Chain of responsibility vs Reflection
Sometime ago I removed a chain of responsibility in a web site that I'am working on.
The chain would call a method to generate a dynamic form for the website. Every object called would either return their form or "pass the ball" to the next object to retrieve the form.
The website has around 300+ classes with this logic, no big deal in terms of performance but I found it horrible to see it and debugging it.

So I decided to remove the chain call and just replaced it with reflection, I know what object I have to call by a unique static "name" (the same name was used in the chain to check if the object has to load the form or "pass the ball") of the class and by foreaching all the objects in a list I'll check that name to be sure to call the correct class/method.

I know that reflection is supposed to be slower in terms of performance but after some tests I can't see any sustantial difference and since the code is much cleaner it's easier to understand and debug.

So my question is:

Is this a correct approach or is there any better pattern to use in a case like this ?

I feel like I use reflection more then I should when I'am coding and I don't know if it is always the better option.

This in 1 class:

```<code>foreach (TemplateHandler t in objectList)
{
    if (t.GetType().GetProperty("serviceCode") != null)
    {
        if (t.GetType().GetProperty("serviceCode").GetValue(t).ToString() == serviceCodeToCallFromParam)
        {
            return t.GetTemplateParam(serviceCodeToCallFromParam/*, ...other params...*/);
        }
    }
}
</code>```

over this in 300+ class:

```<code>public override List<Form> GetTemplateParam(string serviceCode)
{
    if (serviceCode == ClassServiceCode)
    {
        // long form logic build.
        //..
    }
    else
    {
        if (successor != null)
            form = successor.GetTemplateParam(serviceCode);
    }
    return form;
}
</code>```

答:
Reflection solution looks better if I have to choose from those two. Passing ball for 300 times looks meaningless.

But, as you noted, the performance might be the issue. If you already know the class to call for getting work done, why not implement something like Builder or Factory pattern to create an instance of appropriate class and get the work done through.

Even simpler is the switch-case structure. Put and creation code in switch-case and use the resultant object to do work.

Edit 1:

```<code>public T CreateTemplate<T>() where T : ITemplate
{
    ITemplate template = null;
    if(typeof(T) == typeof(Type1Template))
        template = new Type1Template(....);
    else if(typeof(T) == typeof(Type2Template))
        template = new Type2Template(....);
    else
        throw new TemplateException("Template type is not configured.");

    return (T)template;
}
</code>```

Edit 2

See if something like below helps then:

```<code>public T CreateTemplate<T>()
{
    ITemplate template = (T)Activator.CreateInstance(typeof(T));
    return template;
}
</code>```

Title: Chain of responsibility vs Reflection

Body:
Sometime ago I removed a chain of responsibility in a web site that I'am working on.
The chain would call a method to generate a dynamic form for the website. Every object called would either return their form or "pass the ball" to the next object to retrieve the form.
The website has around 300+ classes with this logic, no big deal in terms of performance but I found it horrible to see it and debugging it.

So I decided to remove the chain call and just replaced it with reflection, I know what object I have to call by a unique static "name" (the same name was used in the chain to check if the object has to load the form or "pass the ball") of the class and by foreaching all the objects in a list I'll check that name to be sure to call the correct class/method.

I know that reflection is supposed to be slower in terms of performance but after some tests I can't see any sustantial difference and since the code is much cleaner it's easier to understand and debug.

So my question is:

Is this a correct approach or is there any better pattern to use in a case like this ?

I feel like I use reflection more then I should when I'am coding and I don't know if it is always the better option.

This in 1 class:

foreach (TemplateHandler t in objectList)
{
    if (t.GetType().GetProperty("serviceCode") != null)
    {
        if (t.GetType().GetProperty("serviceCode").GetValue(t).ToString() == serviceCodeToCallFromParam)
        {
            return t.GetTemplateParam(serviceCodeToCallFromParam/*, ...other params...*/);
        }
    }
}

over this in 300+ class:

public override List<Form> GetTemplateParam(string serviceCode)
{
    if (serviceCode == ClassServiceCode)
    {
        // long form logic build.
        //..
    }
    else
    {
        if (successor != null)
            form = successor.GetTemplateParam(serviceCode);
    }
    return form;
}

Body:
Reflection solution looks better if I have to choose from those two. Passing ball for 300 times looks meaningless.

But, as you noted, the performance might be the issue. If you already know the class to call for getting work done, why not implement something like Builder or Factory pattern to create an instance of appropriate class and get the work done through.

Even simpler is the switch-case structure. Put and creation code in switch-case and use the resultant object to do work.

Edit 1:

public T CreateTemplate<T>() where T : ITemplate
{
    ITemplate template = null;
    if(typeof(T) == typeof(Type1Template))
        template = new Type1Template(....);
    else if(typeof(T) == typeof(Type2Template))
        template = new Type2Template(....);
    else
        throw new TemplateException("Template type is not configured.");

    return (T)template;
}

Edit 2

See if something like below helps then:

public T CreateTemplate<T>()
{
    ITemplate template = (T)Activator.CreateInstance(typeof(T));
    return template;
}


来源: stackexchange

问:
Random number for dice (help)
```<code>import java.util.*;
import java.lang.*;

public class Main {

public static void main(String[] args) {

    Random dice = new Random();
    int a[]=new int [7];

    for(int i = 1 ; i <=100;i++){
        ++a[1+dice.nextInt(6)];
    }
    System.out.println("Sno\t Values");

    int no;
    for(int i=1;i<a.length;i++){

        System.out.println(i+"\t"+a[i]);
    }

}
}

Sno  Values
1   19
2   13
3   16
4   16
5   19
6   18
</code>```

Can any one please explain this line "++a[1+dice.nextInt(6)]"

i know this program provides random number generated from 1-6 on how many times within the given value

答:
Yes, first you have

```<code>int a[]=new int [7];
</code>```

which is an array that can hold 7 elements (valid indices being 0-6), all of which have an initial value of 0. Then

```<code>++a[1+dice.nextInt(6)];
</code>```

is saying

```<code>int randomIndex = 1 + dice.nextInt(6); // <-- a random value 1 to 6 inclusive
a[randomIndex] = a[randomIndex] + 1;
</code>```

Which is counting how many ones through sixes are rolled.

ContentLicense: CC BY-SA 3.0

Title: Random number for dice (help)

Body:
import java.util.*;
import java.lang.*;

public class Main {

public static void main(String[] args) {

    Random dice = new Random();
    int a[]=new int [7];

    for(int i = 1 ; i <=100;i++){
        ++a[1+dice.nextInt(6)];
    }
    System.out.println("Sno\t Values");

    int no;
    for(int i=1;i<a.length;i++){

        System.out.println(i+"\t"+a[i]);
    }

}
}

Sno  Values
1   19
2   13
3   16
4   16
5   19
6   18

Can any one please explain this line "++a[1+dice.nextInt(6)]"

i know this program provides random number generated from 1-6 on how many times within the given value

Body:
Yes, first you have

int a[]=new int [7];

which is an array that can hold 7 elements (valid indices being 0-6), all of which have an initial value of 0. Then

++a[1+dice.nextInt(6)];

is saying

int randomIndex = 1 + dice.nextInt(6); // <-- a random value 1 to 6 inclusive
a[randomIndex] = a[randomIndex] + 1;

Which is counting how many ones through sixes are rolled.


问:
Running ASP.Net Core and PHP on Azure
Short: I'm trying to get PHP to run in the same site as an ASP.Net Core site.

Long: I've re-written my web-site to migrate from an WebForms site an ASP.Net core 1.1 site.  My old site ran both ASP.NET and PHP together (I had an instance of WordPress running under a sub-folder that was used to write blog posts into a sqlite database, essentially using it as a content management piece and it's worked well for that for 4 years).

I had hoped to do the same thing with ASP.Net Core on Azure but am running into issues.  I've published the site and the .Net side fires up and runs.  The PHP no longer works however (it seems like those files maybe routing through ASP.Net Core?..

In Azure I'm using the .Net Framework 4.6 and PHP 5.6.  "index.php" is setup as one of the default documents.  I have tried setting up handler mappings to the php-cgi.exe.  I found the following in the EventLog which makes me think the files aren't being routed to PHP:

<Event>
        <System>
            <Provider Name="IIS AspNetCore Module"/>
            <EventID>1000</EventID>
            <Level>0</Level>
            <Task>0</Task>
            <Keywords>Keywords</Keywords>
            <TimeCreated SystemTime="2017-06-05T18:36:25Z"/>
            <EventRecordID>426103812</EventRecordID>
            <Channel>Application</Channel>
            <Computer>RD0003FF4207D0</Computer>
            <Security/>
        </System>
        <EventData>
            <Data>Application 'MACHINE/WEBROOT/APPHOST/YOURSITE/BLOG' with physical root 'D:\home\site\wordpress\' failed to start process with commandline '".\yoursite.exe" ', ErrorCode = '0x80070002 : 0.</Data>
        </EventData>
    </Event>

Notes:

I attempted to pull the WordPress files out of the published content and make it a virtual directory (this resulted in a HTTP Error 502.5 Process Failure when PHP content would be referenced).

I left the WordPress files as a sub folder in my ASP.Net Core site and re-published, these seem to route through ASP.Net Core (and take me to a 404 when PHP pages are accessed.. although the static files in that folder reference fine).

What do I need to do to run ASP.Net Core and PHP in the same site?

答:
I'm not an ASP.Net Core expert but I believe that virtual directory is the best choice to achieve your requirement. You can check out the following threads for details.

How can I host a php script on a dotnet core web app hosted at Azure

Create virtual directory on same azure web app

Title: Running ASP.Net Core and PHP on Azure


问:
How to create an android application by explicitly creating AndroidManifest.xml?
I want to create an android application on the android studio from scratch without using the auto xml layout(AndroidManifest.xml) file generation and rather explicitly creating it by myself.</p>

答: Just right click res folder -> New -> Android Resource file, that is how you make an xml file explicitly and than you can include it in the java file!!</p>


问:
Filling certain directories
I'm making this program to "fill" a certain directory. But the issue is when I tick "auto hide" it reappears after about 30-40 seconds.

Is there any other way around this as it would be really appreciated. Thanks :)

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Drive_Filler
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        textBox1.Text = "H:/";
    }

    public bool isRunning = true;
    public string current;
    string[] alpha = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

    private void button1_Click(object sender, EventArgs e)
    {
        if (checkBox1.Checked == true)
        {
            this.Opacity = 0;
            this.ShowInTaskbar = false;
        }
        createnew(textBox1.Text);
    }

    public void createnew(string dir)
    {
        while (isRunning)
        {
            Random rnd = new Random();
            current = alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)];
            System.IO.Directory.CreateDirectory(dir + current);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
}
}
</code>```

答:
The form reappeared because it was being unresponsive. Also, there are many problems in your code, and I couldn't understand of your purposes either.

First of all, createnew has an infinite loop. It will run in the UI Thread, causing your form to appear as a sign to warn user about unresponsive state. Moreover, rnd should be declared once only. Random of C# (and many other languages) use a time-dependent default seed value. In other words, with 2 Random instances initialized almost simultaneously, both Random's arrays of values will be the same.

So I suggest creating Random rnd as a field of your Form1, and put the loop in another thread, using Task, BackgroundWorker, ThreadPool or anything.

```<code>Task.Run(() =>
        {
            while (isRunning)
            {
                current = alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)];
                System.IO.Directory.CreateDirectory(dir + current);
            }
        }
        );
</code>```

Title: Filling certain directories

Body:
I'm making this program to "fill" a certain directory. But the issue is when I tick "auto hide" it reappears after about 30-40 seconds.

Is there any other way around this as it would be really appreciated. Thanks :)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Drive_Filler
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        textBox1.Text = "H:/";
    }

    public bool isRunning = true;
    public string current;
    string[] alpha = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };

    private void button1_Click(object sender, EventArgs e)
    {
        if (checkBox1.Checked == true)
        {
            this.Opacity = 0;
            this.ShowInTaskbar = false;
        }
        createnew(textBox1.Text);
    }

    public void createnew(string dir)
    {
        while (isRunning)
        {
            Random rnd = new Random();
            current = alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)];
            System.IO.Directory.CreateDirectory(dir + current);
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }
}
}

Body:
The form reappeared because it was being unresponsive. Also, there are many problems in your code, and I couldn't understand of your purposes either.

First of all, createnew has an infinite loop. It will run in the UI Thread, causing your form to appear as a sign to warn user about unresponsive state. Moreover, rnd should be declared once only. Random of C# (and many other languages) use a time-dependent default seed value. In other words, with 2 Random instances initialized almost simultaneously, both Random's arrays of values will be the same.

So I suggest creating Random rnd as a field of your Form1, and put the loop in another thread, using Task, BackgroundWorker, ThreadPool or anything.

Task.Run(() =>
        {
            while (isRunning)
            {
                current = alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)] + alpha[rnd.Next(0, 26)];
                System.IO.Directory.CreateDirectory(dir + current);
            }
        }
        );


问:
How to use tf.session.run() for testing (not updating network's parameters)?
Normally I use tf.session.run() for training my networks, and use eval() for getting test accuracy or loss. But I see people also use session.run() for getting testing result, which is very strange for me. I thought tf.session.run() is only for training, not testing.

Is there any secret under tf.session.run() that I didn't know?

Thank you very much!

答:
tf.session.run() is meant to run one or several TF operations, or evaluate TF tensors, possibly even mixing of these two categories.

When called on a tensor, it will basically evaluate it just like eval(). You can use it for training, with sess.run(train_op, feed_dict=train_data), which will update your variable values, because this is what train_op does. However, if you call sess.run(accuracy, feed_dict=data), it will evaluate the value of the accuracy tensor when the input values are those given by data, regardless of whether this is training, validation or testing data, and it will not change the variable values, since you're just evaluating a tensor, not running an operation that changes variable values.

So tf.session.run() is much broader than you thought indeed, it is the usual way to run inference or evaluate your performance, even at test time !

You can even do multiple things at once, which avoids doing the forward pass multiple times on the same input:

```<code>_, loss_value, accuracy_value = sess.run([train_op, loss_tensor, accuracy_tensor], feed_dict=data)
print('Loss value: %f' % loss_value)
</code>```

Body:
tf.session.run() is meant to run one or several TF operations, or evaluate TF tensors, possibly even mixing of these two categories.

When called on a tensor, it will basically evaluate it just like eval(). You can use it for training, with sess.run(train_op, feed_dict=train_data), which will update your variable values, because this is what train_op does. However, if you call sess.run(accuracy, feed_dict=data), it will evaluate the value of the accuracy tensor when the input values are those given by data, regardless of whether this is training, validation or testing data, and it will not change the variable values, since you're just evaluating a tensor, not running an operation that changes variable values.

So tf.session.run() is much broader than you thought indeed, it is the usual way to run inference or evaluate your performance, even at test time !

You can even do multiple things at once, which avoids doing the forward pass multiple times on the same input:

_, loss_value, accuracy_value = sess.run([train_op, loss_tensor, accuracy_tensor], feed_dict=data)
print('Loss value: %f' % loss_value)


问:
nifi: how to change value of json?
i have processor InvokeHTTP which gives json result.
for instance:

```<code>{
  "revision" : {
    "clientId" : "dc572274-4b71-11b6-e415-b91e391bcf4d",
    "version" : 7
  },
  "id" : "dc572260-4b71-11b6-0371-f73573ab44fe",
  "uri" : "http://x.x.x.x:9090/nifi-api/processors/dc572260-4b71-0371-73ab44fe",
  "position" : {
    "x" : -1021.9568138214972,
    "y" : 333.2029958718132
  }
}
</code>```

i want to change the value of version dynamically for each incoming response of InvokeHTTP.
how to achieve this?

答:
i could suggest ExecuteScript processor with groovy language

import groovy.json.*

def ff = session.get()
if(!ff) return
ff = session.write(ff, {rawIn, rawOut->
    //parse flowfile content to maps & arrays
    def json = new JsonSlurper().parse(rawIn, "UTF-8")
    //change json
    json.revision.version =  (json.revision.version as Long) + 1
    //write to output changed content
    rawOut.withWriter("UTF-8"){ it.write( JsonOutput.toJson(json) )}
} as StreamCallback)
session.transfer(ff, REL_SUCCESS)
```

Title: nifi: how to change value of json?

Body:
i have processor InvokeHTTP which gives json result.
for instance:

{
  "revision" : {
    "clientId" : "dc572274-4b71-11b6-e415-b91e391bcf4d",
    "version" : 7
  },
  "id" : "dc572260-4b71-11b6-0371-f73573ab44fe",
  "uri" : "http://x.x.x.x:9090/nifi-api/processors/dc572260-4b71-0371-73ab44fe",
  "position" : {
    "x" : -1021.9568138214972,
    "y" : 333.2029958718132
  }
}

i want to change the value of version dynamically for each incoming response of InvokeHTTP.
how to achieve this?


问:
Capturing array of vectors in lambda makes elements const
```<code>#include <vector>

void main() {
  std::vector<int> test[2];
  auto funct = [test](){ test[0].push_back(1); };
  funct();
}
</code>```

As a result I get

main.cc:5:45: error: passing ‘const std::vector’ as ‘this’ argument of ‘void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = int; _Alloc = std::allocator; std::vector<_Tp, _Alloc>::value_type = int]’ discards qualifiers [-fpermissive]
     auto funct = test{ test[0].push_back(1); };

How can I capture test pointer without making its values const? Is there any other way other than making it a vector<vector<int>>? Why is it even becoming a const?

答:
You can try this one.</p>

```<code>#include <vector>

int main() {
  std::vector<int> test[2];
  auto funct = [&test](){ test[0].push_back(1); };
  funct();
  return 0;
}
</code>```

Body:
#include <vector>

void main() {
  std::vector<int> test[2];
  auto funct = [test](){ test[0].push_back(1); };
  funct();
}

As a result I get

main.cc:5:45: error: passing ‘const std::vector’ as ‘this’ argument of ‘void std::vector<_Tp, _Alloc>::push_back(std::vector<_Tp, _Alloc>::value_type&&) [with _Tp = int; _Alloc = std::allocator; std::vector<_Tp, _Alloc>::value_type = int]’ discards qualifiers [-fpermissive]
     auto funct = test{ test[0].push_back(1); };

How can I capture test pointer without making its values const? Is there any other way other than making it a vector<vector<int>>? Why is it even becoming a const?

Body:
You can try this one.

#include <vector>

int main() {
  std::vector<int> test[2];
  auto funct = [&test](){ test[0].push_back(1); };
  funct();
  return 0;
}


问:
Add role numbers in table dynamically using angular js
I have created one simple table,for this table am getting data from controller.
Here I am trying to add S.no , But I don't know how to do it.

For now am just displaying {{x.id}} as s.no from backend,I dont want to display {{x.id}} as serial number but I need to pass it inside update method.

Can anyone teach me how to add serial numbers in angular?

HTML:

```<code><body ng-app="intranet_App">
    <div class="container">
            <div class="table-responsive">
                <table class="table table-hover table-bordered" id="mydata" ng-controller="myCtrl">
                    <thead class="colorBlue">
                        <tr>
                            <th>S.No</th>
                            <th>Role Name</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody id="">
                        <tr ng-repeat="x in roleList | filter:searchText">
                            <td>{{x.Id}}</td>
                            <td>
                                <span ng-hide="editMode">{{x.name}}</span>
                                <input type="text" ng-show="editMode" ng-model="x.name" />
                            </td>
                            <td>
                                <i class="edit fa fa-pencil-square-o" id="edit{{x.Id}}" ng-click="editMode = true;edit(x.Id)" ng-hide="editMode"></i>
                                <i class="update fa fa-floppy-o" id="update{{x.Id}}" ng-hide="true" ng-show="editMode" ng-click="update(x.name,x.Id);editMode = false"></i>
                                <i class="editCancel fa fa-times" id="editCancel{{x.Id}}" ng-click="editMode = false" ng-hide="true" ng-show="editMode"></i>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
    </div>
</body>
</code>```

SCRIPT:

```<code><script>
    var app=angular
                .module("intranet_App", [])
                .controller('myCtrl', function ($scope, $http) {
                    $scope.updateItem = [];
                    $scope.updatedList = function (val,id) {
                        $scope.updateItem.push(val,id);
                        $scope.json = angular.toJson(val,id);
                        if ($scope.json) {
                            $scope.json = { "name": val,"id":id }
                        }
                        console.log($scope.json)
                    }
                    $http.post("/Admin/getRolesList")
                    .then(function (response) {
                        $scope.roleList = response.data;
                    });
                    //$scope.edit=function(val){
                    //    $scope.editing = $scope.items.indexOf(val);
                    //}
                    $scope.update = function (val, id) {
                        $scope.updatedList(val,id);
                        var requestHeaders = {
                            "Content-type" : 'application/json'
                        }
                        var httpRequest={
                            method:'post',
                            url: '/Admin/RoleUpdate',
                            headers: requestHeaders
                        };
                        httpRequest.data = $scope.json;
                        $http(httpRequest).then(function (response) {
                            alert("success")
                        })

                    }
                    $scope.cancel = function (val) {

                    }
                })
</script>
</code>```

答:
Easiest Solution:
You can simply add {{$index}} in your td element to do this.

```<code>                <tr ng-repeat="x in roleList | filter:searchText">
                    <td>{{$index + 1}}</td>
                    <td>
                        <span ng-hide="editMode">{{x.name}}</span>
                        <input type="text" ng-show="editMode" ng-model="x.name" />
                    </td>
                    <td>
                        <i class="edit fa fa-pencil-square-o" id="edit{{x.Id}}" ng-click="editMode = true;edit(x.Id)" ng-hide="editMode"></i>
                        <i class="update fa fa-floppy-o" id="update{{x.Id}}" ng-hide="true" ng-show="editMode" ng-click="update(x.name,x.Id);editMode = false"></i>
                        <i class="editCancel fa fa-times" id="editCancel{{x.Id}}" ng-click="editMode = false" ng-hide="true" ng-show="editMode"></i>
                    </td>
                </tr>
</code>```

Alternative Solution:
Or you can push a serial no key into your array likewise.

```<code>$http.post("/Admin/getRolesList")
.then(function (response) {
 $scope.roleList = response.data;
 for(var i=0;i<$scope.roleList.length;i++)
  $scope.roleList[i].serialNo = i+1;
            });
</code>```

And populate it in the UI like

```<code> <tr ng-repeat="x in roleList | filter:searchText">
                            <td>{{x.serialNo}}</td>
                            <td>
                                <span ng-hide="editMode">{{x.name}}</span>
                                <input type="text" ng-show="editMode" ng-model="x.name" />
                            </td>
                            <td>
                                <i class="edit fa fa-pencil-square-o" id="edit{{x.Id}}" ng-click="editMode = true;edit(x.Id)" ng-hide="editMode"></i>
                                <i class="update fa fa-floppy-o" id="update{{x.Id}}" ng-hide="true" ng-show="editMode" ng-click="update(x.name,x.Id);editMode = false"></i>
                                <i class="editCancel fa fa-times" id="editCancel{{x.Id}}" ng-click="editMode = false" ng-hide="true" ng-show="editMode"></i>
                            </td>
                        </tr>
</code>```

Body:
I have created one simple table,for this table am getting data from controller.
Here I am trying to add S.no , But I don't know how to do it.

For now am just displaying {{x.id}} as s.no from backend,I dont want to display {{x.id}} as serial number but I need to pass it inside update method.

Can anyone teach me how to add serial numbers in angular?

HTML:

                            S.No
                            Role Name
                            Action

                            {{x.Id}}

                                {{x.name}}
                                <input type="text" ng-show="editMode" ng-model="x.name" />

SCRIPT:

Body:
Easiest Solution:
You can simply add {{$index}} in your td element to do this.

                <tr ng-repeat="x in roleList | filter:searchText">
                    <td>{{$index + 1}}</td>
                    <td>
                        <span ng-hide="editMode">{{x.name}}</span>
                        <input type="text" ng-show="editMode" ng-model="x.name" />
                    </td>
                    <td>
                        <i class="edit fa fa-pencil-square-o" id="edit{{x.Id}}" ng-click="editMode = true;edit(x.Id)" ng-hide="editMode"></i>
                        <i class="update fa fa-floppy-o" id="update{{x.Id}}" ng-hide="true" ng-show="editMode" ng-click="update(x.name,x.Id);editMode = false"></i>
                        <i class="editCancel fa fa-times" id="editCancel{{x.Id}}" ng-click="editMode = false" ng-hide="true" ng-show="editMode"></i>
                    </td>
                </tr>

Alternative Solution:
Or you can push a serial no key into your array likewise.

$http.post("/Admin/getRolesList")
.then(function (response) {
 $scope.roleList = response.data;
 for(var i=0;i<$scope.roleList.length;i++)
  $scope.roleList[i].serialNo = i+1;
            });

And populate it in the UI like

 <tr ng-repeat="x in roleList | filter:searchText">
                            <td>{{x.serialNo}}</td>
                            <td>
                                <span ng-hide="editMode">{{x.name}}</span>
                                <input type="text" ng-show="editMode" ng-model="x.name" />
                            </td>
                            <td>
                                <i class="edit fa fa-pencil-square-o" id="edit{{x.Id}}" ng-click="editMode = true;edit(x.Id)" ng-hide="editMode"></i>
                                <i class="update fa fa-floppy-o" id="update{{x.Id}}" ng-hide="true" ng-show="editMode" ng-click="update(x.name,x.Id);editMode = false"></i>
                                <i class="editCancel fa fa-times" id="editCancel{{x.Id}}" ng-click="editMode = false" ng-hide="true" ng-show="editMode"></i>
                            </td>
                        </tr>


问:
Soap error, Encoding: object has no 'RecordId' property
I am doing a registration form online that connects to a soap web service and should be able to save payment information through it.
The PHP is like this

```<code>    function create_member_fee()
      {
        $wsdl = 'WSDL LOCATION';
        $client = new mySoap($wsdl, array('trace' => 1));
        $request = array(
           'obj'=>array(
                  'Member'=>array('Number'=>$NUMBER),
                  'Amount'=>$PRICE,
                  'CreditCard'=>array(
                                'TComboBox_ARCreditCardType'=>$_POST['CT'],
                                'CardNumber'=>$_POST['CN'],
                                'ExpDate'=>mktime(0,0,0,$_POST['CM'],1,$_POST['CY']),
                                'SSNumber'=>$NUMBER_PAYER
                                )
             ),
           'opt'=>array('MemberAction'=>new SoapParam('_ActionInsert','ns1:TActionMethod'))
          );
        $result = $client->__call('CreateMemberFee',$request);
        return $result;
      }
</code>```

And here is the WSDL function and complex types.

```<code><message name="CreateMemberFee85Request">
<part name="obj" type="ns1:TMemberFee"/>
<part name="opt" type="ns1:TMemberFeeOptions"/>
</message>

<xs:complexType name="TMemberFee">
<xs:sequence>
<xs:element name="Member" type="ns1:TMemberV2"/>
<xs:element name="Payer" type="ns1:TPerson"/>
<xs:element name="ItemCode" type="xs:string"/>
<xs:element name="Amount" type="xs:double"/>
<xs:element name="CreditCard" type="ns1:TCreditCard"/>
<xs:element name="Saleperson" type="xs:string"/>
<xs:element name="ContactName" type="xs:string"/>
<xs:element name="DiscountPercent" type="xs:double"/>
<xs:element name="ReductionPayment" type="xs:double"/>
<xs:element name="DiscountValidUntil" type="xs:dateTime"/>
<xs:element name="PaymentTerm" type="xs:string"/>
<xs:element name="PaymentMode" type="xs:string"/>
<xs:element name="Memo" type="xs:string"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="TMemberV2">
<xs:sequence>
<xs:element name="RecordID" type="xs:int"/>
<xs:element name="Number" type="xs:string"/>
<xs:element name="Name" type="xs:string"/>
<xs:element name="SSNumber" type="xs:string"/>
<xs:element name="Address1" type="xs:string"/>
<xs:element name="Address2" type="xs:string"/>
<xs:element name="Address3" type="xs:string"/>
<xs:element name="Address4" type="xs:string"/>
<xs:element name="ZipCode" type="xs:string"/>
<xs:element name="City" type="xs:string"/>
<xs:element name="CountryCode" type="xs:string"/>
<xs:element name="CountryName" type="xs:string"/>
<xs:element name="CountyCode" type="xs:string"/>
<xs:element name="Phone" type="xs:string"/>
<xs:element name="PhoneLocal" type="xs:string"/>
<xs:element name="PhoneMobile" type="xs:string"/>
<xs:element name="PhoneFax" type="xs:string"/>
<xs:element name="Telex" type="xs:string"/>
<xs:element name="Email" type="xs:string"/>
<xs:element name="Password" type="xs:string"/>
<xs:element name="Group" type="xs:string"/>
<xs:element name="Tag" type="xs:string"/>
<xs:element name="SalesPerson" type="xs:string"/>
<xs:element name="Discount" type="xs:double"/>
<xs:element name="ItemReceivers" type="ns1:ArrayOfItemReceiver"/>
<xs:element name="Contacts" type="ns1:ArrayOfContacts"/>
<xs:element name="PaymentType" type="xs:string"/>
<xs:element name="CurrencyCode" type="xs:string"/>
<xs:element name="NoVat" type="xs:boolean"/>
<xs:element name="LedgerCode" type="xs:string"/>
<xs:element name="RecordCreated" type="xs:dateTime"/>
<xs:element name="RecordModified" type="xs:dateTime"/>
<xs:element name="Blocked" type="xs:boolean"/>
<xs:element name="Dead" type="xs:boolean"/>
<xs:element name="Retierd" type="xs:boolean"/>
<xs:element name="Disabled" type="xs:boolean"/>
<xs:element name="Points" type="xs:double"/>
<xs:element name="BankCode" type="xs:string"/>
<xs:element name="BankAccGroup" type="xs:string"/>
<xs:element name="BankAccount" type="xs:string"/>
<xs:element name="MemberSubGroups" type="ns1:ArrayOfMemberSubGroups"/>
<xs:element name="Carrer" type="ns1:ArrayOfMemberCarrer"/>
<xs:element name="Membership" type="ns1:ArrayOfMemberMemberships"/>
<xs:element name="Education" type="ns1:ArrayOfMemberEducations"/>
<xs:element name="Applications" type="ns1:ArrayOfMemberApplication"/>
<xs:element name="Funds" type="ns1:ArrayOfMemberFunds"/>
<xs:element name="CreditCard" type="ns1:TCreditCard"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="TPerson">
<xs:sequence>
<xs:element name="Number" type="xs:string"/>
<xs:element name="Name" type="xs:string"/>
<xs:element name="SSNumber" type="xs:string"/>
<xs:element name="Address1" type="xs:string"/>
<xs:element name="Address2" type="xs:string"/>
<xs:element name="Address3" type="xs:string"/>
<xs:element name="Address4" type="xs:string"/>
<xs:element name="ZipCode" type="xs:string"/>
<xs:element name="City" type="xs:string"/>
<xs:element name="CountryCode" type="xs:string"/>
<xs:element name="CountryName" type="xs:string"/>
<xs:element name="CountyCode" type="xs:string"/>
<xs:element name="Phone" type="xs:string"/>
<xs:element name="PhoneLocal" type="xs:string"/>
<xs:element name="PhoneMobile" type="xs:string"/>
<xs:element name="PhoneFax" type="xs:string"/>
<xs:element name="Email" type="xs:string"/>
<xs:element name="RecordCreated" type="xs:dateTime"/>
<xs:element name="RecordModified" type="xs:dateTime"/>
<xs:element name="Blocked" type="xs:boolean"/>
<xs:element name="Gender" type="ns1:TGender"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="TCreditCard">
<xs:sequence>
<xs:element name="CardType" type="ns2:TComboBox_ARCreditCardType"/>
<xs:element name="CardNumber" type="xs:string"/>
<xs:element name="ExpDate" type="xs:dateTime"/>
<xs:element name="SSNumber" type="xs:string"/>
<xs:element name="Name" type="xs:string"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="TMemberFeeOptions">
<xs:sequence>
<xs:element name="MemberAction" type="ns1:TActionMethod"/>
</xs:sequence>
</xs:complexType>

<xs:simpleType name="TActionMethod">
<xs:restriction base="xs:string">
<xs:enumeration value="_ActionUse"/>
<xs:enumeration value="_ActionInsert"/>
<xs:enumeration value="_ActionEdit"/>
<xs:enumeration value="_ActionInsertEdit"/>
<xs:enumeration value="_ActionInsertMerge"/>
<xs:enumeration value="_ActionUseInsert"/>
</xs:restriction>
</xs:simpleType>
</code>```

The error generated when calling create_member_fee() is like this

```<code>Fatal error: Uncaught SoapFault exception: [Client] SOAP-ERROR: Encoding: object has no 'RecordID' property in...
</code>```

I am relatively new at PHP and im given this massive assignment to finish before the weekend, and frankly im at a loss, if anyone can help and tell me why this error is being generated i will be greatful. The $client->__getLastRequest() does not work so i dont know how the xml in the request looks like, wich makes my life more difficult.

答: I was once puzzeled by an error like this. It turned out the property wasn't missing in the request but in the response. The error message did not contain any specification.</p>

Body:
I am doing a registration form online that connects to a soap web service and should be able to save payment information through it.
The PHP is like this

    function create_member_fee()
      {
        $wsdl = 'WSDL LOCATION';
        $client = new mySoap($wsdl, array('trace' => 1));
        $request = array(
           'obj'=>array(
                  'Member'=>array('Number'=>$NUMBER),
                  'Amount'=>$PRICE,
                  'CreditCard'=>array(
                                'TComboBox_ARCreditCardType'=>$_POST['CT'],
                                'CardNumber'=>$_POST['CN'],
                                'ExpDate'=>mktime(0,0,0,$_POST['CM'],1,$_POST['CY']),
                                'SSNumber'=>$NUMBER_PAYER
                                )
             ),
           'opt'=>array('MemberAction'=>new SoapParam('_ActionInsert','ns1:TActionMethod'))
          );
        $result = $client->__call('CreateMemberFee',$request);
        return $result;
      }

And here is the WSDL function and complex types.

<message name="CreateMemberFee85Request">
<part name="obj" type="ns1:TMemberFee"/>
<part name="opt" type="ns1:TMemberFeeOptions"/>
</message>

<xs:complexType name="TMemberFee">
<xs:sequence>
<xs:element name="Member" type="ns1:TMemberV2"/>
<xs:element name="Payer" type="ns1:TPerson"/>
<xs:element name="ItemCode" type="xs:string"/>
<xs:element name="Amount" type="xs:double"/>
<xs:element name="CreditCard" type="ns1:TCreditCard"/>
<xs:element name="Saleperson" type="xs:string"/>
<xs:element name="ContactName" type="xs:string"/>
<xs:element name="DiscountPercent" type="xs:double"/>
<xs:element name="ReductionPayment" type="xs:double"/>
<xs:element name="DiscountValidUntil" type="xs:dateTime"/>
<xs:element name="PaymentTerm" type="xs:string"/>
<xs:element name="PaymentMode" type="xs:string"/>
<xs:element name="Memo" type="xs:string"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="TMemberV2">
<xs:sequence>
<xs:element name="RecordID" type="xs:int"/>
<xs:element name="Number" type="xs:string"/>
<xs:element name="Name" type="xs:string"/>
<xs:element name="SSNumber" type="xs:string"/>
<xs:element name="Address1" type="xs:string"/>
<xs:element name="Address2" type="xs:string"/>
<xs:element name="Address3" type="xs:string"/>
<xs:element name="Address4" type="xs:string"/>
<xs:element name="ZipCode" type="xs:string"/>
<xs:element name="City" type="xs:string"/>
<xs:element name="CountryCode" type="xs:string"/>
<xs:element name="CountryName" type="xs:string"/>
<xs:element name="CountyCode" type="xs:string"/>
<xs:element name="Phone" type="xs:string"/>
<xs:element name="PhoneLocal" type="xs:string"/>
<xs:element name="PhoneMobile" type="xs:string"/>
<xs:element name="PhoneFax" type="xs:string"/>
<xs:element name="Telex" type="xs:string"/>
<xs:element name="Email" type="xs:string"/>
<xs:element name="Password" type="xs:string"/>
<xs:element name="Group" type="xs:string"/>
<xs:element name="Tag" type="xs:string"/>
<xs:element name="SalesPerson" type="xs:string"/>
<xs:element name="Discount" type="xs:double"/>
<xs:element name="ItemReceivers" type="ns1:ArrayOfItemReceiver"/>
<xs:element name="Contacts" type="ns1:ArrayOfContacts"/>
<xs:element name="PaymentType" type="xs:string"/>
<xs:element name="CurrencyCode" type="xs:string"/>
<xs:element name="NoVat" type="xs:boolean"/>
<xs:element name="LedgerCode" type="xs:string"/>
<xs:element name="RecordCreated" type="xs:dateTime"/>
<xs:element name="RecordModified" type="xs:dateTime"/>
<xs:element name="Blocked" type="xs:boolean"/>
<xs:element name="Dead" type="xs:boolean"/>
<xs:element name="Retierd" type="xs:boolean"/>
<xs:element name="Disabled" type="xs:boolean"/>
<xs:element name="Points" type="xs:double"/>
<xs:element name="BankCode" type="xs:string"/>
<xs:element name="BankAccGroup" type="xs:string"/>
<xs:element name="BankAccount" type="xs:string"/>
<xs:element name="MemberSubGroups" type="ns1:ArrayOfMemberSubGroups"/>
<xs:element name="Carrer" type="ns1:ArrayOfMemberCarrer"/>
<xs:element name="Membership" type="ns1:ArrayOfMemberMemberships"/>
<xs:element name="Education" type="ns1:ArrayOfMemberEducations"/>
<xs:element name="Applications" type="ns1:ArrayOfMemberApplication"/>
<xs:element name="Funds" type="ns1:ArrayOfMemberFunds"/>
<xs:element name="CreditCard" type="ns1:TCreditCard"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="TPerson">
<xs:sequence>
<xs:element name="Number" type="xs:string"/>
<xs:element name="Name" type="xs:string"/>
<xs:element name="SSNumber" type="xs:string"/>
<xs:element name="Address1" type="xs:string"/>
<xs:element name="Address2" type="xs:string"/>
<xs:element name="Address3" type="xs:string"/>
<xs:element name="Address4" type="xs:string"/>
<xs:element name="ZipCode" type="xs:string"/>
<xs:element name="City" type="xs:string"/>
<xs:element name="CountryCode" type="xs:string"/>
<xs:element name="CountryName" type="xs:string"/>
<xs:element name="CountyCode" type="xs:string"/>
<xs:element name="Phone" type="xs:string"/>
<xs:element name="PhoneLocal" type="xs:string"/>
<xs:element name="PhoneMobile" type="xs:string"/>
<xs:element name="PhoneFax" type="xs:string"/>
<xs:element name="Email" type="xs:string"/>
<xs:element name="RecordCreated" type="xs:dateTime"/>
<xs:element name="RecordModified" type="xs:dateTime"/>
<xs:element name="Blocked" type="xs:boolean"/>
<xs:element name="Gender" type="ns1:TGender"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="TCreditCard">
<xs:sequence>
<xs:element name="CardType" type="ns2:TComboBox_ARCreditCardType"/>
<xs:element name="CardNumber" type="xs:string"/>
<xs:element name="ExpDate" type="xs:dateTime"/>
<xs:element name="SSNumber" type="xs:string"/>
<xs:element name="Name" type="xs:string"/>
</xs:sequence>
</xs:complexType>

<xs:complexType name="TMemberFeeOptions">
<xs:sequence>
<xs:element name="MemberAction" type="ns1:TActionMethod"/>
</xs:sequence>
</xs:complexType>

<xs:simpleType name="TActionMethod">
<xs:restriction base="xs:string">
<xs:enumeration value="_ActionUse"/>
<xs:enumeration value="_ActionInsert"/>
<xs:enumeration value="_ActionEdit"/>
<xs:enumeration value="_ActionInsertEdit"/>
<xs:enumeration value="_ActionInsertMerge"/>
<xs:enumeration value="_ActionUseInsert"/>
</xs:restriction>
</xs:simpleType>

The error generated when calling create_member_fee() is like this

Fatal error: Uncaught SoapFault exception: [Client] SOAP-ERROR: Encoding: object has no 'RecordID' property in...

I am relatively new at PHP and im given this massive assignment to finish before the weekend, and frankly im at a loss, if anyone can help and tell me why this error is being generated i will be greatful. The $client->__getLastRequest() does not work so i dont know how the xml in the request looks like, wich makes my life more difficult.


问:
Assign value to variable in Scala Parser
i have a question about the Parser in Scala. I'll just post the important part here so that there would not be too much codes. For the eval Function:

```<code>def eval(t: Term): Double = t match {
    case Addition(l, r) => eval(l) + eval(r)
    case Multiplication(l, r) => eval(l) * eval(r)
    case Numeric(i) => i
    case Variable("X") => 3
    }
</code>```

And the calculate function:

```<code>def calculate(arg: String): Double = {
    return eval(parseAll(term, arg).get)
  }
</code>```

now i should overload the function "calculate" so that it takes an extra Parameter tup : (String, Double) and assign the value for this String. For example ("Y",2) then Y = 2 in the Parser. And then calculate the parser. But i don't know how to assign the value for this String. I had a stupid idea and tried this but it didn't work.

```<code>def calculate(arg: String, tup : (String, Double)) : Double = {
    tup match {
      case (a,b) => {
        def eval(t : Term): Double = t match {
          case Variable(a) => b
        }
        return eval(parseAll(term, arg).get)
      }
    }
</code>```

can you guys pls help me out ? Thank you !!

答:
You're almost there, you just need to tell the compiler that the a in your Variable pattern is actually the a from your (a, b) pattern. By default, what you do is called shadowing of the variable name a (in the scope of this pattern match, a is the value extracted in Variable, and the other a is forgotten).

What you want is something like

```<code>...
  case Variable(`a`) => b
...
</code>```

or, if your expression gets a little more complicated, you should rather use a guard:

```<code>...
  case Variable(v) if v == a => b
...
</code>```

EDIT However, now your eval function is not well defined. You need to put it all at once:

```<code>def eval(t: Term, varAssignement: (String, Double)): Double = t match {
  case Addition(l, r) => eval(l) + eval(r)
  case Multiplication(l, r) => eval(l) * eval(r)
  case Numeric(i) => i
  case Variable(a) if a == varAssignment._1 => varAssignment._2
}
</code>```

Or, if you want to have multiple variables:

```<code>def eval(t: Term, assignments: Map[String, Double]): Double = t match {
  case Addition(l, r) => eval(l) + eval(r)
  case Multiplication(l, r) => eval(l) * eval(r)
  case Numeric(i) => i
  case Variable(a) if assignments.exists(a) => assignments(a)
}
</code>```

Beware that you'll still get MatchErrors whenever an unassigned variable is used.

Body:
i have a question about the Parser in Scala. I'll just post the important part here so that there would not be too much codes. For the eval Function:

def eval(t: Term): Double = t match {
    case Addition(l, r) => eval(l) + eval(r)
    case Multiplication(l, r) => eval(l) * eval(r)
    case Numeric(i) => i
    case Variable("X") => 3
    }

And the calculate function:

def calculate(arg: String): Double = {
    return eval(parseAll(term, arg).get)
  }

now i should overload the function "calculate" so that it takes an extra Parameter tup : (String, Double) and assign the value for this String. For example ("Y",2) then Y = 2 in the Parser. And then calculate the parser. But i don't know how to assign the value for this String. I had a stupid idea and tried this but it didn't work.

def calculate(arg: String, tup : (String, Double)) : Double = {
    tup match {
      case (a,b) => {
        def eval(t : Term): Double = t match {
          case Variable(a) => b
        }
        return eval(parseAll(term, arg).get)
      }
    }

can you guys pls help me out ? Thank you !!

Body:
You're almost there, you just need to tell the compiler that the a in your Variable pattern is actually the a from your (a, b) pattern. By default, what you do is called shadowing of the variable name a (in the scope of this pattern match, a is the value extracted in Variable, and the other a is forgotten).

What you want is something like

...
  case Variable(`a`) => b
...

or, if your expression gets a little more complicated, you should rather use a guard:

...
  case Variable(v) if v == a => b
...

EDIT However, now your eval function is not well defined. You need to put it all at once:

def eval(t: Term, varAssignement: (String, Double)): Double = t match {
  case Addition(l, r) => eval(l) + eval(r)
  case Multiplication(l, r) => eval(l) * eval(r)
  case Numeric(i) => i
  case Variable(a) if a == varAssignment._1 => varAssignment._2
}

Or, if you want to have multiple variables:

def eval(t: Term, assignments: Map[String, Double]): Double = t match {
  case Addition(l, r) => eval(l) + eval(r)
  case Multiplication(l, r) => eval(l) * eval(r)
  case Numeric(i) => i
  case Variable(a) if assignments.exists(a) => assignments(a)
}

Beware that you'll still get MatchErrors whenever an unassigned variable is used.


问:
How to sum columns that have a field in common in Postgresql?
How to calculate total length for all rows that have a certain value?

Let's say there's the following table:

```<code> id | unit_id | length | column to be filled with total length
 1  |   1     | 10
 2  |   1     |  4
 3  |   1     |  5
 4  |   2     |  3
 5  |   3     |  3
 6  |   3     |  6
</code>```

In this case, how to update the table, making all the rows that have unit_id of 1 to have the sum of all the length of rows that have unit_id of 1 (10 + 4 + 5 = 19) then both rows that have a unit_id of 3 to have 9.

I've tried

```<code>update test.routes
set total_length = (select sum(length) from test.routes where unit_id = unit_id) where unit_id = unit_id
</code>```

But what it does is that it just updates the entire table with the same value, how to update the correct sum for each unit_id?

答:
try CTE:</p>

```<code>t=# with a as (select *, sum(length) over (partition by unit_id) from routes)
t-# update routes u set total_length = a.sum
t-# from a
t-# where a.id = u.id;
UPDATE 6
Time: 0.520 ms
t=# select * from routes ;
 id | unit_id | length | total_length
----+---------+--------+--------------
  1 |       1 |     10 |           19
  2 |       1 |      4 |           19
  3 |       1 |      5 |           19
  4 |       2 |      3 |            3
  5 |       3 |      3 |            3
  6 |       4 |      6 |            6
(6 rows)
</code>```

Body:
How to calculate total length for all rows that have a certain value?

Let's say there's the following table:

 id | unit_id | length | column to be filled with total length
 1  |   1     | 10
 2  |   1     |  4
 3  |   1     |  5
 4  |   2     |  3
 5  |   3     |  3
 6  |   3     |  6

In this case, how to update the table, making all the rows that have unit_id of 1 to have the sum of all the length of rows that have unit_id of 1 (10 + 4 + 5 = 19) then both rows that have a unit_id of 3 to have 9.

I've tried

update test.routes
set total_length = (select sum(length) from test.routes where unit_id = unit_id) where unit_id = unit_id

But what it does is that it just updates the entire table with the same value, how to update the correct sum for each unit_id?

Body:
try CTE:

t=# with a as (select *, sum(length) over (partition by unit_id) from routes)
t-# update routes u set total_length = a.sum
t-# from a
t-# where a.id = u.id;
UPDATE 6
Time: 0.520 ms
t=# select * from routes ;
 id | unit_id | length | total_length
----+---------+--------+--------------
  1 |       1 |     10 |           19
  2 |       1 |      4 |           19
  3 |       1 |      5 |           19
  4 |       2 |      3 |            3
  5 |       3 |      3 |            3
  6 |       4 |      6 |            6
(6 rows)


问:
VS 2013 MSTest vs nUnit vs xUnit
I realize there have been a LOT of questions on this topic but somehow I haven't found one that addressed my needs.

My team is looking to start automated Unit testing our application. We have never done it before and nobody on the team has much experience with it. I have been asked to research and find a framework for automating our Unit Testing. So far, I have narrowed the choices down to MSTest, NUnit and xUnit.

All across the internet, I read negative reviews about MSTest but it seems the most convenient tool to me for our purpose.

1) Our application is .NET

2) We use licensed VS IDE for our development across the team.

3) Source Control is Team Foundation Server 2010

4) We plan to integrate CI/CD as part of our software delivery process.

I feel that MSTest integrates right into this setup and provides the cleanest interface for us to work on. Is there a significant advantage with NUnit or xUnit over MSTest that we should consider?

答:
Here is a brief Analysis of the 3 Frameworks and ranked by color.

Legend of the Coloring:

MSTest it is good only because it is simple and integrated into Visual Studio and it comes from Microsoft. Its not flexible enough and not very extensible. But more than just a unit test framework, it also supports Integration tests, Web (load) performance tests. The other 2 are pure Unit Test Frameworks. So I would say MSTest is "Jack of all Trades, Master of none."

NUnit is my choice because its been the best consistently long enough. It is more flexible and simple with very good user base, documentation and community support.

XUnit is least of my choice because it follows a slightly different style and personally I do not see much advantage over NUnit. In some cases you will need to do some refactoring your code to fit into the test cases. But this is just my opinion as there are many who prefers XUnit.

Title: VS 2013 MSTest vs nUnit vs xUnit


问:
Regex to determine if a string is a name of a range or a cell's address
I'm struggling to come up with a regular expression pattern that can help me determine if a string is a cell's address or if it is a cell's name.

Here are some examples of cell addresses:

"E5"

"AA55:E5"

"DD5555:DDD55555, E5, F5:AA55"

"$F7:$G$7"

Here are some examples of cell names:

"bis_document_id"

"PCR1MM_YPCVolume"

"sheet_error7"

"blahE5"

"training_A1"

"myNameIsGeorgeJR"

Is there a regex pattern you guys can come up with that will match all of either group and none of the other?

I have been able to think of a couple of ways to determine what a string is not:

If it has any other character than "$" or ":" in it, I know it is not a cell's name and is most likely a cell's address.

If it has more than three consecutive numbers, it is most likely not a cell's address.

A cell's address is extremely unlikely to have more than 2 letters preceding a number, 99.9% of the cell addresses will be in columns A to ZZ.

Alas, these three small tests can hardly prove what this string is.

Thanks for the help!

答:
After trying several solutions I had to modify a regex so it works for me. my version only support non-named ranges.

```<code>((?![\=,\(\);])(\w+!)|('.+'!))?((\$?[A-Z]{1,3}\$?[0-9]{1,7}(:\$?[A-Z]{1,3}\$?[0-9]{1,7})?)|(\$?[A-Z]{1,3}(:\$?[A-Z]{1,3}\$?)))
</code>```

It will capture ranges in all of the following situations

```<code>=FUNCTION(F:F)
=FUNCTION($B22,G$5)
=SUM($F$10:$F$11)
=$J10-$K10
=SUMMARY!D4
</code>```

I created the following function for RegEx. but first tick the reference to "Microsoft VBScript Regular Expressions 5.5" from Tools>References

```<code>Function RegExp(ByVal sText As String, ByVal sPattern, Optional bGlobal As Boolean = True, Optional bIgnoreCase As Boolean = False, Optional bArray As Boolean = False) As Variant
    Dim objRegex As New RegExp
    Dim Matches As MatchCollection
    Dim Match As Match
    Dim i As Integer
    objRegex.IgnoreCase = bIgnoreCase
    objRegex.Global = bGlobal
    objRegex.Pattern = sPattern
    If objRegex.test(sText) Then
        Set Matches = objRegex.Execute(sText)
        If Matches.count <> 0 Then
            If bArray Then ' if we want to return array instead of MatchCollection
                ReDim aMatches(Matches.count - 1) As Variant
                For Each Match In Matches
                    aMatches(i) = Match.value
                    i = i + 1
                Next
                RegExp = aMatches
            Else
                Set RegExp = Matches
            End If
        End If
    End If
End Function
</code>```

Body:
After trying several solutions I had to modify a regex so it works for me. my version only support non-named ranges.

((?![\=,\(\);])(\w+!)|('.+'!))?((\$?[A-Z]{1,3}\$?[0-9]{1,7}(:\$?[A-Z]{1,3}\$?[0-9]{1,7})?)|(\$?[A-Z]{1,3}(:\$?[A-Z]{1,3}\$?)))

It will capture ranges in all of the following situations

=FUNCTION(F:F)
=FUNCTION($B22,G$5)
=SUM($F$10:$F$11)
=$J10-$K10
=SUMMARY!D4

I created the following function for RegEx. but first tick the reference to "Microsoft VBScript Regular Expressions 5.5" from Tools>References

Function RegExp(ByVal sText As String, ByVal sPattern, Optional bGlobal As Boolean = True, Optional bIgnoreCase As Boolean = False, Optional bArray As Boolean = False) As Variant
    Dim objRegex As New RegExp
    Dim Matches As MatchCollection
    Dim Match As Match
    Dim i As Integer
    objRegex.IgnoreCase = bIgnoreCase
    objRegex.Global = bGlobal
    objRegex.Pattern = sPattern
    If objRegex.test(sText) Then
        Set Matches = objRegex.Execute(sText)
        If Matches.count <> 0 Then
            If bArray Then ' if we want to return array instead of MatchCollection
                ReDim aMatches(Matches.count - 1) As Variant
                For Each Match In Matches
                    aMatches(i) = Match.value
                    i = i + 1
                Next
                RegExp = aMatches
            Else
                Set RegExp = Matches
            End If
        End If
    End If
End Function


问:
ExtJs Two way binding between parent and child component
I have two components: A panel and a custom text field.

The panel has a viewmodel and I want to bind a value (called testData) from that viewmodel to a property (called test) of the custom text field.

That works fine ...basically.

But when the test property of the text field is changed, the testData in the viewmodel of the panel does not update accordingly. I mean when the test property of the child element (the textfield) is modified, the testData property of the panel's viewmodel should contain the same value that is in test, just like a normal two-way bind.

I'm not sure what I'm doing wrong, but here is what I've tried to far:
https://fiddle.sencha.com/#fiddle/20pu&view/editor

```<code>Ext.define('MyMain', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.main',

    width: '100%',
    bodyPadding: 10,

    viewModel: {
        data: {
            testData: 'Example Data'
        }
    },

    bind: {
        title: '{testData}'
    },

    items: {
        xtype: 'myField',
        bind: {
            test: '{testData}'
        }
    }
})

Ext.define('MyField', {
    extend: 'Ext.form.field.Text',
    alias: 'widget.myField',
    fieldLabel: 'Data',
    width: '100%',

    config: {
        test: null // when test is changed, it should also affect the {testData} bind of the main component, causing the title to change
    },

    setTest(value) {
        this.test = value + ' modified!' // because of the bind, this /should/ automatically get appied to the viewmodel's `testData` and thus to the panel title
        this.setValue(this.test) // whenever the `test` property is changed, we write the contents to the value of the text field (just to visualize the `test` property).
        // But as you can see, the panel title will still just say `Example Data` and not `Example Data modified!` as it should.
    },
    getTest(){
        return this.test
    }
})

Ext.application({
    name : 'Fiddle',

    launch : function() {
        Ext.create('Ext.container.Viewport', {
            items: [{
                xtype: 'main'
            }]
        })
    }
})
</code>```

答:
If you want to change title while changing Textfield then you have to bind value property because changing textfield's value only changes value property of field.

```<code> bind: {
            test: '{testData}',
            value : '{testData}'
        },
</code>```

If you don't want to bind it with value then on change event you have to set value of test property.

```<code>listeners : {
                change : function(field, newValue, oldValue, eOpts ){
                    field.setTest(newValue);
                }
            }
</code>```

Please refer fiddle.

Body:
I have two components: A panel and a custom text field.

The panel has a viewmodel and I want to bind a value (called testData) from that viewmodel to a property (called test) of the custom text field.

That works fine ...basically.

But when the test property of the text field is changed, the testData in the viewmodel of the panel does not update accordingly. I mean when the test property of the child element (the textfield) is modified, the testData property of the panel's viewmodel should contain the same value that is in test, just like a normal two-way bind.

I'm not sure what I'm doing wrong, but here is what I've tried to far:
https://fiddle.sencha.com/#fiddle/20pu&view/editor

Ext.define('MyMain', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.main',

    width: '100%',
    bodyPadding: 10,

    viewModel: {
        data: {
            testData: 'Example Data'
        }
    },

    bind: {
        title: '{testData}'
    },

    items: {
        xtype: 'myField',
        bind: {
            test: '{testData}'
        }
    }
})

Ext.define('MyField', {
    extend: 'Ext.form.field.Text',
    alias: 'widget.myField',
    fieldLabel: 'Data',
    width: '100%',

    config: {
        test: null // when test is changed, it should also affect the {testData} bind of the main component, causing the title to change
    },

    setTest(value) {
        this.test = value + ' modified!' // because of the bind, this /should/ automatically get appied to the viewmodel's `testData` and thus to the panel title
        this.setValue(this.test) // whenever the `test` property is changed, we write the contents to the value of the text field (just to visualize the `test` property).
        // But as you can see, the panel title will still just say `Example Data` and not `Example Data modified!` as it should.
    },
    getTest(){
        return this.test
    }
})

Ext.application({
    name : 'Fiddle',

    launch : function() {
        Ext.create('Ext.container.Viewport', {
            items: [{
                xtype: 'main'
            }]
        })
    }
})

Body:
If you want to change title while changing Textfield then you have to bind value property because changing textfield's value only changes value property of field.

 bind: {
            test: '{testData}',
            value : '{testData}'
        },

If you don't want to bind it with value then on change event you have to set value of test property.

listeners : {
                change : function(field, newValue, oldValue, eOpts ){
                    field.setTest(newValue);
                }
            }

Please refer fiddle.


问:
Can we combine both and count and process time Trigger in Flink?
I want to make the Windows completed after the count reached 100 or every 5 seconds for the tumbling process time ? That is to say when the elements reached 100, trigger the Windows computation, however if the elements don't reache 100, but the time elapsed 5 seconds, it also trigger the Windows computation, just as the combination of the below two triggers:

.countWindow(100)

.window(TumblingProcessingTimeWindows.of(Time.seconds(5)))

答:
There's no super simple way to do this with the current Flink API.

Your use case needs a combination of state (for counting), and a timer. You can either accomplish this with windows using a custom Trigger, or by using a ProcessFunction.

For the approach with windows plus a custom trigger, looking at the implementations of ProcessingTimeTrigger and CountTrigger will be helpful, as you basically want to blend the two.

ProcessFunction is a lower-level building block that combines managed state with timers, which is exactly what you need, so this is probably easier, especially if you already know how to work with Flink's managed state.

BTW, the online Flink training include materials for learning how to use ProcessFunctions.

ContentLicense: CC BY-SA 4.0


答:
You need to qualify the reference to attribute unit_id. Otherwise, a constraint like where unit_id = unit_id is (apart from null-values) always true and will therefore sum up everything:

```<code>update test.routes r1 set total_length = (select sum(length) from test.routes r2 where r2.unit_id = r1.unit_id)
</code>```

Title: How to sum columns that have a field in common in Postgresql?

Body:
You need to qualify the reference to attribute unit_id. Otherwise, a constraint like where unit_id = unit_id is (apart from null-values) always true and will therefore sum up everything:

update test.routes r1 set total_length = (select sum(length) from test.routes r2 where r2.unit_id = r1.unit_id)


问:
How can force update an ios app
We had developed an ios app and uploaded it to ios server after sometime time some we had done some changes,So new build with new version had uploaded but the users that are having old version is not reflecting with new changes and we had not set any flag or something regard for force update in previous build so can any one tell us how to prevent old version app users to use old version.Please tell how to do that.  </p>

答:
Handling this through an API would be a better option, call api on background thread whenever application becomes active in delegate function i.e. applicationDidBecomeActive.

```<code>- (void)applicationDidBecomeActive:(UIApplication *)application{

// call service here

}
</code>```

then check it after receiving response from api that current version is lesser/equal to updated version like,

```<code>if ([currentAppVersion isEqualToString:versionReceivedFromServer]){

//App is updated

}else{

//App needs to be updated
//Show alert view with only update button and when user tap on it navigate it to you appstore link.

}
</code>```

Title: How can force update an ios app

Body:
Handling this through an API would be a better option, call api on background thread whenever application becomes active in delegate function i.e. applicationDidBecomeActive.

- (void)applicationDidBecomeActive:(UIApplication *)application{

// call service here

}

then check it after receiving response from api that current version is lesser/equal to updated version like,

if ([currentAppVersion isEqualToString:versionReceivedFromServer]){

//App is updated

}else{

//App needs to be updated
//Show alert view with only update button and when user tap on it navigate it to you appstore link.

}


问:
Docker image with Maven fails to run
I want to use Maven in my Docker image.

After looking here https://hub.docker.com/_/maven/, I tried using this Dockerfile:

```<code>FROM openjdk:7

RUN apk add --no-cache curl tar bash

ARG MAVEN_VERSION=3.3.9
ARG USER_HOME_DIR="/root"

RUN mkdir -p /usr/share/maven /usr/share/maven/ref \
  && curl -fsSL http://apache.osuosl.org/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz \
    | tar -xzC /usr/share/maven --strip-components=1 \
  && ln -s /usr/share/maven/bin/mvn /usr/bin/mvn

ENV MAVEN_HOME /usr/share/maven
ENV MAVEN_CONFIG "$USER_HOME_DIR/.m2"

COPY mvn-entrypoint.sh /usr/local/bin/mvn-entrypoint.sh
COPY settings-docker.xml /usr/share/maven/ref/

VOLUME "$USER_HOME_DIR/.m2"

ENTRYPOINT ["/usr/local/bin/mvn-entrypoint.sh"]
CMD ["mvn"]
</code>```

However, I'm getting:

```<code>lstat mvn-entrypoint.sh: no such file or directory
</code>```

I tried different Dockerfiles from the same repositories but they all throw this error.

What's wrong with this dockerfile?
How can I use Maven with Docker?

答:
You need the files copied in the Dockerfile mvn-entrypoint.sh and settings-docker.xml.
You can git clone from https://github.com/carlossg/docker-maven

Title: Docker image with Maven fails to run

Body:
I want to use Maven in my Docker image.

After looking here https://hub.docker.com/_/maven/, I tried using this Dockerfile:

FROM openjdk:7

RUN apk add --no-cache curl tar bash

ARG MAVEN_VERSION=3.3.9
ARG USER_HOME_DIR="/root"

RUN mkdir -p /usr/share/maven /usr/share/maven/ref \
  && curl -fsSL http://apache.osuosl.org/maven/maven-3/$MAVEN_VERSION/binaries/apache-maven-$MAVEN_VERSION-bin.tar.gz \
    | tar -xzC /usr/share/maven --strip-components=1 \
  && ln -s /usr/share/maven/bin/mvn /usr/bin/mvn

ENV MAVEN_HOME /usr/share/maven
ENV MAVEN_CONFIG "$USER_HOME_DIR/.m2"

COPY mvn-entrypoint.sh /usr/local/bin/mvn-entrypoint.sh
COPY settings-docker.xml /usr/share/maven/ref/

VOLUME "$USER_HOME_DIR/.m2"

ENTRYPOINT ["/usr/local/bin/mvn-entrypoint.sh"]
CMD ["mvn"]

However, I'm getting:

lstat mvn-entrypoint.sh: no such file or directory

I tried different Dockerfiles from the same repositories but they all throw this error.

What's wrong with this dockerfile?
How can I use Maven with Docker?


问:
Matplotlib setting title bold while using "Times New Roman"
Originally I can set the figure title to bold by the following:

```<code>import matplotlib.pyplot as plt

plt.title("Test", fontweight="bold")
</code>```

Yet once I use fontname="Times New Roman", fontweight="bold" just won't result in any change at all:

```<code>import matplotlib.pyplot as plt

plt.title("Test", fontname="Times New Roman", fontweight="bold")
</code>```

How shall I set the figure title to bold?

答:
On linux and mac the bold font of TImes New Roman appears to get choosen over the normal one. That is why you don't see changes setting hte normal one to bold, it already is bold.

I know the question is very old, but it still is a problem, at least for me on my mac, when you want to use the normal one. I found a very easy solution to this problem, posted by azag0 on github

```<code>del matplotlib.font_manager.weight_dict['roman']
matplotlib.font_manager._rebuild()
</code>```

https://github.com/matplotlib/matplotlib/issues/5574

If you do this, you will see changes when you set fontweight=bold , as the standard one is choosen correctly.

Body:
Originally I can set the figure title to bold by the following:

import matplotlib.pyplot as plt

plt.title("Test", fontweight="bold")

Yet once I use fontname="Times New Roman", fontweight="bold" just won't result in any change at all:

import matplotlib.pyplot as plt

plt.title("Test", fontname="Times New Roman", fontweight="bold")

How shall I set the figure title to bold?

Body:
On linux and mac the bold font of TImes New Roman appears to get choosen over the normal one. That is why you don't see changes setting hte normal one to bold, it already is bold.

I know the question is very old, but it still is a problem, at least for me on my mac, when you want to use the normal one. I found a very easy solution to this problem, posted by azag0 on github

del matplotlib.font_manager.weight_dict['roman']
matplotlib.font_manager._rebuild()

https://github.com/matplotlib/matplotlib/issues/5574

If you do this, you will see changes when you set fontweight=bold , as the standard one is choosen correctly.


问:
How to use "setPress" a Button from an Activity?
I have a fragment that generates buttons like so:

```<code>public class MyFragment extends Fragment {
    LinearLayout lLayout;
    MyInterface mInterface;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        for (int j = 0; j < 2; j++) {
            final Button btn = new Button(getActivity());
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tellActivityToPressButton(btn);
                }
            }
            lLayout.addView(btn);
        }
        return lLayout;
    }

    public interface MyInterface {
        void pressButton(Button button);
    }

    @Override
    public void onAttach(Context activity) {
        super.onAttach(activity);

        try {
            mInterface = (MyInterface) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() +
        " must implement MyInterface");
        }
    }

    public void tellActivityToPressButton(Button button) {
        mInterface.pressButton(button);
    }
}
</code>```

And my activity is:

```<code>public class Activity extends AppCompatActivity implements MyFragment.MyInterface {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_activity);
        MyFragment frag = new MyFragment();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.container, frag);
    }
    public void pressButton(Button button) {
        button.setPressed(true);
    }
}
</code>```

When I attempt to use this code and run it, the buttons that are created do not remain pressed when I click on them. Why is this? I understand that I could just move the setPressed method into the onClick method for the buttons, but I want it so that I call the setPressed method from the activity like above and the button remains pressed. How can I do this? Or is there any other way to keep a button pressed from the Activity?

答:
```<code>@Override
public void onClick(View v) {
    tellActivityToPressButton(v)
}
</code>```

Try passing v instead of btn here, since your btn reference might be lost by that time. This would mean that you would need to cast your View to a Button somewhere, but that is not a problem.

Body:
I have a fragment that generates buttons like so:

public class MyFragment extends Fragment {
    LinearLayout lLayout;
    MyInterface mInterface;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        for (int j = 0; j < 2; j++) {
            final Button btn = new Button(getActivity());
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tellActivityToPressButton(btn);
                }
            }
            lLayout.addView(btn);
        }
        return lLayout;
    }

    public interface MyInterface {
        void pressButton(Button button);
    }

    @Override
    public void onAttach(Context activity) {
        super.onAttach(activity);

        try {
            mInterface = (MyInterface) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() +
        " must implement MyInterface");
        }
    }

    public void tellActivityToPressButton(Button button) {
        mInterface.pressButton(button);
    }
}

And my activity is:

public class Activity extends AppCompatActivity implements MyFragment.MyInterface {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_activity);
        MyFragment frag = new MyFragment();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(R.id.container, frag);
    }
    public void pressButton(Button button) {
        button.setPressed(true);
    }
}

When I attempt to use this code and run it, the buttons that are created do not remain pressed when I click on them. Why is this? I understand that I could just move the setPressed method into the onClick method for the buttons, but I want it so that I call the setPressed method from the activity like above and the button remains pressed. How can I do this? Or is there any other way to keep a button pressed from the Activity?

Body:
@Override
public void onClick(View v) {
    tellActivityToPressButton(v)
}

Try passing v instead of btn here, since your btn reference might be lost by that time. This would mean that you would need to cast your View to a Button somewhere, but that is not a problem.


问:
Integrate Keycloak Admin Client 3.1.0.Final with Spring Boot 1.5.1
I'm trying to integrate KeyCloak Admin Client with Spring Boot

But there is an exception is thrown when I was trying to create a new account:

```<code>Caused by: javax.ws.rs.ProcessingException: RESTEASY003145: Unable to find a MessageBodyReader of content-type application/json and type class org.keycloak.representations.AccessTokenResponse
</code>```

So I tried to explicitly register Jackson Provider for KeyCloak like this:

```<code>            KeycloakBuilder
            .builder()
            .serverUrl(SERVER_URL)
            .realm(REALM)
            .username(USERNAME)
            .password(PASSWORD)
            .clientId(CLIENT_ID)
            .resteasyClient(new ResteasyClientBuilder()
                  .providerFactory(factory.register(ResteasyJackson2Provider.class))
                    .connectionPoolSize(10)
                    .build())
            .build();
</code>```

But I'm unable to import ResteasyJackson2Provider.class

pom.xml

```<code><dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-spring-security-adapter</artifactId>
    <version>3.1.0.Final</version>
</dependency>
<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-admin-client</artifactId>
    <version>3.1.0.Final</version>
</dependency>
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>3.1.3.Final</version>
</dependency>
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-client</artifactId>
    <version>3.1.3.Final</version>
</dependency>
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jackson2-provider</artifactId>
    <version>3.1.3.Final</version>
</dependency>
</code>```

Btw, if I use resteasy-jackson-provider, I got this exception:

```<code>javax.ws.rs.client.ResponseProcessingException: javax.ws.rs.ProcessingException: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "access_token" (Class org.keycloak.representations.AccessTokenResponse), not marked as ignorable
 at [Source: org.jboss.resteasy.client.jaxrs.internal.ClientResponse$InputStreamWrapper@7cc842b0; line: 1, column: 18] (through reference chain: org.keycloak.representations.AccessTokenResponse["access_token"])
</code>```

答:
After a while, I figured out the solution to this problem:

Firstly, I tested it out with the standalone project (empty maven project), the problem still occurs because of resteasy-jackson-provider. It should be resteasy-jackson2-provider (note that its resteasy-jackson2-provider)

For now, I was known that the problem somehow comes from Spring Boot, RESTeasy. And finally, I come up with this working pom.xml:

```<code>    <dependency>
        <groupId>org.keycloak</groupId>
        <artifactId>keycloak-admin-client</artifactId>
        <version>3.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <version>3.1.3.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson2-provider</artifactId>
        <version>3.1.3.Final</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>2.8.8</version>
    </dependency>
</code>```

One more thing to note is, you should use the admin-cli client in your Keycloak, because by default, it has Direct Access Grants Enabled on

Btw, this is the Java configuration:

```<code>            KeycloakBuilder
            .builder()
            .serverUrl("localhost:8080/auth")
            .realm("master")
            .username("YOUR_USERNAME")
            .password("YOUR_PASSWORD")
            .clientId("admin-cli")
            .build();
</code>```

Working example: https://github.com/phuongtailtranminh/Keycloak-Admin-Client-Spring-Boot-Demo

Body:
I'm trying to integrate KeyCloak Admin Client with Spring Boot

But there is an exception is thrown when I was trying to create a new account:

Caused by: javax.ws.rs.ProcessingException: RESTEASY003145: Unable to find a MessageBodyReader of content-type application/json and type class org.keycloak.representations.AccessTokenResponse

So I tried to explicitly register Jackson Provider for KeyCloak like this:

            KeycloakBuilder
            .builder()
            .serverUrl(SERVER_URL)
            .realm(REALM)
            .username(USERNAME)
            .password(PASSWORD)
            .clientId(CLIENT_ID)
            .resteasyClient(new ResteasyClientBuilder()
                  .providerFactory(factory.register(ResteasyJackson2Provider.class))
                    .connectionPoolSize(10)
                    .build())
            .build();

But I'm unable to import ResteasyJackson2Provider.class

pom.xml

<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-spring-security-adapter</artifactId>
    <version>3.1.0.Final</version>
</dependency>
<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-admin-client</artifactId>
    <version>3.1.0.Final</version>
</dependency>
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jaxrs</artifactId>
    <version>3.1.3.Final</version>
</dependency>
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-client</artifactId>
    <version>3.1.3.Final</version>
</dependency>
<dependency>
    <groupId>org.jboss.resteasy</groupId>
    <artifactId>resteasy-jackson2-provider</artifactId>
    <version>3.1.3.Final</version>
</dependency>

Btw, if I use resteasy-jackson-provider, I got this exception:

javax.ws.rs.client.ResponseProcessingException: javax.ws.rs.ProcessingException: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "access_token" (Class org.keycloak.representations.AccessTokenResponse), not marked as ignorable
 at [Source: org.jboss.resteasy.client.jaxrs.internal.ClientResponse$InputStreamWrapper@7cc842b0; line: 1, column: 18] (through reference chain: org.keycloak.representations.AccessTokenResponse["access_token"])

Body:
After a while, I figured out the solution to this problem:

Firstly, I tested it out with the standalone project (empty maven project), the problem still occurs because of resteasy-jackson-provider. It should be resteasy-jackson2-provider (note that its resteasy-jackson2-provider)

For now, I was known that the problem somehow comes from Spring Boot, RESTeasy. And finally, I come up with this working pom.xml:

    <dependency>
        <groupId>org.keycloak</groupId>
        <artifactId>keycloak-admin-client</artifactId>
        <version>3.1.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <version>3.1.3.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson2-provider</artifactId>
        <version>3.1.3.Final</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.8</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>2.8.8</version>
    </dependency>

One more thing to note is, you should use the admin-cli client in your Keycloak, because by default, it has Direct Access Grants Enabled on

Btw, this is the Java configuration:

            KeycloakBuilder
            .builder()
            .serverUrl("localhost:8080/auth")
            .realm("master")
            .username("YOUR_USERNAME")
            .password("YOUR_PASSWORD")
            .clientId("admin-cli")
            .build();

Working example: https://github.com/phuongtailtranminh/Keycloak-Admin-Client-Spring-Boot-Demo


问:
Symfony 3 Form using RepeatedType with FOSRest
How can you submit a RepeatedType using FOSRest?

I have added the following formtype:

```<code>/**
 * {@inheritdoc}
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('email', TextType::class);
    $builder->add('firstName', TextType::class);
    $builder->add('lastName', TextType::class);
    $builder->add('password', RepeatedType::class, [
        'type' => PasswordType::class,
        'invalid_message' => 'The password fields must match.',
        'required' => true
    ]);
}
</code>```

And this is the data I submit:

```<code>array(1) {
["user"]=>
array(4) {
    ["email"]=>
    string(21) "Testuser@test.be"
    ["firstName"]=>
    string(4) "Test"
    ["lastName"]=>
    string(9) "User"
    ["password"]=>
    array(2) {
          ["first"]=>
          string(8) "password"
          ["second"]=>
          string(8) "password"
    }
  }
}
</code>```

Everything works, except the repeatedType throws: This form should not contain extra fields.

What's the correct format to submit to a repeatedType? The docs aren't really clear on this ...

Thank you

答:
try to change this:

```<code>$builder->add('password', RepeatedType::class, [
    'type' => PasswordType::class,
    'invalid_message' => 'The password fields must match.',
    'required' => true
]);
</code>```

to this:

```<code>$builder->add('password', RepeatedType::class, [
    'type' => PasswordType::class,
    'first_options'  => array('label' => 'Password'),
    'second_options' => array('label' => 'Repeat Password')
]);
</code>```

Body:
How can you submit a RepeatedType using FOSRest?

I have added the following formtype:

/**
 * {@inheritdoc}
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('email', TextType::class);
    $builder->add('firstName', TextType::class);
    $builder->add('lastName', TextType::class);
    $builder->add('password', RepeatedType::class, [
        'type' => PasswordType::class,
        'invalid_message' => 'The password fields must match.',
        'required' => true
    ]);
}

And this is the data I submit:

array(1) {
["user"]=>
array(4) {
    ["email"]=>
    string(21) "Testuser@test.be"
    ["firstName"]=>
    string(4) "Test"
    ["lastName"]=>
    string(9) "User"
    ["password"]=>
    array(2) {
          ["first"]=>
          string(8) "password"
          ["second"]=>
          string(8) "password"
    }
  }
}

Everything works, except the repeatedType throws: This form should not contain extra fields.

What's the correct format to submit to a repeatedType? The docs aren't really clear on this ...

Thank you

Body:
try to change this:

$builder->add('password', RepeatedType::class, [
    'type' => PasswordType::class,
    'invalid_message' => 'The password fields must match.',
    'required' => true
]);

to this:

$builder->add('password', RepeatedType::class, [
    'type' => PasswordType::class,
    'first_options'  => array('label' => 'Password'),
    'second_options' => array('label' => 'Repeat Password')
]);


问:
C# Odbc Stored procedure call - Procedure or function expects parameter which was not supplied
I have a basic stored procedure

```<code>ALTER PROCEDURE [dbo].[GetOrdersEmailContent]
    @Name nvarchar(50),
    @Body nvarchar(2000) OUTPUT
AS
BEGIN
    --SET NOCOUNT ON
    SET @Body = (SELECT Content
                 FROM ORDERS_tblEmailContent
                 WHERE Name = @Name)
END
</code>```

which I am calling from C# with the following code

```<code>using (DbConnection)
{
    DbConnection.Open();

    using (OdbcCommand DbCommand = DbConnection.CreateCommand())
    {
        DbCommand.CommandType = CommandType.StoredProcedure;
        DbCommand.CommandText = " GetOrdersEmailContent";

        DbCommand.Parameters.Add("@Name", OdbcType.NVarChar, 50);
        DbCommand.Parameters["@Name"].Value = templateName;
        DbCommand.Parameters["@Name"].Direction = ParameterDirection.Input;

        DbCommand.Parameters.Add("@Body", OdbcType.NVarChar, 2000);
        DbCommand.Parameters["@Body"].Value = DBNull.Value;
        DbCommand.Parameters["@Body"].Direction = ParameterDirection.Output;

        DbCommand.ExecuteNonQuery();

        emailBody = DbCommand.Parameters["@Body"].Value.ToString();
    }
}

DbConnection.Close();
</code>```

When the ExecuteNonQuery runs, it returns the following error:

ERROR [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Procedure or function 'GetOrdersEmailContent' expects parameter '@Name', which was not supplied.

Can anyone advise? I have looked through other similar questions but none of the solutions apply or resolve the issue

答:
Considering templateName have not empty. There is not need to specify direction for @Name:

```<code>using (DbConnection)
        {
            DbConnection.Open();
            using (OdbcCommand DbCommand = DbConnection.CreateCommand())
            {
                DbCommand.CommandType = CommandType.StoredProcedure;
                DbCommand.CommandText = " GetOrdersEmailContent";

                DbCommand.Parameters.Add("@Name", OdbcType.NVarChar, 50);
                DbCommand.Parameters["@Name"].Value = templateName;

                DbCommand.Parameters.Add("@Body", OdbcType.NVarChar, 2000);
                DbCommand.Parameters["@Body"].Value = DBNull.Value;
                DbCommand.Parameters["@Body"].Direction = ParameterDirection.Output;

                DbCommand.ExecuteNonQuery();

                emailBody = DbCommand.Parameters["@Body"].Value.ToString();
            }
        }
        DbConnection.Close();
</code>```

Body:
I have a basic stored procedure

ALTER PROCEDURE [dbo].[GetOrdersEmailContent]
    @Name nvarchar(50),
    @Body nvarchar(2000) OUTPUT
AS
BEGIN
    --SET NOCOUNT ON
    SET @Body = (SELECT Content
                 FROM ORDERS_tblEmailContent
                 WHERE Name = @Name)
END

which I am calling from C# with the following code

using (DbConnection)
{
    DbConnection.Open();

    using (OdbcCommand DbCommand = DbConnection.CreateCommand())
    {
        DbCommand.CommandType = CommandType.StoredProcedure;
        DbCommand.CommandText = " GetOrdersEmailContent";

        DbCommand.Parameters.Add("@Name", OdbcType.NVarChar, 50);
        DbCommand.Parameters["@Name"].Value = templateName;
        DbCommand.Parameters["@Name"].Direction = ParameterDirection.Input;

        DbCommand.Parameters.Add("@Body", OdbcType.NVarChar, 2000);
        DbCommand.Parameters["@Body"].Value = DBNull.Value;
        DbCommand.Parameters["@Body"].Direction = ParameterDirection.Output;

        DbCommand.ExecuteNonQuery();

        emailBody = DbCommand.Parameters["@Body"].Value.ToString();
    }
}

DbConnection.Close();

When the ExecuteNonQuery runs, it returns the following error:

ERROR [42000] [Microsoft][SQL Server Native Client 11.0][SQL Server]Procedure or function 'GetOrdersEmailContent' expects parameter '@Name', which was not supplied.

Can anyone advise? I have looked through other similar questions but none of the solutions apply or resolve the issue

Body:
Considering templateName have not empty. There is not need to specify direction for @Name:

using (DbConnection)
        {
            DbConnection.Open();
            using (OdbcCommand DbCommand = DbConnection.CreateCommand())
            {
                DbCommand.CommandType = CommandType.StoredProcedure;
                DbCommand.CommandText = " GetOrdersEmailContent";

                DbCommand.Parameters.Add("@Name", OdbcType.NVarChar, 50);
                DbCommand.Parameters["@Name"].Value = templateName;

                DbCommand.Parameters.Add("@Body", OdbcType.NVarChar, 2000);
                DbCommand.Parameters["@Body"].Value = DBNull.Value;
                DbCommand.Parameters["@Body"].Direction = ParameterDirection.Output;

                DbCommand.ExecuteNonQuery();

                emailBody = DbCommand.Parameters["@Body"].Value.ToString();
            }
        }
        DbConnection.Close();


问:
MVC in Visual Studio Express
I got Visual Studio 2010 Express C# Edition. I'm using WinXP as OS.

How do I get ASP.Net MVC in it? I saw another question that stated that MVC was included automatically, but I cannot find it anywhere. I've also tried by installing MVC3 RC2. Didn't show up either.

Isn't it possible to use MVC with Express edition?

(I've also got VS 2008 Professional on the same computer)

Edit

I needed the Visual Studio Web Developer Edition to get MVC2.

But how do I get MVC3?

Edit 2

I have XP Home edition which is not supported by web platform installer since IIS is not included. I guess that's why MVC3 wont install in Visual Studio 2010 Express (although it installed fine on my computer which is a bit strange)

答:
You need to explicitly download MVC 3 RC2 from here and install it:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=955d593e-cbd1-4ed1-88eb-02ff79dd74d8

ContentLicense: CC BY-SA 2.5

Title: MVC in Visual Studio Express


问:
How can I implement an add/edit parameter mechanism?
Assume this is my current URL:

```<code>http://example.com/search?param1=foo&param2=bar
</code>```

Now I want to add param3=baz. So this is the code:

```<code><a href="?param3=baz" >add param3</a>
//=> http://example.com/search?param3=baz
</code>```

See? param1 and param2 will be removed. So I have to handle it like this:

```<code><?php
    $query_str = parse_url($url, PHP_URL_QUERY);
    parse_str($query_str, $query_params);
    $query_params = $query_params == '' ? '?' : $query_params . '&';
?>

<a href="?{$query_params}param3=baz" >add param3</a>
</code>```

Seems ugly, but ok, nevermind. Now what happens if a parameter be already exist and I need to edit it? Assume this example:

```<code>http://example.com/search?param1=foo&param2=bar
</code>```

Now how can I make a link which edits the value of parame2? (plus keeping other parameters)

答:
There is no way to write a relative URI that preserves the existing query string while adding additional parameters to it.

You have to Do again:

```<code>search?param1=foo&param=bar&param3=baz
</code>```

Or

Using Javascript is Possible

How to add a parameter to the URL?

Or

```<code>function currentUrl() {
    $protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
    $host     = $_SERVER['HTTP_HOST'];
    $script   = $_SERVER['SCRIPT_NAME'];
    $params   = $_SERVER['QUERY_STRING'];

    return $protocol . '://' . $host . $script . '?' . $params;
}
</code>```

Then add your value with something like;

```<code>echo currentUrl().'&param3=baz';
</code>```

or

Whatever GET parameters you had will still be there and if param3 was a
  parameter before it will be overwritten, otherwise it will be included
  at the end.

```<code>http_build_query(array_merge($_GET, array("param3"=>"baz")))
</code>```

Body:
Assume this is my current URL:

http://example.com/search?param1=foo&param2=bar

Now I want to add param3=baz. So this is the code:

add param3
//=> http://example.com/search?param3=baz

See? param1 and param2 will be removed. So I have to handle it like this:

<?php
    $query_str = parse_url($url, PHP_URL_QUERY);
    parse_str($query_str, $query_params);
    $query_params = $query_params == '' ? '?' : $query_params . '&';
?>

add param3

Seems ugly, but ok, nevermind. Now what happens if a parameter be already exist and I need to edit it? Assume this example:

http://example.com/search?param1=foo&param2=bar

Now how can I make a link which edits the value of parame2? (plus keeping other parameters)

Body:
There is no way to write a relative URI that preserves the existing query string while adding additional parameters to it.

You have to Do again:

search?param1=foo&param=bar&param3=baz

Or

Using Javascript is Possible

How to add a parameter to the URL?

Or

function currentUrl() {
    $protocol = strpos(strtolower($_SERVER['SERVER_PROTOCOL']),'https') === FALSE ? 'http' : 'https';
    $host     = $_SERVER['HTTP_HOST'];
    $script   = $_SERVER['SCRIPT_NAME'];
    $params   = $_SERVER['QUERY_STRING'];

    return $protocol . '://' . $host . $script . '?' . $params;
}

Then add your value with something like;

echo currentUrl().'&param3=baz';

or

Whatever GET parameters you had will still be there and if param3 was a
  parameter before it will be overwritten, otherwise it will be included
  at the end.

http_build_query(array_merge($_GET, array("param3"=>"baz")))