问:
How to convert this jquery code into javascript DOM code?
Hi everyone I was just wondering if anyone know how to convert this css/jquery code into javascript DOM code?

I started coding my entire code using javascript DOM for a project but then I found this code which will make the background image move upwards in an infinite loop.

I just need some help in figuring out how to convert the code since I know nothing about jquery.

    $(function(){
            var x = 0;
            setInterval(function(){
                $('body').css('background-position','0'+--x + 'px');
            }, 10);
    })```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    html,body {    height: 100%; overflow: hidden;}
    body {
        background-image: url('http://lorempixel.com/1900/1200/');
        background-repeat: repeat-y;
        background-size: 100% 100%;
    }</code>```

```<code>html,body {    height: 100%; overflow: hidden;}
body {
    background-image: url('http://lorempixel.com/1900/1200/');
    background-repeat: repeat-y;
    background-size: 100% 100%;
}

$(function(){
        var x = 0;
        setInterval(function(){
            $('body').css('background-position','0'+--x + 'px');
        }, 10);
})
</code>```

答:
$('body') selects the body element; .css(prop, value) sets the CSS property prop to value. With the plain DOM API, you can get the body using document.body and assign styles by assigning to properties on the element’s style, noting that hyphenated-names become camelCase.

```<code>var x = 0;

setInterval(function () {
    document.body.style.backgroundPosition = '0 ' + --x + 'px';
}, 10);
</code>```

Body:
Hi everyone I was just wondering if anyone know how to convert this css/jquery code into javascript DOM code?

I started coding my entire code using javascript DOM for a project but then I found this code which will make the background image move upwards in an infinite loop.

I just need some help in figuring out how to convert the code since I know nothing about jquery.

    $(function(){
            var x = 0;
            setInterval(function(){
                $('body').css('background-position','0'+--x + 'px');
            }, 10);
    })

    html,body {    height: 100%; overflow: hidden;}
    body {
        background-image: url('http://lorempixel.com/1900/1200/');
        background-repeat: repeat-y;
        background-size: 100% 100%;
    }

html,body {    height: 100%; overflow: hidden;}
body {
    background-image: url('http://lorempixel.com/1900/1200/');
    background-repeat: repeat-y;
    background-size: 100% 100%;
}

$(function(){
        var x = 0;
        setInterval(function(){
            $('body').css('background-position','0'+--x + 'px');
        }, 10);
})

Body:
$('body') selects the body element; .css(prop, value) sets the CSS property prop to value. With the plain DOM API, you can get the body using document.body and assign styles by assigning to properties on the element’s style, noting that hyphenated-names become camelCase.

var x = 0;

setInterval(function () {
    document.body.style.backgroundPosition = '0 ' + --x + 'px';
}, 10);


来源: stackexchange

问:
F#, implement fold3, fold4, fold_n
I am interested to implement fold3, fold4 etc., similar to List.fold and List.fold2. e.g.

```<code>// TESTCASE
let polynomial (x:double) a b c = a*x + b*x*x + c*x*x*x
let A = [2.0; 3.0; 4.0; 5.0]
let B = [1.5; 1.0; 0.5; 0.2]
let C = [0.8; 0.01; 0.001; 0.0001]

let result = fold3 polynomial 0.7 A B C
// 2.0 * (0.7   ) + 1.5 * (0.7   )^2 + 0.8    * (0.7   )^3 -> 2.4094
// 3.0 * (2.4094) + 1.0 * (2.4094)^2 + 0.01   * (2.4094)^3 -> 13.173
// 4.0 * (13.173) + 0.5 * (13.173)^2 + 0.001  * (13.173)^3 -> 141.75
// 5.0 * (141.75) + 0.2 * (141.75)^2 + 0.0001 * (141.75)^3 -> 5011.964
//
// Output: result = 5011.964
</code>```

My first method is grouping the 3 lists A, B, C, into a list of tuples, and then apply list.fold

```<code>let fold3 f x A B C =
    List.map3 (fun a b c -> (a,b,c)) A B C
       |> List.fold (fun acc (a,b,c) -> f acc a b c) x

// e.g. creates [(2.0,1.5,0.8);  (3.0,1.0,0.01); ......]
</code>```

My second method is to declare a mutable data, and use List.map3

```<code>let mutable result = 0.7
List.map3 (fun a b c ->
               result <- polynomial result a b c  // Change mutable data
               // Output intermediate data
               result) A B C
// Output from List.map3: [2.4094; 13.17327905; 141.7467853; 5011.963942]
// result mutable: 5011.963942
</code>```

I would like to know if there are other ways to solve this problem. Thank you.

答:
You could check the implementation for ideas:

https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/array.fs

```<code>  let fold<'T,'State> (f : 'State -> 'T -> 'State) (acc: 'State) (array:'T[]) =
        checkNonNull "array" array
        let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)
        let mutable state = acc
        for i = 0 to array.Length-1 do
            state <- f.Invoke(state,array.[i])
        state
</code>```

here's a few implementations for you:

```<code>let fold2<'a,'b,'State> (f : 'State -> 'a -> 'b -> 'State) (acc: 'State) (a:'a array) (b:'b array) =
  let mutable state = acc
  Array.iter2 (fun x y->state<-f state x y) a b
  state

let iter3 f (a: 'a[]) (b: 'b[]) (c: 'c[]) =
  let f = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(f)
  if a.Length <> b.Length || a.Length <> c.Length then failwithf "length"
  for i = 0 to a.Length-1 do
    f.Invoke(a.[i], b.[i], c.[i])

let altIter3 f (a: 'a[]) (b: 'b[]) (c: 'c[]) =
  if a.Length <> b.Length || a.Length <> c.Length then failwithf "length"
  for i = 0 to a.Length-1 do
    f (a.[i]) (b.[i]) (c.[i])

let fold3<'a,'b,'State> (f : 'State -> 'a -> 'b -> 'c -> 'State) (acc: 'State) (a:'a array) (b:'b array) (c:'c array) =
  let mutable state = acc
  iter3 (fun x y z->state<-f state x y z) a b c
  state
</code>```

NB. we don't have an iter3, so, implement that. OptimizedClosures.FSharpFunc only allow up to 5 (or is it 7?) params. There are a finite number of type slots available. It makes sense. You can go higher than this, of course, without using the OptimizedClosures stuff.

... anyway, generally, you don't want to be iterating too many lists / arrays / sequences at once. So I'd caution against going too high.

... the better way forward in such cases may be to construct a record or tuple from said lists / arrays, first. Then, you can just use map and iter, which are already baked in. This is what zip / zip3 are all about (see: "(array1.[i],array2.[i],array3.[i])")

```<code>    let zip3 (array1: _[]) (array2: _[]) (array3: _[]) =
        checkNonNull "array1" array1
        checkNonNull "array2" array2
        checkNonNull "array3" array3
        let len1 = array1.Length
        if len1 <> array2.Length || len1 <> array3.Length then invalidArg3ArraysDifferent "array1" "array2" "array3" len1 array2.Length array3.Length
        let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked len1
        for i = 0 to res.Length-1 do
            res.[i] <- (array1.[i],array2.[i],array3.[i])
        res
</code>```

I'm working with arrays at the moment, so my solution pertained to those. Sorry about that. Here's a recursive version for lists.

```<code>let fold3 f acc a b c =
  let mutable state = acc
  let rec fold3 f a b c =
    match a,b,c with
    | [],[],[] -> ()
    | [],_,_
    | _,[],_
    | _,_,[] -> failwith "length"
    | ahead::atail, bhead::btail, chead::ctail ->
        state <- f state ahead bhead chead
        fold3 f atail btail ctail
    fold3 f a b c
</code>```

i.e. we define a recursive function within a function which acts upon/mutates/changes the outer scoped mutable acc variable (a closure in functional speak). Finally, this gets returned.

It's pretty cool how much type information gets inferred about these functions. In the array examples above, mostly I was explicit with 'a 'b 'c. This time, we let type inference kick in. It knows we're dealing with lists from the :: operator. That's kind of neat.

NB. the compiler will probably unwind this tail-recursive approach so that it is just a loop behind-the-scenes. Generally, get a correct answer before optimising. Just mentioning this, though, as food for later thought.

ContentLicense: CC BY-SA 3.0

Title: F#, implement fold3, fold4, fold_n

Body:
I am interested to implement fold3, fold4 etc., similar to List.fold and List.fold2. e.g.

// TESTCASE
let polynomial (x:double) a b c = a*x + b*x*x + c*x*x*x
let A = [2.0; 3.0; 4.0; 5.0]
let B = [1.5; 1.0; 0.5; 0.2]
let C = [0.8; 0.01; 0.001; 0.0001]

let result = fold3 polynomial 0.7 A B C
// 2.0 * (0.7   ) + 1.5 * (0.7   )^2 + 0.8    * (0.7   )^3 -> 2.4094
// 3.0 * (2.4094) + 1.0 * (2.4094)^2 + 0.01   * (2.4094)^3 -> 13.173
// 4.0 * (13.173) + 0.5 * (13.173)^2 + 0.001  * (13.173)^3 -> 141.75
// 5.0 * (141.75) + 0.2 * (141.75)^2 + 0.0001 * (141.75)^3 -> 5011.964
//
// Output: result = 5011.964

My first method is grouping the 3 lists A, B, C, into a list of tuples, and then apply list.fold

let fold3 f x A B C =
    List.map3 (fun a b c -> (a,b,c)) A B C
       |> List.fold (fun acc (a,b,c) -> f acc a b c) x

// e.g. creates [(2.0,1.5,0.8);  (3.0,1.0,0.01); ......]

My second method is to declare a mutable data, and use List.map3

let mutable result = 0.7
List.map3 (fun a b c ->
               result <- polynomial result a b c  // Change mutable data
               // Output intermediate data
               result) A B C
// Output from List.map3: [2.4094; 13.17327905; 141.7467853; 5011.963942]
// result mutable: 5011.963942

I would like to know if there are other ways to solve this problem. Thank you.

Body:
You could check the implementation for ideas:

https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/array.fs

  let fold<'T,'State> (f : 'State -> 'T -> 'State) (acc: 'State) (array:'T[]) =
        checkNonNull "array" array
        let f = OptimizedClosures.FSharpFunc<_,_,_>.Adapt(f)
        let mutable state = acc
        for i = 0 to array.Length-1 do
            state <- f.Invoke(state,array.[i])
        state

here's a few implementations for you:

let fold2<'a,'b,'State> (f : 'State -> 'a -> 'b -> 'State) (acc: 'State) (a:'a array) (b:'b array) =
  let mutable state = acc
  Array.iter2 (fun x y->state<-f state x y) a b
  state

let iter3 f (a: 'a[]) (b: 'b[]) (c: 'c[]) =
  let f = OptimizedClosures.FSharpFunc<_,_,_,_>.Adapt(f)
  if a.Length <> b.Length || a.Length <> c.Length then failwithf "length"
  for i = 0 to a.Length-1 do
    f.Invoke(a.[i], b.[i], c.[i])

let altIter3 f (a: 'a[]) (b: 'b[]) (c: 'c[]) =
  if a.Length <> b.Length || a.Length <> c.Length then failwithf "length"
  for i = 0 to a.Length-1 do
    f (a.[i]) (b.[i]) (c.[i])

let fold3<'a,'b,'State> (f : 'State -> 'a -> 'b -> 'c -> 'State) (acc: 'State) (a:'a array) (b:'b array) (c:'c array) =
  let mutable state = acc
  iter3 (fun x y z->state<-f state x y z) a b c
  state

NB. we don't have an iter3, so, implement that. OptimizedClosures.FSharpFunc only allow up to 5 (or is it 7?) params. There are a finite number of type slots available. It makes sense. You can go higher than this, of course, without using the OptimizedClosures stuff.

... anyway, generally, you don't want to be iterating too many lists / arrays / sequences at once. So I'd caution against going too high.

... the better way forward in such cases may be to construct a record or tuple from said lists / arrays, first. Then, you can just use map and iter, which are already baked in. This is what zip / zip3 are all about (see: "(array1.[i],array2.[i],array3.[i])")

    let zip3 (array1: _[]) (array2: _[]) (array3: _[]) =
        checkNonNull "array1" array1
        checkNonNull "array2" array2
        checkNonNull "array3" array3
        let len1 = array1.Length
        if len1 <> array2.Length || len1 <> array3.Length then invalidArg3ArraysDifferent "array1" "array2" "array3" len1 array2.Length array3.Length
        let res = Microsoft.FSharp.Primitives.Basics.Array.zeroCreateUnchecked len1
        for i = 0 to res.Length-1 do
            res.[i] <- (array1.[i],array2.[i],array3.[i])
        res

I'm working with arrays at the moment, so my solution pertained to those. Sorry about that. Here's a recursive version for lists.

let fold3 f acc a b c =
  let mutable state = acc
  let rec fold3 f a b c =
    match a,b,c with
    | [],[],[] -> ()
    | [],_,_
    | _,[],_
    | _,_,[] -> failwith "length"
    | ahead::atail, bhead::btail, chead::ctail ->
        state <- f state ahead bhead chead
        fold3 f atail btail ctail
    fold3 f a b c

i.e. we define a recursive function within a function which acts upon/mutates/changes the outer scoped mutable acc variable (a closure in functional speak). Finally, this gets returned.

It's pretty cool how much type information gets inferred about these functions. In the array examples above, mostly I was explicit with 'a 'b 'c. This time, we let type inference kick in. It knows we're dealing with lists from the :: operator. That's kind of neat.

NB. the compiler will probably unwind this tail-recursive approach so that it is just a loop behind-the-scenes. Generally, get a correct answer before optimising. Just mentioning this, though, as food for later thought.


问:
Can SpannableString be Serializable?
I want post an object with SpannableString by Intent. I let the object implement Serializable, but it will throw

java.io.NotSerializableException: android.text.SpannableString

So I let SpannableString implement Serializable.

```<code>private class MySpannableString extends SpannableString implements Serializable{
    public MySpannableString(CharSequence source) {
        super(source);
    }
}
</code>```

But I can't get the object in the next Activity.

答:
I have tested pass SpannableString as Serializable but it will throw error in second activity like Can not cast Serializable to SpannableString, null value will return as default. So I think it may impossible.

However we can pass SpannableString by simple way below

First Activity

```<code>SpannableString text == ...;
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("KEY", text);
startActivity(intent);
</code>```

Second Activity

```<code>SpannableString a = (SpannableString). getIntent().getCharSequenceExtra("KEY");
//we can get value because SpannableString implements CharSequence
</code>```

DEMO

Title: Can SpannableString be Serializable?

Body:
I want post an object with SpannableString by Intent. I let the object implement Serializable, but it will throw

java.io.NotSerializableException: android.text.SpannableString

So I let SpannableString implement Serializable.

private class MySpannableString extends SpannableString implements Serializable{
    public MySpannableString(CharSequence source) {
        super(source);
    }
}

But I can't get the object in the next Activity.

Body:
I have tested pass SpannableString as Serializable but it will throw error in second activity like Can not cast Serializable to SpannableString, null value will return as default. So I think it may impossible.

However we can pass SpannableString by simple way below

First Activity

SpannableString text == ...;
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("KEY", text);
startActivity(intent);

Second Activity

SpannableString a = (SpannableString). getIntent().getCharSequenceExtra("KEY");
//we can get value because SpannableString implements CharSequence

DEMO


问:
Azure Virtual Machine not accessible after RDP port changed
I've changed RDP port to 8080 in registry on my Azure Virtual Machine (Windows Server). Now it is not accessible from outside, I cant connect it.

Azure VM is managed by Resource Manager (not Classic VM).

UPDATE:

Turning secuiruty rules so allow all not helped.

答:
It used to be possible to change your RDP port in Classic portal using endpoints. but in RM portal you cannot change your RDP port.

If you are trying to secure your box or by pass the security firewall to connect to your box, I recommend using Azure Load Balancer NAT rules, you can create a NAT rule to translate a custom port to 3389, and then you can only allow connectivity from LB to your VM, this a trick I use when I want to by pass the corporate's firewall, for example port 443.

Make sure you attach the LB to your VM from the NAT rule section


问:
Break error while creating a calendar

Have break error Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode==0x0). No errors with build, just when run, have a break

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let calendars = self.calendars {
        return calendars.count
    }
    return 0

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!
</code>```

//error happens here

```<code>    if self.calendars != nil {
    let calendarName = self.calendars?[(indexPath as NSIndexPath).row].title
        cell.textLabel?.text = calendarName
    } else {
        cell.textLabel?.text = "Unknown Calendar Name"
    }
    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destinationVC = segue.destination as! UINavigationController
    let addCalendarVC = destinationVC.viewControllers[0] as! AddCalendarViewController
    addCalendarVC.delegate = self
}
func calendarDidAdd() {
    self.loadCalendars()
    self.refreshTableView()
}
</code>```

}

答:
```<code>tableView.dequeueReusableCell(withIdentifier: "Cell")!
</code>```

You are unwrapping an optional value which might be nil in the first place. Cell might not have been created yet especially if you haven't registered the cell's class with that identifier so it'll crash first time table tries to populate the cell. You should first check if cell is nil:

```<code>var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
  cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
}
...
</code>```

Title: Break error while creating a calendar

Body:
Have break error Thread 1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode==0x0). No errors with build, just when run, have a break

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let calendars = self.calendars {
        return calendars.count
    }
    return 0

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")!

//error happens here

    if self.calendars != nil {
    let calendarName = self.calendars?[(indexPath as NSIndexPath).row].title
        cell.textLabel?.text = calendarName
    } else {
        cell.textLabel?.text = "Unknown Calendar Name"
    }
    return cell
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let destinationVC = segue.destination as! UINavigationController
    let addCalendarVC = destinationVC.viewControllers[0] as! AddCalendarViewController
    addCalendarVC.delegate = self
}
func calendarDidAdd() {
    self.loadCalendars()
    self.refreshTableView()
}

}

Body:
tableView.dequeueReusableCell(withIdentifier: "Cell")!

You are unwrapping an optional value which might be nil in the first place. Cell might not have been created yet especially if you haven't registered the cell's class with that identifier so it'll crash first time table tries to populate the cell. You should first check if cell is nil:

var cell = tableView.dequeueReusableCell(withIdentifier: "Cell")
if cell == nil {
  cell = UITableViewCell(style: .default, reuseIdentifier: "Cell")
}
...


问:
html reset doesn't work with javascript
I'm having a drop down with onChange event which will call the javascript method.

but when I change to some value and clicking reset , its reset to orignial value, but the onChange javascript event is not calling.

```<code><select onChange="method1()">
<option>....
</select>

<input type="reset" value="reset" />
</code>```

After click the reset button, the value is setting to old value but the onChange event is not working...

答:
I believe you should be using the onchange event. I've never heard of the valueChange event.

Updated for question edit:

You will need to add a method to the onreset event of your form tag in order for you to run Javascript when your reset button is clicked. See here for more info. This is a simple example, which requires two Javascript functions, formReset and selectChanged.

```<code><form onreset="formReset">
    <select id="s" onchange="selectChanged">
        <option>Hello</option>
        <option>World</option>
    </select>
    <input type="reset" />
</form>
</code>```

ContentLicense: CC BY-SA 2.5

Title: html reset doesn't work with javascript

Body:
I'm having a drop down with onChange event which will call the javascript method.

but when I change to some value and clicking reset , its reset to orignial value, but the onChange javascript event is not calling.

<select onChange="method1()">
<option>....
</select>

<input type="reset" value="reset" />

After click the reset button, the value is setting to old value but the onChange event is not working...

Body:
I believe you should be using the onchange event. I've never heard of the valueChange event.

Updated for question edit:

You will need to add a method to the onreset event of your form tag in order for you to run Javascript when your reset button is clicked. See here for more info. This is a simple example, which requires two Javascript functions, formReset and selectChanged.

<form onreset="formReset">
    <select id="s" onchange="selectChanged">
        <option>Hello</option>
        <option>World</option>
    </select>
    <input type="reset" />
</form>


问:
Vue Router and Vuex
I have 2 questions.
1. How can I catch undefined routes and redirect to 404 page?
2. How I can use Vuex actions to get data from api? I know that vuex mutations must be sync and actions async. But I can get data with mutations and can use then promise. but can't in actions or I do anything mistake. Please give me beautiful example for that(component type). I use vuex in laravel mix in Laravel project. Thanks...</p>

答:
Generally speaking, you shouldn't be getting undefined routes if you're defining all of the routes within an app. You can define a redirect in your routes configuration as such:

```<code>[
    {
        path: 'admin/posts/list',
        name: 'post-list',
    },
    {
        path: 'admin/posts',
        redirect: 'admin/posts/list'
    }
]

// you can also redirect to a named route instead
// of a path like this:
{
    path: 'admin/posts',
    redirect: { name: 'post-list' }
}
</code>```

If you wanted to do a "catch all" that grabs any paths not matched and redirect to your 404 component/view, then you could do it like this:

```<code>{
    path: '*',
    redirect: '/404'
}
</code>```

Make sure that is at the bottom of your routes definition as the last route because it will catch any routes in the tree it is above.

As for your question about mutations/actions, asynchronous API requests like fetching data from an API only every happen within actions when you're using Vuex.Taken from the documentation on actions:

```<code>actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}
</code>```

Title: Vue Router and Vuex

Body:
Generally speaking, you shouldn't be getting undefined routes if you're defining all of the routes within an app. You can define a redirect in your routes configuration as such:

[
    {
        path: 'admin/posts/list',
        name: 'post-list',
    },
    {
        path: 'admin/posts',
        redirect: 'admin/posts/list'
    }
]

// you can also redirect to a named route instead
// of a path like this:
{
    path: 'admin/posts',
    redirect: { name: 'post-list' }
}

If you wanted to do a "catch all" that grabs any paths not matched and redirect to your 404 component/view, then you could do it like this:

{
    path: '*',
    redirect: '/404'
}

Make sure that is at the bottom of your routes definition as the last route because it will catch any routes in the tree it is above.

As for your question about mutations/actions, asynchronous API requests like fetching data from an API only every happen within actions when you're using Vuex.Taken from the documentation on actions:

actions: {
  actionA ({ commit }) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        commit('someMutation')
        resolve()
      }, 1000)
    })
  }
}


问:
Setting property value of object in a deep javascript Array
I was wondering if anyone could help figure out how i can set the value of a property in an object which can be found in a deep Array.

Below is an example of the Tree array

I would like to know how i can insert

```<code>var newObjectToInsert = {id: 999, name: 'new name'};
</code>```

in the 'nodes' array of the object whose id === 3901

var tree = [
  {
    id: 1,
    name: 'Level 1 - A',
    nodes: [
      {
        id: 33,
        name: 'Level 2 = A',
        nodes: []
      },

      {
        id: 21,
        name: 'Level 2 = B',
        nodes: []
      }
    ]
  },

  {
    id: 2,
    name: 'Level 1 - B',
    nodes: []
  },

  {
    id: 3,
    name: 'Level 1 - B',
    nodes: [
      {
        id: 65,
        name: 'Level 2 = A',
        nodes: []
      },

      {
        id: 124,
        name: 'Level 2 = A',
        nodes: [
          {
            id: 3901,
            name: 'Level 3 - A'
          },

          {
            id: 29182,
            name: 'Level 3 - B',
            nodes: [
              {
                id: 32423413,
                name: 'Level 4 - A'
              }
            ]
          }
        ]
      },

      {
        id: 534,
        name: 'Level 2 = A',
        nodes: []
      }
    ]
  },
];```

答:
You can use a native Array#some to achieve a recursive traversal. An advantage towards using this approach is it already provides a mechanism to stop the traversal once it finds the node that we want to insert the new object.

```<code>var inserted = tree.some(function cb(v) {
  var nodes = v.nodes || [];
  return v.id === nodeId?
    (v.nodes = nodes).push(newObjectToInsert):
    nodes.some(cb);
});
</code>```

var tree = [{
    id: 1,
    name: 'Level 1 - A',
    nodes: [{
        id: 33,
        name: 'Level 2 = A',
        nodes: []
      },

      {
        id: 21,
        name: 'Level 2 = B',
        nodes: []
      }
    ]
  },

  {
    id: 2,
    name: 'Level 1 - B',
    nodes: []
  },

  {
    id: 3,
    name: 'Level 1 - B',
    nodes: [{
        id: 65,
        name: 'Level 2 = A',
        nodes: []
      },

      {
        id: 124,
        name: 'Level 2 = A',
        nodes: [{
            id: 3901,
            name: 'Level 3 - A'
          },

          {
            id: 29182,
            name: 'Level 3 - B',
            nodes: [{
              id: 32423413,
              name: 'Level 4 - A'
            }]
          }
        ]
      },

      {
        id: 534,
        name: 'Level 2 = A',
        nodes: []
      }
    ]
  },
];

var newObjectToInsert = {id: 999, name: 'new name'};
var nodeId = 3901;

var inserted = tree.some(function cb(v) {
  var nodes = v.nodes || [];
  return v.id === nodeId?
    (v.nodes = nodes).push(newObjectToInsert):
    nodes.some(cb);
});

console.log(tree);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body > div { min-height: 100%; top: 0; }</code>```

```

Body:
I was wondering if anyone could help figure out how i can set the value of a property in an object which can be found in a deep Array.

Below is an example of the Tree array

I would like to know how i can insert

var newObjectToInsert = {id: 999, name: 'new name'};

in the 'nodes' array of the object whose id === 3901

var tree = [
  {
    id: 1,
    name: 'Level 1 - A',
    nodes: [
      {
        id: 33,
        name: 'Level 2 = A',
        nodes: []
      },

      {
        id: 21,
        name: 'Level 2 = B',
        nodes: []
      }
    ]
  },

  {
    id: 2,
    name: 'Level 1 - B',
    nodes: []
  },

  {
    id: 3,
    name: 'Level 1 - B',
    nodes: [
      {
        id: 65,
        name: 'Level 2 = A',
        nodes: []
      },

      {
        id: 124,
        name: 'Level 2 = A',
        nodes: [
          {
            id: 3901,
            name: 'Level 3 - A'
          },

          {
            id: 29182,
            name: 'Level 3 - B',
            nodes: [
              {
                id: 32423413,
                name: 'Level 4 - A'
              }
            ]
          }
        ]
      },

      {
        id: 534,
        name: 'Level 2 = A',
        nodes: []
      }
    ]
  },
];

Body:
You can use a native Array#some to achieve a recursive traversal. An advantage towards using this approach is it already provides a mechanism to stop the traversal once it finds the node that we want to insert the new object.

var inserted = tree.some(function cb(v) {
  var nodes = v.nodes || [];
  return v.id === nodeId?
    (v.nodes = nodes).push(newObjectToInsert):
    nodes.some(cb);
});

var tree = [{
    id: 1,
    name: 'Level 1 - A',
    nodes: [{
        id: 33,
        name: 'Level 2 = A',
        nodes: []
      },

      {
        id: 21,
        name: 'Level 2 = B',
        nodes: []
      }
    ]
  },

  {
    id: 2,
    name: 'Level 1 - B',
    nodes: []
  },

  {
    id: 3,
    name: 'Level 1 - B',
    nodes: [{
        id: 65,
        name: 'Level 2 = A',
        nodes: []
      },

      {
        id: 124,
        name: 'Level 2 = A',
        nodes: [{
            id: 3901,
            name: 'Level 3 - A'
          },

          {
            id: 29182,
            name: 'Level 3 - B',
            nodes: [{
              id: 32423413,
              name: 'Level 4 - A'
            }]
          }
        ]
      },

      {
        id: 534,
        name: 'Level 2 = A',
        nodes: []
      }
    ]
  },
];

var newObjectToInsert = {id: 999, name: 'new name'};
var nodeId = 3901;

var inserted = tree.some(function cb(v) {
  var nodes = v.nodes || [];
  return v.id === nodeId?
    (v.nodes = nodes).push(newObjectToInsert):
    nodes.some(cb);
});

console.log(tree);

body > div { min-height: 100%; top: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>


问:
How to deploy service in Cloud Foundry?
I am a newbie in CloudFoundry and I will appreciate your help.

So, I need to create CF ServiceBroker for our product and I try to figure out how to do it properly.

I've found in the documentation types of deployments:

https://docs.cloudfoundry.org/services/overview.html

The following are examples of valid deployment models.

1) Entire service packaged and deployed by BOSH alongside Cloud Foundry

2) Broker packaged and deployed by BOSH alongside Cloud Foundry, rest of
  the service deployed and maintained by other means.

3) Broker (and optionally service) pushed as an application to Cloud Foundry user space

4) Entire service, including broker, deployed and maintained
  outside of Cloud Foundry by other means

I've seen so far examples of deployment type 3 and 4 - it is obvious - all I need just to implement ServiceBroker API, deploy it and create service broker with the command 'cf create-service-broker'. And with these deployment type, I need to maintain my service back end. For example, if my service provides MongoDB as a service, I need to have the server (for example in Amazon) with installed MongoDB database. And ServiceBroker will delegate all apps there.

But I can't find any examples of 1 and 2 deployment type. As I understood so far the first deployment type allows to deploy ServiceBroker and Service backend on Cloud Foundry. So, with this type, I need not to have the separate server with installed MongoDB, but I can deploy, somehow,  Mongo database to the CloudFoundry.

So, my questions are:

1) is my understanding correct?

2) is there are any examples how to deploy service broker and service backend on CLoudFounry?

Thank you for your help.

答:
1) No, it allows you to deploy your own releases/deployment alongside with CloudFoundry (or on a separate IaaS) using bosh.

The proper question to ask is "How to create a bosh release for my application and service broker with bosh v2 manifest deployment".

2) The best way is to look on existing projects within https://github.com/cloudfoundry and https://github.com/cloudfoundry-community, like https://github.com/cloudfoundry/cf-mysql-deployment and https://github.com/cloudfoundry/cf-mysql-release

More on https://bosh.io/docs#basic-deploy and https://bosh.io/docs/manifest-v2.html

Prepare for a high learning curve.

Title: How to deploy service in Cloud Foundry?


问:
Evaluate string as input keyword in matlab
How to evaluate a string which could be changed dynamically in code? for example:

```<code>A=rand(60, 60);
RangeC='10:end,:';
B=A(RangeC);
</code>```

I know this is quite easy for others, but I have struggled for hours! Thanks in advance!

答:
You can use the eval function but I would suggest to seperate RangeC in two variables like the example below. Also end won't be able to be evaluated so you can use size instead.

```<code>A=rand(60, 60);
RangeC1='10:size(A,1)';
RangeC2='1:size(A,2)';
B=A(eval(RangeC1), eval(RangeC2));
</code>```

Body:
How to evaluate a string which could be changed dynamically in code? for example:

A=rand(60, 60);
RangeC='10:end,:';
B=A(RangeC);

I know this is quite easy for others, but I have struggled for hours! Thanks in advance!

Body:
You can use the eval function but I would suggest to seperate RangeC in two variables like the example below. Also end won't be able to be evaluated so you can use size instead.

A=rand(60, 60);
RangeC1='10:size(A,1)';
RangeC2='1:size(A,2)';
B=A(eval(RangeC1), eval(RangeC2));


问:
Checking if files are empty or not through Linux command line
I want to check with bash script if files with same extensions in a directory empty or not and print out the name of the file if it is not empty.</p>

答:
Job for find (GNU find precisely), assuming the extension to match is .txt, and directory to check is /directory:

```<code>find /directory -maxdepth 1 -type f -name '*.txt' -not -empty
</code>```

Recursively:

```<code>find /directory -type f -name '*.txt' -not -empty
</code>```

Slow shell-way, using for to iterate over the files, and test ([) to check the conditions:

```<code>for f in /directory/*.txt; do [ -f "$f" ] && [ -s "$f" ] && echo "$f"; done
</code>```

Recursively, with bash's globstar:

```<code>shopt -s globstar
for f in /directory/**/*.txt; do [ -f "$f" ] && [ -s "$f" ] && echo "$f"; done
</code>```

Body:
Job for find (GNU find precisely), assuming the extension to match is .txt, and directory to check is /directory:

find /directory -maxdepth 1 -type f -name '*.txt' -not -empty

Recursively:

find /directory -type f -name '*.txt' -not -empty

Slow shell-way, using for to iterate over the files, and test ([) to check the conditions:

for f in /directory/*.txt; do [ -f "$f" ] && [ -s "$f" ] && echo "$f"; done

Recursively, with bash's globstar:

shopt -s globstar
for f in /directory/**/*.txt; do [ -f "$f" ] && [ -s "$f" ] && echo "$f"; done


问:
jQuery: Loop print only one value
I have below code

```<code><script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>
<table id="main_table">
    <tr>
        <td><input name="" value="3" id="id_3" checked="checked" type="checkbox"></td>
        <td><input name="qty[]" value="5.0000" type="text"></td>
    </tr>
    <tr>
        <td><input name="" value="4" id="id_4" checked="checked" type="checkbox"></td>
        <td><input name="qty[]" value="2.0000" type="text"></td>
    </tr>
    <tr>
        <td><input name="" value="5" id="id_5" checked="checked" type="checkbox"></td>
        <td><input name="qty[]" value="3.0000" type="text"></td>
    </tr>
</table>
<script>
jQuery('table#main_table').each( function(){
    if(jQuery(this).find("input:checkbox").is(':checked')){
         var txt = jQuery(this).find("input[name='qty[]']").val();
         alert(txt);
    }
});
</code>```

I need to check within table if checkbox is checked then print it's qty value.  But below code only prints 1 value. Instead of all

What I'm missing?

答:
Your loop is for tr not for table.

jQuery('table#main_table tr').each( function(){
    if(jQuery(this).find("input:checkbox").is(':checked')){
         var txt = jQuery(this).find("input[name='qty[]']").val();
         console.log(txt);
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="main_table">
    <tr>
        <td><input name="" value="3" id="id_3" checked="checked" type="checkbox"></td>
        <td><input name="qty[]" value="5.0000" type="text"></td>
    </tr>
    <tr>
        <td><input name="" value="4" id="id_4" checked="checked" type="checkbox"></td>
        <td><input name="qty[]" value="2.0000" type="text"></td>
    </tr>
    <tr>
        <td><input name="" value="5" id="id_5" checked="checked" type="checkbox"></td>
        <td><input name="qty[]" value="3.0000" type="text"></td>
    </tr>
</table></code>```

Title: jQuery: Loop print only one value

Body:
I have below code

        <input name="" value="3" id="id_3" checked="checked" type="checkbox">
        <input name="qty[]" value="5.0000" type="text">

        <input name="" value="4" id="id_4" checked="checked" type="checkbox">
        <input name="qty[]" value="2.0000" type="text">

        <input name="" value="5" id="id_5" checked="checked" type="checkbox">
        <input name="qty[]" value="3.0000" type="text">

Body:
Your loop is for tr not for table.

jQuery('table#main_table tr').each( function(){
    if(jQuery(this).find("input:checkbox").is(':checked')){
         var txt = jQuery(this).find("input[name='qty[]']").val();
         console.log(txt);
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="main_table">
    <tr>
        <td><input name="" value="3" id="id_3" checked="checked" type="checkbox"></td>
        <td><input name="qty[]" value="5.0000" type="text"></td>
    </tr>
    <tr>
        <td><input name="" value="4" id="id_4" checked="checked" type="checkbox"></td>
        <td><input name="qty[]" value="2.0000" type="text"></td>
    </tr>
    <tr>
        <td><input name="" value="5" id="id_5" checked="checked" type="checkbox"></td>
        <td><input name="qty[]" value="3.0000" type="text"></td>
    </tr>
</table>


问:
How to show this
I have a question. I want to make a app for mind reader. First i want to give 1 to 100 number and ask the user to think in mind a number.on next i want to display 1 to 50 and two button yes,no.  When click on yes it shows 1 to 25 and on no it shows 50 to 75 and so on.</p>

答:
use Biginteger and BigDecimal instead of int and decimal       </p>

```<code>BigInteger a=new BigInteger(valueA);
BigInteger b=new BigInteger(valueB);
BigInteger c=a.multiply(b);
</code>```

Title: How to show this

Body:
use Biginteger and BigDecimal instead of int and decimal

BigInteger a=new BigInteger(valueA);
BigInteger b=new BigInteger(valueB);
BigInteger c=a.multiply(b);


问:
Why Android EditText have to click the second time to trigger the event?
The xml file:

```<code><EditText
        android:drawableLeft="@drawable/icon_lock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:id="@+id/et_pwd"
        android:drawableRight="@drawable/icon_closeeye_32"
        style="@style/editText_base"
        android:hint="@string/pwd_input"/>
</code>```

Outside is LinearLayout

The code:

```<code>private boolean isTouch = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN :
            Drawable drawableRight = etPwd.getCompoundDrawables()[2];

            if(drawableRight == null && event.getAction() != MotionEvent.ACTION_UP) {
                return false;
            }
            if (event.getX() > etPwd.getWidth()
                    - etPwd.getPaddingRight()
                    - drawableRight.getIntrinsicWidth()){
                Drawable drawableLeft = getResources().getDrawable(R.drawable.icon_lock);
                drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());
                if (isTouch) {
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    Drawable drawableOpenEye = getResources().getDrawable(R.drawable.icon_openeye_32);
                    drawableOpenEye.setBounds(0, 0, drawableOpenEye.getMinimumWidth(), drawableOpenEye.getMinimumHeight());
                    etPwd.setCompoundDrawables(drawableLeft, null, drawableOpenEye, null);
                } else {
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    Drawable drawableCloseEye = getResources().getDrawable(R.drawable.icon_closeeye_32);
                    drawableCloseEye.setBounds(0, 0, drawableCloseEye.getMinimumWidth(), drawableCloseEye.getMinimumHeight());
                    etPwd.setCompoundDrawables(drawableLeft, null, drawableCloseEye, null);
                }
                isTouch = !isTouch;
                etPwd.setSelection(etPwd.getText().toString().length());
            }

            break;
        case MotionEvent.ACTION_MOVE :

            break;
        case MotionEvent.ACTION_UP :

            break;
    }

    return false;
}
</code>```

Now! Did not respond for the first time , Click the second time to show the icon open , to show / hide the password.

And i`ve already implements View.OnTouchListener , find the relevant controls to do the click event . Help me , thanks!

答:
Try this,

XML:

```<code><RelativeLayout
        android:id="@+id/relative01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_username"
        android:background="@drawable/selector"
        android:padding="10dp">

        <com.mycalculator.utils.CustomEditText
            android:id="@+id/et_pwd"
            android:layout_width="fill_parent"
            android:layout_height="42dp"
            android:layout_toStartOf="@+id/iv_show_pwd"
            android:background="@null"
            android:hint="@string/Password"
            android:inputType="textPassword"
            android:singleLine="true"
            android:textColor="@color/colorBlack"
             />

        <ImageView
            android:id="@+id/iv_show_pwd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_centerVertical="true"
            android:layout_marginEnd="3dp"
            android:layout_marginStart="3dp"
            android:src="@drawable/icon_closeeye_32" />
</RelativeLayout>
</code>```

selector:

```<code><?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners android:radius="6dp" />

    <gradient
        android:angle="90" />
    <solid android:color="@color/colorWhite"/>
    <stroke
        android:width="1dp"
        android:color="@color/Gray" />

</shape>
</code>```

JAVA:

```<code>EditText et_pwd = (EditText) findViewById(R.id.et_pwd);
ImageView iv_show_pwd = (ImageView) findViewById(R.id.iv_show_pwd);

iv_show_pwd.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (et_pwd.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
            et_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            iv_show_pwd.setImageResource(R.drawable.ic_visible);
        } else {
            et_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
            iv_show_pwd.setImageResource(R.drawable.ic_invisible);
        }
    }
});
</code>```

Body:
The xml file:

<EditText
        android:drawableLeft="@drawable/icon_lock"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:id="@+id/et_pwd"
        android:drawableRight="@drawable/icon_closeeye_32"
        style="@style/editText_base"
        android:hint="@string/pwd_input"/>

Outside is LinearLayout

The code:

private boolean isTouch = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN :
            Drawable drawableRight = etPwd.getCompoundDrawables()[2];

            if(drawableRight == null && event.getAction() != MotionEvent.ACTION_UP) {
                return false;
            }
            if (event.getX() > etPwd.getWidth()
                    - etPwd.getPaddingRight()
                    - drawableRight.getIntrinsicWidth()){
                Drawable drawableLeft = getResources().getDrawable(R.drawable.icon_lock);
                drawableLeft.setBounds(0, 0, drawableLeft.getMinimumWidth(), drawableLeft.getMinimumHeight());
                if (isTouch) {
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    Drawable drawableOpenEye = getResources().getDrawable(R.drawable.icon_openeye_32);
                    drawableOpenEye.setBounds(0, 0, drawableOpenEye.getMinimumWidth(), drawableOpenEye.getMinimumHeight());
                    etPwd.setCompoundDrawables(drawableLeft, null, drawableOpenEye, null);
                } else {
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    Drawable drawableCloseEye = getResources().getDrawable(R.drawable.icon_closeeye_32);
                    drawableCloseEye.setBounds(0, 0, drawableCloseEye.getMinimumWidth(), drawableCloseEye.getMinimumHeight());
                    etPwd.setCompoundDrawables(drawableLeft, null, drawableCloseEye, null);
                }
                isTouch = !isTouch;
                etPwd.setSelection(etPwd.getText().toString().length());
            }

            break;
        case MotionEvent.ACTION_MOVE :

            break;
        case MotionEvent.ACTION_UP :

            break;
    }

    return false;
}

Now! Did not respond for the first time , Click the second time to show the icon open , to show / hide the password.

And i`ve already implements View.OnTouchListener , find the relevant controls to do the click event . Help me , thanks!

Body:
Try this,

XML:

<RelativeLayout
        android:id="@+id/relative01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/et_username"
        android:background="@drawable/selector"
        android:padding="10dp">

        <com.mycalculator.utils.CustomEditText
            android:id="@+id/et_pwd"
            android:layout_width="fill_parent"
            android:layout_height="42dp"
            android:layout_toStartOf="@+id/iv_show_pwd"
            android:background="@null"
            android:hint="@string/Password"
            android:inputType="textPassword"
            android:singleLine="true"
            android:textColor="@color/colorBlack"
             />

        <ImageView
            android:id="@+id/iv_show_pwd"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_centerVertical="true"
            android:layout_marginEnd="3dp"
            android:layout_marginStart="3dp"
            android:src="@drawable/icon_closeeye_32" />
</RelativeLayout>

selector:

<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <corners android:radius="6dp" />

    <gradient
        android:angle="90" />
    <solid android:color="@color/colorWhite"/>
    <stroke
        android:width="1dp"
        android:color="@color/Gray" />

</shape>

JAVA:

EditText et_pwd = (EditText) findViewById(R.id.et_pwd);
ImageView iv_show_pwd = (ImageView) findViewById(R.id.iv_show_pwd);

iv_show_pwd.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (et_pwd.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
            et_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            iv_show_pwd.setImageResource(R.drawable.ic_visible);
        } else {
            et_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
            iv_show_pwd.setImageResource(R.drawable.ic_invisible);
        }
    }
});


问:
Why are my UITableViewCell's repeating?
When I scroll offscreen I get some repeating cells. How can I fix this?</p>

```<code>// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = [NSString stringWithFormat:@"Bar Cafe",indexPath.row];
            break;
        case 1:
            cell.textLabel.text = [NSString stringWithFormat:@"Boutique Hester",indexPath.row];
            break;
        case 2:
            cell.textLabel.text = [NSString stringWithFormat:@"Boutique Hester Shoes",indexPath.row];
            break;
        case 3:
            cell.textLabel.text = [NSString stringWithFormat:@"Local Advice - Paulina",indexPath.row];
            break;
        case 4:
            cell.textLabel.text = [NSString stringWithFormat:@"Museum Brileyeglass",indexPath.row];
            break;
        case 5:
            cell.textLabel.text = [NSString stringWithFormat:@"Redlight Swans",indexPath.row];
            break;
        case 6:
            cell.textLabel.text = [NSString stringWithFormat:@"Reefer Flying Dutchman",indexPath.row];
            break;
        case 7:
            cell.textLabel.text = [NSString stringWithFormat:@"Reefer Tiani Hempshop",indexPath.row];
            break;

        default:
            break;
    }

    // Configure the cell...
    //cell.textLabel.text = [NSString stringWithFormat:@"Featured Event %d",indexPath.row];
    //cell.detailTextLabel.text = [NSString stringWithFormat:@"Description %d", indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}
</code>```

答:
Your code working fine for me, no problems at all.

I think you want to print indexPath.row at each row. If so, you have to change as follows:

```<code>[NSString stringWithFormat:@"Reefer Tiani Hempshop %d",indexPath.row];
</code>```

Even though the numberOfRowsInSection: returns more than 8 there will be no chance for reputation.

Title: Why are my UITableViewCell's repeating?

Body:
When I scroll offscreen I get some repeating cells. How can I fix this?

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    switch (indexPath.row) {
        case 0:
            cell.textLabel.text = [NSString stringWithFormat:@"Bar Cafe",indexPath.row];
            break;
        case 1:
            cell.textLabel.text = [NSString stringWithFormat:@"Boutique Hester",indexPath.row];
            break;
        case 2:
            cell.textLabel.text = [NSString stringWithFormat:@"Boutique Hester Shoes",indexPath.row];
            break;
        case 3:
            cell.textLabel.text = [NSString stringWithFormat:@"Local Advice - Paulina",indexPath.row];
            break;
        case 4:
            cell.textLabel.text = [NSString stringWithFormat:@"Museum Brileyeglass",indexPath.row];
            break;
        case 5:
            cell.textLabel.text = [NSString stringWithFormat:@"Redlight Swans",indexPath.row];
            break;
        case 6:
            cell.textLabel.text = [NSString stringWithFormat:@"Reefer Flying Dutchman",indexPath.row];
            break;
        case 7:
            cell.textLabel.text = [NSString stringWithFormat:@"Reefer Tiani Hempshop",indexPath.row];
            break;

        default:
            break;
    }

    // Configure the cell...
    //cell.textLabel.text = [NSString stringWithFormat:@"Featured Event %d",indexPath.row];
    //cell.detailTextLabel.text = [NSString stringWithFormat:@"Description %d", indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;
}

Body:
Your code working fine for me, no problems at all.

I think you want to print indexPath.row at each row. If so, you have to change as follows:

[NSString stringWithFormat:@"Reefer Tiani Hempshop %d",indexPath.row];

Even though the numberOfRowsInSection: returns more than 8 there will be no chance for reputation.

ContentLicense: CC BY-SA 4.0


问:
Delete action is not working in laravel?
I have a form which has the delete button in it.

```<code> <form method="post" id="delform" action="{{ url('/templates/delete',[$template->template_id]) }}">
    {{ method_field('DELETE') }}
  {{ csrf_field() }}

 <input type="submit" class="btn btn-danger" id="del" value="delete>

  </form>
</code>```

then in my routes web.php:

```<code>Route::delete('/templates/delete/{id}','TemplateController@delete');
</code>```

when i click on delete i get this error:

what am i doing wong please help? thanks in advance

I have added my composer.json here:

```<code>{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
    "php": ">=5.6.4",
    "laravel/framework": "5.4.*",
    "laravel/tinker": "~1.0",
    "maatwebsite/excel": "~2.1.0"        "rmccue/requests": ">=1.0"    },
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~5.7"
},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},
"scripts": {
    "post-root-package-install": [
        "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
        "php artisan key:generate"
    ],
    "post-install-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postInstall",
        "php artisan optimize"
    ],
    "post-update-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postUpdate",
        "php artisan optimize"
    ]
},
"config": {
    "preferred-install": "dist",
    "sort-packages": true
}
}
</code>```

here is the console logs:

答:
You forgot double-quotes to close value from input submit

```<code><input type="submit" ... value="delete">
</code>```

and a comma in composer json after package:

```<code>"maatwebsite/excel": "~2.1.0",
</code>```

Finally HTML forms do not support PUT, PATCH or DELETE actions. So, when defining PUT, PATCH or  DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method.

```<code><input type="hidden" name="_method" value="DELETE">
</code>```

You may use the method_field helper to generate the _method input:

```<code>{{ method_field('DELETE') }}
</code>```

Laravel routes documentation

Look at rest conventions

Body:
I have a form which has the delete button in it.

 <form method="post" id="delform" action="{{ url('/templates/delete',[$template->template_id]) }}">
    {{ method_field('DELETE') }}
  {{ csrf_field() }}

 <input type="submit" class="btn btn-danger" id="del" value="delete>

  </form>

then in my routes web.php:

Route::delete('/templates/delete/{id}','TemplateController@delete');

when i click on delete i get this error:

what am i doing wong please help? thanks in advance

I have added my composer.json here:

{
"name": "laravel/laravel",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"license": "MIT",
"type": "project",
"require": {
    "php": ">=5.6.4",
    "laravel/framework": "5.4.*",
    "laravel/tinker": "~1.0",
    "maatwebsite/excel": "~2.1.0"        "rmccue/requests": ">=1.0"    },
"require-dev": {
    "fzaninotto/faker": "~1.4",
    "mockery/mockery": "0.9.*",
    "phpunit/phpunit": "~5.7"
},
"autoload": {
    "classmap": [
        "database"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},
"scripts": {
    "post-root-package-install": [
        "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
        "php artisan key:generate"
    ],
    "post-install-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postInstall",
        "php artisan optimize"
    ],
    "post-update-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postUpdate",
        "php artisan optimize"
    ]
},
"config": {
    "preferred-install": "dist",
    "sort-packages": true
}
}

here is the console logs:

Body:
You forgot double-quotes to close value from input submit

<input type="submit" ... value="delete">

and a comma in composer json after package:

"maatwebsite/excel": "~2.1.0",

Finally HTML forms do not support PUT, PATCH or DELETE actions. So, when defining PUT, PATCH or  DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method.

<input type="hidden" name="_method" value="DELETE">

You may use the method_field helper to generate the _method input:

{{ method_field('DELETE') }}

Laravel routes documentation

Look at rest conventions


问:
How to run executables from terminal in Linux without entering the entire PATH
I'm trying to activate android studio directly from terminal (./studio.sh)
the installation dir is /usr/local/android-studio
and inside there's a bin folder with the script studio.sh

for that I've vi'd ~/.bashrc to include the following line:
export PATH=$PATH:/usr/local/android-studio/bin

When I do echo $PATH i do see the path above appended to the rest of the path
(/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/usr/local/android-studio/bin)

Yet when I run ./studio.sh it prompts me with No such file or directory

Needless to say, if i cd /usr/local/android-studio/bin and then ./studio.sh it works fine

running debian (jessie 'edition')

答:
I simply needed to do studio.sh without the ./
Thanks for ZanCoul for providing the answer.</p>


问:
How to get substrings on both sides of hyphen and trailing substring?
I am currently working on a web app which is using a specific string to call a function.  Here is a sample string:

```<code>$string = "translate from-to word for translate"
</code>```

First I need to validate the string, and it should be like the above $string. How should I validate the string?

Then I need to extract 3 substrings from $string.

The word that precedes the hyphen. (To be named: $target)

The word that follows the hyphen. (To be named: $source)

The text (not including the first space) that follows $source to the end of the string. (To be named: $translate)

This is my coding attempt to get the from and to:

```<code>$found = false;
$source ="";
$target = "";
$next = 3;
$prev = 1;
for($i=0;$i<strlen($string);$i++){
    if($found== false){
        if($string[$i] == "-"){
            $found = true;
            while($string[$i+$prev] != " "){
                $target .= $string[$i+$prev];
                $prev +=1;
            }
            /*$next -=1;
            while($string[$i-$next] != " " && $next > 0){
                $source .= $string[$i-$next];
                $next -=1;
            }*/
        }
    }
}
</code>```

From that code, I only can return the $target which contains to after -.
I don't know how to get $source.

Please show me the fastest way to get the from as $source and to as $target.

Then I need to get word for translate (all of the string after from-to).

So the result should be

```<code>$target = "to";
$source = "from";
$translate = "word for translate";
</code>```

Finally, if the $string has two hyphens, like translate from-to from-to test-test word for translate, it should be return false;

note to and from are random strings.

答:
If I understand your question correctly, this can be done with a regular expression:

```<code><?php
$string = "translate from-to word for translate";
$result = preg_match("/^([\w ]+?) (\w+)-(\w+) ([\w ]+)$/", $string, $matches);
if ($result) {
    print_r($matches);
    $source = $matches[2];
    $target = $matches[3];
    $translate = $matches[4];
} else {
    echo "No match";
}
</code>```

Output:

```<code>Array
(
    [0] => translate from-to word for translate
    [1] => translate
    [2] => from
    [3] => to
    [4] => word for translate
)
</code>```

Here is an explanation of the regular expression.

Body:
I am currently working on a web app which is using a specific string to call a function.  Here is a sample string:

$string = "translate from-to word for translate"

First I need to validate the string, and it should be like the above $string. How should I validate the string?

Then I need to extract 3 substrings from $string.

The word that precedes the hyphen. (To be named: $target)

The word that follows the hyphen. (To be named: $source)

The text (not including the first space) that follows $source to the end of the string. (To be named: $translate)

This is my coding attempt to get the from and to:

$found = false;
$source ="";
$target = "";
$next = 3;
$prev = 1;
for($i=0;$i<strlen($string);$i++){
    if($found== false){
        if($string[$i] == "-"){
            $found = true;
            while($string[$i+$prev] != " "){
                $target .= $string[$i+$prev];
                $prev +=1;
            }
            /*$next -=1;
            while($string[$i-$next] != " " && $next > 0){
                $source .= $string[$i-$next];
                $next -=1;
            }*/
        }
    }
}

From that code, I only can return the $target which contains to after -.
I don't know how to get $source.

Please show me the fastest way to get the from as $source and to as $target.

Then I need to get word for translate (all of the string after from-to).

So the result should be

$target = "to";
$source = "from";
$translate = "word for translate";

Finally, if the $string has two hyphens, like translate from-to from-to test-test word for translate, it should be return false;

note to and from are random strings.

Body:
If I understand your question correctly, this can be done with a regular expression:

<?php
$string = "translate from-to word for translate";
$result = preg_match("/^([\w ]+?) (\w+)-(\w+) ([\w ]+)$/", $string, $matches);
if ($result) {
    print_r($matches);
    $source = $matches[2];
    $target = $matches[3];
    $translate = $matches[4];
} else {
    echo "No match";
}

Output:

Array
(
    [0] => translate from-to word for translate
    [1] => translate
    [2] => from
    [3] => to
    [4] => word for translate
)

Here is an explanation of the regular expression.


问:
how type in command adb -kill server?

when i type in cmd adb kill server it give me that adb not recognized. i cannot find the adb location in windows . what should i do to type in cmd to kill the adb

public class MainActivity extends AppCompatActivity {

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView listView = (ListView) findViewById(R.id.listView);
    TextView textView =(TextView) findViewById(R.id.txt);

    String[] item = getResources().getStringArray(R.array.index);

    ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.activity_second,R.id.txt,item);
      listView.setAdapter(adapter);
    Typeface typeface = Typeface.createFromAsset(getAssets(),"font.ttf");
    textView.setTypeface(typeface);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent = new Intent(MainActivity.this,Second.class);
            intent.putExtra("page",i);
            startActivity(intent);
        }
    });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
</code>```

}

答:
Program adb.exe is inside Android SDK Folder. Here is the path:

```<code>\SDK\platform-tools\
</code>```

Go there(\SDK\platform-tools\) ==> SHIFT & RIGHT click. Then cmd will open inside that directory so that you can run "adb kill-server".

Title: how type in command adb -kill server?

Body:
when i type in cmd adb kill server it give me that adb not recognized. i cannot find the adb location in windows . what should i do to type in cmd to kill the adb

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ListView listView = (ListView) findViewById(R.id.listView);
    TextView textView =(TextView) findViewById(R.id.txt);

    String[] item = getResources().getStringArray(R.array.index);

    ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.activity_second,R.id.txt,item);
      listView.setAdapter(adapter);
    Typeface typeface = Typeface.createFromAsset(getAssets(),"font.ttf");
    textView.setTypeface(typeface);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent = new Intent(MainActivity.this,Second.class);
            intent.putExtra("page",i);
            startActivity(intent);
        }
    });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

Body:
Program adb.exe is inside Android SDK Folder. Here is the path:

\SDK\platform-tools\

Go there(\SDK\platform-tools\) ==> SHIFT & RIGHT click. Then cmd will open inside that directory so that you can run "adb kill-server".


问:
iphone, xcode; Reverse engineer a nib
I was wondering if there is a way i can design a nib/xib file and generate code for that?
meaning, instead of writing lines of code to generate an interface, would'nt it be easier to design and nib file using IB and get the source or something?

Thanks

答:
I think that you may misunderstand what a nib file is. </p>

<p>If you mean that you'd rather create your view objects in interface builder and have outlets automatically inserted into your source files then look to XCode beta, it does that. </p>

Title: iphone, xcode; Reverse engineer a nib

Body:
I think that you may misunderstand what a nib file is.

If you mean that you'd rather create your view objects in interface builder and have outlets automatically inserted into your source files then look to XCode beta, it does that.


问:
Replace attribute not valid html5 with jquery
How to replace attribute and set value with jquery

old html

```<code><div class="container">
<table>
<tr>
    <td width="106" valign="top" style="background: red">
          <p align="center">text</p>
    </td>
</tr>
</table>
</div>
</code>```

New HTML

```<code><div class="container">
<table>
<tr>
    <td style="width:106px; background: red;">
          <p style="text-align:center;">text</p>
    </td>
</tr>
</table>
</div>
</code>```

Thank you in advance

答:
You can simply use the getAttribute() function to retrieve an attribute's value. So, i'll use  as an example:

```<code>var style = 'width:' + $('#container td').getAttribute('width') + ';' + $('#container td').getAttribute('style');
$('#container td').attr('style', style);
</code>```

Will result in . However, this is assuming you only have a single table cell in your table. If you had multiple, you would simply use this concept to apply this method to each cell in the table.

Body:
How to replace attribute and set value with jquery

old html

text

New HTML

text

Thank you in advance

Body:
You can simply use the getAttribute() function to retrieve an attribute's value. So, i'll use <td width="106" valign="top" style="background: red"> as an example:

var style = 'width:' + $('#container td').getAttribute('width') + ';' + $('#container td').getAttribute('style');
$('#container td').attr('style', style);

Will result in <td style="width:106px; background: red;">. However, this is assuming you only have a single table cell in your table. If you had multiple, you would simply use this concept to apply this method to each cell in the table.


问:
How can I get result as 0 if IN() condition value not exist in the table
My table is:

```
s_no  user  join_year  knowledge handled_pojects_count
1     john     2017    PHP        5
2     john     2017    SQL        5
3     gokul    2017    JAVA       3
4     gokul    2017    PHP        2
5     hari     2017    ASP        1
6     hari     2017    Azure      9
```

Below one is my query

```<code>SELECT
COALESCE(SUM(handled_pojects_count),0) AS count,
knowledge
FROM team_members WHERE
join_year = '2017' AND
user = 'john' AND
knowledge IN ('PHP','JAVA');
</code>```

I need the result that should have both values for knowledge like below

```
    project count
    PHP     5
    JAVA    0
```

How can I arrive this?

答:
below one working fine.
Thanks for your help!</p>

```
SELECT
knowledge,
SUM(CASE WHEN join_year = 2017 AND user = 'john' THEN handled_pojects_count ELSE 0 END) as cnt
FROM team_members WHERE
knowledge IN ('PHP','JAVA')
GROUP BY knowledge

```

Body:
My table is:

s_no  user  join_year  knowledge handled_pojects_count
1     john     2017    PHP        5
2     john     2017    SQL        5
3     gokul    2017    JAVA       3
4     gokul    2017    PHP        2
5     hari     2017    ASP        1
6     hari     2017    Azure      9

Below one is my query

SELECT
COALESCE(SUM(handled_pojects_count),0) AS count,
knowledge
FROM team_members WHERE
join_year = '2017' AND
user = 'john' AND
knowledge IN ('PHP','JAVA');

I need the result that should have both values for knowledge like below

    project count
    PHP     5
    JAVA    0

How can I arrive this?

Body:
below one working fine.
Thanks for your help!

SELECT
knowledge,
SUM(CASE WHEN join_year = 2017 AND user = 'john' THEN handled_pojects_count ELSE 0 END) as cnt
FROM team_members WHERE
knowledge IN ('PHP','JAVA')
GROUP BY knowledge


问:
Adding variable amount of tspan elements to text depending on d attribute in d3.js
```<code>var spans = {};
    var counter = 0;
    var f = 0;
    labelT.each(function(d,i){
            var splitted = d.name.split(" ");
            console.log(splitted);
            for(var k = 0,f = 0; k < splitted.length; k++,f += 1.2){
                spans[k] = labelT.select(this).append("tspan")
                .attr("class", "tspan"+counter)
                .attr("dy",f+"em")
                .attr("x",0)
                .text(function(d){return splitted[k]});
                counter ++ ;
            }
            counter ++;
    });
</code>```

I want to add as many tspans to the labelT var which is a text element in dependence of how many words are in the var array splitted. This should result in a new line for each word. the problem is, that I have no idea how to select current labelT element. I tried alread labelT.select in the for loop and and the posted version of selection. can anyone help?
thanks!

答:
While the above solution does work, you should be able to re-bind the data to the element using a "more-D3-style" solution. Please note that I haven't tested this code, so you might need to fiddle with it to get it 100% working:</p>

```<code>labelT.each(function each(d,i) {
    var split = d.name.split(' ');

    d3.select(this)
        .data(split)
        .enter()
        .append('tspan')
        .attr('class', function setAttr(d, i) { return 'tspan' + i; })
        .attr('dy', function setAttr(d, i) { return (i * 1.2) + 'em'; })
        .attr('x', 0)
        .text(function setText(d) { return d; });
});
</code>```

Body:
var spans = {};
    var counter = 0;
    var f = 0;
    labelT.each(function(d,i){
            var splitted = d.name.split(" ");
            console.log(splitted);
            for(var k = 0,f = 0; k < splitted.length; k++,f += 1.2){
                spans[k] = labelT.select(this).append("tspan")
                .attr("class", "tspan"+counter)
                .attr("dy",f+"em")
                .attr("x",0)
                .text(function(d){return splitted[k]});
                counter ++ ;
            }
            counter ++;
    });

I want to add as many tspans to the labelT var which is a text element in dependence of how many words are in the var array splitted. This should result in a new line for each word. the problem is, that I have no idea how to select current labelT element. I tried alread labelT.select in the for loop and and the posted version of selection. can anyone help?
thanks!

Body:
While the above solution does work, you should be able to re-bind the data to the element using a "more-D3-style" solution. Please note that I haven't tested this code, so you might need to fiddle with it to get it 100% working:

labelT.each(function each(d,i) {
    var split = d.name.split(' ');

    d3.select(this)
        .data(split)
        .enter()
        .append('tspan')
        .attr('class', function setAttr(d, i) { return 'tspan' + i; })
        .attr('dy', function setAttr(d, i) { return (i * 1.2) + 'em'; })
        .attr('x', 0)
        .text(function setText(d) { return d; });
});


问:
SVN: how to return to previous revision?
A series of mistakes were made in a project I am working on. How do I revert back to a known working revision and build on top of that? Say I am at revision 15, but I want to go back to revision 10 -- and work on 10 onwards. I'm using Zend Studio.

Can I delete revisions that exist in SVN?

答:
Get the docs from TortoiseSVN office site.

Use the revision log dialog

Use the merge dialog

I use method 2 and work fine on my side.

https://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-howto-rollback.html


问:
ASP.Net MVC vs. Ruby on Rails
If you were starting a new web development project would you use ASP.Net MVC 2 or Ruby on Rails?

I have recently invested some time in to learning Ruby on Rails because I wanted to learn a solid web development framework.  Then I took a new job where I will be using ASP.Net MVC 2.

I know this question is very subjective, but I am planning to write some websites on my own, outside of work, and I would like to get some opinions from others.

答: don't take a poll on stack overflow, use whatever interests you. work is for paying the bills, your personal projects should be for expanding your mind (and having fun)</p>

Title: ASP.Net MVC vs. Ruby on Rails


问:
Getting route params on initial page load
I'm trying to get route parameters for the first time, and I can't seem to figure out how to use ActivatedRoute properly.

Based on the API and docs, I'm trying this to get my route params on page load.

```<code>ngOnInit() {
    const orgSlug: Observable<string> = this.route.params.map(params => {console.log(params); return params.org});
}
</code>```

On page load, nothing gets logged. My assumption would have been on the page load, I would get the initial state of the params object. I tried it both in the ngOnInit and the constructor with no results in either. I know I can check snapshot, but then I'd have to have duplicate code for the initial state and any changed state, which feels wrong.

Am I misunderstanding how observables or the ActivatedRoute works?

答:
You should use subscribe() after the params.

```<code>constructor(private route: ActivatedRoute) {}

ngOnInit() {
   this.route.params.subscribe(params => {
       this.id = params['id']; // do this if it is a number +params['id']

    });
  }
</code>```

Also, you may want to unsubscribe to it ( optional )

```<code>private sub:any;
    constructor(private route: ActivatedRoute) {}

ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.id = params['id']; // do this if it is a number +params['id']

    });
  }
</code>```

And unsubscribe to it when your component is about to destroy

```<code>ngOnDestroy() {
    this.sub.unsubscribe();
  }
</code>```

Though angular will do the garbage collection for you, it is still better to unsubscribe to it manually just to be safe.

Body:
I'm trying to get route parameters for the first time, and I can't seem to figure out how to use ActivatedRoute properly.

Based on the API and docs, I'm trying this to get my route params on page load.

ngOnInit() {
    const orgSlug: Observable<string> = this.route.params.map(params => {console.log(params); return params.org});
}

On page load, nothing gets logged. My assumption would have been on the page load, I would get the initial state of the params object. I tried it both in the ngOnInit and the constructor with no results in either. I know I can check snapshot, but then I'd have to have duplicate code for the initial state and any changed state, which feels wrong.

Am I misunderstanding how observables or the ActivatedRoute works?

Body:
You should use subscribe() after the params.

constructor(private route: ActivatedRoute) {}

ngOnInit() {
   this.route.params.subscribe(params => {
       this.id = params['id']; // do this if it is a number +params['id']

    });
  }

Also, you may want to unsubscribe to it ( optional )

private sub:any;
    constructor(private route: ActivatedRoute) {}

ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.id = params['id']; // do this if it is a number +params['id']

    });
  }

And unsubscribe to it when your component is about to destroy

ngOnDestroy() {
    this.sub.unsubscribe();
  }

Though angular will do the garbage collection for you, it is still better to unsubscribe to it manually just to be safe.


问:
Possible to outsource computations to AWS and utilize results locally?
I'm working on a robot that uses a CNN that needs much more memory than my embedded computer (Jetson TX1) can handle. I was wondering if it would be possible (with an extremely low latency connection) to outsource the heavy computations to EC2 and send the results back to the be used in a Python script. If this is possible, how would I go about it and what would the latency look like (not computations, just sending to and from). </p>

答:
I am a former employee of CENAPAD-UFC (National Centre of HPC, Federal University of Ceará), so I have something to say about outsourcing computer power.

CENAPAD has a big cluster, and it provides computational power for academic research. There, professors and students send their computation and their data, defined the output and go drink a coffee or two, while the cluster go on with the hard work. After lots of flops, the operation ended and they retrieve it via ssh and go back to their laptops.

For big chunks of computation, you wish to minimize any work that is not a useful computation. One such thing is commumication over detached computers. If you need to know when the computation has ended, let the HPC machine tell you that.

To compute stuff effectively, you may want to go deeper in the machine and performe some kind of distribution. I use OpenMP to distribute computation inside the same machine/thread distribution. To distribute between physically separated computers, but next (latency speaking), I use MPI. I have installed also another cluster in UFC for another department. There, the researchers used only MPI.

Maybe some read about distributed/grid/clusterized computing helps you:

https://en.m.wikipedia.org/wiki/SETI@home ; the first example of massive distributed computing that I ever heard

https://en.m.wikipedia.org/wiki/Distributed_computing

https://en.m.wikipedia.org/wiki/Grid_computing

https://en.m.wikipedia.org/wiki/Supercomputer ; this is CENAPAD like stuff

In my opinion, you wish to use a grid-like computation, with your personal PC working as a master node that may call the EC2 slaves; in this scenario, just use communication from master to slave to send program (if really needed) and data, in such a way that the master will have another thing to do not related with the sent data; also, let the slave tells your master when the computation reached it's end.


问:
How to show a UITableViewCell as selected and still receive didDeselectRowAtIndexPath
I have a UITableView which when isEditing=YES shows the cells with standard iOS selection circular 'checkbox' (see picture below). Some of these are 'bookmarked' via CoreData.

tableView:willDisplayCell reads from CoreData and sets
cell.selected = YES;  for the bookmarked cells.

Trouble is that these 'bookmarked' cells do not respond to

```<code>tableView:didDeselectRowAtIndexPath
</code>```

or

```<code>tableView:didSelectRowAtIndexPath
</code>```

Whereas the same callbacks work fine on cells with cell.selected=NO;

The image shows a selected cell above a non selected cell.

This is executed inside

```<code>- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

 if (tableView.isEditing)
    { [cell setSelected:[self isCellFave:indexPath]];  }
</code>```

Where isCellFave does

```<code>- (BOOL) isCellFave:(NSIndexPath *) indexPathIn
{
    BOOL isSelected = NO;
     // Check if this cell is a favourite
    NSError *error;

    NSString * id = [self getIDFromIndexPath:IndexPathIn];

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Event"];
    request.predicate = [NSPredicate predicateWithFormat:@"( id = %@ )", id];
    request.sortDescriptors = @[[[NSSortDescriptor alloc] initWithKey:@"sort1" ascending:YES selector:@selector(caseInsensitiveCompare:)]];

    NSArray *fetchedObjects = [ManagedContext executeFetchRequest:request error:&error];

    if ([fetchedObjects count] !=0) //if a result then it is a fave
    {
        // When we set a cell as selected, all gestures stop working - so we can't deselect it.
        isSelected=YES;
    }
    return isSelected;
}
</code>```

答:
Tapping to a selected cell will not call the
  tableView:didSelectRowAtIndexPath tableView delegate method because that
  cell is already selected. It will work/or get called if you tap the unselected cell.

Body:
I have a UITableView which when isEditing=YES shows the cells with standard iOS selection circular 'checkbox' (see picture below). Some of these are 'bookmarked' via CoreData.

tableView:willDisplayCell reads from CoreData and sets
cell.selected = YES;  for the bookmarked cells.

Trouble is that these 'bookmarked' cells do not respond to

tableView:didDeselectRowAtIndexPath

or

tableView:didSelectRowAtIndexPath

Whereas the same callbacks work fine on cells with cell.selected=NO;

The image shows a selected cell above a non selected cell.

This is executed inside

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

 if (tableView.isEditing)
    { [cell setSelected:[self isCellFave:indexPath]];  }

Where isCellFave does

- (BOOL) isCellFave:(NSIndexPath *) indexPathIn
{
    BOOL isSelected = NO;
     // Check if this cell is a favourite
    NSError *error;

    NSString * id = [self getIDFromIndexPath:IndexPathIn];

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Event"];
    request.predicate = [NSPredicate predicateWithFormat:@"( id = %@ )", id];
    request.sortDescriptors = @[[[NSSortDescriptor alloc] initWithKey:@"sort1" ascending:YES selector:@selector(caseInsensitiveCompare:)]];

    NSArray *fetchedObjects = [ManagedContext executeFetchRequest:request error:&error];

    if ([fetchedObjects count] !=0) //if a result then it is a fave
    {
        // When we set a cell as selected, all gestures stop working - so we can't deselect it.
        isSelected=YES;
    }
    return isSelected;
}


问:
Generate user Oauth2 token from Store, Google Federated Authenticator - WSO2 AM 2.0.0
In API Manager 2.0.0 I have configure a federated authenticator for oauth2, setting-up with a google authentication, and configure a service provider for an application to use this federated authenticator. Then I follow the tutorial [1] in order to use this application with the google authentication.

When I try to generate the keys from the Store portal using Code or Implicit grant types, the server give me the following error:

Error occurred while calling token endpoint: HTTP error code : 400

and in the log shows:

{"error_description":"Provided Authorization Grant is invalid","error":"invalid_grant"}

Can anyone help me with this problem? How can I configure a federated authenticator to consume te APIs/Applications?

Thanks.

Here you can see the debug log of APIM.

[1] http://xacmlinfo.org/2015/04/28/federated-authentication-for-granting-oauth2-access-token-with-wso2-api-manager-apim/

答:
Probably your Service Provider doesn't allow Implicit and Code grants by default.

To change this log into carbon on Service Providers -> List. Choose your SP and then click on Edit.

In the edit page, go to Inbound Authentication Configuration -> OAuth/OpenID Connect Configuration. Your application key and secret should be listed here, the one that you generate on the store.

Click on edit, this will bring all the OAuth grants available. Probably Code and Implicit are unchecked. Check them and click on Update, you should be able to generate tokens using both grants now.


问:
WindowManagerBadTokenException error on dismiss login modal on Xamarin
I am working with Xamarin, I am trying to login using Xamarin.Auth, that works correct, but when my log is successfully and I have to close the modal I am getting this error:

Unhandled Exception:
  Android.Views.WindowManagerBadTokenException: Unable to add window -- token android.os.BinderProxy@a60f6df is not valid; is your activity running?

This is the code that I am using when the login succeed:

```<code>auth.Completed += (sender, eventArgs) => {
    if (eventArgs.IsAuthenticated)
    {
        App.SaveToken(eventArgs.Account.Properties["access_token"]);
        App.SuccessfulLoginAction.Invoke();
    }
    else
    {
        // The user cancelled
    }
}
</code>```

And this is the code in the app.cs to close the modal:

```<code>get
{
    return new Action(() => {

        _NavPage.Navigation.PopModalAsync();
   });
}
</code>```

Any idea why I am getting this error?

答:
I have found the solution, not now, I have found the last year,
if someone had o will have the same issue, bellow you can find the solution,
the reason was because some when something I got a error, the app was not able to handle, then you only have to add a try in this case like the bellow code.

```<code>     try
        {
            auth.Completed += domplete_facebook;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
</code>```

hope this helps someone,
regards

Body:
I am working with Xamarin, I am trying to login using Xamarin.Auth, that works correct, but when my log is successfully and I have to close the modal I am getting this error:

Unhandled Exception:
  Android.Views.WindowManagerBadTokenException: Unable to add window -- token android.os.BinderProxy@a60f6df is not valid; is your activity running?

This is the code that I am using when the login succeed:

auth.Completed += (sender, eventArgs) => {
    if (eventArgs.IsAuthenticated)
    {
        App.SaveToken(eventArgs.Account.Properties["access_token"]);
        App.SuccessfulLoginAction.Invoke();
    }
    else
    {
        // The user cancelled
    }
}

And this is the code in the app.cs to close the modal:

get
{
    return new Action(() => {

        _NavPage.Navigation.PopModalAsync();
   });
}

Any idea why I am getting this error?

Body:
I have found the solution, not now, I have found the last year,
if someone had o will have the same issue, bellow you can find the solution,
the reason was because some when something I got a error, the app was not able to handle, then you only have to add a try in this case like the bellow code.

     try
        {
            auth.Completed += domplete_facebook;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

hope this helps someone,
regards


问:
keyboard not disappear when used resignFirstResponder in iOS
coding environment sierra 10.12，Xcode 8.1. Two textField in my roorView, if   first textfield's text is nil, second textfield will can't  be editing.When i used resignFirstResponder method to turn off keyboard in textFieldDidBeginEditing: method, keyboard not disappear. I add a fullscreen TapGesture in rootView. I'm very confused，anyone have ideas to help me deal with this problem?

`

```<code>  #pragma mark -- UITextFieldDelegate
        - (void)textFieldDidBeginEditing:(UITextField *)textField{
            if (textField == self.password) {
                [self.username resignFirstResponder];
                NSString *name = self.username.text;
                if ([name isEqualToString:@""]) {
                    [CFBlurHUD showFaild:@"sign in error!"];
                    [self performSelector:@selector(dismmiss) withObject:nil afterDelay:1.5f];
                    self.password.enabled = NO;
                }
            }
        }
        - (void)dismmiss{
            [CFBlurHUD dismiss];
            self.password.enabled = YES;
        }

`
</code>```

答:
Because  current textfiled is password: if (textField == self.password) {. But you set:

```<code>[self.username resignFirstResponder];
</code>```

It 's not correct.
Try:

```<code>[self.username resignFirstResponder];
  [self.password resignFirstResponder];
</code>```

or :

```<code>self.view.endEditting = true;
</code>```

use your UITextFieldDelegate methods specifically UITextFieldShouldBeginEditing and return NO and execute the code to show the popover instead. This way the keyboard is never shown to begin with

```<code>- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
 [self.view endEditing:YES];

  return NO;
 }
</code>```

Body:
coding environment sierra 10.12，Xcode 8.1. Two textField in my roorView, if   first textfield's text is nil, second textfield will can't  be editing.When i used resignFirstResponder method to turn off keyboard in textFieldDidBeginEditing: method, keyboard not disappear. I add a fullscreen TapGesture in rootView. I'm very confused，anyone have ideas to help me deal with this problem?

`

  #pragma mark -- UITextFieldDelegate
        - (void)textFieldDidBeginEditing:(UITextField *)textField{
            if (textField == self.password) {
                [self.username resignFirstResponder];
                NSString *name = self.username.text;
                if ([name isEqualToString:@""]) {
                    [CFBlurHUD showFaild:@"sign in error!"];
                    [self performSelector:@selector(dismmiss) withObject:nil afterDelay:1.5f];
                    self.password.enabled = NO;
                }
            }
        }
        - (void)dismmiss{
            [CFBlurHUD dismiss];
            self.password.enabled = YES;
        }

`

Body:
Because  current textfiled is password: if (textField == self.password) {. But you set:

[self.username resignFirstResponder];

It 's not correct.
Try:

[self.username resignFirstResponder];
  [self.password resignFirstResponder];

or :

self.view.endEditting = true;

use your UITextFieldDelegate methods specifically UITextFieldShouldBeginEditing and return NO and execute the code to show the popover instead. This way the keyboard is never shown to begin with

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
 [self.view endEditing:YES];

  return NO;
 }