问:
Oxyplot column series - Add items by using a loop
I have a oxyplot column series which I have masked as a histogram using a linear axis. I get my values from a list called frequency with 20 elements.

I wonder if there is a smarter way to do this:

```<code>this.Items = new Collection<Item>
{
    new Item {Label = "1", Value=frequency[0]},
    new Item {Label = "2", Value=frequency[1]},
    new Item {Label = "3", Value=frequency[2]},
    ...
    new Item {Label = "18", Value=frequency[17]},
    new Item {Label = "19", Value=frequency[18]},
    new Item {Label = "20", Value=frequency[19]},
};
</code>```

I have tried to create a for-loop inside like this:

```<code>this.Items = new Collection<Item>
{
    for (int i = 0; i < 20; i++)
    {
        Items.Add(new Item { Label = i.ToString(), Value = frequency[i]});
    }
};
</code>```

But it does not work.

Does anyone have an idea on how to do this?

答:
You can't put the for loop in the object initializer.

Create the collection.

```<code>this.Items = new Collection<Item>();
</code>```

Populate it:

```<code>for (int i = 0; i< 20; i++)
{
    Items.Add(new Item { Label = i.ToString(), Value = frequency[i] });
}
</code>```

Body:
I have a oxyplot column series which I have masked as a histogram using a linear axis. I get my values from a list called frequency with 20 elements.

I wonder if there is a smarter way to do this:

this.Items = new Collection<Item>
{
    new Item {Label = "1", Value=frequency[0]},
    new Item {Label = "2", Value=frequency[1]},
    new Item {Label = "3", Value=frequency[2]},
    ...
    new Item {Label = "18", Value=frequency[17]},
    new Item {Label = "19", Value=frequency[18]},
    new Item {Label = "20", Value=frequency[19]},
};

I have tried to create a for-loop inside like this:

this.Items = new Collection<Item>
{
    for (int i = 0; i < 20; i++)
    {
        Items.Add(new Item { Label = i.ToString(), Value = frequency[i]});
    }
};

But it does not work.

Does anyone have an idea on how to do this?

Body:
You can't put the for loop in the object initializer.

Create the collection.

this.Items = new Collection<Item>();

Populate it:

for (int i = 0; i< 20; i++)
{
    Items.Add(new Item { Label = i.ToString(), Value = frequency[i] });
}


来源: stackexchange

问:
Dividing the screen into three columns Angular Material Design
I am new to Angular Material Design.   I want to design a form which divides the date into three columns. I created two forms .  The first form contains two div's and second form contain one div.  I want each div in separate columns of the screen and Three div's should divide the screen width equally let's say 33.33% of 100% width but I am getting all the div's in only one column.  Given below is the code I wrote:

```<code><body ng-app="inputErrorsAdvancedApp">
   <div ng-controller="AppCtrl" layout="column" ng-cloak>
     <div md-content layout-padding>
       <form name="userForm">
        <div layout-xs="column">
          <md-input-container class="md-block" flex="30">
            <label>First Name</label>
            <input>
          </md-input-container>
          <md-input-container class="md-block" flex="30">
           <label>Last Name</label>
           <input>
          </md-input-container>
          <md-input-container class="md-block" flex="30">
            <label>Date Of Birth</label>
            <input>
            </md-input-container>
          <md-input-container class="md-block" flex="30">
            <label>Gender</label>
            <input>
            </md-input-container>
          <md-input-container class="md-block" flex="30">
            <label>Email</label>
            <input>
          </md-input-container>
         <md-input-container class="md-block" flex="30">
           <label>Mobile</label>
           <input>
         </md-input-container>
         <md-input-container class="md-block" flex="30">
           <label>Address</label>
           <input>
         </md-input-container>
         <md-input-container class="md-block" flex="30">
           <label>City</label>
           <input>
        </md-input-container>
  </div>
  <div layout-xs="column">
    <md-input-container class="md-block" flex="30">
      <label>Country</label>
      <input>
    </md-input-container>
    <md-input-container class="md-block" flex="30">
      <label>State</label>
      <input>
    </md-input-container>
    <md-input-container class="md-block" flex="30">
     <label>Phone</label>
     <input>
    </md-input-container>
    <md-input-container class="md-block" flex="30">
      <label>Alternate Email</label>
      <input>
    </md-input-container>
    <md-input-container class="md-block" flex="30">
      <label>Alternate Mobile</label>
      <input>
    </md-input-container>
  </div>
</form>
<form name="security">
   <div layout-xs="column">
   <md-input-container class="md-block" flex="30">
     <label>old password</label>
    <input>
   </md-input-container>
   <md-input-container class="md-block" flex="30">
    <label>New Password</label>
    <input>
   </md-input-container>
   <md-input-container class="md-block" flex="30">
    <label>Re-Enter Password</label>
    <input>
   </md-input-container>
  </div>
 </form>
 </div>
</code>```

Here is the plunker for the page I created

https://plnkr.co/edit/nj5o59A3NmqZtCv7HOfy?p=preview

Please help me as how to resolve this issue.

答:
You flex is like the dividing the screen. You can use like this. The screen must be divide to 100%. If you use 3 div or md-input-container flex should be 33. i.e 100/3. If you have 4 divs you should divide the screen 100% to 4 equal parts.

```<code>    <div layout-xs="column">
              <md-input-container class="md-block" flex="33">
                <label>First Name</label>
                <input>
              </md-input-container>
              <md-input-container class="md-block" flex="33">
               <label>Last Name</label>
               <input>
              </md-input-container>
              <md-input-container class="md-block" flex="33">
                <label>Date Of Birth</label>
                <input>
              </md-input-container>
</div>
</code>```

For more information visit the angular material official website.

ContentLicense: CC BY-SA 3.0

Body:
I am new to Angular Material Design.   I want to design a form which divides the date into three columns. I created two forms .  The first form contains two div's and second form contain one div.  I want each div in separate columns of the screen and Three div's should divide the screen width equally let's say 33.33% of 100% width but I am getting all the div's in only one column.  Given below is the code I wrote:

       <form name="userForm">

          <md-input-container class="md-block" flex="30">
            First Name
            <input>
          </md-input-container>
          <md-input-container class="md-block" flex="30">
           Last Name
           <input>
          </md-input-container>
          <md-input-container class="md-block" flex="30">
            Date Of Birth
            <input>
            </md-input-container>
          <md-input-container class="md-block" flex="30">
            Gender
            <input>
            </md-input-container>
          <md-input-container class="md-block" flex="30">
            Email
            <input>
          </md-input-container>
         <md-input-container class="md-block" flex="30">
           Mobile
           <input>
         </md-input-container>
         <md-input-container class="md-block" flex="30">
           Address
           <input>
         </md-input-container>
         <md-input-container class="md-block" flex="30">
           City
           <input>
        </md-input-container>

    <md-input-container class="md-block" flex="30">
      Country
      <input>
    </md-input-container>
    <md-input-container class="md-block" flex="30">
      State
      <input>
    </md-input-container>
    <md-input-container class="md-block" flex="30">
     Phone
     <input>
    </md-input-container>
    <md-input-container class="md-block" flex="30">
      Alternate Email
      <input>
    </md-input-container>
    <md-input-container class="md-block" flex="30">
      Alternate Mobile
      <input>
    </md-input-container>

</form>
<form name="security">

   <md-input-container class="md-block" flex="30">
     old password
    <input>
   </md-input-container>
   <md-input-container class="md-block" flex="30">
    New Password
    <input>
   </md-input-container>
   <md-input-container class="md-block" flex="30">
    Re-Enter Password
    <input>
   </md-input-container>

 </form>

Here is the plunker for the page I created

https://plnkr.co/edit/nj5o59A3NmqZtCv7HOfy?p=preview

Please help me as how to resolve this issue.

Body:
You flex is like the dividing the screen. You can use like this. The screen must be divide to 100%. If you use 3 div or md-input-container flex should be 33. i.e 100/3. If you have 4 divs you should divide the screen 100% to 4 equal parts.

    <div layout-xs="column">
              <md-input-container class="md-block" flex="33">
                <label>First Name</label>
                <input>
              </md-input-container>
              <md-input-container class="md-block" flex="33">
               <label>Last Name</label>
               <input>
              </md-input-container>
              <md-input-container class="md-block" flex="33">
                <label>Date Of Birth</label>
                <input>
              </md-input-container>
</div>

For more information visit the angular material official website.


问:
set up website on local machine
I have a fast dedicated internet connection and a static IP address at my office. I also have a web site that I want to host on my server machine (win server 2003). I know how to setup a web site through IIS but have no clue how to point my domain to my site and configure my server to serve for that domain. Can anyone point me to a preferably step-by-step guide on how to achieve this?</p>

答: This isn't really a programming question, but to start with you need to configure your dns server to point at your static ip address. You can probably do this at the website of your domain name seller.</p>

OwnerDisplayName: Emin

ContentLicense: CC BY-SA 2.5

Title: set up website on local machine

OwnerDisplayName: Beds

LastEditorDisplayName: Beds


问:
Why is it recommended to provide optional radix parameter to parseInt()?
I've always used the parseInt() function in Javascript without passing the radix parameter. As per the MDN documentation here, it's stated that not providing this parameter may result in unpredictable behaviour.

Always specify this parameter to eliminate reader confusion and to
  guarantee predictable behavior.

Could somebody clarify what does this unpredictable behavior mean with some code examples?

答:
Without supplying the radix, parseInt tries to determine what the right radix is by the value you pass in, for example  if the value starts 0x then it determines you must be passing in hex  values. Same applies with 0 (octal).

This becomes problematic when your input is zero-padded but no radix is supplied. Where the result will (possibly) not be as expected

console.log(parseInt(015))```


问:
I want to link one column from one table to same column name with another table in mysql so that i am able to carryout the add,update,delete opeations
I have two table

1: Roll_no Name Address Branch
 2: Roll_no Branch Name Percentage Marks

Is it possible in database that when i will add/update/Delete the data from one table it automatically do the operation on another with out front end programming...

答:
As @Gordan said the triggers are the best way to do this.
Follow the below steps to achieve your requirement,

Create Trigger using the below query,

CREATE TRIGGER trigger_name
AFTER INSERT
   ON 'User' FOR EACH ROW
Insert into 'UserCreatedTime' values(NOW())

What it meant, After inserting the values into 'User' table insert query for 'UserCreatedTime' table will be triggered automatically.

Please check the youtube video for more details,

https://www.youtube.com/watch?v=oKDqZCkBRZ8


问:
Better way to write this jQuery Function?
basically I am trying to trim down some of this code, but I am not sure how to do so, I have 9 DIV's positioned all absolute in different spots. They are all Grey, but when hovered the DIV that is hovered, fades out and the corresponding DIV fades in. Is there a better way to write this?</p>

```<code>$('#l1').hover(function () {
    $(this).fadeOut('300');
    $('#l1c').fadeIn('300')
});
$('#l2').hover(function () {
    $(this).fadeOut('300');
    $('#l2c').fadeIn('300')
});
$('#l3').hover(function () {
    $(this).fadeOut('300');
    $('#l3c').fadeIn('300')
});
$('#l4').hover(function () {
    $(this).fadeOut('300');
    $('#l4c').fadeIn('300')
});
$('#l5').hover(function () {
    $(this).fadeOut('300');
    $('#l5c').fadeIn('300')
});
$('#l6').hover(function () {
    $(this).fadeOut('300');
    $('#l6c').fadeIn('300')
});
$('#l7').hover(function () {
    $(this).fadeOut('300');
    $('#l7c').fadeIn('300')
});
$('#l7').hover(function () {
    $(this).fadeOut('300');
    $('#l7c').fadeIn('300')
});
$('#l1c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l1').fadeIn('300')
});
$('#l2c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l2').fadeIn('300')
});
$('#l3c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l3').fadeIn('300')
});
$('#l4c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l4').fadeIn('300')
});
$('#l5c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l5').fadeIn('300')
});
$('#l6c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l6').fadeIn('300')
});
$('#l7c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l7').fadeIn('300')
});
</code>```

答:
You can add two class for the two types of div. eg: for #l1 to #l7, add class ".ln"; for #l1c to #l7c, add class ".lnc", then use below code:</p>

```<code>$(".ln").live("hover", function(){
  $(this).fadeOut('300');
  $("#" + $(this).attr("id") + "c").fadeIn(300);
};

$(".lnc").live("mouseout", function(){
  var id = $(this).attr("id");
  $(this).fadeOut('300');
  $("#" + id.substring(0, id.length - 1)).fadeIn(300);
};
</code>```

Body:
basically I am trying to trim down some of this code, but I am not sure how to do so, I have 9 DIV's positioned all absolute in different spots. They are all Grey, but when hovered the DIV that is hovered, fades out and the corresponding DIV fades in. Is there a better way to write this?

$('#l1').hover(function () {
    $(this).fadeOut('300');
    $('#l1c').fadeIn('300')
});
$('#l2').hover(function () {
    $(this).fadeOut('300');
    $('#l2c').fadeIn('300')
});
$('#l3').hover(function () {
    $(this).fadeOut('300');
    $('#l3c').fadeIn('300')
});
$('#l4').hover(function () {
    $(this).fadeOut('300');
    $('#l4c').fadeIn('300')
});
$('#l5').hover(function () {
    $(this).fadeOut('300');
    $('#l5c').fadeIn('300')
});
$('#l6').hover(function () {
    $(this).fadeOut('300');
    $('#l6c').fadeIn('300')
});
$('#l7').hover(function () {
    $(this).fadeOut('300');
    $('#l7c').fadeIn('300')
});
$('#l7').hover(function () {
    $(this).fadeOut('300');
    $('#l7c').fadeIn('300')
});
$('#l1c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l1').fadeIn('300')
});
$('#l2c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l2').fadeIn('300')
});
$('#l3c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l3').fadeIn('300')
});
$('#l4c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l4').fadeIn('300')
});
$('#l5c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l5').fadeIn('300')
});
$('#l6c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l6').fadeIn('300')
});
$('#l7c').mouseout(function () {
    $(this).fadeOut('300');
    $('#l7').fadeIn('300')
});

Body:
You can add two class for the two types of div. eg: for #l1 to #l7, add class ".ln"; for #l1c to #l7c, add class ".lnc", then use below code:

$(".ln").live("hover", function(){
  $(this).fadeOut('300');
  $("#" + $(this).attr("id") + "c").fadeIn(300);
};

$(".lnc").live("mouseout", function(){
  var id = $(this).attr("id");
  $(this).fadeOut('300');
  $("#" + id.substring(0, id.length - 1)).fadeIn(300);
};


问:
Search dropdown suggestions
Is there a better way to build an input box with a dropdown list for suggestion other than the following?

```<code><div id="dropdown-group" class="input-group dropdown">
    <input id="keyword" type="search" class="form-control">

    <ul id="suggestion-list" class="dropdown-menu">
        <li>
            <a href="link">
                <img class="img-sm" src="img_path">
                <span>name</span>
            </a>
        </li>
    </ul>
</ul>
</code>```

input-group, dropdown, form-control and dropdown-menu are all bootstrap classes.
I use vuejs and ajax to fill the unordered list (#suggestion-list) as the user types in the search input field (#keyword).
I also listen to the input lost and get focus, where I add and remove the bootstrap class open to open and close the dropdown list. I deliberately skipped that javascript code to focus on html and css.

What is missing is when the functionality to hit the arrow-down key to browse the suggestion list.

Is there a better way to design such a list?

答: What about this. See it in action here. It doesn't matter what you want to do, there's always someone smarter and faster who's done it already.</p>

Title: Search dropdown suggestions

Body:
Is there a better way to build an input box with a dropdown list for suggestion other than the following?

    <input id="keyword" type="search" class="form-control">

                name

input-group, dropdown, form-control and dropdown-menu are all bootstrap classes.
I use vuejs and ajax to fill the unordered list (#suggestion-list) as the user types in the search input field (#keyword).
I also listen to the input lost and get focus, where I add and remove the bootstrap class open to open and close the dropdown list. I deliberately skipped that javascript code to focus on html and css.

What is missing is when the functionality to hit the arrow-down key to browse the suggestion list.

Is there a better way to design such a list?


问:
How to search the file in the Project directory in PyCharm?
How to search the file in the Project directory in PyCharm?

I only can use the Shift + Command + F to find the text in the project, can not find the Project directory file.

答:
Ctrl + Shift + N for Windows

Commad + Shift + O for Mac

PyCharm has pretty extensive abilities to navigate around code. Check out the navigation section of their windows or mac default keymappings for other cool navigation tricks.


问:
Handling Checked Exception in RxJava
I'm beginning to grasp RxJava1 (Now let's not get into why not RxJava2).

I've code like below:

```<code>MoviesAPI.findMovieURLsByType("comedy")
.map(s -> {
                    try {
                        return potentialCheckedException(s); //Throws CheckedException
                    } catch (MyExceptionType ex) {
                        return Exceptions.propagate(ex);
                    }
})
.subscribe(new Subscriber<String>() {
                    public void onCompleted() {
                        System.out.println("------Completed!-------");
                    }

                    public void onError(final Throwable e) {
                        System.out.println(e.getMessage());
                    }

                    public void onNext(final String s) {
                        System.out.println(s);
                    }
});
</code>```

I get compile error like below:

```<code>Error:(28, 17) java: no suitable method found for subscribe(<anonymous rx.Subscriber<java.lang.String>>)
    method rx.Observable.subscribe(rx.functions.Action1<? super java.io.Serializable>) is not applicable
      (argument mismatch; <anonymous rx.Subscriber<java.lang.String>> cannot be converted to rx.functions.Action1<? super java.io.Serializable>)
    method rx.Observable.subscribe(rx.Observer<? super java.io.Serializable>) is not applicable
      (argument mismatch; <anonymous rx.Subscriber<java.lang.String>> cannot be converted to rx.Observer<? super java.io.Serializable>)
    method rx.Observable.subscribe(rx.Subscriber<? super java.io.Serializable>) is not applicable
      (argument mismatch; <anonymous rx.Subscriber<java.lang.String>> cannot be converted to rx.Subscriber<? super java.io.Serializable>)
    method rx.Observable.<T>subscribe(rx.Subscriber<? super T>,rx.Observable<T>) is not applicable
      (cannot infer type-variable(s) T
        (actual and formal argument lists differ in length))
</code>```

If I were to remove the try-catch block and replace potentialCheckedException(s) with say noPotentialCheckedException(s), then the compile-error disappears. Why? What is it that I'm missing? Isn't wrapping CheckedException using Exceptions.propagate(ex) enough?

Thanks in advance.

答: Exceptions.propagate returns RuntimeException and potentialCheckedException returns String I assume. The lambda return type inference then can only find a common supertype of Serializable which is not compatible with an explicitly typed String subscriber. You are more likely want to throw Exceptions.propagate(ex).

Title: Handling Checked Exception in RxJava

Body:
I'm beginning to grasp RxJava1 (Now let's not get into why not RxJava2).

I've code like below:

MoviesAPI.findMovieURLsByType("comedy")
.map(s -> {
                    try {
                        return potentialCheckedException(s); //Throws CheckedException
                    } catch (MyExceptionType ex) {
                        return Exceptions.propagate(ex);
                    }
})
.subscribe(new Subscriber<String>() {
                    public void onCompleted() {
                        System.out.println("------Completed!-------");
                    }

                    public void onError(final Throwable e) {
                        System.out.println(e.getMessage());
                    }

                    public void onNext(final String s) {
                        System.out.println(s);
                    }
});

I get compile error like below:

Error:(28, 17) java: no suitable method found for subscribe(<anonymous rx.Subscriber<java.lang.String>>)
    method rx.Observable.subscribe(rx.functions.Action1<? super java.io.Serializable>) is not applicable
      (argument mismatch; <anonymous rx.Subscriber<java.lang.String>> cannot be converted to rx.functions.Action1<? super java.io.Serializable>)
    method rx.Observable.subscribe(rx.Observer<? super java.io.Serializable>) is not applicable
      (argument mismatch; <anonymous rx.Subscriber<java.lang.String>> cannot be converted to rx.Observer<? super java.io.Serializable>)
    method rx.Observable.subscribe(rx.Subscriber<? super java.io.Serializable>) is not applicable
      (argument mismatch; <anonymous rx.Subscriber<java.lang.String>> cannot be converted to rx.Subscriber<? super java.io.Serializable>)
    method rx.Observable.<T>subscribe(rx.Subscriber<? super T>,rx.Observable<T>) is not applicable
      (cannot infer type-variable(s) T
        (actual and formal argument lists differ in length))

If I were to remove the try-catch block and replace potentialCheckedException(s) with say noPotentialCheckedException(s), then the compile-error disappears. Why? What is it that I'm missing? Isn't wrapping CheckedException using Exceptions.propagate(ex) enough?

Thanks in advance.


问:
Angular2 service method add new item from input
I'm trying to make a method to create a new Player. But when i write something in input and submit my app do nothing (just refresh page).

Here is my code:

service.ts

```<code>import { Injectable } from '@angular/core';
import { Player } from './player';
import { WhitePlayers } from './mock-players';

@Injectable()
export class PlayersService {
  WhitePlayers: Player[];
  name;
  constructor() { }
    getPlayers(): Promise<Player[]> {
        return Promise.resolve(WhitePlayers);
    }

  createPlayer(): void {
    this.WhitePlayers.push(new Player(this.name));
  }

}
</code>```

component.ts

```<code>addPlayer(): void {
      this.playersServices.createPlayer();
    }
</code>```

component.html

```<code><form (submit)="addPlayer()" novalidate>
    <md-input-container>
      <input mdInput [(ngModel)]="name" placeholder="Add player" name="addNewPlayer">
    </md-input-container>
      <button type="submit">Add</button>
</form>
</code>```

Thank you very much for the answers :)

答:
If the page is refreshed your values in the field will be initialized again.

you can change the button type to button to avoid this.

```<code><button type="button">Add</button>
</code>```

You should also check the forms documentation. You can bind the form to a model and use ngSubmit to have a more Angular way in this process.

https://angular.io/guide/forms#submit-the-form-with-ngsubmit

Body:
I'm trying to make a method to create a new Player. But when i write something in input and submit my app do nothing (just refresh page).

Here is my code:

service.ts

import { Injectable } from '@angular/core';
import { Player } from './player';
import { WhitePlayers } from './mock-players';

@Injectable()
export class PlayersService {
  WhitePlayers: Player[];
  name;
  constructor() { }
    getPlayers(): Promise<Player[]> {
        return Promise.resolve(WhitePlayers);
    }

  createPlayer(): void {
    this.WhitePlayers.push(new Player(this.name));
  }

}

component.ts

addPlayer(): void {
      this.playersServices.createPlayer();
    }

component.html

<form (submit)="addPlayer()" novalidate>
    <md-input-container>
      <input mdInput [(ngModel)]="name" placeholder="Add player" name="addNewPlayer">
    </md-input-container>
      <button type="submit">Add</button>
</form>

Thank you very much for the answers :)

Body:
If the page is refreshed your values in the field will be initialized again.

you can change the button type to button to avoid this.

<button type="button">Add</button>

You should also check the forms documentation. You can bind the form to a model and use ngSubmit to have a more Angular way in this process.

https://angular.io/guide/forms#submit-the-form-with-ngsubmit


问:
Login to Bank using VBA
I am hoping to complete 2 simple tasks.  Input the password, and submit username and password to https://ktt.key.com

I am currently able to display my name in the username tab, but am having trouble entering password.  Please provide way to submit too.  Thanks for the help guys.

This is what I have so far...

```<code>Sub login()
  Dim IE As Object
  Dim HTMLDoc As Object
  Dim objCollection As Object

  Const navOpenInNewTab = &H800
  Set IE = CreateObject("InternetExplorer.Application")
  IE.Visible = True
  IE.Navigate "https://ktt.key.com/ktt/cmd/logon"

  Do While IE.Busy Or IE.ReadyState <> 4: Loop

  Set HTMLDoc = IE.document
   Set htmlColl = HTMLDoc.getElementsByName("moduleTarget")

  With HTMLDoc
  HTMLDoc.getElementById("userId").Value = "xxxxx"
  HTMLDoc.getElementByName("moduleTarget").Value = "xxxxxx"
  End With

End Sub
</code>```

答:
I noticed you have objCollection set as an Object, so I will be using that one to populate your password field.

Change:

```<code>With HTMLDoc
    HTMLDoc.getElementById("userId").Value = "xxxxx"
    HTMLDoc.getElementByName("moduleTarget").Value = "xxxxxx"
End With
</code>```

To:

```<code>With HTMLDoc
    HTMLDoc.getElementById("userId").Value = "xxxxx"
End With
</code>```

And then under that, paste:

```<code>Set objCollection = HTMLDoc.getelementsbyname("txtPassword")
objCollection(0).Value = "1234" 'This is your password
</code>```

So what this does it, it set a new object to the txtPassword Element collection.  Then it takes the first index (there's only one index here under "txtPassword") and assigns the value of your choice.  The full code (from With HTMLDoc down) should look like this:

```<code>With HTMLDoc
  HTMLDoc.getElementById("userId").Value = "xxxxx"
End With

Set objCollection = HTMLDoc.getelementsbyname("txtPassword")
objCollection(0).Value = "1234" 'This is your password
</code>```

Let me know if this works for you.

Title: Login to Bank using VBA

Body:
I am hoping to complete 2 simple tasks.  Input the password, and submit username and password to https://ktt.key.com

I am currently able to display my name in the username tab, but am having trouble entering password.  Please provide way to submit too.  Thanks for the help guys.

This is what I have so far...

Sub login()
  Dim IE As Object
  Dim HTMLDoc As Object
  Dim objCollection As Object

  Const navOpenInNewTab = &H800
  Set IE = CreateObject("InternetExplorer.Application")
  IE.Visible = True
  IE.Navigate "https://ktt.key.com/ktt/cmd/logon"

  Do While IE.Busy Or IE.ReadyState <> 4: Loop

  Set HTMLDoc = IE.document
   Set htmlColl = HTMLDoc.getElementsByName("moduleTarget")

  With HTMLDoc
  HTMLDoc.getElementById("userId").Value = "xxxxx"
  HTMLDoc.getElementByName("moduleTarget").Value = "xxxxxx"
  End With

End Sub

Body:
I noticed you have objCollection set as an Object, so I will be using that one to populate your password field.

Change:

With HTMLDoc
    HTMLDoc.getElementById("userId").Value = "xxxxx"
    HTMLDoc.getElementByName("moduleTarget").Value = "xxxxxx"
End With

To:

With HTMLDoc
    HTMLDoc.getElementById("userId").Value = "xxxxx"
End With

And then under that, paste:

Set objCollection = HTMLDoc.getelementsbyname("txtPassword")
objCollection(0).Value = "1234" 'This is your password

So what this does it, it set a new object to the txtPassword Element collection.  Then it takes the first index (there's only one index here under "txtPassword") and assigns the value of your choice.  The full code (from With HTMLDoc down) should look like this:

With HTMLDoc
  HTMLDoc.getElementById("userId").Value = "xxxxx"
End With

Set objCollection = HTMLDoc.getelementsbyname("txtPassword")
objCollection(0).Value = "1234" 'This is your password

Let me know if this works for you.


问:
How to find and replace values of a data frame in R?
I have two sets of Data frames. One contains the region names for different regional code. Another data frames has certain GTU data's with regional code mentioned. I want to replace regional codes of second data with region names based on the 1st data Using R. Please help !</p>

答:
If your data.frames are called df1 and df2 then you could try

try df_final <- merge(df1,df2,by="regional code").

Then df_final will contain everything (also region names and regional code).

Later you can delete the regional code column if you want by using

df_final[, !(colnames(df_final) %in% c("regional code"))]


问:
Frustrating Formula - Help Needed with Google Sheets formula/method
I am struggling to come up with a formula that fits certain criteria and was hoping someone with a better math brain than me might be able to help. What I have is a Google Sheets based tool that determines how much a someone has purchased of a product and then calculates the amount of times a special additional offer will be redeemed based on the amount spent.

As an example, the offer has three tiers to it. Though the actual costs will be variable for different offers let's say the first tier is gained with a $10 purchase, the second with a $20 purchase and the third with a $35 purchase (the only real relationship between the prices is that they get higher for each tier but there is no specific pattern to the costing of different offers). So if the customer bought $35 worth of goods they would get three free gifts, if they bought $45 worth they would get 4 and then an additional spend of $5 (totaling $50) would then allow them to redeem 5 gifts in total. It can be considered like filling a bucket, each time you hit the red line you get a new gift, when the bucket is full it's emptied and the process begins again.

If each tier of the offer was the same cost (e.g. $5, $10 and $15) this would be a simple case of division by the total purchase amount but as there is no specific relationship between the cost of the tiers (they are based on the value of the contents) I am having trouble coming up with a simple 'bucket filling' formula or calculation method that will work for any price ranges given to it. My current solution involved taking the modulus, subtracting offer amounts from the purchase amount etc. but provides plenty of cases where it breaks . If anyone could give me a start or provide some information that might help in my quest I would be highly appreciative and let me know if my explanation is unclear.! Thanks in advance and all the best

EDIT:
The user has three tiers and then the offer wraps around to the start after the initial three are unlocked once, looping until the offer has been maxed out. Avoiding a long sheet with a dynamic column of prices would be preferable and a small, multicell formula would be ideal

答:
I am not quite sure about, everything into one entire formula(is there a formula for loop and building arrays?)
from my understanding the tier amounts are viable, so every time you add a new tier with a new price limit then it must be calculated with a new limit price number...wouldn't it be much easier to write such module in javascript than in a google sheet? :o

anyways here is my workaround, that may could help you to find an idea

Example Doc
https://docs.google.com/spreadsheets/d/1z6mwkxqc2NyLJsH16NFWyL01y0jGcKrNNtuYcJS5dNw/edit#gid=0

my approach :
- enter purchases value
-> filter all items based by smaller than or equal "<=" (save all item somewhere as placeholder)
-> then decrease the purchases value by amount of existing number(max value) based on filtered items
-> save the new purchases value somewhere and begin from filtering again and decreasing the purchases value
(this needs to be done as many times again, till the purchases is empty)

after that, sums up all placeholder


问:
Show only one Shipping rate based on cart amount
Using Woocommerce in WordPress

I am trying to find a way to use 2 shipping charges:

If a customer order is less than n amount then shipping is standard x amount

If a customer order is more than n amount then shipping is reduced to x amount

I also need to hide the standard if the order qualifies for reduced shipping.

Currently woocommerce displays both shipping charges if the order qualifies for reduced shipping

Any ideas how i can resolve this please?

Thanks

答:
Here is a custom function hooked in woocommerce_package_rates action hook that will show only one shipping rate based on the cart amount limit:

```<code>add_filter( 'woocommerce_package_rates', 'hide_sshipping_rate_based_on_cart_amount', 100 );
function hide_sshipping_rate_based_on_cart_amount( $rates ) {

    // HERE define the limit amount to switch of shipping rate (integer)
    $amout_limit = 600;
    // Cart total amount (integer)
    $cart_total = WC()->cart->cart_contents_total;

    // Set below your 2 Rate ID slugs
    if( $cart_total >= $amout_limit )
        unset( $rates['flat_rate:12'] ); // Removes the LOWER Rate
    else
        unset( $rates['flat_rate:8'] ); // Removes the HIGHER Rate

    return $rates;
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Body:
Here is a custom function hooked in woocommerce_package_rates action hook that will show only one shipping rate based on the cart amount limit:

add_filter( 'woocommerce_package_rates', 'hide_sshipping_rate_based_on_cart_amount', 100 );
function hide_sshipping_rate_based_on_cart_amount( $rates ) {

    // HERE define the limit amount to switch of shipping rate (integer)
    $amout_limit = 600;
    // Cart total amount (integer)
    $cart_total = WC()->cart->cart_contents_total;

    // Set below your 2 Rate ID slugs
    if( $cart_total >= $amout_limit )
        unset( $rates['flat_rate:12'] ); // Removes the LOWER Rate
    else
        unset( $rates['flat_rate:8'] ); // Removes the HIGHER Rate

    return $rates;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.


问:
UNPIVOT and JOIN using col and row numbers
I have a data of order per costumer and per date that I achieved to present in the following way:

```<code>ID    Date    Record   ColNumber   RowNumber
----------------------------------------------------------------
</code>```

ColNumber / RowNumber being the position of the information in the formular
(Example: Description of the product is in the first column of the formular,

```<code>                                FORMULAR
                             ________________

Description   BarCode   Amount   RetailPrice  Others
-----------------------------------------------------
</code>```

hence the description of the 4th product on the formular will be of the form:

```<code>ID    Date    Record   ColNumber   RowNumber
----------------------------------------------------------------

ID    Date  Description    1           4
</code>```

"Record" contain all the columns of the formula (Description, BarCode, Amount, Retail Price, etc..)

So the aim is to have a table with the following columns:

```<code>ID    Date    Description    BarCode    Amount    Retail
------------------------------------------------------------------------
</code>```

I feel I need to use a mix of PIVOT and JOIN but what I achieved to do just brought me back to my initial "raw" table.

Here is a sample to make you understand:

```<code>IF OBJECT_ID ('tempdb..#temptab') IS NOT NULL
DROP TABLE #temptab

CREATE TABLE #temptab (
ID INT NOT NULL,
SellDate date NOT NULL,
Record nvarchar(255),
ColNumber int,
RowNumber int)

INSERT INTO #temptab (ID, SellDate, Record, ColNumber, RowNumber) VALUES
(1, '2017-01-01', 'Cookie1', 1, 1),
(1, '2017-01-01', '21312332', 1, 2),
(1, '2017-01-01', '3', 1, 2),
(1, '2017-01-01', 'Banana1', 2, 1),
(2, '2017-01-01', 'Apple1', 1, 1),
(3, '2017-01-01', 'Peach1', 1, 1),
(3, '2017-01-01', '546462', 1, 2);
</code>```

Which gives :

```<code>ID  SellDate    Record  ColNumber       RowNumber
1   2017-01-01  Cookie1    1                1
1   2017-01-01  CH212332   2                1
1   2017-01-01  3         3             1
1   2017-01-01  Banana1    1                2
2   2017-01-01  Apple1     1                1
3   2017-01-01  Peach1     1                1
3   2017-01-01  546462     2                1
</code>```

In the end I would like a table which look like that

```<code>ID  SellDate    Description    BarCode    Amount
1   2017-01-01   Cookie1       CH212332     3
1   2017-01-01   Banana1
2   2017-01-01   Apple1
3   2017-01-01   Peach1          546462
</code>```

(The missing values will be filled either by the reste of the information, I obviously didn't add the whole data in the table, or with NULL's)

答:
Try this it will give your Expected Result

```<code>SELECT ID
    ,SellDate
    ,ISNULL(Record, '') AS Record
    ,ISNULL(BarCode, '') AS BarCode
    ,ISNULL(Amount, '') AS Amount

FROM
(

SELECT ID, SellDate,
 CASE WHEN ISNUMERIC(Record)=0 THEN Record ELSE NULL END AS Record
,CASE WHEN ISNUMERIC(Record)=1  AND
        LEN(CASE WHEN ISNUMERIC(Record)=1 THEN Record ELSE NULL END)>1 THEN Record  ELSE NULL END AS BarCode
,CASE WHEN LEN(CASE WHEN ISNUMERIC(Record)=1 THEN Record ELSE NULL END)=1 THEN Record ELSE NULL END AS Amount
 FROM #temptab
 )DT
</code>```

Result

```<code>ID  SellDate    Record      BarCode     Amount
--------------------------------------------------
1   2017-01-01  Cookie1
1   2017-01-01              21312332
1   2017-01-01                              3
1   2017-01-01  Banana1
2   2017-01-01  Apple1
3   2017-01-01  Peach1
3   2017-01-01               546462
</code>```

Body:
I have a data of order per costumer and per date that I achieved to present in the following way:

ID    Date    Record   ColNumber   RowNumber
----------------------------------------------------------------

ColNumber / RowNumber being the position of the information in the formular
(Example: Description of the product is in the first column of the formular,

                                FORMULAR
                             ________________

Description   BarCode   Amount   RetailPrice  Others
-----------------------------------------------------

hence the description of the 4th product on the formular will be of the form:

ID    Date    Record   ColNumber   RowNumber
----------------------------------------------------------------

ID    Date  Description    1           4

"Record" contain all the columns of the formula (Description, BarCode, Amount, Retail Price, etc..)

So the aim is to have a table with the following columns:

ID    Date    Description    BarCode    Amount    Retail
------------------------------------------------------------------------

I feel I need to use a mix of PIVOT and JOIN but what I achieved to do just brought me back to my initial "raw" table.

Here is a sample to make you understand:

IF OBJECT_ID ('tempdb..#temptab') IS NOT NULL
DROP TABLE #temptab

CREATE TABLE #temptab (
ID INT NOT NULL,
SellDate date NOT NULL,
Record nvarchar(255),
ColNumber int,
RowNumber int)

INSERT INTO #temptab (ID, SellDate, Record, ColNumber, RowNumber) VALUES
(1, '2017-01-01', 'Cookie1', 1, 1),
(1, '2017-01-01', '21312332', 1, 2),
(1, '2017-01-01', '3', 1, 2),
(1, '2017-01-01', 'Banana1', 2, 1),
(2, '2017-01-01', 'Apple1', 1, 1),
(3, '2017-01-01', 'Peach1', 1, 1),
(3, '2017-01-01', '546462', 1, 2);

Which gives :

ID  SellDate    Record  ColNumber       RowNumber
1   2017-01-01  Cookie1    1                1
1   2017-01-01  CH212332   2                1
1   2017-01-01  3         3             1
1   2017-01-01  Banana1    1                2
2   2017-01-01  Apple1     1                1
3   2017-01-01  Peach1     1                1
3   2017-01-01  546462     2                1

In the end I would like a table which look like that

ID  SellDate    Description    BarCode    Amount
1   2017-01-01   Cookie1       CH212332     3
1   2017-01-01   Banana1
2   2017-01-01   Apple1
3   2017-01-01   Peach1          546462

(The missing values will be filled either by the reste of the information, I obviously didn't add the whole data in the table, or with NULL's)

Body:
Try this it will give your Expected Result

SELECT ID
    ,SellDate
    ,ISNULL(Record, '') AS Record
    ,ISNULL(BarCode, '') AS BarCode
    ,ISNULL(Amount, '') AS Amount

FROM
(

SELECT ID, SellDate,
 CASE WHEN ISNUMERIC(Record)=0 THEN Record ELSE NULL END AS Record
,CASE WHEN ISNUMERIC(Record)=1  AND
        LEN(CASE WHEN ISNUMERIC(Record)=1 THEN Record ELSE NULL END)>1 THEN Record  ELSE NULL END AS BarCode
,CASE WHEN LEN(CASE WHEN ISNUMERIC(Record)=1 THEN Record ELSE NULL END)=1 THEN Record ELSE NULL END AS Amount
 FROM #temptab
 )DT

Result

ID  SellDate    Record      BarCode     Amount
--------------------------------------------------
1   2017-01-01  Cookie1
1   2017-01-01              21312332
1   2017-01-01                              3
1   2017-01-01  Banana1
2   2017-01-01  Apple1
3   2017-01-01  Peach1
3   2017-01-01               546462


问:
Loading data from Firebase database which requires authentication throws error firebase could not parse auth token
I have a website that utilizes SQL Server on Azure for all of it's data. I'm partnering with another company to get additional, supplemental information for specific records that exist in my database.

When those "specific reccords" are being viewed, I want to provide another link to retrieve that supplemental information from the Firebase database.

So, I'm trying to write a service that will retrieve this data, here's what I've written so far as a PoC:

```<code>private readonly string firebaseUrl = "https://{myproject}.firebaseio.com/";
private readonly string authToken = "x:xxxxxxxxxxx:xxx:xxxxxxxxxxxxxxxx";

public async Task<IEnumerable<InMatchStat>> GetInMatchStats()
{
    try
    {
        var firebase = new FirebaseClient(firebaseUrl, new FirebaseOptions { AuthTokenAsyncFactory = () => Task.FromResult(authToken) });

        var stats = await firebase.Child("my/collection/path").OnceAsync<InMatchStat>();

        if (stats == null || !stats.Any())
        {
            return null;
        }

        return await Convert(stats.AsEnumerable());
    }
    catch (Exception exception)
    {
        var message = exception.ToString();
    }

    return null;
}
</code>```

This is the error that I'm getting back from Firebase when it tries to execute the var stats = await firebase.Child().... call:

firebase could not parse auth token

Here's a link to the FirebaseDatabase.NET Github page: https://github.com/step-up-labs/firebase-database-dotnet

In case that link goes dead in the future, here's the exact sample that I'm trying to replicate that is shown on that site:

```<code>var auth = "ABCDE"; // your app secret
var firebaseClient = new FirebaseClient(
  "<URL>",
  new FirebaseOptions
  {
    AuthTokenAsyncFactory = () => Task.FromResult(auth)
  });
</code>```

And the query example from that page:

```<code>var firebase = new FirebaseClient("https://dinosaur-facts.firebaseio.com/");
var dinos = await firebase
  .Child("dinosaurs")
  .OrderByKey()
  .StartAt("pterodactyl")
  .LimitToFirst(2)
  .OnceAsync<Dinosaur>();

foreach (var dino in dinos)
{
  Console.WriteLine($"{dino.Key} is {dino.Object.Height}m high.");
}
</code>```

Where am I going wrong with my implementation?

答:
Just want to get this updated as I finally figured out the solution, for me...

Here's where I got the solution from: https://github.com/step-up-labs/firebase-database-dotnet/issues/60

This version passes the email address and password to get the authentication token. Then once we have the token, it gets passed to the Firebase client like before.

(Note: I needed to add the FirebaseAuthentication.net nuget package)

```<code>public async Task<IEnumerable<InMatchStat>> GetInMatchStats()
{
    const string firebaseUrl = "https://xxxxxxxxxxxxxx.firebaseio.com/";
    const string firebaseUsername = "xxxxxxxxxxxxxxxxxxxxx@xxxxx.xxx";
    const string firebasePassword = "xxxxxxxx";
    const string firebaseApiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    bool tryAgain = false;
    FirebaseAuthLink token = null;

    try
    {
        var auth = new FirebaseAuthProvider(new FirebaseConfig(firebaseApiKey));

        do
        {
            try
            {
                token = await auth.SignInWithEmailAndPasswordAsync(firebaseUsername, firebasePassword);
            }
            catch (FirebaseAuthException faException)
            {
                // checking for a false tryAgain because we don't want to try and create the account twice
                if (faException.Reason.ToString() == "UnknownEmailAddress" && !tryAgain)
                {
                    // create, then signin
                    token = await auth.CreateUserWithEmailAndPasswordAsync(firebaseUsername, firebasePassword, "Greg", false);
                    tryAgain = true;
                }

                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }
        while (tryAgain);

        var firebase = new FirebaseClient(firebaseUrl, new FirebaseOptions { AuthTokenAsyncFactory = () => Task.FromResult(token.FirebaseToken) });
        var stats = await firebase.Child("my/collection/path").OnceAsync<InMatchStat>();

        if (stats == null || !stats.Any())
        {
            return null;
        }

        //return await Convert(stats.AsEnumerable());
    }
    catch (Exception exception)
    {
        var message = exception.ToString();
    }

    return null;
}
</code>```

Body:
I have a website that utilizes SQL Server on Azure for all of it's data. I'm partnering with another company to get additional, supplemental information for specific records that exist in my database.

When those "specific reccords" are being viewed, I want to provide another link to retrieve that supplemental information from the Firebase database.

So, I'm trying to write a service that will retrieve this data, here's what I've written so far as a PoC:

private readonly string firebaseUrl = "https://{myproject}.firebaseio.com/";
private readonly string authToken = "x:xxxxxxxxxxx:xxx:xxxxxxxxxxxxxxxx";

public async Task<IEnumerable<InMatchStat>> GetInMatchStats()
{
    try
    {
        var firebase = new FirebaseClient(firebaseUrl, new FirebaseOptions { AuthTokenAsyncFactory = () => Task.FromResult(authToken) });

        var stats = await firebase.Child("my/collection/path").OnceAsync<InMatchStat>();

        if (stats == null || !stats.Any())
        {
            return null;
        }

        return await Convert(stats.AsEnumerable());
    }
    catch (Exception exception)
    {
        var message = exception.ToString();
    }

    return null;
}

This is the error that I'm getting back from Firebase when it tries to execute the var stats = await firebase.Child().... call:

firebase could not parse auth token

Here's a link to the FirebaseDatabase.NET Github page: https://github.com/step-up-labs/firebase-database-dotnet

In case that link goes dead in the future, here's the exact sample that I'm trying to replicate that is shown on that site:

var auth = "ABCDE"; // your app secret
var firebaseClient = new FirebaseClient(
  "<URL>",
  new FirebaseOptions
  {
    AuthTokenAsyncFactory = () => Task.FromResult(auth)
  });

And the query example from that page:

var firebase = new FirebaseClient("https://dinosaur-facts.firebaseio.com/");
var dinos = await firebase
  .Child("dinosaurs")
  .OrderByKey()
  .StartAt("pterodactyl")
  .LimitToFirst(2)
  .OnceAsync<Dinosaur>();

foreach (var dino in dinos)
{
  Console.WriteLine($"{dino.Key} is {dino.Object.Height}m high.");
}

Where am I going wrong with my implementation?

Body:
Just want to get this updated as I finally figured out the solution, for me...

Here's where I got the solution from: https://github.com/step-up-labs/firebase-database-dotnet/issues/60

This version passes the email address and password to get the authentication token. Then once we have the token, it gets passed to the Firebase client like before.

(Note: I needed to add the FirebaseAuthentication.net nuget package)

public async Task<IEnumerable<InMatchStat>> GetInMatchStats()
{
    const string firebaseUrl = "https://xxxxxxxxxxxxxx.firebaseio.com/";
    const string firebaseUsername = "xxxxxxxxxxxxxxxxxxxxx@xxxxx.xxx";
    const string firebasePassword = "xxxxxxxx";
    const string firebaseApiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    bool tryAgain = false;
    FirebaseAuthLink token = null;

    try
    {
        var auth = new FirebaseAuthProvider(new FirebaseConfig(firebaseApiKey));

        do
        {
            try
            {
                token = await auth.SignInWithEmailAndPasswordAsync(firebaseUsername, firebasePassword);
            }
            catch (FirebaseAuthException faException)
            {
                // checking for a false tryAgain because we don't want to try and create the account twice
                if (faException.Reason.ToString() == "UnknownEmailAddress" && !tryAgain)
                {
                    // create, then signin
                    token = await auth.CreateUserWithEmailAndPasswordAsync(firebaseUsername, firebasePassword, "Greg", false);
                    tryAgain = true;
                }

                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }
        while (tryAgain);

        var firebase = new FirebaseClient(firebaseUrl, new FirebaseOptions { AuthTokenAsyncFactory = () => Task.FromResult(token.FirebaseToken) });
        var stats = await firebase.Child("my/collection/path").OnceAsync<InMatchStat>();

        if (stats == null || !stats.Any())
        {
            return null;
        }

        //return await Convert(stats.AsEnumerable());
    }
    catch (Exception exception)
    {
        var message = exception.ToString();
    }

    return null;
}


问:
IOS:UISerachBar Filter name but not the related id with it
i have a JSON Dict in this format

```<code>{
  "382" : "sudhir kumar",
  "268" : "David  ",
  "385" : "aayush test",
  "261" : "Mike watson",
  "277" : "TestDrivers Driver",
  "381" : "sudhir kumar",
  "380" : "sudhir kumar",
  "383" : "asdfgh asdfgh",
  "376" : " "
}
</code>```

I have to display it in UISearchBar. Someone please help me to solve it as when i select any name from search its respective Id also selected

I am using the following code it filtered name but not their related ID's with name

My code is:

```<code>- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{
    tempArray = [NSArray arrayWithArray:DriverNameArray];
    //NSString *stringToSearch = textField.text;

    tempId = [NSArray arrayWithArray:DriverIdArray];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",searchText]; // if you need case sensitive search avoid '[c]' in the predicate

    //NSPredicate * predicateid = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",stringToSearch];

    NSArray *tempresults = [DriverNameArray filteredArrayUsingPredicate:predicate];
    if (tempresults.count > 0)
    {
        tempArray = [NSArray arrayWithArray:tempresults];
        tempId = [NSArray arrayWithArray:tempresults];
    }
    [SEarchTable reloadData];
    //return  YES;
}
</code>```

It always returns the same id for all the filtered names

答:
You are filtering only Drivers' names  array, which is not primarily connected with Drivers' ids array. I suggest you joining id, and name into a dictionary and storing it in one array. So that, whenever you filter it with name, or id the rest info will be stored in one object

```<code>@property (nonatomic, strong) NSMutableArray *allElements
@property (nonatomic, strong) NSArray *filteredArray;
</code>```

`

```<code>  for (int i=0; i < 10; i++) { //Just simple example
        NSDictionary *dictionary = @{@"name": DriverNameArray[i], @"id": DriverIdArray[i] };
        [self.allElements addObject:dictionary];

    }
</code>```

And in your searchbar delegate you can use:

```<code>NSArray *copyArray = [self.allElements copy];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@", searchText];

NSArray *filteredArray = [copyArray filteredArrayUsingPredicate:predicate];

self.filteredArray = filteredArray;

[self.tableView reloadData];
</code>```

Body:
i have a JSON Dict in this format

{
  "382" : "sudhir kumar",
  "268" : "David  ",
  "385" : "aayush test",
  "261" : "Mike watson",
  "277" : "TestDrivers Driver",
  "381" : "sudhir kumar",
  "380" : "sudhir kumar",
  "383" : "asdfgh asdfgh",
  "376" : " "
}

I have to display it in UISearchBar. Someone please help me to solve it as when i select any name from search its respective Id also selected

I am using the following code it filtered name but not their related ID's with name

My code is:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText;
{
    tempArray = [NSArray arrayWithArray:DriverNameArray];
    //NSString *stringToSearch = textField.text;

    tempId = [NSArray arrayWithArray:DriverIdArray];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",searchText]; // if you need case sensitive search avoid '[c]' in the predicate

    //NSPredicate * predicateid = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",stringToSearch];

    NSArray *tempresults = [DriverNameArray filteredArrayUsingPredicate:predicate];
    if (tempresults.count > 0)
    {
        tempArray = [NSArray arrayWithArray:tempresults];
        tempId = [NSArray arrayWithArray:tempresults];
    }
    [SEarchTable reloadData];
    //return  YES;
}

It always returns the same id for all the filtered names

Body:
You are filtering only Drivers' names  array, which is not primarily connected with Drivers' ids array. I suggest you joining id, and name into a dictionary and storing it in one array. So that, whenever you filter it with name, or id the rest info will be stored in one object

@property (nonatomic, strong) NSMutableArray *allElements
@property (nonatomic, strong) NSArray *filteredArray;

`

  for (int i=0; i < 10; i++) { //Just simple example
        NSDictionary *dictionary = @{@"name": DriverNameArray[i], @"id": DriverIdArray[i] };
        [self.allElements addObject:dictionary];

    }

And in your searchbar delegate you can use:

NSArray *copyArray = [self.allElements copy];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name BEGINSWITH %@", searchText];

NSArray *filteredArray = [copyArray filteredArrayUsingPredicate:predicate];

self.filteredArray = filteredArray;

[self.tableView reloadData];


问:
Change current time of video player on scroll depending on height of content
I have a background video (html5 video element), fixed position width and height 100% with some text on it. When I scroll down, the video has to fast forward and the speed has to depend on how long my content (text) is. So the video will be at its end when you scrolled to the bottom.

I found this example: https://codepen.io/anon/pen/GxDJg

And I have this so far:
https://codepen.io/rluijten/project/editor/AOywwy/

```<code>const accelAmount = 0.01;
const bounceAmount = 0.91;
const video = document.getElementById('video');
const main = document.querySelector('main');

let scrollPos = main.scrollTop / 30;
let targetScrollPos = scrollPos;
let accel = 0;

video.pause();

main.addEventListener('scroll', () => {
  targetScrollPos = main.scrollTop / 30;
});

setInterval(() => {
  // accelerate towards the target:
  accel += (targetScrollPos - scrollPos) * accelAmount;

  // clamp the acceleration so that it doesnt go too fast
  if (accel > 1) accel = 1;
  if (accel < -1) accel = -1;

  // move the video scroll position according to the acceleration and how much bouncing you selected:
  scrollPos = (scrollPos + accel) * bounceAmount + (targetScrollPos * (1 - bounceAmount));

  // update video playback
  video.currentTime = scrollPos;
  video.pause();
}, 40);
</code>```

Now I'm trying to make the height of my content equal to the duration of my video. But I don't really have an idea to achieve this. Any thoughts?

答:
    const video = document.getElementById('video');
    const main = document.querySelector('main');

    let targetScrollPos = main.scrollTop;
    let targetScrollMax = main.scrollHeight;
    let step = 0.1;
    let buffer = [];
    let playing = false;

    video.pause();

    function playVideo(pos) {
      if (playing) {
        return buffer.push(pos);
      }
      playing = true;

      var dt = pos - video.currentTime > 0 ? 1 : -1,
        sid = setInterval(() => {
          video.currentTime += dt * step;
          video.pause();

          if (dt > 0 ? video.currentTime >= pos : video.currentTime <= pos) {
            video.currentTime = pos;
            video.pause();
            if (buffer.length) {
              playing = false;
              playVideo(buffer.pop()); // just last one is relevant
              buffer = [];
            }
            playing = false;
            clearInterval(sid);
          }
        }, step * 1000);
    }

    main.addEventListener('scroll', (e) => {
      playVideo(video.duration * main.scrollTop / main.scrollHeight);
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    body,
    html {
      height: 100%;
      margin: 0;
      padding: 0;
    }

    main {
      overflow: scroll;
      overflow-x: hidden;
      height: 100%;
    }

    .video-container {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
      height: 100%;
      z-index: 0;
    }

    .video-container__video {
      position: absolute;
      min-width: 100%;
      min-height: 100%;
      width: auto;
      height: auto;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    .content-block {
      position: relative;
      width: 50%;
      margin-left: auto;
      margin-right: auto;
      margin-bottom: 2px;
      padding: 50px 60px 0;
      overflow: hidden;
      background-color: white;
      z-index: 1;
      opacity: 0.5;
    }

    .content-block:first-child {
      margin-top: 150px;
    }

    .content-block__title {
      font-size: 18px;
      font-weight: bold;
      text-transform: uppercase;
      margin-bottom: 30px;
    }

    .content-block__text {
      margin-bottom: 30px;
    }</code>```

      <title>Video Scroll experiment</title>

        <video id="video" class="video-container__video">
                <source src="https://www.html5rocks.com/tutorials/video/basics/Chrome_ImF.mp4" type="video/mp4">
                Your browser does not support the video tag.
              </video>

            Applications for September 2017 entry are now closed. Please see the FAQ section for application deadlines.

            A unique course in the field of theatre and performance practice, this one-year MA course allows students with a strong, demonstrable background in performance to re-examine and broaden their skills in a truly experimental and highly collaborative framework.

            The emphasis throughout the year is on devised and ensemble work, as you will advance your understanding of performance from a post-Stanislavski standpoint.

            The course, validated by Kingâ€™s College London, one of the worldâ€™s top 20 universities, explores non-mainstream theatre craft internationally. Read about some of graduates in the downloadable PDF

            The course is built around three strands:

            Acting and Performance: Practice and Methodology - Working from the foundation of the Stanislavski â€˜systemâ€™, you will be introduced to the approaches and responses of later practitioners, including Brecht, Copeau, Meyerhold, and Grotowski. International
            historical context is given through exploring the improvisational and physical practice, developments in experimental theatre internationally, new writing, and performance since the early 20th Century. Development of Performance - This dual aspect
            of the course builds on your strengths and skills, whilst improving areas where you are less experienced. The first strand supports you as you refine and improve your understanding of how to develop as an individual within an ensemble environment.
            The second covers vocal and physical performance training, supplemented by Commedia, creative writing, improvisation, and singing. Scene Study - Scene study is woven throughout the course and provides a forum for you to develop and experiment
            with the techniques you are learning.

Course Details

            Our full time, three-year BA in Acting (conservatoire training) develops a high level of technical facility, flexibility, individuality and imagination. The training provides skills in acting, voice, singing and movement, and students apply these skills
            in a wide variety of media including theatre, television, film and radio.

The Program

            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.

The Program

            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.

The Program

            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.

The Program

            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.

The Program

            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.

The Program

            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.

The Program

            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.

The Program

            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.

The Program

            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.

The Program

            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.

    ```

Body:
I have a background video (html5 video element), fixed position width and height 100% with some text on it. When I scroll down, the video has to fast forward and the speed has to depend on how long my content (text) is. So the video will be at its end when you scrolled to the bottom.

I found this example: https://codepen.io/anon/pen/GxDJg

And I have this so far:
https://codepen.io/rluijten/project/editor/AOywwy/

const accelAmount = 0.01;
const bounceAmount = 0.91;
const video = document.getElementById('video');
const main = document.querySelector('main');

let scrollPos = main.scrollTop / 30;
let targetScrollPos = scrollPos;
let accel = 0;

video.pause();

main.addEventListener('scroll', () => {
  targetScrollPos = main.scrollTop / 30;
});

setInterval(() => {
  // accelerate towards the target:
  accel += (targetScrollPos - scrollPos) * accelAmount;

  // clamp the acceleration so that it doesnt go too fast
  if (accel > 1) accel = 1;
  if (accel < -1) accel = -1;

  // move the video scroll position according to the acceleration and how much bouncing you selected:
  scrollPos = (scrollPos + accel) * bounceAmount + (targetScrollPos * (1 - bounceAmount));

  // update video playback
  video.currentTime = scrollPos;
  video.pause();
}, 40);

Now I'm trying to make the height of my content equal to the duration of my video. But I don't really have an idea to achieve this. Any thoughts?

Body:
    const video = document.getElementById('video');
    const main = document.querySelector('main');

    let targetScrollPos = main.scrollTop;
    let targetScrollMax = main.scrollHeight;
    let step = 0.1;
    let buffer = [];
    let playing = false;

    video.pause();

    function playVideo(pos) {
      if (playing) {
        return buffer.push(pos);
      }
      playing = true;

      var dt = pos - video.currentTime > 0 ? 1 : -1,
        sid = setInterval(() => {
          video.currentTime += dt * step;
          video.pause();

          if (dt > 0 ? video.currentTime >= pos : video.currentTime <= pos) {
            video.currentTime = pos;
            video.pause();
            if (buffer.length) {
              playing = false;
              playVideo(buffer.pop()); // just last one is relevant
              buffer = [];
            }
            playing = false;
            clearInterval(sid);
          }
        }, step * 1000);
    }

    main.addEventListener('scroll', (e) => {
      playVideo(video.duration * main.scrollTop / main.scrollHeight);
    });

    body,
    html {
      height: 100%;
      margin: 0;
      padding: 0;
    }

    main {
      overflow: scroll;
      overflow-x: hidden;
      height: 100%;
    }

    .video-container {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
      height: 100%;
      z-index: 0;
    }

    .video-container__video {
      position: absolute;
      min-width: 100%;
      min-height: 100%;
      width: auto;
      height: auto;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    .content-block {
      position: relative;
      width: 50%;
      margin-left: auto;
      margin-right: auto;
      margin-bottom: 2px;
      padding: 50px 60px 0;
      overflow: hidden;
      background-color: white;
      z-index: 1;
      opacity: 0.5;
    }

    .content-block:first-child {
      margin-top: 150px;
    }

    .content-block__title {
      font-size: 18px;
      font-weight: bold;
      text-transform: uppercase;
      margin-bottom: 30px;
    }

    .content-block__text {
      margin-bottom: 30px;
    }

    <html>

    <head>
      <title>Video Scroll experiment</title>

    </head>

    <body>
      <div class="video-container">
        <video id="video" class="video-container__video">
                <source src="https://www.html5rocks.com/tutorials/video/basics/Chrome_ImF.mp4" type="video/mp4">
                Your browser does not support the video tag.
              </video>
      </div>

      <main class="main">
        <div class="content-block">
          <p class="content-block__text">
            Applications for September 2017 entry are now closed. Please see the FAQ section for application deadlines.
          </p>

          <p class="content-block__text">
            A unique course in the field of theatre and performance practice, this one-year MA course allows students with a strong, demonstrable background in performance to re-examine and broaden their skills in a truly experimental and highly collaborative framework.
          </p>

          <p class="content-block__text">
            The emphasis throughout the year is on devised and ensemble work, as you will advance your understanding of performance from a post-Stanislavski standpoint.
          </p>

          <p class="content-block__text">
            The course, validated by Kingâ€™s College London, one of the worldâ€™s top 20 universities, explores non-mainstream theatre craft internationally. Read about some of graduates in the downloadable PDF
          </p>
        </div>

        <div class="content-block">
          <p class="content-block__text">
            The course is built around three strands:
          </p>

          <p class="content-block__text">
            Acting and Performance: Practice and Methodology - Working from the foundation of the Stanislavski â€˜systemâ€™, you will be introduced to the approaches and responses of later practitioners, including Brecht, Copeau, Meyerhold, and Grotowski. International
            historical context is given through exploring the improvisational and physical practice, developments in experimental theatre internationally, new writing, and performance since the early 20th Century. Development of Performance - This dual aspect
            of the course builds on your strengths and skills, whilst improving areas where you are less experienced. The first strand supports you as you refine and improve your understanding of how to develop as an individual within an ensemble environment.
            The second covers vocal and physical performance training, supplemented by Commedia, creative writing, improvisation, and singing. Scene Study - Scene study is woven throughout the course and provides a forum for you to develop and experiment
            with the techniques you are learning.
          </p>
        </div>

        <div class="content-block">
          <h2 class="content-block__title">Course Details</h2>
          <p class="content-block__text">
            Our full time, three-year BA in Acting (conservatoire training) develops a high level of technical facility, flexibility, individuality and imagination. The training provides skills in acting, voice, singing and movement, and students apply these skills
            in a wide variety of media including theatre, television, film and radio.
          </p>
        </div>

        <div class="content-block">
          <h2 class="content-block__title">The Program</h2>
          <p class="content-block__text">
            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.
          </p>
        </div>

        <div class="content-block">
          <h2 class="content-block__title">The Program</h2>
          <p class="content-block__text">
            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.
          </p>
        </div>

        <div class="content-block">
          <h2 class="content-block__title">The Program</h2>
          <p class="content-block__text">
            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.
          </p>
        </div>

        <div class="content-block">
          <h2 class="content-block__title">The Program</h2>
          <p class="content-block__text">
            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.
          </p>
        </div>

        <div class="content-block">
          <h2 class="content-block__title">The Program</h2>
          <p class="content-block__text">
            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.
          </p>
        </div>

        <div class="content-block">
          <h2 class="content-block__title">The Program</h2>
          <p class="content-block__text">
            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.
          </p>
        </div>

        <div class="content-block">
          <h2 class="content-block__title">The Program</h2>
          <p class="content-block__text">
            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.
          </p>
        </div>

        <div class="content-block">
          <h2 class="content-block__title">The Program</h2>
          <p class="content-block__text">
            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.
          </p>
        </div>

        <div class="content-block">
          <h2 class="content-block__title">The Program</h2>
          <p class="content-block__text">
            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.
          </p>
        </div>

        <div class="content-block">
          <h2 class="content-block__title">The Program</h2>
          <p class="content-block__text">
            The training is classically based because we believe this provides the best foundation for acting in any form or media. However, the training also includes a thorough grounding in contemporary plays and styles as well as classes in camera and microphone
            technique. Your work will be continuously assessed with extensive individual feedback through regular sessions, written reports, and one-to-one tutorials.
          </p>
        </div>
      </main>

      <footer class="footer"></footer>

    </body>

    </html>


问:
How is Angular's *ngFor loop implemented?
I wonder how does Angular's *ngFor directive actually work under the hood? I would like to know the whole process that happens when I use the directive.

For downvoters: I've seen the ng-for-of file, although there is no single usage of passed to *ngFor array's e.g. join() method that I know is invoked. Thanks for your support :)
Here is the plunker that shows the behavior: https://plnkr.co/edit/IXVxWrSOhLBgvSal6PWL?p=preview

答:
Here is a high level overview. Suppose you define your template like this:

```<code><span *ngFor="let item of items">{{item}}</span>
</code>```

Then it's transformed to the following by the compiler:

```<code><ng-template let-item [ngForOf]="items">
    <span>{{item}}</span>
</ng-template>
</code>```

Then Angular applies ngForOf directive to the template element. Since this directive's host element is template, it injects the templateRef. It also injects the viewContainerRef that acts as an anchor element and will be used to add DOM elements alongside:

```<code>  constructor(
       private _viewContainer: ViewContainerRef,
       private _template: TemplateRef<NgForOfContext<T>>,
</code>```

The directive defines ngForOf as an input and then waits until it's initialized and creates a differ:

```<code>  ngOnChanges(changes: SimpleChanges): void {
      const value = changes['ngForOf'].currentValue;
          this._differ = this._differs.find(value).create(this.ngForTrackBy);
</code>```

Then on each check detection cycle it compares the values to the previous values using this differ:

```<code>  ngDoCheck(): void {
    if (this._differ) {
      const changes = this._differ.diff(this.ngForOf);
      if (changes) this._applyChanges(changes);
    }
  }
</code>```

If the values changed, it applies the changes doing the the following things:

1) generates embedded view context for each item in items

```<code>context = new NgForOfContext<T>(null !, this.ngForOf, -1, -1)
</code>```

2) creates embedded view with this context using the templateRef which effectively renders new value in the DOM

```<code>this._viewContainer.createEmbeddedView(
                this._template, context , currentIndex);
</code>```

3) adds relevant values to context

```<code>  viewRef.context.index = i;
  viewRef.context.count = ilen;
  viewRef.context.$implicit = record.item;`
</code>```

Now, your question:

although it doesn't explain why e..g join() method is invoked on array
  passed to

It's called by the function normalizeDebugBindingValue here because your application is running in the development mode:

```<code>function normalizeDebugBindingValue(value: any): string {
  try {
    // Limit the size of the value as otherwise the DOM just gets polluted.
    return value != null ? value.toString().slice(0, 30) : value;
                           ^^^^^^^^^^^^^^^
  } catch (e) {
    return '[ERROR] Exception while trying to serialize the value';
  }
}
</code>```

If you enable production mode, this function will no longer be called. Check the plunker.

Body:
Here is a high level overview. Suppose you define your template like this:

<span *ngFor="let item of items">{{item}}</span>

Then it's transformed to the following by the compiler:

<ng-template let-item [ngForOf]="items">
    <span>{{item}}</span>
</ng-template>

Then Angular applies ngForOf directive to the template element. Since this directive's host element is template, it injects the templateRef. It also injects the viewContainerRef that acts as an anchor element and will be used to add DOM elements alongside:

  constructor(
       private _viewContainer: ViewContainerRef,
       private _template: TemplateRef<NgForOfContext<T>>,

The directive defines ngForOf as an input and then waits until it's initialized and creates a differ:

  ngOnChanges(changes: SimpleChanges): void {
      const value = changes['ngForOf'].currentValue;
          this._differ = this._differs.find(value).create(this.ngForTrackBy);

Then on each check detection cycle it compares the values to the previous values using this differ:

  ngDoCheck(): void {
    if (this._differ) {
      const changes = this._differ.diff(this.ngForOf);
      if (changes) this._applyChanges(changes);
    }
  }

If the values changed, it applies the changes doing the the following things:

1) generates embedded view context for each item in items

context = new NgForOfContext<T>(null !, this.ngForOf, -1, -1)

2) creates embedded view with this context using the templateRef which effectively renders new value in the DOM

this._viewContainer.createEmbeddedView(
                this._template, context , currentIndex);

3) adds relevant values to context

  viewRef.context.index = i;
  viewRef.context.count = ilen;
  viewRef.context.$implicit = record.item;`

Now, your question:

although it doesn't explain why e..g join() method is invoked on array
  passed to

It's called by the function normalizeDebugBindingValue here because your application is running in the development mode:

function normalizeDebugBindingValue(value: any): string {
  try {
    // Limit the size of the value as otherwise the DOM just gets polluted.
    return value != null ? value.toString().slice(0, 30) : value;
                           ^^^^^^^^^^^^^^^
  } catch (e) {
    return '[ERROR] Exception while trying to serialize the value';
  }
}

If you enable production mode, this function will no longer be called. Check the plunker.

ContentLicense: CC BY-SA 4.0


问:
Deployed Web Core API: Response status code does not indicate success: 404 (Not Found).
I have deployed a new application that contains a Web Project which communicates with a Web Core API.
I have used this link as a reference to set it up;
https://learn.microsoft.com/en-us/aspnet/core/publishing/iis
IIS has been set up for a while on this test server, so some the steps did not need to be repeated.
In IIS if I browse the Web API is launches as follows.

But if I do likewise for the web project that uses it, I am getting this error:

```<code>Response status code does not indicate success: 404 (Not Found) for a simple get call to the Web API.
</code>```

What should I be considering to fix this?

答: I found that the URI I needed on the deployment server needed to have the name of my application, whilst in development this was not needed. Once I made that correction it worked fine. </p>

Body:
I have deployed a new application that contains a Web Project which communicates with a Web Core API.
I have used this link as a reference to set it up;
https://learn.microsoft.com/en-us/aspnet/core/publishing/iis
IIS has been set up for a while on this test server, so some the steps did not need to be repeated.
In IIS if I browse the Web API is launches as follows.

But if I do likewise for the web project that uses it, I am getting this error:

Response status code does not indicate success: 404 (Not Found) for a simple get call to the Web API.

What should I be considering to fix this?


问:
com.liferay.portlet.ActionResponseImpl cannot be cast to com.liferay.portlet.ActionResponseImpl
I tried to cast Action response like this:

```<code> private void mappingMethod(ActionResponse response) {

        ActionResponseImpl actionResponseImpl = (ActionResponseImpl)response;
...}
</code>```

In debugging on "Expression Evaluation" window I can see the type of "responce" is ActionResponseImpl, and cast does not cause exception. But on runtime I have this exeption:

java.lang.ClassCastException: com.liferay.portlet.ActionResponseImpl cannot be cast to com.liferay.portlet.ActionResponseImpl

Please tell me what is the problem.

P.S.: In PortalImpl class, the copyRequestParameters method has same string, but here it's working....

答:
This type of errors are produced by different classloaders. A class is identified by their fully qualified class name AND its Classloader. So if you embedd portal-impl in your portlet; the action is going to receive an ActionResponseImpl instance from the portal classloader and is trying to cast this one to a class of your portlet class loader .

see more: http://www.javaspecialists.eu/archive/Issue018.html

Body:
I tried to cast Action response like this:

 private void mappingMethod(ActionResponse response) {

        ActionResponseImpl actionResponseImpl = (ActionResponseImpl)response;
...}

In debugging on "Expression Evaluation" window I can see the type of "responce" is ActionResponseImpl, and cast does not cause exception. But on runtime I have this exeption:

java.lang.ClassCastException: com.liferay.portlet.ActionResponseImpl cannot be cast to com.liferay.portlet.ActionResponseImpl

Please tell me what is the problem.

P.S.: In PortalImpl class, the copyRequestParameters method has same string, but here it's working....


问:
Use cucumber Tags in different feature file
Instead create multiple feature files is it possible to have just one feature file and another file where I can call different sequence of cucumber tags like:

@step1, @step2

@step1, @step2, @step3

@step1, @step2, @step3, @step4

So that I can just run this file from RubyMine?

Thanks

答:
Of course you can put all the scenarios for a project in one file.

But is it something that you want to do?

Remember, Cucumber is a BDD tool designed to bridge conversive issues between the development team and the business people. Separating each feature into a new file means that the business can pull out an individual feature and view it when it is done, to understand why it is there in terms of business value, and when it needs improving it's easy to add to/edit the existing scenarios.

Having them in the same file may make it easier for you, but when something fails, it'll be harder to find the issue when you have to scroll down a 10,000 line long file.

Instead, improve your folder structure so that features are easier to find, and tag features and scenarios across the files. Create a bash script to run suites if you want to, or just use the command line: "cucumber --tags @tag1" for instance.


问:
Javascript Concat Multidimensional Array
I am trying to concat a multidimensional array so I can iterate and display all the data.  There is a very good post on how to access nested data here, but I am looking for a solution that works with a specific data structure.

Here is my data:

```<code>var data = {
"Nike": [
    {
    "id": "1",
    "name": "test",
    "myimage": "image.gif"},

     {
    "id": "2",
    "name": "test",
    "myimage": "image.gif"}
],

"Adidas": [
    {
    "id": "3",
    "name": "Football Boots",
    "myimage": "image.gif"},

     {
    "id": "4",
    "name": "Running Shoes",
    "myimage": "image.gif"}
]}
</code>```

I seem to be able to get the values from the Nike array if I do this:

```<code>var result = data.Adidas;

for (var i = 0; i < result.length; i++) {
 var object = result[i];
 for (property in object) {
    var value = object[property];
    alert(property + "=" + value + "<br>");
 }
}
</code>```

However I would like to be able to display all the array items (id's 1-4).

What I have tried to do is:

```<code>var result = [].concat.apply([], data);
</code>```

... and loop over the result variable using the same for loop, but it doesn't work.

My ideal end result would be to display the four products under each brand name. I don't require to show the actual brand name itself.  For example:

```<code> "id": "1",
    "name": "test",
    "myimage": "image.gif"

 "id": "2",
    "name": "test",
    "myimage": "image.gif"

"id": "3",
    "name": "Football Boots",
    "myimage": "image.gif",

"id": "4",
    "name": "Running Shoes",
    "myimage": "image.gif"
</code>```

Any help appreciated.

Cheers

答:
You can use reduce and iterate over the keys of the object, then create your array:

```<code>var mashed = Object.keys(data).reduce(function(arr, key) {
    return arr.concat(data[key]);
}, []);
</code>```

Demo: https://jsfiddle.net/kvd6egn5/

Body:
I am trying to concat a multidimensional array so I can iterate and display all the data.  There is a very good post on how to access nested data here, but I am looking for a solution that works with a specific data structure.

Here is my data:

var data = {
"Nike": [
    {
    "id": "1",
    "name": "test",
    "myimage": "image.gif"},

     {
    "id": "2",
    "name": "test",
    "myimage": "image.gif"}
],

"Adidas": [
    {
    "id": "3",
    "name": "Football Boots",
    "myimage": "image.gif"},

     {
    "id": "4",
    "name": "Running Shoes",
    "myimage": "image.gif"}
]}

I seem to be able to get the values from the Nike array if I do this:

var result = data.Adidas;

for (var i = 0; i < result.length; i++) {
 var object = result[i];
 for (property in object) {
    var value = object[property];
    alert(property + "=" + value + "
");
 }
}

However I would like to be able to display all the array items (id's 1-4).

What I have tried to do is:

var result = [].concat.apply([], data);

... and loop over the result variable using the same for loop, but it doesn't work.

My ideal end result would be to display the four products under each brand name. I don't require to show the actual brand name itself.  For example:

 "id": "1",
    "name": "test",
    "myimage": "image.gif"

 "id": "2",
    "name": "test",
    "myimage": "image.gif"

"id": "3",
    "name": "Football Boots",
    "myimage": "image.gif",

"id": "4",
    "name": "Running Shoes",
    "myimage": "image.gif"

Any help appreciated.

Cheers

Body:
You can use reduce and iterate over the keys of the object, then create your array:

var mashed = Object.keys(data).reduce(function(arr, key) {
    return arr.concat(data[key]);
}, []);

Demo: https://jsfiddle.net/kvd6egn5/


问:
"sh: Error: Can't open display" when I try to start a program from python
I have this really strange problem, basically I want to start xpdf (or Libreoffice) from my Python script, that is started by a systemd-service. When I start the script from terminal everything is working fine, but when I plug in my USB device that start the Service, I'll get this Error in my syslog:

```<code>sh[2321]: Error: Can't open Display
</code>```

This error has something to do with X11, that's what my Google searches tell me.
So, my question is: How can I properly run a program like xpdf or libreoffice from Python?

```<code> import subprocess
 subprocess.call("/usr/bin/xpdf")
</code>```

This is it, basically. I know that it has something to do with the graphical enviroment, but I don't know how I can solve it.

答:
It finally worked, after trying and going crazy for around 2 weeks.
What worked was

```<code>os.system("DISPLAY=:0 /usr/bin/xpdf)
</code>```

I know that subprocess.call is the better way to call the program, but it doesn't seem to work right now.
I'll try the way that Yann suggested later on, but for now I'm just overwhelmed with joy that it just works.

Thank you all for your help, I really appreciate it!

Body:
I have this really strange problem, basically I want to start xpdf (or Libreoffice) from my Python script, that is started by a systemd-service. When I start the script from terminal everything is working fine, but when I plug in my USB device that start the Service, I'll get this Error in my syslog:

sh[2321]: Error: Can't open Display

This error has something to do with X11, that's what my Google searches tell me.
So, my question is: How can I properly run a program like xpdf or libreoffice from Python?

 import subprocess
 subprocess.call("/usr/bin/xpdf")

This is it, basically. I know that it has something to do with the graphical enviroment, but I don't know how I can solve it.

Body:
It finally worked, after trying and going crazy for around 2 weeks.
What worked was

os.system("DISPLAY=:0 /usr/bin/xpdf)

I know that subprocess.call is the better way to call the program, but it doesn't seem to work right now.
I'll try the way that Yann suggested later on, but for now I'm just overwhelmed with joy that it just works.

Thank you all for your help, I really appreciate it!


问:
get value form nested map type map[string]interface{}
I'm trying to get all value from nested map and, I don't know how I can do that.

```<code>package main

import "fmt"

func main() {
    m := map[string]interface{}{
        "date":       "created",
        "clientName": "data.user.name",
        "address": map[string]interface{}{
            "street": "x.address",
        },
        "other": map[string]interface{}{
            "google": map[string]interface{}{
                "value": map[string]interface{}{
                    "x": "y.address",
                },
            },
        },
        "new_address": map[string]interface{}{
            "address": "z.address",
        },
    }

    for i := range m {
        fmt.Println(m[i])
        // how I can get value from other nested map?
    }
}
</code>```

how I can get value from other nested map?

答:
You should use nonpanic casting to target value.

```<code>for i := range m {
    nestedMap, ok := m[i].(map[string]interface{})
    if ok {
        // Do what you want
    }
}
</code>```

More details: https://golang.org/ref/spec#Type_assertions

Body:
I'm trying to get all value from nested map and, I don't know how I can do that.

package main

import "fmt"

func main() {
    m := map[string]interface{}{
        "date":       "created",
        "clientName": "data.user.name",
        "address": map[string]interface{}{
            "street": "x.address",
        },
        "other": map[string]interface{}{
            "google": map[string]interface{}{
                "value": map[string]interface{}{
                    "x": "y.address",
                },
            },
        },
        "new_address": map[string]interface{}{
            "address": "z.address",
        },
    }

    for i := range m {
        fmt.Println(m[i])
        // how I can get value from other nested map?
    }
}

how I can get value from other nested map?

Body:
You should use nonpanic casting to target value.

for i := range m {
    nestedMap, ok := m[i].(map[string]interface{})
    if ok {
        // Do what you want
    }
}

More details: https://golang.org/ref/spec#Type_assertions