问:
ActionController::UnknownFormat on AJAX with remote true
I'm trying to open a Bootstrap modal trough remote true calls, cause I need to passa some params to modal.

So, I have this code:

index.html

```<code>...

<%= link_to("<i class='fa fa-upload'></i>".html_safe, {:controller => :blocked_phone_numbers, :action => :show_modal, :blocked_phone_numbers_group_id => blocked_phone_numbers_groups.id}, :class => "btn btn-primary btn-xs", remote: true) %>

...

<div id="modalImportNumbers">
  <%= render partial: 'show_modal' %>
</div>

...
</code>```

blocked_phone_numbers_controller.rb

```<code>def show_modal   @blocked_phone_numbers_group = BlockedPhoneNumbersGroup.find(params[:blocked_phone_numbers_group_id]) respond_to do |format|
    format.js   end end
</code>```

show_modal.js.erb

```<code>$('#modalImportNumbers').html("<%= j render partial: 'show_modal' %>");
$('#modalImportar').modal('show');
</code>```

_show_modal.html.erb

```<code><div id="modalImportar" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header" style="background-color: #5a4371; color: #fff">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">×</span>
        </button>
        <h4 class="modal-title" id="modalLabel"><%= t(:item_7) %></h4>
      </div>
      <div class="row">
        <div class="col-xs-12 col-md-12 col-md-offset-0">
          <div class="modal-body">

            <%= form_tag({:action => "import"}, {:multipart => true}) do |form| %>

              ...

            <% end %>

          </div>
        </div>
      </div>
    </div>
  </div>
</div>
</code>```

routes.rb

```<code>Rails.application.routes.draw do

  root 'login#index'

  match ':controller(/:action(/:id))(.:format)', via: [:get, :post]
end
</code>```

The problem is that I keep getting this error:

ActionController::UnknownFormat (ActionController::UnknownFormat):

app/controllers/blocked_phone_numbers_controller.rb:25:in `show_modal'

NameError: uninitialized constant Mime::HTML

I have jQuery import on my application.js, so, I read about in many threads here but I cant figure out what is happening.

Someone could help me understand this error, please?

I'm using Rails 5.1 and Bootstrap 3.7

Thanks!

答:
routes.rb

```<code>match '/show_modal' => 'blocked_phone_numbers#show_modal', as: 'show_modal', via: [:get, :post]
</code>```

index.html.erb

```<code>...

<%= link_to show_modal_path(blocked_phone_numbers_group_id: blocked_phone_numbers_groups.id), class: 'btn btn-primary btn-xs', method: :post, :remote => true do%>
  <i class='fa fa-upload'></i%>
<%end%>

...

<div id="modalImportNumbers">
  <%= render partial: 'show_modal' %>
</div>

...
</code>```

Body:
I'm trying to open a Bootstrap modal trough remote true calls, cause I need to passa some params to modal.

So, I have this code:

index.html

...

<%= link_to("".html_safe, {:controller => :blocked_phone_numbers, :action => :show_modal, :blocked_phone_numbers_group_id => blocked_phone_numbers_groups.id}, :class => "btn btn-primary btn-xs", remote: true) %>

...

  <%= render partial: 'show_modal' %>

...

blocked_phone_numbers_controller.rb

def show_modal   @blocked_phone_numbers_group = BlockedPhoneNumbersGroup.find(params[:blocked_phone_numbers_group_id]) respond_to do |format|
    format.js   end end

show_modal.js.erb

$('#modalImportNumbers').html("<%= j render partial: 'show_modal' %>");
$('#modalImportar').modal('show');

_show_modal.html.erb

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

<%= t(:item_7) %>

            <%= form_tag({:action => "import"}, {:multipart => true}) do |form| %>

              ...

            <% end %>

routes.rb

Rails.application.routes.draw do

  root 'login#index'

  match ':controller(/:action(/:id))(.:format)', via: [:get, :post]
end

The problem is that I keep getting this error:

ActionController::UnknownFormat (ActionController::UnknownFormat):

app/controllers/blocked_phone_numbers_controller.rb:25:in `show_modal'

NameError: uninitialized constant Mime::HTML

I have jQuery import on my application.js, so, I read about in many threads here but I cant figure out what is happening.

Someone could help me understand this error, please?

I'm using Rails 5.1 and Bootstrap 3.7

Thanks!

Body:
routes.rb

match '/show_modal' => 'blocked_phone_numbers#show_modal', as: 'show_modal', via: [:get, :post]

index.html.erb

...

<%= link_to show_modal_path(blocked_phone_numbers_group_id: blocked_phone_numbers_groups.id), class: 'btn btn-primary btn-xs', method: :post, :remote => true do%>
  <i class='fa fa-upload'></i%>
<%end%>

...

<div id="modalImportNumbers">
  <%= render partial: 'show_modal' %>
</div>

...


来源: stackexchange

问:
Vue/Vuex > Cannot track state changed when I use Object.defineProperty() method
I use Vue.js and Vuex.

I make a simple todolist app.

I make a done toggle button with Vuex using Object.defineProperty() method.

When I click done toggle button, Vue and Vuex cannot trace change immediately.

It only trace change when I just reassign property's value.

For example

This works:

```<code>Vuex.Store({
    state: {
        todolist: [
            { todo: 'test1', done: false },
            { todo: 'test2', done: true },
            { todo: 'test3', done: false },
            { todo: 'test4', done: false }
        ]
    },
    mutations: {
        ...
        [Constant.DONE_TOGGLE]: (state, payload) => {
            const changeState = state;
            changeState.todolist[payload.index].done = !state.todolist[payload.index].done;
        },
        ...
    }
});
</code>```

But this does NOT work!

```<code>Vuex.Store({
    state: {
        todolist: [
            { todo: 'test1', done: false },
            { todo: 'test2', done: true },
            { todo: 'test3', done: false },
            { todo: 'test4', done: false }
        ]
    },
    mutations: {
        ...
        [Constant.DONE_TOGGLE]: (state, payload) => {
            Object.defineProperty(state.todolist[payload.index], 'done', { value: !state.todolist[payload.index].done });
        },
        ...
    }
});
</code>```

below code trace changes of done toggle only OTHER mutations change state.

Why it does?

Here is my github repository link.

My app is in /EX11/todolistapp.

My Vuex file is in /EX11/todolistapp/src/store/index.js

Thanks for reading my question.
Sorry for not good at English.
Have a nice day!

答:
This is due to a Javascript limitation -- Vue cannot detect changes to an element of an array when done via an index.

But why not just grab the todo item and change it's done property directly?

```<code>var item = state.todolist[payload.index];
item.done = !item.done;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I use Vue.js and Vuex.

I make a simple todolist app.

I make a done toggle button with Vuex using Object.defineProperty() method.

When I click done toggle button, Vue and Vuex cannot trace change immediately.

It only trace change when I just reassign property's value.

For example

This works:

Vuex.Store({
    state: {
        todolist: [
            { todo: 'test1', done: false },
            { todo: 'test2', done: true },
            { todo: 'test3', done: false },
            { todo: 'test4', done: false }
        ]
    },
    mutations: {
        ...
        [Constant.DONE_TOGGLE]: (state, payload) => {
            const changeState = state;
            changeState.todolist[payload.index].done = !state.todolist[payload.index].done;
        },
        ...
    }
});

But this does NOT work!

Vuex.Store({
    state: {
        todolist: [
            { todo: 'test1', done: false },
            { todo: 'test2', done: true },
            { todo: 'test3', done: false },
            { todo: 'test4', done: false }
        ]
    },
    mutations: {
        ...
        [Constant.DONE_TOGGLE]: (state, payload) => {
            Object.defineProperty(state.todolist[payload.index], 'done', { value: !state.todolist[payload.index].done });
        },
        ...
    }
});

below code trace changes of done toggle only OTHER mutations change state.

Why it does?

Here is my github repository link.

My app is in /EX11/todolistapp.

My Vuex file is in /EX11/todolistapp/src/store/index.js

Thanks for reading my question.
Sorry for not good at English.
Have a nice day!

Body:
This is due to a Javascript limitation -- Vue cannot detect changes to an element of an array when done via an index.

But why not just grab the todo item and change it's done property directly?

var item = state.todolist[payload.index];
item.done = !item.done;

ContentLicense: CC BY-SA 4.0


问:
Identify how the function has been called in closure javascript
Recently i faced one problem in hackerrank which has to calculate multiplication operation and has to return the answer. For example

```<code>function multiply(a,b) {
     return a*b;
}
</code>```

Now here is the problem the function might call in different ways such as

```<code>multiply(4,5);
multiply(4)(5);
multiply(4)(5)(6);
</code>```

I know we have to closure apporach for the second one which is multiply(4)(5). I had written code for that

```<code>function multiply(a,b) {
  return function(b) {
    return a*b;
  }
}
</code>```

Now what if its been multiply function has been called with 3 arguments multiply(4)(5)(6). How can i identify how the function has been called and how can i write a common solution for all the inputs.

Any help is appreciated. Thanks

答:
The Problem with this approach is the ambiguity of the returned value. It has to be a Number AND a function, both at the same time.

due to the valueOf() method you can simulate that behaviour, but I'd rarely reccomend to use that in production.

const wrap = (accumulator, value) => {
  let fn = (...args) => args.length? wrap(accumulator, args.reduce(accumulator, value)): fn;
  fn.valueOf = () => value;
  return fn;
}

let mul = wrap((a,b) => a*b, 1);

console.log(+mul(4,5));
console.log(+mul(4,5)(6));
console.log(mul(4,5) * 6);
console.log(+mul(4)(5,6)(7)(8,9)()(10));

//or maybe a different operation?
let add = wrap((a,b) => a+b, 0);

console.log(+add(1,2,3,4,5));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper{top:0;max-height:100%!important;}</code>```

Downside of this approach, it's made so flexible (and ambigious), it's pretty much useless since it's way too hard to grasp what result you'll get when using this somewhere inline. What if some functions you'll feed this into do a typecheck? Then you're in trouble.

Body:
Recently i faced one problem in hackerrank which has to calculate multiplication operation and has to return the answer. For example

function multiply(a,b) {
     return a*b;
}

Now here is the problem the function might call in different ways such as

multiply(4,5);
multiply(4)(5);
multiply(4)(5)(6);

I know we have to closure apporach for the second one which is multiply(4)(5). I had written code for that

function multiply(a,b) {
  return function(b) {
    return a*b;
  }
}

Now what if its been multiply function has been called with 3 arguments multiply(4)(5)(6). How can i identify how the function has been called and how can i write a common solution for all the inputs.

Any help is appreciated. Thanks

Body:
The Problem with this approach is the ambiguity of the returned value. It has to be a Number AND a function, both at the same time.

due to the valueOf() method you can simulate that behaviour, but I'd rarely reccomend to use that in production.

const wrap = (accumulator, value) => {
  let fn = (...args) => args.length? wrap(accumulator, args.reduce(accumulator, value)): fn;
  fn.valueOf = () => value;
  return fn;
}

let mul = wrap((a,b) => a*b, 1);

console.log(+mul(4,5));
console.log(+mul(4,5)(6));
console.log(mul(4,5) * 6);
console.log(+mul(4)(5,6)(7)(8,9)()(10));

//or maybe a different operation?
let add = wrap((a,b) => a+b, 0);

console.log(+add(1,2,3,4,5));

.as-console-wrapper{top:0;max-height:100%!important;}

Downside of this approach, it's made so flexible (and ambigious), it's pretty much useless since it's way too hard to grasp what result you'll get when using this somewhere inline. What if some functions you'll feed this into do a typecheck? Then you're in trouble.


问:
go test fails, empty slice where JSON should have been
I am testing a piece of code, called Compile:

```<code>// Compile takes in code, and returns JSON
// bytes and an error if there was one
func Compile(in string) ([]byte, error) {
    // iterate through every line in the code
    for _, line := range strings.Split(in, "\n") {
        // Divide the line into sections
        // for easier processing
        tokens := strings.Split(line, " ")
        for _, a := range availableExpressions {
            for _, b := range availableStatements {
                if tokens[1] == b {
                    // It is an expression, so
                    // calculate the value of
                    // the expression
                    var val int
                    num1, err := strconv.Atoi(tokens[0])
                    if err != nil {
                        return nil, err
                    }
                    num2, err := strconv.Atoi(tokens[1])
                    if err != nil {
                        return nil, err
                    }
                    args := []int{num1, num2}
                    switch b {
                    case "+":
                        val = args[0] + args[1]
                    case "*":
                        val = args[0] * args[1]
                    case "-":
                        val = args[0] - args[1]
                    case "/":
                        val = args[0] / args[1]
                    }
                    cmd := &Mixed{
                        isExpression: true,
                        isStatement:  false,
                        Value: &Expression{
                            Name: b,
                            // for some reason go doesn't
                            // let me put args directly
                            Arguments: []interface{}{args},
                            Value:     val,
                        }}
                    fmt.Println(cmd.Value)
                    commands = append(commands, cmd)
                } else if tokens[0] == a {
                    // argument is a statement, don't bother
                    // to evaluate the value
                    arguments := strings.Join(tokens[1:], " ")
                    cmd := &Mixed{
                        isStatement:  true,
                        isExpression: false,
                        Value: &Statement{
                            Name:      a,
                            Arguments: []interface{}{arguments},
                        }}
                    fmt.Println(cmd.Value)
                    commands = append(commands, cmd)
                }
            }
        }
    }
    gen, err := json.Marshal(commands)
    // fmt prints an empty slice
    // no matter what is in
    fmt.Println(commands)
    // empty the commands
    commands = make([]*Mixed, 0)
    if err != nil {
        return nil, err
    }
    return gen, nil
}
</code>```

But when running the test:

```<code>$ cat compile_test.go
package main

import "fmt"
import "testing"

func TestCompile(t *testing.T) {
    cases := []struct {
        in  string
        out string
    }{
        {
            in:  "print \"Hello World\"",
            out: "[{\"Name\":\"print\",\"Arguments\":[\"Hello World\"]}]",
        },
        {
            in:  "print \"My name is Jack White\"",
            out: "[{\"Name\":\"print\",\"Arguments\":[\"My name is Jack White\"]}]",
        },
    }
    real_stuff, err := Compile(cases[0].in)
    if err != nil {
        fmt.Printf("error: %s\n", err)
    }
    if string(real_stuff) != cases[0].out {
        fmt.Printf("got %s, expected %s\n", string(real_stuff), cases[0].out)
        t.Fail()
    }
    real_stuff, err = Compile(cases[1].in)
    if err != nil {
        fmt.Printf("error: %s\n", err)
    }
    if string(real_stuff) != cases[1].out {
        fmt.Printf("got %s, expected %s\n", string(real_stuff), cases[1].out)
        t.Fail()
    }
}
$ go test
[]
got [], expected [{"Name":"print","Arguments":["Hello World"]}]
[]
got [], expected [{"Name":"print","Arguments":["My name is Jack White"]}]
--- FAIL: TestCompile (0.06s)
</code>```

Can someone explain why the test fails and why Compile doesn't work?

答:
You need to debug your code logic:

I switched:

```<code>    for _, a := range availableExpressions {
        for _, b := range availableStatements {
</code>```

with:

```<code>    for _, a := range availableStatements {
        for _, b := range availableExpressions {
</code>```

Run this:

```<code>package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "strconv"
    "strings"
)

// Function not implemented yet,
// but there for completedness
type Function struct {
    Name      string
    Arguments []interface{}
    // A function can contain
    // both expressions and
    // statements
    Code []Mixed
}

// Mixed can be either Statement
// or Expression
type Mixed struct {
    isStatement  bool
    isExpression bool
    Value        interface{}
}

// Statement represents
// statements. How a statement
// is used is entirely up to
// the interpreter.
type Statement struct {
    Name      string
    Arguments []interface{}
}

// Since an Expression
// is calculated beforehand,
// store the value
type Expression struct {
    Name      string
    Arguments []interface{}
    Value     interface{}
}

// commands contains commands to
// execute later.
// It is of type Mixed because Mixed
// can be of type Expression or Statement
var commands = make([]*Mixed, 0)

var availableStatements = []string{
    "print",
}
var availableExpressions = []string{
    "+",
    "-",
    "*",
    "/",
}

// Compile takes in code, and returns JSON
// bytes and an error if there was one
func Compile(in string) ([]byte, error) {
    // iterate through every line in the code
    for _, line := range strings.Split(in, "\n") {
        // Divide the line into sections
        // for easier processing
        tokens := strings.Split(line, " ")
        for _, a := range availableStatements {
            for _, b := range availableExpressions {
                if tokens[1] == b {
                    // It is an expression, so
                    // calculate the value of
                    // the expression
                    var val int
                    num1, err := strconv.Atoi(tokens[0])
                    if err != nil {
                        return nil, err
                    }
                    num2, err := strconv.Atoi(tokens[1])
                    if err != nil {
                        return nil, err
                    }
                    args := []int{num1, num2}
                    switch b {
                    case "+":
                        val = args[0] + args[1]
                    case "*":
                        val = args[0] * args[1]
                    case "-":
                        val = args[0] - args[1]
                    case "/":
                        val = args[0] / args[1]
                    }
                    cmd := &Mixed{
                        isExpression: true,
                        isStatement:  false,
                        Value: &Expression{
                            Name: b,
                            // for some reason go doesn't
                            // let me put args directly
                            Arguments: []interface{}{args},
                            Value:     val,
                        }}
                    fmt.Println(cmd.Value)
                    commands = append(commands, cmd)
                } else if tokens[0] == a {
                    // argument is a statement, don't bother
                    // to evaluate the value
                    arguments := strings.Join(tokens[1:], " ")
                    cmd := &Mixed{
                        isStatement:  true,
                        isExpression: false,
                        Value: &Statement{
                            Name:      a,
                            Arguments: []interface{}{arguments},
                        }}
                    fmt.Println(cmd.Value)
                    commands = append(commands, cmd)
                }
            }
        }
    }
    gen, err := json.Marshal(commands)
    fmt.Println(commands)
    // empty the commands
    commands = make([]*Mixed, 0)
    if err != nil {
        return nil, err
    }
    return gen, nil
}

func Execute(input_file string) error {
    // open input file
    f, err := ioutil.ReadFile(input_file)
    if err != nil {
        return err
    }
    // unmarshal the JSON
    var data []*Mixed
    err = json.Unmarshal(f, data)
    if err != nil {
        return err
    }
    for _, v := range data {
        var a *Expression
        var b *Statement
        // get absolute value of v
        if v.isExpression {
            a = v.Value.(*Expression)
            b = nil
        } else if v.isStatement {
            b = v.Value.(*Statement)
            a = nil
        }
        // since the expression is
        // already calculated at compile-time,
        // don't bother evaluating
        if a != nil {
            fmt.Println(a.Value)
        }
        if b != nil {
            // on the other hand, evaluate
            // statements since they're *not*
            // evaluated at compile-time
            switch b.Name {
            case "print":
                for _, n := range b.Arguments {
                    fmt.Printf("%v", n)
                }
                fmt.Printf("\n")
            }
        }
    }
    return nil
}

func main() {
    cases := []struct {
        in  string
        out string
    }{
        {
            in:  "print \"Hello World\"",
            out: "[{\"Name\":\"print\",\"Arguments\":[\"Hello World\"]}]",
        },
        {
            in:  "print \"My name is Jack White\"",
            out: "[{\"Name\":\"print\",\"Arguments\":[\"My name is Jack White\"]}]",
        },
    }
    real_stuff, err := Compile(cases[0].in)
    if err != nil {
        fmt.Printf("error: %s\n", err)
    }
    fmt.Println(string(real_stuff))
    if string(real_stuff) != cases[0].out {
        fmt.Printf("got %s, expected %s\n", string(real_stuff), cases[0].out)
        //t.Fail()
    }
    real_stuff, err = Compile(cases[1].in)
    if err != nil {
        fmt.Printf("error: %s\n", err)
    }
    fmt.Println(string(real_stuff))
    if string(real_stuff) != cases[1].out {
        fmt.Printf("got %s, expected %s\n", string(real_stuff), cases[1].out)
        //t.Fail()
    }
}
</code>```

output (go test):

```<code>&{print ["Hello World"]}
&{print ["Hello World"]}
&{print ["Hello World"]}
&{print ["Hello World"]}
[0xc04204e3c0 0xc04204e420 0xc04204e460 0xc04204e4c0]
got [{"Value":{"Name":"print","Arguments":["\"Hello World\""]}},{"Value":{"Name":"print","Arguments":["\"Hello World\""]}},{"Value":{"Name":"print","Arguments":["\"Hello World\""]}},{"Value":{"Name":"print","Arguments":["\"Hello World\""]}}], expected [{"Name":"print","Arguments":["Hello World"]}]
&{print ["My name is Jack White"]}
&{print ["My name is Jack White"]}
&{print ["My name is Jack White"]}
&{print ["My name is Jack White"]}
[0xc04204e6e0 0xc04204e720 0xc04204e760 0xc04204e7c0]
got [{"Value":{"Name":"print","Arguments":["\"My name is Jack White\""]}},{"Value":{"Name":"print","Arguments":["\"My name is Jack White\""]}},{"Value":{"Name":"print","Arguments":["\"My name is Jack White\""]}},{"Value":{"Name":"print","Arguments":["\"My name is Jack White\""]}}], expected [{"Name":"print","Arguments":["My name is Jack White"]}]
--- FAIL: TestCompile (0.00s)
FAIL
exit status 1
FAIL    ar/sogo 0.016s
</code>```

Body:
I am testing a piece of code, called Compile:

// Compile takes in code, and returns JSON
// bytes and an error if there was one
func Compile(in string) ([]byte, error) {
    // iterate through every line in the code
    for _, line := range strings.Split(in, "\n") {
        // Divide the line into sections
        // for easier processing
        tokens := strings.Split(line, " ")
        for _, a := range availableExpressions {
            for _, b := range availableStatements {
                if tokens[1] == b {
                    // It is an expression, so
                    // calculate the value of
                    // the expression
                    var val int
                    num1, err := strconv.Atoi(tokens[0])
                    if err != nil {
                        return nil, err
                    }
                    num2, err := strconv.Atoi(tokens[1])
                    if err != nil {
                        return nil, err
                    }
                    args := []int{num1, num2}
                    switch b {
                    case "+":
                        val = args[0] + args[1]
                    case "*":
                        val = args[0] * args[1]
                    case "-":
                        val = args[0] - args[1]
                    case "/":
                        val = args[0] / args[1]
                    }
                    cmd := &Mixed{
                        isExpression: true,
                        isStatement:  false,
                        Value: &Expression{
                            Name: b,
                            // for some reason go doesn't
                            // let me put args directly
                            Arguments: []interface{}{args},
                            Value:     val,
                        }}
                    fmt.Println(cmd.Value)
                    commands = append(commands, cmd)
                } else if tokens[0] == a {
                    // argument is a statement, don't bother
                    // to evaluate the value
                    arguments := strings.Join(tokens[1:], " ")
                    cmd := &Mixed{
                        isStatement:  true,
                        isExpression: false,
                        Value: &Statement{
                            Name:      a,
                            Arguments: []interface{}{arguments},
                        }}
                    fmt.Println(cmd.Value)
                    commands = append(commands, cmd)
                }
            }
        }
    }
    gen, err := json.Marshal(commands)
    // fmt prints an empty slice
    // no matter what is in
    fmt.Println(commands)
    // empty the commands
    commands = make([]*Mixed, 0)
    if err != nil {
        return nil, err
    }
    return gen, nil
}

But when running the test:

$ cat compile_test.go
package main

import "fmt"
import "testing"

func TestCompile(t *testing.T) {
    cases := []struct {
        in  string
        out string
    }{
        {
            in:  "print \"Hello World\"",
            out: "[{\"Name\":\"print\",\"Arguments\":[\"Hello World\"]}]",
        },
        {
            in:  "print \"My name is Jack White\"",
            out: "[{\"Name\":\"print\",\"Arguments\":[\"My name is Jack White\"]}]",
        },
    }
    real_stuff, err := Compile(cases[0].in)
    if err != nil {
        fmt.Printf("error: %s\n", err)
    }
    if string(real_stuff) != cases[0].out {
        fmt.Printf("got %s, expected %s\n", string(real_stuff), cases[0].out)
        t.Fail()
    }
    real_stuff, err = Compile(cases[1].in)
    if err != nil {
        fmt.Printf("error: %s\n", err)
    }
    if string(real_stuff) != cases[1].out {
        fmt.Printf("got %s, expected %s\n", string(real_stuff), cases[1].out)
        t.Fail()
    }
}
$ go test
[]
got [], expected [{"Name":"print","Arguments":["Hello World"]}]
[]
got [], expected [{"Name":"print","Arguments":["My name is Jack White"]}]
--- FAIL: TestCompile (0.06s)

Can someone explain why the test fails and why Compile doesn't work?

Body:
You need to debug your code logic:

I switched:

    for _, a := range availableExpressions {
        for _, b := range availableStatements {

with:

    for _, a := range availableStatements {
        for _, b := range availableExpressions {

Run this:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "strconv"
    "strings"
)

// Function not implemented yet,
// but there for completedness
type Function struct {
    Name      string
    Arguments []interface{}
    // A function can contain
    // both expressions and
    // statements
    Code []Mixed
}

// Mixed can be either Statement
// or Expression
type Mixed struct {
    isStatement  bool
    isExpression bool
    Value        interface{}
}

// Statement represents
// statements. How a statement
// is used is entirely up to
// the interpreter.
type Statement struct {
    Name      string
    Arguments []interface{}
}

// Since an Expression
// is calculated beforehand,
// store the value
type Expression struct {
    Name      string
    Arguments []interface{}
    Value     interface{}
}

// commands contains commands to
// execute later.
// It is of type Mixed because Mixed
// can be of type Expression or Statement
var commands = make([]*Mixed, 0)

var availableStatements = []string{
    "print",
}
var availableExpressions = []string{
    "+",
    "-",
    "*",
    "/",
}

// Compile takes in code, and returns JSON
// bytes and an error if there was one
func Compile(in string) ([]byte, error) {
    // iterate through every line in the code
    for _, line := range strings.Split(in, "\n") {
        // Divide the line into sections
        // for easier processing
        tokens := strings.Split(line, " ")
        for _, a := range availableStatements {
            for _, b := range availableExpressions {
                if tokens[1] == b {
                    // It is an expression, so
                    // calculate the value of
                    // the expression
                    var val int
                    num1, err := strconv.Atoi(tokens[0])
                    if err != nil {
                        return nil, err
                    }
                    num2, err := strconv.Atoi(tokens[1])
                    if err != nil {
                        return nil, err
                    }
                    args := []int{num1, num2}
                    switch b {
                    case "+":
                        val = args[0] + args[1]
                    case "*":
                        val = args[0] * args[1]
                    case "-":
                        val = args[0] - args[1]
                    case "/":
                        val = args[0] / args[1]
                    }
                    cmd := &Mixed{
                        isExpression: true,
                        isStatement:  false,
                        Value: &Expression{
                            Name: b,
                            // for some reason go doesn't
                            // let me put args directly
                            Arguments: []interface{}{args},
                            Value:     val,
                        }}
                    fmt.Println(cmd.Value)
                    commands = append(commands, cmd)
                } else if tokens[0] == a {
                    // argument is a statement, don't bother
                    // to evaluate the value
                    arguments := strings.Join(tokens[1:], " ")
                    cmd := &Mixed{
                        isStatement:  true,
                        isExpression: false,
                        Value: &Statement{
                            Name:      a,
                            Arguments: []interface{}{arguments},
                        }}
                    fmt.Println(cmd.Value)
                    commands = append(commands, cmd)
                }
            }
        }
    }
    gen, err := json.Marshal(commands)
    fmt.Println(commands)
    // empty the commands
    commands = make([]*Mixed, 0)
    if err != nil {
        return nil, err
    }
    return gen, nil
}

func Execute(input_file string) error {
    // open input file
    f, err := ioutil.ReadFile(input_file)
    if err != nil {
        return err
    }
    // unmarshal the JSON
    var data []*Mixed
    err = json.Unmarshal(f, data)
    if err != nil {
        return err
    }
    for _, v := range data {
        var a *Expression
        var b *Statement
        // get absolute value of v
        if v.isExpression {
            a = v.Value.(*Expression)
            b = nil
        } else if v.isStatement {
            b = v.Value.(*Statement)
            a = nil
        }
        // since the expression is
        // already calculated at compile-time,
        // don't bother evaluating
        if a != nil {
            fmt.Println(a.Value)
        }
        if b != nil {
            // on the other hand, evaluate
            // statements since they're *not*
            // evaluated at compile-time
            switch b.Name {
            case "print":
                for _, n := range b.Arguments {
                    fmt.Printf("%v", n)
                }
                fmt.Printf("\n")
            }
        }
    }
    return nil
}

func main() {
    cases := []struct {
        in  string
        out string
    }{
        {
            in:  "print \"Hello World\"",
            out: "[{\"Name\":\"print\",\"Arguments\":[\"Hello World\"]}]",
        },
        {
            in:  "print \"My name is Jack White\"",
            out: "[{\"Name\":\"print\",\"Arguments\":[\"My name is Jack White\"]}]",
        },
    }
    real_stuff, err := Compile(cases[0].in)
    if err != nil {
        fmt.Printf("error: %s\n", err)
    }
    fmt.Println(string(real_stuff))
    if string(real_stuff) != cases[0].out {
        fmt.Printf("got %s, expected %s\n", string(real_stuff), cases[0].out)
        //t.Fail()
    }
    real_stuff, err = Compile(cases[1].in)
    if err != nil {
        fmt.Printf("error: %s\n", err)
    }
    fmt.Println(string(real_stuff))
    if string(real_stuff) != cases[1].out {
        fmt.Printf("got %s, expected %s\n", string(real_stuff), cases[1].out)
        //t.Fail()
    }
}

output (go test):

&{print ["Hello World"]}
&{print ["Hello World"]}
&{print ["Hello World"]}
&{print ["Hello World"]}
[0xc04204e3c0 0xc04204e420 0xc04204e460 0xc04204e4c0]
got [{"Value":{"Name":"print","Arguments":["\"Hello World\""]}},{"Value":{"Name":"print","Arguments":["\"Hello World\""]}},{"Value":{"Name":"print","Arguments":["\"Hello World\""]}},{"Value":{"Name":"print","Arguments":["\"Hello World\""]}}], expected [{"Name":"print","Arguments":["Hello World"]}]
&{print ["My name is Jack White"]}
&{print ["My name is Jack White"]}
&{print ["My name is Jack White"]}
&{print ["My name is Jack White"]}
[0xc04204e6e0 0xc04204e720 0xc04204e760 0xc04204e7c0]
got [{"Value":{"Name":"print","Arguments":["\"My name is Jack White\""]}},{"Value":{"Name":"print","Arguments":["\"My name is Jack White\""]}},{"Value":{"Name":"print","Arguments":["\"My name is Jack White\""]}},{"Value":{"Name":"print","Arguments":["\"My name is Jack White\""]}}], expected [{"Name":"print","Arguments":["My name is Jack White"]}]
--- FAIL: TestCompile (0.00s)
FAIL
exit status 1
FAIL    ar/sogo 0.016s


问:
Store and call method from a HashMap
I have 2 files: ImplementationProvider and CaseHandler.

ImplementationProvider:

```<code>class ImplementationProvider {
    public void method1(Object[] params) {}
    public void method2(Object[] params) {}
    ...
    public void method100(Object[] params) {}
}
</code>```

CaseHandler:

```<code>class CaseHandler {
    ImplementationProvider ip; // auto injected
    public void handle(String s, String param) {
        switch(s) {
            case USE_CASE_ONE: ip.method1(param); break;
            case USE_CASE_TWO: ip.method2(param); break;
            ...
        }
    }
}
</code>```

How can I refactor the CaseHandler so that the USE_CASE strings are keys in a HashMap where the values would be the methods? The main issue I'm having is the propagation of the parameters. Other answers here recommend using an interface, however I need to provide the parameter on runtime.

答:
If you are using Java 8, you can lever the Consumer functional interface to parametrize your map's values with.

Example:

```<code>private static Map<String, Consumer<String>> MAP = new HashMap<>();
static {
    MAP.put("USE_CASE_ONE", (s) -> {/*TODO something with param s*/});
    // etc.
}
</code>```

... then somewhere else:

```<code>public void handle(String key, String param) {
        // TODO check key exists
        MAP.get(key).accept(param);
}
</code>```

What happens here is that for each given key set entry, you map it with a function that consumes a String (your param).

Then, you invoke the Consumer's accept on your given param in one line.

Title: Store and call method from a HashMap

Body:
I have 2 files: ImplementationProvider and CaseHandler.

ImplementationProvider:

class ImplementationProvider {
    public void method1(Object[] params) {}
    public void method2(Object[] params) {}
    ...
    public void method100(Object[] params) {}
}

CaseHandler:

class CaseHandler {
    ImplementationProvider ip; // auto injected
    public void handle(String s, String param) {
        switch(s) {
            case USE_CASE_ONE: ip.method1(param); break;
            case USE_CASE_TWO: ip.method2(param); break;
            ...
        }
    }
}

How can I refactor the CaseHandler so that the USE_CASE strings are keys in a HashMap where the values would be the methods? The main issue I'm having is the propagation of the parameters. Other answers here recommend using an interface, however I need to provide the parameter on runtime.

Body:
If you are using Java 8, you can lever the Consumer functional interface to parametrize your map's values with.

Example:

private static Map<String, Consumer<String>> MAP = new HashMap<>();
static {
    MAP.put("USE_CASE_ONE", (s) -> {/*TODO something with param s*/});
    // etc.
}

... then somewhere else:

public void handle(String key, String param) {
        // TODO check key exists
        MAP.get(key).accept(param);
}

What happens here is that for each given key set entry, you map it with a function that consumes a String (your param).

Then, you invoke the Consumer's accept on your given param in one line.


问:
Ng-show shows div no matter what
Okay so what I'm trying to do is the following: if the input called 'autoPack' is empty, show the div 'forma_reservas_gustos'. If it is not empty, do NOT show the div. The problem I'm having is that no matter what the value from the input is, the div is always displayed. I've tried so many things but nothing seems to be working.

HTML:

```<code><input type="hidden" name="autoPack" id="autoPack" ng-model="autoPack" value="">

<div class="forma_reservas_gustos" ng-show="!autoPack">
  <div class="forma_reservas_gustos_interior wid1k pbot20">
    <div class="paso">
      <div class="butpasos">
        <img src="/wp-content/uploads/2017/08/uno.png" />
      </div>
      <div class="textpasos">
        <h3>SELECCIONA EL PACK DE EXPERIENCIAS QUE MÁS TE GUSTE</h3>
      </div>
    </div>
    [...]
</code>```

JS

```<code>document.forms["forma_reservas_form"].autoPack.value = "xxxx";
</code>```

When I inspect it with Google Developer Tools, the html input does have the value 'xxxx'. So it is in fact not empty, therefore the div should not be displayed yet it is for some strange reason. Can anybody help me?

答:
Looks like autoPack needs to be a property of $scope...not just a property on the form.

```<code>...
$scope.autoPack = "xxxx";
...
</code>```

Title: Ng-show shows div no matter what

Body:
Okay so what I'm trying to do is the following: if the input called 'autoPack' is empty, show the div 'forma_reservas_gustos'. If it is not empty, do NOT show the div. The problem I'm having is that no matter what the value from the input is, the div is always displayed. I've tried so many things but nothing seems to be working.

HTML:

<input type="hidden" name="autoPack" id="autoPack" ng-model="autoPack" value="">

SELECCIONA EL PACK DE EXPERIENCIAS QUE MÁS TE GUSTE

    [...]

JS

document.forms["forma_reservas_form"].autoPack.value = "xxxx";

When I inspect it with Google Developer Tools, the html input does have the value 'xxxx'. So it is in fact not empty, therefore the div should not be displayed yet it is for some strange reason. Can anybody help me?

Body:
Looks like autoPack needs to be a property of $scope...not just a property on the form.

...
$scope.autoPack = "xxxx";
...


问:
Resize image with javascript canvas (smoothly)
I'm trying to resize some images with canvas but I'm clueless on how to smoothen them.
On photoshop, browsers etc.. there are a few algorithms they use (e.g. bicubic, bilinear) but I don't know if these are built into canvas or not.

Here's my fiddle: http://jsfiddle.net/EWupT/

```<code>var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width=300
canvas.height=234
ctx.drawImage(img, 0, 0, 300, 234);
document.body.appendChild(canvas);
</code>```

The first one is a normal resized image tag, and the second one is canvas. Notice how the canvas one is not as smooth. How can I achieve 'smoothness'?

答:
I wrote small js-utility to crop and resize image on front-end. Here is link on GitHub project. Also you can get blob from final image to send it.</p>

```<code>import imageSqResizer from './image-square-resizer.js'

let resizer = new imageSqResizer(
    'image-input',
    300,
    (dataUrl) =>
        document.getElementById('image-output').src = dataUrl;
);
//Get blob
let formData = new FormData();
formData.append('files[0]', resizer.blob);

//get dataUrl
document.getElementById('image-output').src = resizer.dataUrl;
</code>```

Body:
I'm trying to resize some images with canvas but I'm clueless on how to smoothen them.
On photoshop, browsers etc.. there are a few algorithms they use (e.g. bicubic, bilinear) but I don't know if these are built into canvas or not.

Here's my fiddle: http://jsfiddle.net/EWupT/

var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width=300
canvas.height=234
ctx.drawImage(img, 0, 0, 300, 234);
document.body.appendChild(canvas);

The first one is a normal resized image tag, and the second one is canvas. Notice how the canvas one is not as smooth. How can I achieve 'smoothness'?

Body:
I wrote small js-utility to crop and resize image on front-end. Here is link on GitHub project. Also you can get blob from final image to send it.

import imageSqResizer from './image-square-resizer.js'

let resizer = new imageSqResizer(
    'image-input',
    300,
    (dataUrl) =>
        document.getElementById('image-output').src = dataUrl;
);
//Get blob
let formData = new FormData();
formData.append('files[0]', resizer.blob);

//get dataUrl
document.getElementById('image-output').src = resizer.dataUrl;


问:
Modifying an element in a dataframe with iterrows()
I am trying to change an element in a large dataframe

e.g

```<code>Keyword                         |cat1|cat2|cat3|
--------------------------------|----|----|----|
beach holiday                   |    |    |    |
package beach holiday           |    |    |    |
inclusive package beach holiday |    |    |    |
</code>```

I run a method find_keywords(Keyword) which passes in the Key word e.g. "inclusive package beach holiday" which compares against a text list of categories and returns the first three relevant categories.

```<code>'''
Input a Keyword, breaks it down and finds which category it matches
'''
def find_keywords(keywords):
words = keywords.split()
wordlist = []
for word in words:
    if word in categories:
        wordlist.append(word)
wordlist = wordlist [:3]
return wordlist
</code>```

In this case:

```<code>['inclusive','package','beach']
</code>```

this is all fine and when i run my main method on the data

```<code>if __name__ == '__main__':

df = get_csv(csv)

for index, row in df.iterrows():
    row['Keyword'].lower()
    print(row['Keyword'])
    tokens = find_keywords(row['Keyword'])
    print(tokens)
</code>```

it returns:

```<code>beach holiday
['beach','holiday']
package beach holiday
['package','beach','holiday']
inclusive package beach holiday
['inclusive','package','beach']
</code>```

How would i take the list for each and add it to the cat1/cat2/cat3 column

producing the dataframe:

```<code>Keyword                         |cat1   |cat2    |cat3   |
--------------------------------|----   |----    |----   |
beach holiday                   |beach  |holiday |       |
package beach holiday           |package|beach   |holiday|
inclusive package beach holiday |inclusive|package|beach |
</code>```

Using @DaFanat's solution I was able to get what i asked for however I have a slight permutation on this, would it be possible check against a dictionary instead of a list?

e.g

```<code>{'beach': ['beach', 'sand', 'coast'],
'hotel': ['hotel', 'resort']}
</code>```

and then apply the head term to the category, e.g if it found sand it would mark it beach.

My attempt:
    if name == 'main':

```<code>df = get_csv(csv)
h = open('head_categories.txt','r')
mydict = h.read()
mydict = ast.literal_eval(mydict)

for key in mydict.keys():
    item = key
    if item in mydict[key]:
        target_cats = item
        find_keywords = lambda kw: [s for s in kw.split() if s in target_cats]

        df.loc[:, 'cat_list'] = df['Keyword'].apply(lambda x: find_keywords(x))
        for i in range(1, 4):
            df.loc[:, 'cat{0}'.format(i)] = df['cat_list'].apply(lambda x: x[i-1] if len(x) >= i else '')

print(df)
df.to_csv('kuoniTesting.csv')
</code>```

答:
I think this can do the job:</p>

```<code>target_cats = ['cat', 'dog', 'cow']
df = pd.DataFrame({'Keyword': ['cat dog cow', 'cat dog', 'dog sheep']})
find_keywords = lambda kw: [s for s in kw.split() if s in target_cats]

df.loc[:, 'cat_list'] = df['Keyword'].apply(lambda x: find_keywords(x))
for i in range(1, 4):
    df.loc[:, 'cat{0}'.format(i)] = df['cat_list'].apply(lambda x: x[i-1] if len(x) >= i else '')

     Keyword      cat_list         cat1 cat2 cat3
  0  cat dog cow  [cat, dog, cow]  cat  dog  cow
  1      cat dog       [cat, dog]  cat  dog
  2    dog sheep            [dog]  dog
</code>```

Body:
I am trying to change an element in a large dataframe

e.g

Keyword                         |cat1|cat2|cat3|
--------------------------------|----|----|----|
beach holiday                   |    |    |    |
package beach holiday           |    |    |    |
inclusive package beach holiday |    |    |    |

I run a method find_keywords(Keyword) which passes in the Key word e.g. "inclusive package beach holiday" which compares against a text list of categories and returns the first three relevant categories.

'''
Input a Keyword, breaks it down and finds which category it matches
'''
def find_keywords(keywords):
words = keywords.split()
wordlist = []
for word in words:
    if word in categories:
        wordlist.append(word)
wordlist = wordlist [:3]
return wordlist

In this case:

['inclusive','package','beach']

this is all fine and when i run my main method on the data

if __name__ == '__main__':

df = get_csv(csv)

for index, row in df.iterrows():
    row['Keyword'].lower()
    print(row['Keyword'])
    tokens = find_keywords(row['Keyword'])
    print(tokens)

it returns:

beach holiday
['beach','holiday']
package beach holiday
['package','beach','holiday']
inclusive package beach holiday
['inclusive','package','beach']

How would i take the list for each and add it to the cat1/cat2/cat3 column

producing the dataframe:

Keyword                         |cat1   |cat2    |cat3   |
--------------------------------|----   |----    |----   |
beach holiday                   |beach  |holiday |       |
package beach holiday           |package|beach   |holiday|
inclusive package beach holiday |inclusive|package|beach |

Using @DaFanat's solution I was able to get what i asked for however I have a slight permutation on this, would it be possible check against a dictionary instead of a list?

e.g

{'beach': ['beach', 'sand', 'coast'],
'hotel': ['hotel', 'resort']}

and then apply the head term to the category, e.g if it found sand it would mark it beach.

My attempt:
    if name == 'main':

df = get_csv(csv)
h = open('head_categories.txt','r')
mydict = h.read()
mydict = ast.literal_eval(mydict)

for key in mydict.keys():
    item = key
    if item in mydict[key]:
        target_cats = item
        find_keywords = lambda kw: [s for s in kw.split() if s in target_cats]

        df.loc[:, 'cat_list'] = df['Keyword'].apply(lambda x: find_keywords(x))
        for i in range(1, 4):
            df.loc[:, 'cat{0}'.format(i)] = df['cat_list'].apply(lambda x: x[i-1] if len(x) >= i else '')

print(df)
df.to_csv('kuoniTesting.csv')

Body:
I think this can do the job:

target_cats = ['cat', 'dog', 'cow']
df = pd.DataFrame({'Keyword': ['cat dog cow', 'cat dog', 'dog sheep']})
find_keywords = lambda kw: [s for s in kw.split() if s in target_cats]

df.loc[:, 'cat_list'] = df['Keyword'].apply(lambda x: find_keywords(x))
for i in range(1, 4):
    df.loc[:, 'cat{0}'.format(i)] = df['cat_list'].apply(lambda x: x[i-1] if len(x) >= i else '')

     Keyword      cat_list         cat1 cat2 cat3
  0  cat dog cow  [cat, dog, cow]  cat  dog  cow
  1      cat dog       [cat, dog]  cat  dog
  2    dog sheep            [dog]  dog


问:
The onQueryTextSubmit in SearchView is processed twice in Android Java
Why the onQueryTextSubmit method in SearchView is processed twice?
I need one result, how can I do it?

This is my code:

```<code> public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            if (query != null)
                audioRequest(query);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });
    return true;
}
</code>```

答:
Want to search more than 1 word?

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query)
            {return  false; }

```<code>        @Override
        public boolean onQueryTextChange(String newText) {

            newText = newText.toLowerCase();

            final ArrayList<DictObjectModel> filteredList = new ArrayList<DictObjectModel>();

            for (int i = 0; i < wordcombimelist.size(); i++) {

                final String text = wordcombimelist.get(i).toLowerCase();
                if (text.contains(newText)) {

                    filteredList.add(new DictObjectModel(wordcombimelist.get(i),meancombimelist.get(i)));
                }
            }
            adapter = new CustomAdapter(filteredList);
            recyclerView.setAdapter(adapter);

            return true;
        }
    });
</code>```

Body:
Why the onQueryTextSubmit method in SearchView is processed twice?
I need one result, how can I do it?

This is my code:

 public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            if (query != null)
                audioRequest(query);
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });
    return true;
}

Body:
Want to search more than 1 word?

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query)
            {return  false; }

        @Override
        public boolean onQueryTextChange(String newText) {

            newText = newText.toLowerCase();

            final ArrayList<DictObjectModel> filteredList = new ArrayList<DictObjectModel>();

            for (int i = 0; i < wordcombimelist.size(); i++) {

                final String text = wordcombimelist.get(i).toLowerCase();
                if (text.contains(newText)) {

                    filteredList.add(new DictObjectModel(wordcombimelist.get(i),meancombimelist.get(i)));
                }
            }
            adapter = new CustomAdapter(filteredList);
            recyclerView.setAdapter(adapter);

            return true;
        }
    });


问:
Multi column combo box in Kendo for Angular 2
I am trying to create multi-column combo-box in Kendo-Angular 2.I can't find it in the documentation: https://www.telerik.com/kendo-angular-ui/components/dropdowns/ Is this option present in the Kendo support for Angular 2?</p>

答:
The MultiSelect component provides numerous templates, which could be used to control the rendering of the header, footer and the item content. That being said, we can easily achieve different layout using some additional styling.

```<code><kendo-multiselect
    [data]="listItems"
    [(ngModel)]="value"
    [textField]="'text'"
    [valueField]="'value'"
  >
  <ng-template kendoMultiSelectHeaderTemplate>
    <div class="dropdown-header k-widget k-header">
      <span>Value</span>
      <span>Text</span>
    </div>
  </ng-template>
  <ng-template kendoMultiSelectItemTemplate let-dataItem>
    <span class="k-state-default"><h3>{{dataItem.value}}</h3></span>
    <span class="k-state-default"><h3>{{dataItem.text}}</h3></span>
  </ng-template>
</kendo-multiselect>
</code>```

Here is a plunker that demonstrates the templates usage:

http://plnkr.co/edit/BvdyXuQ4TQ5OFwDliqYd?p=preview

Please note, that the component doesn't have table-like layout and you will need to implement it manually. Nevertheless as it is shown in the demo, this shouldn't be a tough task.

Body:
The MultiSelect component provides numerous templates, which could be used to control the rendering of the header, footer and the item content. That being said, we can easily achieve different layout using some additional styling.

<kendo-multiselect
    [data]="listItems"
    [(ngModel)]="value"
    [textField]="'text'"
    [valueField]="'value'"
  >
  <ng-template kendoMultiSelectHeaderTemplate>
    <div class="dropdown-header k-widget k-header">
      <span>Value</span>
      <span>Text</span>
    </div>
  </ng-template>
  <ng-template kendoMultiSelectItemTemplate let-dataItem>
    <span class="k-state-default"><h3>{{dataItem.value}}</h3></span>
    <span class="k-state-default"><h3>{{dataItem.text}}</h3></span>
  </ng-template>
</kendo-multiselect>

Here is a plunker that demonstrates the templates usage:

http://plnkr.co/edit/BvdyXuQ4TQ5OFwDliqYd?p=preview

Please note, that the component doesn't have table-like layout and you will need to implement it manually. Nevertheless as it is shown in the demo, this shouldn't be a tough task.


问:
How to write a List of string arrays to txt file
Is it possible to write a List of string arrays to txt file?

This is my code and I'm not sure how to make the final step. I made a list through which I foreach based on the number the user inputs, and it returns all the values correctly, but I can't seem to be able to save all the data to a txt file.

```<code> static void Main(string[] args)
    {
        Console.WriteLine("Unesi broj:");

        int userNumber = Convert.ToInt32(Console.ReadLine());

        var numberLIst = Enumerable.Range(1,userNumber).ToList();

        string path = @"C:\Users\mcrnic\Desktop\scriptFolder\input.txt";

        List<string[]> listaStringova = new List<string[]>();

        int n = 0;

        foreach (var data in numberLIst)
        {

            n++;

            #region Varijable
            var textBoxNumberRangeFirst = "tbxNumberRangeFirstInput" + data;
            var textBoxNumberRangeSecond = "tbxNumberRangeSecondInput" + data;
            var textBoxNumberRangeThird = "tbxNumberRangeThirdInput" + data;
            var textBoxHomeNumbersFirst = "tbxRangeOfHomeNumbersFirstInput" + data;
            var textBoxHomeNumbersSecond = "tbxRangeOfHomeNumbersSecondInput" + data;
            var textBoxVPNFirst = "tbxRangeOfShortVPNNumbersFirstInput" + data;
            var textBoxVPNSecond = "tbxRangeOfShortVPNNumbersSecondInput" + data;
            var checkBoxNumberTransfer = "cbxNumberTransfer" + data;
            var checkBoxSecretNumber = "cbxSecretNumber" + data;
            var checkBoxSearchByNumber = "cbxSearchByNumber" + data;
            var checkBoxZ1 = "cbxZ1_" + data;
            var checkBoxZ2 = "cbxZ2_" + data;
            var checkBoxZ3 = "cbxZ3_" + data;
            var checkBoxZ4 = "cbxZ4_" + data;
            var checkBoxZ5 = "cbxZ5_" + data;
            var checkBoxZ6 = "cbxZ6_" + data;
            var checkBoxZ7 = "cbxZ7_" + data;
            #endregion

            string[] htmlLinije = {"<%-- Row" + n + " --%>",
                                "<div class=&row rowFullWidth form-inline pb10& hidden>",
                                "<div class=&col-sm-4&>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxNumberRangeFirst + "& class=&form-control textbox-width-25 ml10& ReadOnly=&true& />",
                                "<span class=&pr5 pl5&>/</span><asp:TextBox runat=&server& ID=&" + textBoxNumberRangeSecond +"& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "<span class=&pr5 pl5&>-</span><asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxNumberTransfer + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSecretNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSearchByNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false& />",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& /><span class=&pr10 pl10&>-</span>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& /><span class=&pr10 pl10&>-</span>",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "</div>",
                                "<div class=&col-sm-2&>",
                                "<div class=&pt5&>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ1 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ2 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ3 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ4 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ5 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ6 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ7 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "</div>",
                                "</div>",
                                "</div>",
                                ""
            };

            listaStringova.Add(htmlLinije);
        }

        System.IO.File.WriteAllLines(path, listaStringova);

    }
</code>```

I get this error when I try to WriteAllLines:

Error CS1503  Argument 2: cannot convert from System.Collections.Generic.List to string[]

答:
You can simply use this one line of code :</p>

```<code>System.IO.File.WriteAllLines(path, listaStringova.SelectMany(i => i));
</code>```

Body:
Is it possible to write a List of string arrays to txt file?

This is my code and I'm not sure how to make the final step. I made a list through which I foreach based on the number the user inputs, and it returns all the values correctly, but I can't seem to be able to save all the data to a txt file.

 static void Main(string[] args)
    {
        Console.WriteLine("Unesi broj:");

        int userNumber = Convert.ToInt32(Console.ReadLine());

        var numberLIst = Enumerable.Range(1,userNumber).ToList();

        string path = @"C:\Users\mcrnic\Desktop\scriptFolder\input.txt";

        List<string[]> listaStringova = new List<string[]>();

        int n = 0;

        foreach (var data in numberLIst)
        {

            n++;

            #region Varijable
            var textBoxNumberRangeFirst = "tbxNumberRangeFirstInput" + data;
            var textBoxNumberRangeSecond = "tbxNumberRangeSecondInput" + data;
            var textBoxNumberRangeThird = "tbxNumberRangeThirdInput" + data;
            var textBoxHomeNumbersFirst = "tbxRangeOfHomeNumbersFirstInput" + data;
            var textBoxHomeNumbersSecond = "tbxRangeOfHomeNumbersSecondInput" + data;
            var textBoxVPNFirst = "tbxRangeOfShortVPNNumbersFirstInput" + data;
            var textBoxVPNSecond = "tbxRangeOfShortVPNNumbersSecondInput" + data;
            var checkBoxNumberTransfer = "cbxNumberTransfer" + data;
            var checkBoxSecretNumber = "cbxSecretNumber" + data;
            var checkBoxSearchByNumber = "cbxSearchByNumber" + data;
            var checkBoxZ1 = "cbxZ1_" + data;
            var checkBoxZ2 = "cbxZ2_" + data;
            var checkBoxZ3 = "cbxZ3_" + data;
            var checkBoxZ4 = "cbxZ4_" + data;
            var checkBoxZ5 = "cbxZ5_" + data;
            var checkBoxZ6 = "cbxZ6_" + data;
            var checkBoxZ7 = "cbxZ7_" + data;
            #endregion

            string[] htmlLinije = {"<%-- Row" + n + " --%>",
                                "
",
                                "
",
                                "<asp:TextBox runat=&server& ID=&" + textBoxNumberRangeFirst + "& class=&form-control textbox-width-25 ml10& ReadOnly=&true& />",
                                "/<asp:TextBox runat=&server& ID=&" + textBoxNumberRangeSecond +"& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "-<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-25& ReadOnly=&true&/>",
                                "
",
                                "
",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxNumberTransfer + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSecretNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false&/>",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxSearchByNumber + "& AutoPostBack=&false& CssClass=&checkbox pl20 pr15 pt5& Enabled=&false& />",
                                "
",
                                "
",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& />-",
                                "<asp:TextBox runat=&server& ID=&" + textBoxHomeNumbersSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "
",
                                "
",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNFirst + "& class=&form-control textbox-width-40& ReadOnly=&true& />-",
                                "<asp:TextBox runat=&server& ID=&" + textBoxVPNSecond + "& class=&form-control textbox-width-40& ReadOnly=&true& />",
                                "
",
                                "
",
                                "
",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ1 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ2 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ3 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ4 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ5 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ6 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "<asp:CheckBox runat=&server& ID=&" + checkBoxZ7 + "& AutoPostBack=&false& CssClass=&checkbox pr5& Enabled=&false& />",
                                "
",
                                "
",
                                "
",
                                ""
            };

            listaStringova.Add(htmlLinije);
        }

        System.IO.File.WriteAllLines(path, listaStringova);

    }

I get this error when I try to WriteAllLines:

Error CS1503  Argument 2: cannot convert from System.Collections.Generic.List to string[]

Body:
You can simply use this one line of code :

System.IO.File.WriteAllLines(path, listaStringova.SelectMany(i => i));


问:
How to continue using Git on mac after uninstalling Xcode (with Android Studio)?
I have installed Git on my Mac. When I do a "whereis" in my terminal the route is:

```<code>/usr/bin/git
</code>```

I use Android Studio and the GitHub desktop client and had no problems so far.

Previously I had installed Xcode, but I uninstalled it a week ago. Since then, Android Studio does not detect Git, I get the following error:

xcrun: error: active developer path
  ("/Volumes/Vega/Applications/Xcode.app/Contents/Developer") does not
  exist, use xcode-select --switch path/to/Xcode.app to specify the
  Xcode that you wish to use for command line developer tools (or see
  man xcode-select)

Android Studio shows the same executable path to Git
indicating the terminal (/usr/bin/git), but when I click on the "test" button it displays the same error.

I do not handle very well Git from the terminal, always use the desktop client.

What do I have to do to continue using Git on my Android studio (or anywhere) now that I uninstalled Xcode?

I searched for information but I can not fix it.

答:
Try this :</p>

```<code>xcode-select --install
</code>```

Body:
I have installed Git on my Mac. When I do a "whereis" in my terminal the route is:

/usr/bin/git

I use Android Studio and the GitHub desktop client and had no problems so far.

Previously I had installed Xcode, but I uninstalled it a week ago. Since then, Android Studio does not detect Git, I get the following error:

xcrun: error: active developer path
  ("/Volumes/Vega/Applications/Xcode.app/Contents/Developer") does not
  exist, use xcode-select --switch path/to/Xcode.app to specify the
  Xcode that you wish to use for command line developer tools (or see
  man xcode-select)

Android Studio shows the same executable path to Git
indicating the terminal (/usr/bin/git), but when I click on the "test" button it displays the same error.

I do not handle very well Git from the terminal, always use the desktop client.

What do I have to do to continue using Git on my Android studio (or anywhere) now that I uninstalled Xcode?

I searched for information but I can not fix it.

Body:
Try this :

xcode-select --install


问:
What is the keyboard shortcut in Visual Studio Code to pop up the Quick Fix menu?
In the Visual Studio Code IDE, when it red squiggle underlines code, how do you pop up the menu to show "Quick Fix" suggestions and choose one of the suggested fixes to apply to your code? Example of underlined code:

答:
On the Mac, use the Command + . keys to pop up a menu of Quick Fix suggestions.

On Windows, use the Ctrl + . keys.

Then just select the Quick Fix suggestion that you want to apply to your code.

Example on the Mac:


问:
error: method onCreate(Bundle) is already defined in class MainActivity
I'm pretty new to android development. I'm aware I shouldn't use duplicate onCreate(), but I don't know how to do this than. I'm creating two spinners from sqlite database on the same layout.

My code is:

```<code>import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import java.util.ArrayList;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Create DataHelper object and insert some sample data
        DataHelper datahelper = new DataHelper(this);

        datahelper.insertBreed ("Beagle");
        datahelper.insertBreed ("Bulldog");
        datahelper.insertBreed ("Chow Chow");

        // Get sample data from the database and display them in the spinner
        Spinner spinner = (Spinner) findViewById(R.id.spinnerBreeds);
        ArrayList<String> list = datahelper.getAllBreeds();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list);
        spinner.setAdapter(adapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Create DataHelper object and insert some sample data
        DataHelper2 datahelper2 = new DataHelper2(this);

        datahelper2.insertAge("1");
        datahelper2.insertAge ("2");
        datahelper2.insertAge("3");

        // Get sample data from the database and display them in the spinner
        Spinner spinner = (Spinner) findViewById(R.id.spinnerAge);
        ArrayList<String> list = datahelper2.getAllAge();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list);
        spinner.setAdapter(adapter);
    }
}
</code>```

答:
You cannot have 2 override of same method inside your class.

Just copy the code that initialize these 2 spinners from second onCreate() to the first one. Change variable name of spinner and adapter to avoid duplicate. (Ex: spinner -> spinnerBreeds/spinnerAge, datahelper -> breedsDataHelper/ageDataHelper, adapter -> breedsAdapter/ageAdapter)

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Create DataHelper object and insert some sample data
    DataHelper datahelper = new DataHelper(this);
    datahelper.insertBreed ("Beagle");
    datahelper.insertBreed ("Bulldog");
    datahelper.insertBreed ("Chow Chow");

    // Get sample data from the database and display them in the spinner
    Spinner spinnerBreeds= (Spinner) findViewById(R.id.spinnerBreeds);
    ArrayList<String> list = datahelper.getAllBreeds();
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list);
    spinnerBreeds.setAdapter(adapter);

    //Init second spinner
    DataHelper2 datahelper2 = new DataHelper2(this);
    datahelper2.insertAge("1");
    datahelper2.insertAge ("2");
    datahelper2.insertAge("3");

    // Get sample data from the database and display them in the spinner
    Spinner spinnerAge = (Spinner) findViewById(R.id.spinnerAge);
    ArrayList<String> list2 = datahelper2.getAllAge();
    ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list2);
    spinnerAge.setAdapter(adapter2);
}
</code>```

Body:
I'm pretty new to android development. I'm aware I shouldn't use duplicate onCreate(), but I don't know how to do this than. I'm creating two spinners from sqlite database on the same layout.

My code is:

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import java.util.ArrayList;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Create DataHelper object and insert some sample data
        DataHelper datahelper = new DataHelper(this);

        datahelper.insertBreed ("Beagle");
        datahelper.insertBreed ("Bulldog");
        datahelper.insertBreed ("Chow Chow");

        // Get sample data from the database and display them in the spinner
        Spinner spinner = (Spinner) findViewById(R.id.spinnerBreeds);
        ArrayList<String> list = datahelper.getAllBreeds();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list);
        spinner.setAdapter(adapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Create DataHelper object and insert some sample data
        DataHelper2 datahelper2 = new DataHelper2(this);

        datahelper2.insertAge("1");
        datahelper2.insertAge ("2");
        datahelper2.insertAge("3");

        // Get sample data from the database and display them in the spinner
        Spinner spinner = (Spinner) findViewById(R.id.spinnerAge);
        ArrayList<String> list = datahelper2.getAllAge();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list);
        spinner.setAdapter(adapter);
    }
}

Body:
You cannot have 2 override of same method inside your class.

Just copy the code that initialize these 2 spinners from second onCreate() to the first one. Change variable name of spinner and adapter to avoid duplicate. (Ex: spinner -> spinnerBreeds/spinnerAge, datahelper -> breedsDataHelper/ageDataHelper, adapter -> breedsAdapter/ageAdapter)

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

    // Create DataHelper object and insert some sample data
    DataHelper datahelper = new DataHelper(this);
    datahelper.insertBreed ("Beagle");
    datahelper.insertBreed ("Bulldog");
    datahelper.insertBreed ("Chow Chow");

    // Get sample data from the database and display them in the spinner
    Spinner spinnerBreeds= (Spinner) findViewById(R.id.spinnerBreeds);
    ArrayList<String> list = datahelper.getAllBreeds();
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list);
    spinnerBreeds.setAdapter(adapter);

    //Init second spinner
    DataHelper2 datahelper2 = new DataHelper2(this);
    datahelper2.insertAge("1");
    datahelper2.insertAge ("2");
    datahelper2.insertAge("3");

    // Get sample data from the database and display them in the spinner
    Spinner spinnerAge = (Spinner) findViewById(R.id.spinnerAge);
    ArrayList<String> list2 = datahelper2.getAllAge();
    ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list2);
    spinnerAge.setAdapter(adapter2);
}


问:
pushViewController not working in xib in swift
I'm using a xibs and swift, is there a way i can use pushViewController to go to another view and come back programatically ?

Error: fatal error: unexpectedly found nil while unwrapping an Optional value

Things i've tried:

Setting it to root view doesn't allow to go back

2.

```<code>let rvc: LoginViewController = LoginViewController()
self.navigationController!.pushViewController(rvc, animated: true)
</code>```

And if i change from navigationController! to navigationController? nothing happens

答:
Try This, I have face error message while push to view controller,

Error: fatal error: unexpectedly found nil while unwrapping an Optional value

Before push to view controller we have to do initialisation of window as mention in below code

```<code>   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

   // Do initialisation of window to avoid error message

    self.window = UIWindow(frame: UIScreen.main.bounds);
    let vc = HomeViewController(nibName: "HomeViewController", bundle: nil)
    nav.pushViewController(vc, animated: false)
    // Set the window’s root view controller
    self.window!.rootViewController = nav
    // Present the window
    self.window!.makeKeyAndVisible()
    return true
    }
</code>```

Body:
I'm using a xibs and swift, is there a way i can use pushViewController to go to another view and come back programatically ?

Error: fatal error: unexpectedly found nil while unwrapping an Optional value

Things i've tried:

Setting it to root view doesn't allow to go back

2.

let rvc: LoginViewController = LoginViewController()
self.navigationController!.pushViewController(rvc, animated: true)

And if i change from navigationController! to navigationController? nothing happens

Body:
Try This, I have face error message while push to view controller,

Error: fatal error: unexpectedly found nil while unwrapping an Optional value

Before push to view controller we have to do initialisation of window as mention in below code

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

   // Do initialisation of window to avoid error message

    self.window = UIWindow(frame: UIScreen.main.bounds);
    let vc = HomeViewController(nibName: "HomeViewController", bundle: nil)
    nav.pushViewController(vc, animated: false)
    // Set the window’s root view controller
    self.window!.rootViewController = nav
    // Present the window
    self.window!.makeKeyAndVisible()
    return true
    }


问:
How can I add a badge to a standard UIButton?
Is it possible to add a standard-looking badge to a standard UIButton?

If it's not supported semi-natively, what would be the simplest way to achieve this?

Example image:

答:
Here's a VERY NICE class by Sascha Paulus called CustomBadge, that builds and renders custom badges using Core Graphics. They're just UIView subclasses, so you lay them out using their frame just like any other UIView subclass.

I've used this library many times and always been pleased with the results. Flexible, easy to use. Totally recommend it.


问:
Elasticsearch: Term search not working on special characters
I am using Elasticsearch latest version 5.6.4. I want to index the special characters and search them for the field title.special. Below is my mappings:

```<code>PUT index1
    {
    "mappings": {
          "isContainer:false": {
            "properties": {
              "connectorSpecific": {
                "properties": {

              "title": {
                "type": "text",
                "store": true,
                "fields": {
                  "special":{
                     "type": "text",
                     "analyzer": "special",
                     "search_analyzer": "special"
                }
                }
              }
            }
          }
        },
        "settings": {
          "index": {
            "analysis": {
              "analyzer": {

                  "special": {
                  "filter": [
                    "lowercase"
                  ],
                  "tokenizer": "whitespace"
                }
              }

            }
            }
            }
          }
        }
      }
</code>```

When I query in Kibana using term query,

```<code>GET index1/_search
{
  "query": {
    "term": {
      "title.special": {
        "value": "-unconstrained_net_use_inf_tw"
      }
    }
  }
}
</code>```

Nothing returns. But when I do a match search, documents do return. for eg.

```<code>GET index1/_search
{
  "query": {
    "match": {
      "title.special": {
        "value": "-unconstrained_net_use_inf_tw"
      }
    }
  }
}
</code>```

Is there something wrong in my mappings? How to make term query work on special characters like *,-,+ etc. Any help is appreciated

答:
the term query works with the keyword datatype. title.special is a text datatype.to make term query work you have to change your title.special mapping
Take a look here, the section called Why doesn’t the term query match my document?
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-term-query.html</p>

Body:
I am using Elasticsearch latest version 5.6.4. I want to index the special characters and search them for the field title.special. Below is my mappings:

PUT index1
    {
    "mappings": {
          "isContainer:false": {
            "properties": {
              "connectorSpecific": {
                "properties": {

              "title": {
                "type": "text",
                "store": true,
                "fields": {
                  "special":{
                     "type": "text",
                     "analyzer": "special",
                     "search_analyzer": "special"
                }
                }
              }
            }
          }
        },
        "settings": {
          "index": {
            "analysis": {
              "analyzer": {

                  "special": {
                  "filter": [
                    "lowercase"
                  ],
                  "tokenizer": "whitespace"
                }
              }

            }
            }
            }
          }
        }
      }

When I query in Kibana using term query,

GET index1/_search
{
  "query": {
    "term": {
      "title.special": {
        "value": "-unconstrained_net_use_inf_tw"
      }
    }
  }
}

Nothing returns. But when I do a match search, documents do return. for eg.

GET index1/_search
{
  "query": {
    "match": {
      "title.special": {
        "value": "-unconstrained_net_use_inf_tw"
      }
    }
  }
}

Is there something wrong in my mappings? How to make term query work on special characters like *,-,+ etc. Any help is appreciated


问:
Setting reducer type in cascading
How would you set different type of reducers in cascading for output for HadoopFlowConnector? In all tutorials we only see the default TextDelimited being used. </p>

答: I am little confused by the terms reducer and output which you have used here. If you are asking what else we can use in place of TextDelimited while sinking the output in cascading then I can say that : TextDelimited is a type of Scheme in cascading and other schemes which are present SequenceFile, TextLine, AvroScheme. You can use one as per your data and requirement. By using any of these scheme you can make your Tap and connect the tail of output to it.</p>

Title: Setting reducer type in cascading


问:
How can I set big array size in pascal?
I need to create an array in pascal with an enormous size, is such thing possible ?
I know the size number, I mean it's not n or unknown, it's just a really really big number:

2 ^ 255

Can I do that or not ? and if not is there any other way I can make something like that happen ?
Thanks in advance

Update:
The peoblem I'm trying to solve is, by giving a number between 1 to 255 (including 1 & 255), I need to print all Gray Code with length of that number, for example:
giving n=2 the program should print:
00, 01, 11, 10

since I have the max number of size that I can enter I assumed I'd make an array with the max number, the thing is maybe I can solve this with recursion, but I;m very new to pascal so I don't know how can I do that (at least not yet)

here's what I meant:
type arr = array[1..255,1..MAXINT] of integer;

hints and tips can be very helpful <3

答:
I guess it is an XY problem. Is seems useless to store such a big ammount of data in an array instead of fetching it on demand.

Here are the reasons:

The supposed array must be populated programmatically (a human being is unable to populate such an array manually) and this means you definitely have an algorithm for that purpose.

How will you allocate 10^64 GB (calculated by @Alex-K) of memory to store all this data?

Windows 7/8 Ultimate x64 has a maximum RAM limit of 192 GB and 512 GB respectively (for x32 - 4 GB only).

How much time you think it will take to initialize this array and assign values to its memebers?

Conclusion:

Why not to use a function Foo(const bt:byte; const it: cardinal): integer; intended to populate the array for the purpose of fetching the necessary values? You will fetch the data from something like Foo(100 ,32000) instead of MyArray[100, 32000].

If you have some exclusions (values that are different from those calculated by Foo changed at runtime by your user) you can ever store them in an array of TMyRec (or TList) where TMyRec = record Val: integer; Bt: byte; It: cardinal; end;.

Title: How can I set big array size in pascal?


问:
C# call nav web service without adding a web reference
I am working on a project that requires me to connect to a Microsoft Dynamics NAV web service, and get some data. However, we do not have access to this web service from the development environment, so I am unable to add a Web Reference to my project, in the usual way.

Is there a way, to "dynamically" connect to the web reference, in run-time, by providing URL, user, password & domain? Then create dynamic objects, and call the methods of the web service? (So I would make a console application, that only runs on the production environment, because there's the access to the web service)

From my initial research I found a couple of ways, where there's a function, that returns object type objects. I usually have credential problems with this : Unauthorized access (401)

I am very new to these web services, by the way...

Method i've been using so far, without any luck:

```<code>internal static object CallWebService(string webServiceAsmxUrl, string serviceName, string methodName, object[] args)

    {
        System.Net.WebClient client = new System.Net.WebClient();
        CredentialCache cc = new CredentialCache();
        cc.Add(
            new Uri(webServiceAsmxUrl),
            "NTLM",
            new NetworkCredential("user", "password", "domain"));
        client.Credentials = cc;
        // Connect To the web service
        System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");

        // Now read the WSDL file describing a service.
        ServiceDescription description = ServiceDescription.Read(stream);
        ///// LOAD THE DOM /////////

        // Initialize a service description importer.

        ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

        importer.ProtocolName = "Soap12"; // Use SOAP 1.2.

        importer.AddServiceDescription(description, null, null);

        // Generate a proxy client.

        importer.Style = ServiceDescriptionImportStyle.Client;

        // Generate properties to represent primitive values.

        importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

        // Initialize a Code-DOM tree into which we will import the service.

        CodeNamespace nmspace = new CodeNamespace();

        CodeCompileUnit unit1 = new CodeCompileUnit();

        unit1.Namespaces.Add(nmspace);

        // Import the service into the Code-DOM tree. This creates proxy code that uses the service.

        ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);

        //THIS IS WHERE IT's NOT COMPLYING. warning will be "NoGeneratedCode"
        if (warning == 0) // If zero then we are good to go

        {

            // Generate the proxy code

            CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");

            // Compile the assembly proxy with the appropriate references

            string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" };

            CompilerParameters parms = new CompilerParameters(assemblyReferences);

            CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);

            // Check For Errors
            if (results.Errors.Count > 0)

            {

                foreach (CompilerError oops in results.Errors)

                {

                    System.Diagnostics.Debug.WriteLine("========Compiler error============");

                    System.Diagnostics.Debug.WriteLine(oops.ErrorText);

                }

                throw new System.Exception("Compile Error Occured calling webservice. Check Debug ouput window.");

            }

            // Finally, Invoke the web service method

            object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);

            MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);

            return mi.Invoke(wsvcClass, args);

        }

        else

        {

            return null;

        }

    }
</code>```

It always returns null.

答:
I know it's an old post but I just stumbled across the exact same issue. I fixed it by changing

```<code>importer.ProtocolName = "Soap12"; // Use SOAP 1.2.
</code>```

to

```<code>importer.ProtocolName = "Soap"; // Woohoo
</code>```

The allowed values for the ProtocolName are:

"Soap"

"Soap12"

"HttpPost"

"HttpGet"

"HttpSoap"

as per the documentation.

Hope that helps someone who comes across a similar issue!

Body:
I am working on a project that requires me to connect to a Microsoft Dynamics NAV web service, and get some data. However, we do not have access to this web service from the development environment, so I am unable to add a Web Reference to my project, in the usual way.

Is there a way, to "dynamically" connect to the web reference, in run-time, by providing URL, user, password & domain? Then create dynamic objects, and call the methods of the web service? (So I would make a console application, that only runs on the production environment, because there's the access to the web service)

From my initial research I found a couple of ways, where there's a function, that returns object type objects. I usually have credential problems with this : Unauthorized access (401)

I am very new to these web services, by the way...

Method i've been using so far, without any luck:

internal static object CallWebService(string webServiceAsmxUrl, string serviceName, string methodName, object[] args)

    {
        System.Net.WebClient client = new System.Net.WebClient();
        CredentialCache cc = new CredentialCache();
        cc.Add(
            new Uri(webServiceAsmxUrl),
            "NTLM",
            new NetworkCredential("user", "password", "domain"));
        client.Credentials = cc;
        // Connect To the web service
        System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");

        // Now read the WSDL file describing a service.
        ServiceDescription description = ServiceDescription.Read(stream);
        ///// LOAD THE DOM /////////

        // Initialize a service description importer.

        ServiceDescriptionImporter importer = new ServiceDescriptionImporter();

        importer.ProtocolName = "Soap12"; // Use SOAP 1.2.

        importer.AddServiceDescription(description, null, null);

        // Generate a proxy client.

        importer.Style = ServiceDescriptionImportStyle.Client;

        // Generate properties to represent primitive values.

        importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

        // Initialize a Code-DOM tree into which we will import the service.

        CodeNamespace nmspace = new CodeNamespace();

        CodeCompileUnit unit1 = new CodeCompileUnit();

        unit1.Namespaces.Add(nmspace);

        // Import the service into the Code-DOM tree. This creates proxy code that uses the service.

        ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);

        //THIS IS WHERE IT's NOT COMPLYING. warning will be "NoGeneratedCode"
        if (warning == 0) // If zero then we are good to go

        {

            // Generate the proxy code

            CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");

            // Compile the assembly proxy with the appropriate references

            string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" };

            CompilerParameters parms = new CompilerParameters(assemblyReferences);

            CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);

            // Check For Errors
            if (results.Errors.Count > 0)

            {

                foreach (CompilerError oops in results.Errors)

                {

                    System.Diagnostics.Debug.WriteLine("========Compiler error============");

                    System.Diagnostics.Debug.WriteLine(oops.ErrorText);

                }

                throw new System.Exception("Compile Error Occured calling webservice. Check Debug ouput window.");

            }

            // Finally, Invoke the web service method

            object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);

            MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);

            return mi.Invoke(wsvcClass, args);

        }

        else

        {

            return null;

        }

    }

It always returns null.

Body:
I know it's an old post but I just stumbled across the exact same issue. I fixed it by changing

importer.ProtocolName = "Soap12"; // Use SOAP 1.2.

to

importer.ProtocolName = "Soap"; // Woohoo

The allowed values for the ProtocolName are:

"Soap"

"Soap12"

"HttpPost"

"HttpGet"

"HttpSoap"

as per the documentation.

Hope that helps someone who comes across a similar issue!


问:
Ignore part of a string when splitting using regular expression in R
I'm trying to split a string in R (using strsplit) at some specific points (dash, -) however not if the dash are within a string in brackets ([).

Example:

```<code>xx <- c("Radio Stations-Listened to Past Week-Toronto [FM-CFXJ-93.5 (93.5 The Move)]","Total Internet-Time Spent Online-Past 7 Days")
xx
  [1] "Radio Stations-Listened to Past Week-Toronto [FM-CFXJ-93.5 (93.5 The Move)]"
  [2] "Total Internet-Time Spent Online-Past 7 Days"
</code>```

should give me something like:

```<code>list(c("Radio Stations","Listened to Past Week","Toronto [FM-CFXJ-93.5 (93.5 The Move)]"), c("Total Internet","Time Spent Online","Past 7 Days"))
  [[1]]
  [1] "Radio Stations"                         "Listened to Past Week"
  [3] "Toronto [FM-CFXJ-93.5 (93.5 The Move)]"

  [[2]]
  [1] "Total Internet"    "Time Spent Online" "Past 7 Days"
</code>```

Is there a way with regular expression to do this?  The position and the number of dashs change within each elements of the vector, and there is not always brackets.  However, when there are brackets, they are always at the end.

I've tried different things, but none are working:

```<code>## Trying to match "-" before "[" in Perl
strsplit(xx, split = "-(?=\\[)", perl=T)
# does nothing

## trying to first extract what follow "[" then splitting what is preceding that
temp <- strsplit(xx, "[", fixed = T)
temp <- lapply(temp, function(yy) substr(head(yy, -1),"-"))
# doesn't work as there are some elements with no brackets...
</code>```

Any help would be appreciated.

答:
Based on: Regex for matching a character, but not when it's enclosed in square bracket

You can use:

```<code>strsplit(xx, "-(?![^\\[]*\\])", perl = TRUE)
[[1]]
[1] "Radio Stations"                         "Listened to Past Week"
[3] "Toronto [FM-CFXJ-93.5 (93.5 The Move)]"

[[2]]
[1] "Total Internet"    "Time Spent Online" "Past 7 Days"
</code>```

Body:
I'm trying to split a string in R (using strsplit) at some specific points (dash, -) however not if the dash are within a string in brackets ([).

Example:

xx <- c("Radio Stations-Listened to Past Week-Toronto [FM-CFXJ-93.5 (93.5 The Move)]","Total Internet-Time Spent Online-Past 7 Days")
xx
  [1] "Radio Stations-Listened to Past Week-Toronto [FM-CFXJ-93.5 (93.5 The Move)]"
  [2] "Total Internet-Time Spent Online-Past 7 Days"

should give me something like:

list(c("Radio Stations","Listened to Past Week","Toronto [FM-CFXJ-93.5 (93.5 The Move)]"), c("Total Internet","Time Spent Online","Past 7 Days"))
  [[1]]
  [1] "Radio Stations"                         "Listened to Past Week"
  [3] "Toronto [FM-CFXJ-93.5 (93.5 The Move)]"

  [[2]]
  [1] "Total Internet"    "Time Spent Online" "Past 7 Days"

Is there a way with regular expression to do this?  The position and the number of dashs change within each elements of the vector, and there is not always brackets.  However, when there are brackets, they are always at the end.

I've tried different things, but none are working:

## Trying to match "-" before "[" in Perl
strsplit(xx, split = "-(?=\\[)", perl=T)
# does nothing

## trying to first extract what follow "[" then splitting what is preceding that
temp <- strsplit(xx, "[", fixed = T)
temp <- lapply(temp, function(yy) substr(head(yy, -1),"-"))
# doesn't work as there are some elements with no brackets...

Any help would be appreciated.

Body:
Based on: Regex for matching a character, but not when it's enclosed in square bracket

You can use:

strsplit(xx, "-(?![^\\[]*\\])", perl = TRUE)
[[1]]
[1] "Radio Stations"                         "Listened to Past Week"
[3] "Toronto [FM-CFXJ-93.5 (93.5 The Move)]"

[[2]]
[1] "Total Internet"    "Time Spent Online" "Past 7 Days"