问:
JQuery GET request won't get correct data from php echo
I am trying to fill a table using a jquery .get request, the url being a php file. The php gets data from a database, then it should return a json array back to the jquery, array which will fill the table. While the length of the array is returned as it should, the table cells are empty.

Here is my get.php function:

```<code><?php
$mysqli=new mysqli("localhost:3306","root","","leagues");
if (mysqli_connect_errno())
{
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$return_arr = array();
$query = "SELECT * FROM league";

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_row())
    {
        $return_arr[] = $row;
    }
}
$mysqli->close();
header('Content-Type: application/json');
echo json_encode($return_arr);
?>
</code>```

And here is my jquery get function

```<code>$.get('php/get.php',function(responseJson)
    {
        if(responseJson!=null)
        {
            $("#tableleague").find("tr:gt(0)").remove();
            var table1 = $("#tableleague");
            $.each(responseJson, function(key,value) {
                var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
                rowNew.children().eq(0).text(value['teams']);
                rowNew.children().eq(1).text(value['playedgames']);
                rowNew.children().eq(2).text(value['wongames']);
                rowNew.children().eq(3).text(value['tiegames']);
                rowNew.children().eq(4).text(value['lostgames']);
                rowNew.children().eq(5).text(value['scoredgoal']);
                rowNew.children().eq(6).text(value['receivedgoal']);
                rowNew.children().eq(7).text(value['points']);
                rowNew.appendTo(table1);
            });
        }
    });
</code>```

Here is how my webpage looks, with the php file response shown.

Since the response is ok, what am I doing wrong that the cells aren't filled? Thank you.

答:
You can turn the php json into javascript object

```<code> obj = JSON.parse(json);
</code>```

es:

```<code>var json='{"ex1":"test","ex2":[{"sub1":"test"},{"sub2":""s2test}],"ex3":true}';
var obj = JSON.parse(json);
</code>```

after you can acces to data with :

```<code>obj.ex1 // test
obj.ex2[0].sub2 //s2test
</code>```

Body:
I am trying to fill a table using a jquery .get request, the url being a php file. The php gets data from a database, then it should return a json array back to the jquery, array which will fill the table. While the length of the array is returned as it should, the table cells are empty.

Here is my get.php function:

<?php
$mysqli=new mysqli("localhost:3306","root","","leagues");
if (mysqli_connect_errno())
{
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$return_arr = array();
$query = "SELECT * FROM league";

if ($result = $mysqli->query($query)) {
    while ($row = $result->fetch_row())
    {
        $return_arr[] = $row;
    }
}
$mysqli->close();
header('Content-Type: application/json');
echo json_encode($return_arr);
?>

And here is my jquery get function

$.get('php/get.php',function(responseJson)
    {
        if(responseJson!=null)
        {
            $("#tableleague").find("tr:gt(0)").remove();
            var table1 = $("#tableleague");
            $.each(responseJson, function(key,value) {
                var rowNew = $("

");
                rowNew.children().eq(0).text(value['teams']);
                rowNew.children().eq(1).text(value['playedgames']);
                rowNew.children().eq(2).text(value['wongames']);
                rowNew.children().eq(3).text(value['tiegames']);
                rowNew.children().eq(4).text(value['lostgames']);
                rowNew.children().eq(5).text(value['scoredgoal']);
                rowNew.children().eq(6).text(value['receivedgoal']);
                rowNew.children().eq(7).text(value['points']);
                rowNew.appendTo(table1);
            });
        }
    });

Here is how my webpage looks, with the php file response shown.

Since the response is ok, what am I doing wrong that the cells aren't filled? Thank you.

Body:
You can turn the php json into javascript object

 obj = JSON.parse(json);

es:

var json='{"ex1":"test","ex2":[{"sub1":"test"},{"sub2":""s2test}],"ex3":true}';
var obj = JSON.parse(json);

after you can acces to data with :

obj.ex1 // test
obj.ex2[0].sub2 //s2test


来源: stackexchange

问:
Some strings in a array match another array
I can't figure out how to have apart of an array match a whole array and i want to pretend that we don't know that usersInData[0,1,2,3] is the same as verifiedUsers[0,1,2,3], i want to somehow match the same value without using the index of each array.

I tried this-

```<code>var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]

var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

if usersInData == verifiedUsers {
    print("special user")
} else {
    print("regular user")
}
</code>```

but it prints "regular user", so basically it didn't work.
I want the verified users to be different than the regular users. So for example user "hello" gets a special verified icon etc. Thank you!

答:
You have to use the contains : func contains(_ element: String) -> Bool. Unfortunately the default implementation of this function compare only one element.

You have to extend Array and create func containsArray(array: [Element]) -> Bool.

Let's do it :

```<code>extension Array where Element: Equatable {
    func containsArray(array: [Element]) -> Bool {
        return !array.contains { !self.contains($0) }
    }
}
</code>```

How to use it in your code :

```<code>var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]
var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

if usersInData.containsArray(array: verifiedUsers) {
    print("Special user")
} else {

    print("Regular user")
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I can't figure out how to have apart of an array match a whole array and i want to pretend that we don't know that usersInData[0,1,2,3] is the same as verifiedUsers[0,1,2,3], i want to somehow match the same value without using the index of each array.

I tried this-

var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]

var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

if usersInData == verifiedUsers {
    print("special user")
} else {
    print("regular user")
}

but it prints "regular user", so basically it didn't work.
I want the verified users to be different than the regular users. So for example user "hello" gets a special verified icon etc. Thank you!

Body:
You have to use the contains : func contains(_ element: String) -> Bool. Unfortunately the default implementation of this function compare only one element.

You have to extend Array and create func containsArray(array: [Element]) -> Bool.

Let's do it :

extension Array where Element: Equatable {
    func containsArray(array: [Element]) -> Bool {
        return !array.contains { !self.contains($0) }
    }
}

How to use it in your code :

var usersInData = ["hello", "hello1", "hello2", "hello3", "hello4", "hello5", "hello6", "hello7"]
var verifiedUsers = ["hello", "hello1", "hello2", "hello3"]

if usersInData.containsArray(array: verifiedUsers) {
    print("Special user")
} else {

    print("Regular user")
}


问:
Wakanda tutorial (angular 4): can not create angular components with angular cli
Trying out the wakanda angular 4 todo tutorial:
https://wakanda.github.io/doc/#/tutorial?section=main

Can not create angular components in step 2: Error message in the
  console after trying to generate an angular component: "You have to be
  inside an Angular CLI project in order to use the generate command."

Environment:
@angular/cli: 1.1.0
node: 7.5,0
os win32 x64

Tried to update "@angular/cli" version from "1.0.0" in package.json:

```<code>"devDependencies": {
  "@angular/cli": "1.1.0"
</code>```

But it did not solve the problem.

答: Solved: rename duplicated file .angular-cli.json to angular-cli.jso (duplicated without leading dot).

Body:
Trying out the wakanda angular 4 todo tutorial:
https://wakanda.github.io/doc/#/tutorial?section=main

Can not create angular components in step 2: Error message in the
  console after trying to generate an angular component: "You have to be
  inside an Angular CLI project in order to use the generate command."

Environment:
@angular/cli: 1.1.0
node: 7.5,0
os win32 x64

Tried to update "@angular/cli" version from "1.0.0" in package.json:

"devDependencies": {
  "@angular/cli": "1.1.0"

But it did not solve the problem.


问:
Generate a random birthday given an age
I'm looking for a good algorithm, preferably using the CLR's DateTime type and other built-in stuff, versus just using on-the-metal maths, for guessing a birthday date given an age.

The date should be realistic looking, and not just always 1st of January. I need them for testing an app where a number containing the birthday digits is validated with a Luhn check-digit.

What I have so far is to subtract the age from now, giving me a minimum date. Then I can randomize years, months, and days to add. Yet that latter process is rough in terms of getting the wrong random month or day could change the eventual age for the date.

答:
A quick-and-dirty solution that finds a date between min and max using Ticks:

```<code>var min = DateTime.Parse("1988/02/10");
var max = DateTime.Parse("2016/01/05");

var minTicks = min.Ticks;
var maxTicks = max.Ticks;

var baseTicks = maxTicks-minTicks;

var rnd = new Random();

var toAdd = (long)(rnd.NextDouble()*baseTicks);

var newDate = new DateTime(minTicks+toAdd);
</code>```

Of course if you need multiple dates you may add them to a list:

```<code>public static List<DateTime> GetBirthdaysBetweenDates(DateTime minDate, DateTime maxDate, int number = 1)
{
    if(minDate > maxDate) throw new ArgumentException("minDate can't be greater then maxDate");

    var dates = new List<DateTime>();

    if(number <= 0) return dates;

    var rnd = new Random();

    var ticks = maxDate.Ticks - minDate.Ticks;

    for(var i = 0; i < number; i++)
    {
        var toAdd = (long)(rnd.NextDouble() * ticks);
        dates.Add(new DateTime(minDate.Ticks + toAdd));
    }

    return dates;
}
</code>```

Title: Generate a random birthday given an age

Body:
A quick-and-dirty solution that finds a date between min and max using Ticks:

var min = DateTime.Parse("1988/02/10");
var max = DateTime.Parse("2016/01/05");

var minTicks = min.Ticks;
var maxTicks = max.Ticks;

var baseTicks = maxTicks-minTicks;

var rnd = new Random();

var toAdd = (long)(rnd.NextDouble()*baseTicks);

var newDate = new DateTime(minTicks+toAdd);

Of course if you need multiple dates you may add them to a list:

public static List<DateTime> GetBirthdaysBetweenDates(DateTime minDate, DateTime maxDate, int number = 1)
{
    if(minDate > maxDate) throw new ArgumentException("minDate can't be greater then maxDate");

    var dates = new List<DateTime>();

    if(number <= 0) return dates;

    var rnd = new Random();

    var ticks = maxDate.Ticks - minDate.Ticks;

    for(var i = 0; i < number; i++)
    {
        var toAdd = (long)(rnd.NextDouble() * ticks);
        dates.Add(new DateTime(minDate.Ticks + toAdd));
    }

    return dates;
}


问:
Get logged in user from time-stamp
I have 2 tables in my DB. One tracks when users log in: id, name, IP, & time-stamp. The other is a series of events: id, event name, IP, & time-stamp.

Is there an easy way to see which user is logged on given a specific event?.

For example, if I have

```<code>id  l_ip          l_user  l_time
0   172.16.1.10   ces77   2010-12-14 09:02:12
1   172.16.1.64   ces34   2010-12-14 10:06:43
2   172.16.1.10   ces47   2010-12-14 11:10:52
</code>```

and

```<code>id  e_name   e_ip         e_time
0   remove   172.16.1.10  2010-12-14 09:10:33
1   run      172.16.1.64  2010-12-14 10:15:10
2   change   172.16.1.64  2010-12-14 10:20:32
3   run      172.16.1.10  2010-12-14 12:55:59
</code>```

could I run a query to give me the user for each one of the events so it would produce?

```<code>id  e_name   e_ip         e_time               l_user
0   remove   172.16.1.10  2010-12-14 09:10:33  ces77
1   run      172.16.1.64  2010-12-14 10:15:10  ces34
2   change   172.16.1.64  2010-12-14 10:20:32  ces34
3   run      172.16.1.10  2010-12-14 12:55:59  ces47
</code>```

答:
The best way to handle this is from code that accesses the database.  It won't likely be terribly fast, because the necessary data to efficiently answer the question is not available; you'll have to look at records, and then for each record answer the question "which user was logged in at this time?".

A suggestion might be to perform a bit of de-normalization on your schema, and permit the user information to appear in two tables.  If you use usernames as the key into your user table, then you can just make the l_user column be a FK pointing to that table.  Of course, you'll still need a program written to update the tables to include the data that you're looking for in the first place, and there is no way to make it 100% correct for all time-stamps, unless you can guarantee certain things like "the user did not log out between timestamps A and B" and so forth.

I'd write a program first to get the answers to the question that you're looking to answer right now, and then I would strongly consider crafting a few enhancements to the data structure so that you can always answer this question with nothing more than a single SQL query.  Essentially, iterate over every event, find who was logged in when that event occurred, and write that out somewhere (unless you can afford to keep that information in memory to work with it later, of course).

ContentLicense: CC BY-SA 2.5

Title: Get logged in user from time-stamp

Body:
I have 2 tables in my DB. One tracks when users log in: id, name, IP, & time-stamp. The other is a series of events: id, event name, IP, & time-stamp.

Is there an easy way to see which user is logged on given a specific event?.

For example, if I have

id  l_ip          l_user  l_time
0   172.16.1.10   ces77   2010-12-14 09:02:12
1   172.16.1.64   ces34   2010-12-14 10:06:43
2   172.16.1.10   ces47   2010-12-14 11:10:52

and

id  e_name   e_ip         e_time
0   remove   172.16.1.10  2010-12-14 09:10:33
1   run      172.16.1.64  2010-12-14 10:15:10
2   change   172.16.1.64  2010-12-14 10:20:32
3   run      172.16.1.10  2010-12-14 12:55:59

could I run a query to give me the user for each one of the events so it would produce?

id  e_name   e_ip         e_time               l_user
0   remove   172.16.1.10  2010-12-14 09:10:33  ces77
1   run      172.16.1.64  2010-12-14 10:15:10  ces34
2   change   172.16.1.64  2010-12-14 10:20:32  ces34
3   run      172.16.1.10  2010-12-14 12:55:59  ces47


问:
@Import vs @ContextConfiguration for importing beans in unit tests
I was able to set up and successfully run three different test configurations with SpringBoot 1.5.3

Method #1. Importing Bean with use of @Import annotation

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@Import({MyBean.class})
public class MyBeanTest() {
    @Autowired
    private MyBean myBean;
}
</code>```

Method #2. Importing Bean with use of @ContextConfiguration annotation

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyBean.class})
public class MyBeanTest() {
    @Autowired
    private MyBean myBean;
}
</code>```

Method #3 (with internal class configuration; based on the official blog post)

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class MyBeanTest() {

    @Configuration
    static class ContextConfiguration {
        @Bean
        public MyBean myBean() {
            return new MyBean();
        }
    }

    @Autowired
    private MyBean myBean;

}
</code>```

Taking into account @Import annotation documentation

Indicates one or more {@link Configuration @Configuration} classes to
  import.

and the fact that MyBean is not a configuration class, but a bean class annotated with @Component annotation it looks like Method #1 is not correct.

From @ContextConfiguration documentation

{@code @ContextConfiguration} defines class-level metadata that is
  used to determine how to load and configure an {@link
  org.springframework.context.ApplicationContext ApplicationContext}
  for integration tests.

Sounds like it is better applicable to unit tests, but still, should load a kind of a configuration.

Methods #1 and #2 are shorter and simpler.
Method #3 looks like a correct way.

Am I right? Are there other criteria why I should use method #3, like performance or something else?

答:
You actually don't need to specify the loader if you go with option #3. From the doc
In addition to the example from the doc you can override the env. with @TestPropertySource if you need to inject properties in the environment without using the real ones.</p>

```<code>@RunWith(SpringRunner.class)
// ApplicationContext will be loaded from the
// static nested Config class
@ContextConfiguration
@TestPropertySource(properties = { "timezone = GMT", "port: 4242" })
public class OrderServiceTest {

    @Configuration
    static class Config {

        // this bean will be injected into the OrderServiceTest class
        @Bean
        public OrderService orderService() {
            OrderService orderService = new OrderServiceImpl();
            // set properties, etc.
            return orderService;
        }
    }

    @Autowired
    private OrderService orderService;

    @Test
    public void testOrderService() {
        // test the orderService
    }

}
</code>```

Body:
I was able to set up and successfully run three different test configurations with SpringBoot 1.5.3

Method #1. Importing Bean with use of @Import annotation

@RunWith(SpringJUnit4ClassRunner.class)
@Import({MyBean.class})
public class MyBeanTest() {
    @Autowired
    private MyBean myBean;
}

Method #2. Importing Bean with use of @ContextConfiguration annotation

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MyBean.class})
public class MyBeanTest() {
    @Autowired
    private MyBean myBean;
}

Method #3 (with internal class configuration; based on the official blog post)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class MyBeanTest() {

    @Configuration
    static class ContextConfiguration {
        @Bean
        public MyBean myBean() {
            return new MyBean();
        }
    }

    @Autowired
    private MyBean myBean;

}

Taking into account @Import annotation documentation

Indicates one or more {@link Configuration @Configuration} classes to
  import.

and the fact that MyBean is not a configuration class, but a bean class annotated with @Component annotation it looks like Method #1 is not correct.

From @ContextConfiguration documentation

{@code @ContextConfiguration} defines class-level metadata that is
  used to determine how to load and configure an {@link
  org.springframework.context.ApplicationContext ApplicationContext}
  for integration tests.

Sounds like it is better applicable to unit tests, but still, should load a kind of a configuration.

Methods #1 and #2 are shorter and simpler.
Method #3 looks like a correct way.

Am I right? Are there other criteria why I should use method #3, like performance or something else?

Body:
You actually don't need to specify the loader if you go with option #3. From the doc
In addition to the example from the doc you can override the env. with @TestPropertySource if you need to inject properties in the environment without using the real ones.

@RunWith(SpringRunner.class)
// ApplicationContext will be loaded from the
// static nested Config class
@ContextConfiguration
@TestPropertySource(properties = { "timezone = GMT", "port: 4242" })
public class OrderServiceTest {

    @Configuration
    static class Config {

        // this bean will be injected into the OrderServiceTest class
        @Bean
        public OrderService orderService() {
            OrderService orderService = new OrderServiceImpl();
            // set properties, etc.
            return orderService;
        }
    }

    @Autowired
    private OrderService orderService;

    @Test
    public void testOrderService() {
        // test the orderService
    }

}


问:
How to fetch default value in input using angularjs?
Hi all How to get default value in input using angular js?

my plunker please look at my plunker I want to fetch directquestion values are defaults in an input field.

"directquestion": "582c1f4b53cf7fec2ddf282e", i am expecting to fetch directquestion values defaulty in above input field...

if we fetch that ng-model values in an input field, the data's are got a filter.

I want to filter direct question values through the input field....

if anyone knows the solution please help me thanks in advance...

答:
You can assign to your directquestion the initial value from array.

So you can do this:

```<code>$scope.directquestion = $scope.questions[0].directquestion;
</code>```

Body:
You can assign to your directquestion the initial value from array.

So you can do this:

$scope.directquestion = $scope.questions[0].directquestion;


问:
ReactJS How to add a show more/show less button
I'm new to React and I want to add a simple "Show more" button to my Application. I have an array with data, where I want to show 3 entries as a default. When a user clicks on show more, the rest of the data should be rendered, and the Button should change the text to show less. I'm not exactly sure how to do it.

This is what I got so far:

```<code>class Application extends React.Component {
  constructor() {
    super()

    this.cars = [
     { "name" : "Audi", "country" : "Germany"},
     { "name" : "BMW", "country" : "Germany" },
     { "name" : "Chevrolet", "country" : "USA" },
     { "name" : "Citroen", "country" : "France" },
     { "name" : "Hyundai", "country" : "South Korea" },
     { "name" : "Mercedes-Benz", "country" : "Germany" },
     { "name" : "Renault", "country" : "France" },
     { "name" : "Seat", "country" : "Spain" },
   ]

   this.isLoaded = false

  }

  showMore() {
   // show more entries
   // switch to "show less"
  }

  render() {
    return <div className="container">
     <h3>Click show more to see more data</h3>
     <div className="row">
       <h3>List of Cars</h3>
       <ul>
         {this.cars.slice(0,3).map((car, i) => <li key={i}>{car.name} - {car.country}</li>)}
       </ul>
     </div>
     <p>
      <a className="btn btn-primary" onClick={this.showMore()}>Show more</a>.
     </p>
   </div>;
  }
}

React.render(<Application />, document.getElementById('app'));
</code>```

Here is a JSBin with the code in action

Can someone help me out?

答:
You do some things wrong. You need to understand what a state is and how react interact with it. When a state change, your render function is called again, it allow you to have dynamic rendering based on your current state.

First, initialize your state with what you want (here, I could have put only rowsToDisplay, but I guess you want to be able to update your cars as well).

You should bind this to your function showMore so when it's called, it get that "this" refers to your Component.

OnClick, showMore will be called; the function update your state. By updating it, render will be called again (remember that a change in your state call render again with your new values). This should be the only way for you to update the view.

```<code>class Application extends React.Component {
  constructor(props) {
    super(props)

    this.state = {cars : [
      { "name" : "Audi", "country" : "Germany"},
      { "name" : "BMW", "country" : "Germany" },
      { "name" : "Chevrolet", "country" : "USA" },
      { "name" : "Citroen", "country" : "France" },
      { "name" : "Hyundai", "country" : "South Korea" },
      { "name" : "Mercedes-Benz", "country" : "Germany" },
      { "name" : "Renault", "country" : "France" },
      { "name" : "Seat", "country" : "Spain" },
    ],
    rowsToDisplay : 4};
    this.showMore = this.showMore.bind(this);
  }

  showMore() {
    let carLength = this.state.cars.length;
    this.setState({rowsToDisplay:carLength});
    // show more entries
    // switch to "show less"
  }
  render() {
    return <div className="container">
      <h3>Click show more to see more data</h3>
      <div className="row">
        <h3>List of Cars</h3>
        <ul>
          {this.state.cars.slice(0,this.state.rowsToDisplay).map((car, i) => <li key={i}>{car.name} - {car.country}</li>)}
        </ul>
      </div>
      <p>
        <a className="btn btn-primary" onClick={this.showMore}>Show more</a>.
      </p>
    </div>;
  }
}

React.render(<Application />, document.getElementById('app'));
</code>```

Feel free to ask questions, but please read the doc first :
https://facebook.github.io/react/docs/state-and-lifecycle.html

Body:
I'm new to React and I want to add a simple "Show more" button to my Application. I have an array with data, where I want to show 3 entries as a default. When a user clicks on show more, the rest of the data should be rendered, and the Button should change the text to show less. I'm not exactly sure how to do it.

This is what I got so far:

class Application extends React.Component {
  constructor() {
    super()

    this.cars = [
     { "name" : "Audi", "country" : "Germany"},
     { "name" : "BMW", "country" : "Germany" },
     { "name" : "Chevrolet", "country" : "USA" },
     { "name" : "Citroen", "country" : "France" },
     { "name" : "Hyundai", "country" : "South Korea" },
     { "name" : "Mercedes-Benz", "country" : "Germany" },
     { "name" : "Renault", "country" : "France" },
     { "name" : "Seat", "country" : "Spain" },
   ]

   this.isLoaded = false

  }

  showMore() {
   // show more entries
   // switch to "show less"
  }

  render() {
    return

Click show more to see more data

List of Cars

         {this.cars.slice(0,3).map((car, i) =>
{car.name} - {car.country}
)}

      Show more.

;
  }
}

React.render(<Application />, document.getElementById('app'));

Here is a JSBin with the code in action

Can someone help me out?

Body:
You do some things wrong. You need to understand what a state is and how react interact with it. When a state change, your render function is called again, it allow you to have dynamic rendering based on your current state.

First, initialize your state with what you want (here, I could have put only rowsToDisplay, but I guess you want to be able to update your cars as well).

You should bind this to your function showMore so when it's called, it get that "this" refers to your Component.

OnClick, showMore will be called; the function update your state. By updating it, render will be called again (remember that a change in your state call render again with your new values). This should be the only way for you to update the view.

class Application extends React.Component {
  constructor(props) {
    super(props)

    this.state = {cars : [
      { "name" : "Audi", "country" : "Germany"},
      { "name" : "BMW", "country" : "Germany" },
      { "name" : "Chevrolet", "country" : "USA" },
      { "name" : "Citroen", "country" : "France" },
      { "name" : "Hyundai", "country" : "South Korea" },
      { "name" : "Mercedes-Benz", "country" : "Germany" },
      { "name" : "Renault", "country" : "France" },
      { "name" : "Seat", "country" : "Spain" },
    ],
    rowsToDisplay : 4};
    this.showMore = this.showMore.bind(this);
  }

  showMore() {
    let carLength = this.state.cars.length;
    this.setState({rowsToDisplay:carLength});
    // show more entries
    // switch to "show less"
  }
  render() {
    return <div className="container">
      <h3>Click show more to see more data</h3>
      <div className="row">
        <h3>List of Cars</h3>
        <ul>
          {this.state.cars.slice(0,this.state.rowsToDisplay).map((car, i) => <li key={i}>{car.name} - {car.country}</li>)}
        </ul>
      </div>
      <p>
        <a className="btn btn-primary" onClick={this.showMore}>Show more</a>.
      </p>
    </div>;
  }
}

React.render(<Application />, document.getElementById('app'));

Feel free to ask questions, but please read the doc first :
https://facebook.github.io/react/docs/state-and-lifecycle.html


问:
iOS Development: Is there ever a time when it's appropriate for an app to kill itself?
I've been developing iOS apps for enterprise use for several years now. It was an adjustment from having spent many (!) years developing desktop apps. One of the first things I learned very early on was that it is frowned upon for an app to kill itself. The posters in the Apple dev forum were downright hostile about it, which is a reason I never go there anymore.

Now I have an app that has very critical functions, and it requires that the user accept the terms and conditions before using the app, and that the app will not function if the terms have not been accepted. The choice is there to accept or to decline, but it seems like the best thing to do when the user actively declines is to kill the app entirely.

My question is, under those circumstances, would there be anything wrong with that? Will I be damned to developers hell for eternity?

答:
You can change the interaction here.

Instead of accept (and use the app) or decline (and never be able to use the app) change it to accept (and use the app) or nothing.

If the user does not accept then they cannot use the app. They do not have to decline anything. Absence of acceptance is all you need.

If they don't accept then don't do anything. They can always come back later and accept and start using the app.


问:
java.upcasting
i have this example:

```<code>class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    static void test(One o) {o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new One());
    }
}
</code>```

Results:

```<code>One!!!
One!!!
</code>```

ok, no questions.

than, i try modified my code:

only this method:

```<code>public static void main(String args[])
    {
        test(new Jenia());
        }
</code>```

results:

```<code>One!!!
One!!!
</code>```

ok, we have this results because - here upcasting(Jenia-One).

its all ok too, but, modified again:
 in class Jenia override methodtestOne`:

```<code>public void testOne(){System.out.println("Two!!!");}
</code>```

so i have this code:

```<code>class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    public void testOne(){System.out.println("Two!!!");}

    static void test(One o){o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new Jenia());
    }
}
</code>```

and results:

```<code>Two!!!
One!!!
</code>```

my question: why Two!!! ?? why we not lost override methods?

答: When you call o.testOne() in test method, it calls Jenia.testOne since the o is an instance of Jenia. You can check it by o.getClass().getName();.

Title: java.upcasting

Body:
i have this example:

class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    static void test(One o) {o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new One());
    }
}

Results:

One!!!
One!!!

ok, no questions.

than, i try modified my code:

only this method:

public static void main(String args[])
    {
        test(new Jenia());
        }

results:

One!!!
One!!!

ok, we have this results because - here upcasting(Jenia-One).

its all ok too, but, modified again:
 in class Jenia override methodtestOne`:

public void testOne(){System.out.println("Two!!!");}

so i have this code:

class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    public void testOne(){System.out.println("Two!!!");}

    static void test(One o){o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new Jenia());
    }
}

and results:

Two!!!
One!!!

my question: why Two!!! ?? why we not lost override methods?


问:
Insert in vector after each even value specific number
I need to insert -20 after each even element, but my code not workint correctly,
what i'm doing wrong?</p>

```<code>srand(time(NULL));
vector <int> v;

for (int i = 0; i < 15; i++)
{
    v.push_back(rand()%100);
    cout << v[i] << endl;
}

cout << "Vector after inserting new value: \n\n";
for (int i = 0; i < v.size(); i++)
{
    if (v[i]%2==0)
    {
        v.insert(v.begin()+i, -20);

    }
    cout << v[i] << endl;
    i = i + 1;
}
</code>```

答:
Using i++ and i = i + 1 is not going to end well.

Clearly, you only need to increment i twice if you insert an element.

If you want to insert an element just after position i, then you'll need to use

```<code>v.insert(v.begin() + 1 + i, ...)
</code>```

Body:
I need to insert -20 after each even element, but my code not workint correctly,
what i'm doing wrong?

srand(time(NULL));
vector <int> v;

for (int i = 0; i < 15; i++)
{
    v.push_back(rand()%100);
    cout << v[i] << endl;
}

cout << "Vector after inserting new value: \n\n";
for (int i = 0; i < v.size(); i++)
{
    if (v[i]%2==0)
    {
        v.insert(v.begin()+i, -20);

    }
    cout << v[i] << endl;
    i = i + 1;
}

Body:
Using i++ and i = i + 1 is not going to end well.

Clearly, you only need to increment i twice if you insert an element.

If you want to insert an element just after position i, then you'll need to use

v.insert(v.begin() + 1 + i, ...)


问:
Make text boxes different sizes
I have some fields (such as name, phone number, company) a user can fill out. The text boxes are good sizes, except for one, which is a "note" field. I want the note text box to be very large when compared to the other text box fields, but I am only able to make all the text boxes the same size.

_form.html.erb/vendors

```<code><%= form_for @vendor do |f| %>

#this text field will be a regular size
  <p>
    <%= f.label :company %><br>
    <%= f.text_field :company %>
  </p>

#more code...

#I want this text field to be large
 <body>
     <div class = "notes">
         <p>
             <%= f.label :notes %><br>
             <%= f.text_field :notes %>
        </p>
     </div>
 </body>

  <p>
    <%= f.submit %>
  </p>

</div>

<% end %>
</code>```

my css file

```<code>input[type=text]{
    width: 40%;
    padding: 12px 12px;
    border: 2px solid #ccc;
    background-color: white;
}

textarea {
    width: 20%;
    height: 10px;
    padding: 12px 12px;
    border: 2px solid #ccc;
    background-color: white;
    resize: none
}

#more code...
</code>```

答:
Use the cols and rows property. <%= f.text_area :notes, :cols => "10", :rows => "10" %>
 You can also just specify size like: <%= f.text_area :notes, size: "60x12" %>

Title: Make text boxes different sizes

Body:
I have some fields (such as name, phone number, company) a user can fill out. The text boxes are good sizes, except for one, which is a "note" field. I want the note text box to be very large when compared to the other text box fields, but I am only able to make all the text boxes the same size.

_form.html.erb/vendors

<%= form_for @vendor do |f| %>

#this text field will be a regular size

    <%= f.label :company %>

    <%= f.text_field :company %>

#more code...

#I want this text field to be large

             <%= f.label :notes %>

             <%= f.text_field :notes %>

    <%= f.submit %>

<% end %>

my css file

input[type=text]{
    width: 40%;
    padding: 12px 12px;
    border: 2px solid #ccc;
    background-color: white;
}

textarea {
    width: 20%;
    height: 10px;
    padding: 12px 12px;
    border: 2px solid #ccc;
    background-color: white;
    resize: none
}

#more code...


答:
you can try with something like this:</p>

```<code>//define lowest and highest days here
DateTime dateFrom = new DateTime(2017, 1, 1);
DateTime dateTo = new DateTime(2018, 1, 1);
//calculate number of days
int daysRange = dateTo.Subtract(dateFrom).Days;

//list to hold generated birthdays
List<DateTime> birthdays = new List<DateTime>();

//randomizer
Random rand = new Random();
//number of birthdays to generate
int number = 10;
for (int i = 0; i<number; i++)
{
    //genrate number between 0 and daysRange and add that many days to dateFrom
    DateTime newDate = dateFrom.AddDays(rand.Next(daysRange));
    //add to list
    birthdays.Add(newDate);
}
</code>```

Title: Generate a random birthday given an age

Body:
I'm looking for a good algorithm, preferably using the CLR's DateTime type and other built-in stuff, versus just using on-the-metal maths, for guessing a birthday date given an age.

The date should be realistic looking, and not just always 1st of January. I need them for testing an app where a number containing the birthday digits is validated with a Luhn check-digit.

What I have so far is to subtract the age from now, giving me a minimum date. Then I can randomize years, months, and days to add. Yet that latter process is rough in terms of getting the wrong random month or day could change the eventual age for the date.

Body:
you can try with something like this:

//define lowest and highest days here
DateTime dateFrom = new DateTime(2017, 1, 1);
DateTime dateTo = new DateTime(2018, 1, 1);
//calculate number of days
int daysRange = dateTo.Subtract(dateFrom).Days;

//list to hold generated birthdays
List<DateTime> birthdays = new List<DateTime>();

//randomizer
Random rand = new Random();
//number of birthdays to generate
int number = 10;
for (int i = 0; i<number; i++)
{
    //genrate number between 0 and daysRange and add that many days to dateFrom
    DateTime newDate = dateFrom.AddDays(rand.Next(daysRange));
    //add to list
    birthdays.Add(newDate);
}


答: Thats the desired behaviour.. which method gets called depends on the runtime type, not the reference type. Since the obect is type of Jenia, the Jenia version of testOne gets called, even if the reference is type of One. Thats plain old polymorphism.

Title: java.upcasting


问:
Where does the space from the top-margin came from?
I started to learn CSS, and I got to that example in the internet:
https://www.w3schools.com/css/tryit.asp?filename=trycss_margin_shorthand

But I tried to play with it, and changed some things. Now the code looks like:

 div#my {
        border: 8px solid black;
        margin-left: 0%;
        margin-right: 0%;

        height: 500px;

        background-color: red;
    }

    div {
        border: 5px solid black;
        margin: inherit;
        background-color: lightblue;
    }

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="my">
   <div>This div element has a top margin of 100px, a right margin of 150px, a bottom margin of 100px, and a left margin of 80px.</div>
</div></code>```

What I see is a big blue block inside a big red block. The blue block collapse with his left and right sides to the red block's border, but from the top I have margin for some reason.

I think its because I chose inherit in the css element. But that says that I have a default margin to the page. Please, help here to understand.

答:
As noone seems to have explained this properly I will try for you.

The inherit keyword in css means that you inherit the styles directly from it's parent. As you have set all divs to inherit their margins, they will inherit that property from their direct parent.

The final div (the div that is nested inside #my) will inherit from the #my div. - As you have not set any margin for top and bottom, this will also stay as inherit.

This means that the #my div will inherit the top and bottom margin (left and right have been set and so will not be inherited) from it's parent, which is the body tag.

The body tag has 8px of margin (depending on which browser you use - I use chrome) so this is inherited by all the divs, which is why you have 8px margin at the top of the inner div.  If you want no margin on that final div, you can either remove the margin property altogether, or just set it to 0 instead of inherit.

So to summarise inner div inherits from parent div called my, which in turn inherits from parent body tag, which is set to 8px (or browser default) so your margin comes from your body tag.

More information on css inherit

Body:
I started to learn CSS, and I got to that example in the internet:
https://www.w3schools.com/css/tryit.asp?filename=trycss_margin_shorthand

But I tried to play with it, and changed some things. Now the code looks like:

 div#my {
        border: 8px solid black;
        margin-left: 0%;
        margin-right: 0%;

        height: 500px;

        background-color: red;
    }

    div {
        border: 5px solid black;
        margin: inherit;
        background-color: lightblue;
    }

This div element has a top margin of 100px, a right margin of 150px, a bottom margin of 100px, and a left margin of 80px.

What I see is a big blue block inside a big red block. The blue block collapse with his left and right sides to the red block's border, but from the top I have margin for some reason.

I think its because I chose inherit in the css element. But that says that I have a default margin to the page. Please, help here to understand.


问:
Is it possible to add two header files to a single swift project?
I have created two header files names commonclass.h and header.h in my Swift project. How to add those two file paths in the bridging header? I can add only one path to it and I need to add the second file path as well to bridging header.</p>

答:
You don't have to add both header paths but only one and that is Bridging Header file only.

You can add bridging header to your project as this SO answer and then #import whatever header files you want to access from swift into this bridging header.


问:
Google Fit Rest Api Step Counts inconsistent and different from Fit App
This seems to be a common enough problem that there are a lot of entries when one googles for help but nothing has helped me yet.

I am finding that the results provided by the REST API for estimated_steps are wildly different from those that appear in the device app.

I am running a fetch task for users via cron job on a PHP/Laravel app.

I'm using this https://developers.google.com/fit/scenarios/read-daily-step-total - estimated_steps to retrieve the step count.

Some days the data is correct. Some days its wildly different. For instance, on one given day, the REST API gives step count of 5661 while the app shows 11,108. Then there are six seven days when the stream is correct.

Has anyone faced this sort of behavior? I've tested for timezone differences, logged and analyzed the response json to see if i'm making some obvious mistake, but nope.

答:
You may check this How do I get the same step count as the Google Fit app? documentation. Be noted that even when using the right data source, your step count may still be different from that of the Google Fit app.

This could be due to one of the following reasons:

On Wear, the Fit MicroApp when connected will display step counts queried on the phone and transferred over via the Wearable APIs. Other MicroApps accessing local-only data will only get watch steps. We are working on making this easier for developers.

Sometimes the step calculation code for the Google Fit app is updated with bug fixes before we are able to release the fixes to developers (which requires a Google Play Services release). We are also working on making it possible for developers to access fixes at the same time.

The Fit app uses a specific data source for steps and it adds some functionality (which can be seen on the documentation) on top of the default merged steps stream.

You can access the "estimated" steps stream as shown here:

```<code>derived:com.google.step_count.delta:com.google.android.gms:estimated_steps
</code>```

Hope this helps!

Body:
You may check this How do I get the same step count as the Google Fit app? documentation. Be noted that even when using the right data source, your step count may still be different from that of the Google Fit app.

This could be due to one of the following reasons:

On Wear, the Fit MicroApp when connected will display step counts queried on the phone and transferred over via the Wearable APIs. Other MicroApps accessing local-only data will only get watch steps. We are working on making this easier for developers.

Sometimes the step calculation code for the Google Fit app is updated with bug fixes before we are able to release the fixes to developers (which requires a Google Play Services release). We are also working on making it possible for developers to access fixes at the same time.

The Fit app uses a specific data source for steps and it adds some functionality (which can be seen on the documentation) on top of the default merged steps stream.

You can access the "estimated" steps stream as shown here:

derived:com.google.step_count.delta:com.google.android.gms:estimated_steps

Hope this helps!


问:
Elements doesn't survive state change for css transitions in React
I have a highscore list that updates automatically with current scores once every minute.

It then updates the component with this.setState({ data: newData });.

Below I sort the new data by score, run each item through map that updates their style.top.

Javascript

```<code>...

let current = this.state.data.sort((a,b) => {
  if(a.score < b.score) return -1;
  if(a.score > b.score) return 1;
  return 0;
});

let items = current.map((item,i) => {
  return (
    <div
      key={item.name}
      className="item"
      style={{ top: (i*30) + 'px', backgroundColor: item.color }}>
        {item.name}
    </div>
  );
});

return (
  <div>
    {items}
  </div>
);
</code>```

CSS

```<code>.item {
  position: absolute;
  transition: top 1s;
}
</code>```

I want the items to animate up and down to their new positions, but this doesn't happen. The browser seems to remember parts of the DOM, but not others.

React seems to understand which item is which by using the unique key, if I inspect using React Developer Tools, but the actual DOM doesn't.

Even stranger, only items moving up the list (higher score) seems to be remembered. Items moving down is recreated, and therefor the transition doesn't work. They just pop into existence without transitioning to their new position.

Here is a working example to demonstrate. (JSFiddle)

答:
React redraws the DOM elements you update. This will resolve in really odd behaviours, such as blinking, jumping etc.

The React team offered a couple of solutions for this before they started working on Fiber instead. With the release of Fiber I hope we'll see better support for transitions and animations.

Until that time, I recommend you use external libs for animations such as:
https://github.com/FormidableLabs/react-animations For general animation.

And https://github.com/reactjs/react-transition-group for elements entering and exiting the DOM.

Body:
I have a highscore list that updates automatically with current scores once every minute.

It then updates the component with this.setState({ data: newData });.

Below I sort the new data by score, run each item through map that updates their style.top.

Javascript

...

let current = this.state.data.sort((a,b) => {
  if(a.score  b.score) return 1;
  return 0;
});

let items = current.map((item,i) => {
  return (

        {item.name}

  );
});

return (

    {items}

);

CSS

.item {
  position: absolute;
  transition: top 1s;
}

I want the items to animate up and down to their new positions, but this doesn't happen. The browser seems to remember parts of the DOM, but not others.

React seems to understand which item is which by using the unique key, if I inspect using React Developer Tools, but the actual DOM doesn't.

Even stranger, only items moving up the list (higher score) seems to be remembered. Items moving down is recreated, and therefor the transition doesn't work. They just pop into existence without transitioning to their new position.

Here is a working example to demonstrate. (JSFiddle)


问:
Moq and Async fun using LazyCache
I'm trying to mock a function named GetOrAddAsync. It's defined as:

```<code>Task<T> GetOrAddAsync<T>(string key, Func<Task<T>> addItemFactory, DateTimeOffset expires);
</code>```

When I use it in my actual code I use it like:

```<code>DateTimeOffset cacheTimeout = new DateTimeOffset(DateTime.Now.AddHours(config.CacheHours));
Func<Task<IEnumerable<int>>> func = async () => await (from s in dbContext.Names select s.First).ToListAsync();

return await cache.GetOrAddAsync(key, func, cacheTimeout);
</code>```

So basically if the key exists it will return what's in it and if not it'll create a key and fill it with data returned from the passed in Func<>.

My mocking attempt of this so far is as follows:

```<code>cache.Setup(x => x.GetOrAddAsync(It.IsAny<string>(), It.IsAny<Func<Task<IEnumerable<int>>>>(), It.IsAny<DateTimeOffset>()))
                .ReturnsAsync(async (string key, Func<Task<IEnumerable<int>>> func, DateTimeOffset policy) =>
                    {
                        return await func.Invoke();
                    });
</code>```

However, this is returning an error:

Cannot convert lambda expression to type 'IEnumerable' because it's not a delegate type.

My mind is ready to explode with this syntax :)

答: Rather than having to mock the LazyCache API using Moq yourself why not just use the mock version provided by the framework? It just executes whatever your delegate to be cached is and never does any caching. Check out MockCachingService.cs</p>

Title: Moq and Async fun using LazyCache

Body:
I'm trying to mock a function named GetOrAddAsync. It's defined as:

Task<T> GetOrAddAsync<T>(string key, Func<Task<T>> addItemFactory, DateTimeOffset expires);

When I use it in my actual code I use it like:

DateTimeOffset cacheTimeout = new DateTimeOffset(DateTime.Now.AddHours(config.CacheHours));
Func<Task<IEnumerable<int>>> func = async () => await (from s in dbContext.Names select s.First).ToListAsync();

return await cache.GetOrAddAsync(key, func, cacheTimeout);

So basically if the key exists it will return what's in it and if not it'll create a key and fill it with data returned from the passed in Func<>.

My mocking attempt of this so far is as follows:

cache.Setup(x => x.GetOrAddAsync(It.IsAny<string>(), It.IsAny<Func<Task<IEnumerable<int>>>>(), It.IsAny<DateTimeOffset>()))
                .ReturnsAsync(async (string key, Func<Task<IEnumerable<int>>> func, DateTimeOffset policy) =>
                    {
                        return await func.Invoke();
                    });

However, this is returning an error:

Cannot convert lambda expression to type 'IEnumerable' because it's not a delegate type.

My mind is ready to explode with this syntax :)


问:
What would prevent code running in a Docker container from connecting to a database on a separate server?
I have a .NET Core 1.1 app running in a Docker container on Ubuntu 14.04, and it fails to connect to the SQL Server database running on a separate server.

The error is:

Unhandled Exception: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 25 - Connection string is not valid)

I have deployed the same image with the same command line on another Ubuntu 14.04 server, and it connects fine.

A console app running on the problem server (outside of Docker) can connect with the same connection string.

As far as I can see from the documentation, an app running in a container has access to the external network by default, so what could be blocking this connection?

答:
Does this help?

Connect to SQL Server database from a docker container

Also, Googling this "docker connect to sql server database" seems to return a lot of helpful results.


问:
What is the regular expression for Date format dd\mm\yyyy?
What is the regular expression for Date format dd\mm\yyyy? I am unable to find out regex for this format?</p>

Body:
I tried this ^[0-3]{1}[0-9]{1}/[0-1]{1}[1-2]{1}/[1-9]{1}[0-9]{3}$ and it works

String dateRegEx="^[0-3]{1}[0-9]{1}/[0-1]{1}[1-2]{1}/[1-9]{1}[0-9]{3}$";
System.out.println(Pattern.matches(dateRegEx, "01/01/1990"));


问:
Performing A Query On Field Generated From Sub Query
I have two tables, Clients and Jobs.

I am doing a report on clients, and as part of the query, I also return a count of how many jobs we have done for each client. The code is as follows:

```<code>SELECT * ,
(SELECT COUNT(*) FROM Jobs WHERE ClientID = Clients.ID) AS JobsCount
FROM Clients
</code>```

I now need to modify this to allow conditional queries based on the JobsCount, such as "return all clients with more than 100 jobs". Simply adding a where clause on JobsCount doesnt seem to work - Invalid column name 'JobsCount'.

How can i query on a column that is generated through a sub query?

答:
```<code>Select clients.* ,jobcount
from clients
inner join
(Select COUNT(*) as jobcount,clientid FROM Jobs group by clientid having count(*)>100 )Jobs
On jobs.clientid=clients.clientid
</code>```

Grouping the job count and filtering | removing using having condition with job count >100. Inner join will filter | removing the clients with job count <100 or client doesn't exists with Jobs table.

Body:
I have two tables, Clients and Jobs.

I am doing a report on clients, and as part of the query, I also return a count of how many jobs we have done for each client. The code is as follows:

SELECT * ,
(SELECT COUNT(*) FROM Jobs WHERE ClientID = Clients.ID) AS JobsCount
FROM Clients

I now need to modify this to allow conditional queries based on the JobsCount, such as "return all clients with more than 100 jobs". Simply adding a where clause on JobsCount doesnt seem to work - Invalid column name 'JobsCount'.

How can i query on a column that is generated through a sub query?

Body:
Select clients.* ,jobcount
from clients
inner join
(Select COUNT(*) as jobcount,clientid FROM Jobs group by clientid having count(*)>100 )Jobs
On jobs.clientid=clients.clientid

Grouping the job count and filtering | removing using having condition with job count >100. Inner join will filter | removing the clients with job count <100 or client doesn't exists with Jobs table.


问:
Application not running on Android device
My application is running properly on emulator but not on device. Earlier I have run the same app on device many a times. I have turned USB- Debugging on my device, also set debuggable to true in manifest.

When I try to use command adb devices, it's showing me an empty list of devices.

Has anybody encountered same problem anytime?

Thanx in advance.

答:
This is just a list of things to try/check

-> Unknown Source to true

-> Debuggable requires USB Debugging

-> Non Mass Storage mode/USB connect to access the SD Card

-> unplug replug

-> reboot the phone (to be sure you can unplug the usb and remove the battery)

-> restart adb

Can you see an emulator ? can you launch your app on the emulator? can you launch a different project on the phone?


问:
What is wrong with my code? (selecting all from DB not working)
Long time that i dont program php.

i made a function for the  cliente profile,so the cliente can see his logo

this is the cliente code

```<code>function display_logo(){
    global $conn;

    $stmt = $conn->prepare("SELECT LogoImage FROM usuarios WHERE email=?");
    $stmt->bind_param("s", $em);
    $em = $_SESSION['useremail'];
    $stmt->execute();
    $result = $stmt->get_result();
    $rows = $result->fetch_assoc();

    $img =$rows['LogoImage'];
    echo '<img style="    margin-top: -14;
    object-fit: contain;" src="includes/file?file=' . $img. '"  />';

}
</code>```

This code works fine for the  cliente profile.
But  now i am trying to display all users in my admin painel.

This way ...

```<code>function display_all_logo(){
    global $conn;

    $stmt = $conn->prepare("SELECT * LogoImage FROM usuarios");

    // $stmt = $conn->prepare("SELECT  LogoImage FROM usuarios WHERE nome=?");
    // $stmt->bind_param("s", $em);
    // $em = $_SESSION['userName'];
    $stmt->execute();
    $stmt->bind_result($LogoImage);

     while($stmt->fetch()) {
        $tmp = array();
        $tmp["LogoImage"] = $LogoImage;

        array_push($LogoImage, $tmp);
    }

    $img =$rows['LogoImage'];

echo '<img style="    margin-top: -14;
object-fit: contain;" src="includes/file?file=' . $img. '"  />';

}
</code>```

i know that i'm doing something wrong, please someone help, long time that i don't program php.

Fixed

```<code>function display_all_logo($user_logo){
    global $conn;

     $stmt = $conn->prepare("SELECT LogoImage FROM usuarios WHERE  logoImage = ?  ");

    $stmt->bind_param("s", $em);
    $em = $user_logo;
    $stmt->execute();

    $result = $stmt->get_result();
    $rows = $result->fetch_assoc();

    $img =$rows['LogoImage'];

return '<img style="    margin-top: -14;
object-fit: contain;" src="includes/file?file=' . $img. '"  />';

}
</code>```

答:
```<code>function display_all_logo(){
    global $conn;

    $stmt = $conn->prepare("SELECT LogoImage FROM usuarios");
</code>```

Body:
Long time that i dont program php.

i made a function for the  cliente profile,so the cliente can see his logo

this is the cliente code

function display_logo(){
    global $conn;

    $stmt = $conn->prepare("SELECT LogoImage FROM usuarios WHERE email=?");
    $stmt->bind_param("s", $em);
    $em = $_SESSION['useremail'];
    $stmt->execute();
    $result = $stmt->get_result();
    $rows = $result->fetch_assoc();

    $img =$rows['LogoImage'];
    echo '';

}

This code works fine for the  cliente profile.
But  now i am trying to display all users in my admin painel.

This way ...

function display_all_logo(){
    global $conn;

    $stmt = $conn->prepare("SELECT * LogoImage FROM usuarios");

    // $stmt = $conn->prepare("SELECT  LogoImage FROM usuarios WHERE nome=?");
    // $stmt->bind_param("s", $em);
    // $em = $_SESSION['userName'];
    $stmt->execute();
    $stmt->bind_result($LogoImage);

     while($stmt->fetch()) {
        $tmp = array();
        $tmp["LogoImage"] = $LogoImage;

        array_push($LogoImage, $tmp);
    }

    $img =$rows['LogoImage'];

echo '';

}

i know that i'm doing something wrong, please someone help, long time that i don't program php.

Fixed

function display_all_logo($user_logo){
    global $conn;

     $stmt = $conn->prepare("SELECT LogoImage FROM usuarios WHERE  logoImage = ?  ");

    $stmt->bind_param("s", $em);
    $em = $user_logo;
    $stmt->execute();

    $result = $stmt->get_result();
    $rows = $result->fetch_assoc();

    $img =$rows['LogoImage'];

return '';

}


问:
ramda findIndex with gaps
I have the following code where I want to fill in the id, so I'm thinking to write something like this:

```<code>const data = [
 { id: 'some-id' },
 { id: 'some-other-id' },
 { id: 'third-id' },
];

const tabIndex = R.findIndex(R.propEq('id', R.__))(data);
</code>```

So I can use it like this tabIndex('third-id'), but this is not a function.
What do I miss or confuse with this?

The following works

```<code>const tabIndex = (id) => R.findIndex(R.propEq('id', id))(data);
</code>```

But I thought, that is the point of R.__ gaps function.

答:
I think that by far the simplest way to do this is

```<code>const matchId = (id, data) => R.findIndex(R.propEq('id', id), data);
matchId('third-id', data); //=> 2
</code>```

If you really want to make this points-free, Ramda offers several functions to help, such as useWith and converge (for which one can often substitute lift.)  This one would take useWith:

```<code>const matchId = R.useWith(findIndex, [R.propEq('id'), R.identity]);
matchId('third-id', data); //=> 3
</code>```

But I find the first version much more readable.  You can find both on the Ramda REPL.

Do pay attention to the side note from Emissary.  The R.__ placeholder is essentially used to show gaps between the arguments you supply; as a final argument it doesn't do anything.

Title: ramda findIndex with gaps

Body:
I have the following code where I want to fill in the id, so I'm thinking to write something like this:

const data = [
 { id: 'some-id' },
 { id: 'some-other-id' },
 { id: 'third-id' },
];

const tabIndex = R.findIndex(R.propEq('id', R.__))(data);

So I can use it like this tabIndex('third-id'), but this is not a function.
What do I miss or confuse with this?

The following works

const tabIndex = (id) => R.findIndex(R.propEq('id', id))(data);

But I thought, that is the point of R.__ gaps function.

Body:
I think that by far the simplest way to do this is

const matchId = (id, data) => R.findIndex(R.propEq('id', id), data);
matchId('third-id', data); //=> 2

If you really want to make this points-free, Ramda offers several functions to help, such as useWith and converge (for which one can often substitute lift.)  This one would take useWith:

const matchId = R.useWith(findIndex, [R.propEq('id'), R.identity]);
matchId('third-id', data); //=> 3

But I find the first version much more readable.  You can find both on the <a href="http://ramdajs.com/repl/?v=0.24.0#?const%20data%20%3D%20%5B%0A%20%7B%20id%3A%20%27some-id%27%20%7D%2C%0A%20%7B%20id%3A%20%27some-other-id%27%20%7D%2C%0A%20%7B%20id%3A%20%27third-id%27%20%7D%2C%0A%5D%3B%0A%0A%0A%2F%2F%20const%20matchId%20%3D%20%28id%2C%20data%29%20%3D%3E%20R.findIndex%28R.propEq%28%27id%27%2C%20id%29%2C%20data%29%3B%0A%2F%2F%20or%0Aconst%20matchId%20%3D%20R.useWith%28findIndex%2C%20%5BR.propEq%28%27id%27%29%2C%20R.identity%5D%29%3B%0A%0AmatchId%28%27third-id%27%2C%20data%29" rel="nofollow noreferrer">Ramda REPL.

Do pay attention to the side note from Emissary.  The R.__ placeholder is essentially used to show gaps between the arguments you supply; as a final argument it doesn't do anything.


问:
Specifics on How Glassfish Server is Run with IntelliJ Debugger?
I'm curious as to how the IntelliJ debugger uses the domain.xml of my glassfish server and reports a webpage when requested.

Specifically, I have an IntelliJ project called blobGame that uses a Glassfish server that opens a webpage called blobGame when the artifacts .war and .ear are deployed.

Firstly, how are these artifacts deployed? When I deploy them, I MUST have the URL of the localhost be http://localhost:60836/blobGame_war_exploded, and localhost:60836/blobGame DOES NOT WORK, even if I change it in the debug configuration - here is my debugger info

Why is this? Why does the url have to be /blobGame_war_exploded? It cannot even be /blobGame_ear_exploded, as I see that also in the domain.xml.

Here is the snippet of domain.xml for my domain called "domain2":

  <applications>
    <application object-type="user" name="blobGame_ear_exploded" directory-deployed="true" location="file:/C:/Users/Kevin/EECS/blobGame/out/artifacts/blobGame_ear_exploded/">
      <property name="archiveType" value="ear"></property>
      <property name="isComposite" value="true"></property>
      <property name="appLocation" value="file:/C:/Users/Kevin/EECS/blobGame/out/artifacts/blobGame_ear_exploded/"></property>
      <property name="org.glassfish.ejb.container.application_unique_id" value="98074431158681600"></property>
      <property name="defaultAppName" value="blobGame_ear_exploded"></property>
      <module name="web.war">
        <engine sniffer="ejb"></engine>
        <engine sniffer="security"></engine>
        <engine sniffer="weld"></engine>
        <engine sniffer="web"></engine>
      </module>
      <engine sniffer="ear"></engine>
    </application>
    <application context-root="/blobGame_war_exploded" object-type="user" name="blobGame_war_exploded" directory-deployed="true" location="file:/C:/Users/Kevin/EECS/blobGame/out/artifacts/blobGame_war_exploded/">
      <property name="archiveType" value="war"></property>
      <property name="appLocation" value="file:/C:/Users/Kevin/EECS/blobGame/out/artifacts/blobGame_war_exploded/"></property>
      <property name="org.glassfish.ejb.container.application_unique_id" value="98074431158812672"></property>
      <property name="defaultAppName" value="blobGame_war_exploded"></property>
      <module name="blobGame_war_exploded">
        <engine sniffer="ejb"></engine>
        <engine sniffer="security"></engine>
        <engine sniffer="weld"></engine>
        <engine sniffer="web"></engine>
      </module>
    </application>
  </applications>```
</div>
</div>
</p>

<p>SECOND of all, why does the deployment still use previous artifacts (as I assume they are) when I redeploy or restart the server?</p>

<p>Specifically, when I press restart, I get the exact same HTML and javascript files I was left with before, and even if I edited the html or JS files during the time before my second debug.
(I add alert("test") in the new debug, but it does not show up in the new debug. When I access the index.html page independently the alert does show up).</p>

<p>Here is the index.html</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>keyBoardDemo</title>
    </head>
    <body>
        <canvas id="canvas" width="800" height="600" style="border:1px solid #000000;"></canvas>
        <p id="main"></p>
        <script type="text/javascript" src=resources.js></script>
        <script type="text/javascript" src=canvas.js></script>
        <script type="text/javascript" src=keyboard.js></script>
        <script type="text/javascript" src=packethandler.js></script>
        <script type="text/javascript" src=player.js></script>
        <script type="text/javascript" src=websocket.js></script>
    </body>
</html></code>```

and here is the canvas.js that it calls:

alert("test 123"); //this is not called on the second redeployment!

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");```

答:
Firstly, how are these artifacts deployed? When I deploy them, I MUST have the URL ...

By default, IDEA computes context root from the artifact name, by replacing unsupported characters with underscores. Thus, the 'blobGame:war exploded' artifact, by default gets 'blobGame_war_exploded' context root.

To change the context root for the artifact, you may want to open the 'Deployment' tab of the run configuration, check 'Use custom context root' and enter the desired value into the field

'Open browser' field on the 'Server' tab does not affect the server settings, it just allows you to open whatever URL you like after the server start. The field value defaults to the URL computed from the first artifact, but once user have changed it IDEA assumes that user knows better.

Specifically, when I press restart, I get the exact same HTML and javascript files I was left with before, ...

The expected sequence is as follows:

make a change to a resource

update the application on the server with the mentioned 'Update <> application' action: 'Update resource' choice should be enough for an exploded application, redeploy/restart may be needed for archive artifact

reload (refresh) the page, that uses the resource in browser

I suspect you're missing the last (3) step. Please note, step (2) only updates the resource on the server, and to see a change in browser (on client) you should reload the corresponding resources from server by refreshing the page manually.

Hope that helps,
I am going to redirect your second post to this answer

Body:
I'm curious as to how the IntelliJ debugger uses the domain.xml of my glassfish server and reports a webpage when requested.

Specifically, I have an IntelliJ project called blobGame that uses a Glassfish server that opens a webpage called blobGame when the artifacts .war and .ear are deployed.

Firstly, how are these artifacts deployed? When I deploy them, I MUST have the URL of the localhost be http://localhost:60836/blobGame_war_exploded, and localhost:60836/blobGame DOES NOT WORK, even if I change it in the debug configuration - here is my debugger info

Why is this? Why does the url have to be /blobGame_war_exploded? It cannot even be /blobGame_ear_exploded, as I see that also in the domain.xml.

Here is the snippet of domain.xml for my domain called "domain2":

  <applications>
    <application object-type="user" name="blobGame_ear_exploded" directory-deployed="true" location="file:/C:/Users/Kevin/EECS/blobGame/out/artifacts/blobGame_ear_exploded/">
      <property name="archiveType" value="ear"></property>
      <property name="isComposite" value="true"></property>
      <property name="appLocation" value="file:/C:/Users/Kevin/EECS/blobGame/out/artifacts/blobGame_ear_exploded/"></property>
      <property name="org.glassfish.ejb.container.application_unique_id" value="98074431158681600"></property>
      <property name="defaultAppName" value="blobGame_ear_exploded"></property>
      <module name="web.war">
        <engine sniffer="ejb"></engine>
        <engine sniffer="security"></engine>
        <engine sniffer="weld"></engine>
        <engine sniffer="web"></engine>
      </module>
      <engine sniffer="ear"></engine>
    </application>
    <application context-root="/blobGame_war_exploded" object-type="user" name="blobGame_war_exploded" directory-deployed="true" location="file:/C:/Users/Kevin/EECS/blobGame/out/artifacts/blobGame_war_exploded/">
      <property name="archiveType" value="war"></property>
      <property name="appLocation" value="file:/C:/Users/Kevin/EECS/blobGame/out/artifacts/blobGame_war_exploded/"></property>
      <property name="org.glassfish.ejb.container.application_unique_id" value="98074431158812672"></property>
      <property name="defaultAppName" value="blobGame_war_exploded"></property>
      <module name="blobGame_war_exploded">
        <engine sniffer="ejb"></engine>
        <engine sniffer="security"></engine>
        <engine sniffer="weld"></engine>
        <engine sniffer="web"></engine>
      </module>
    </application>
  </applications>

SECOND of all, why does the deployment still use previous artifacts (as I assume they are) when I redeploy or restart the server?

Specifically, when I press restart, I get the exact same HTML and javascript files I was left with before, and even if I edited the html or JS files during the time before my second debug.
(I add alert("test") in the new debug, but it does not show up in the new debug. When I access the index.html page independently the alert does show up).

Here is the index.html

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>keyBoardDemo</title>

        <canvas id="canvas" width="800" height="600" style="border:1px solid #000000;"></canvas>

and here is the canvas.js that it calls:

alert("test 123"); //this is not called on the second redeployment!

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");


问:
Automake/Autoconf scripts custom directory
My project's root folder is PROJECT, and there is only one script in PROJECT/scripts/abc.sh, which I want to install it into the directory /usr/share/xxx/abc.sh.

Because it is not install into /usr/bin/abc.sh, so bin_SCRIPTS = abc.sh is incorrect.

Could you please tell me how to write the Makefile.am?

答:
You'll need to define the install directory:

```<code>xxxdir = $(datarootdir)/xxx

xxx_SCRIPTS = scripts/abc.sh
</code>```

More typically as something like:

```<code>pkgdata_SCRIPTS = scripts/abc.sh
</code>```

where automake has already setup pkgdatadir.

Body:
You'll need to define the install directory:

xxxdir = $(datarootdir)/xxx

xxx_SCRIPTS = scripts/abc.sh

More typically as something like:

pkgdata_SCRIPTS = scripts/abc.sh

where automake has already setup pkgdatadir.


问:
How to implement multiple lifecycle hooks for an Angular2 component?
I know that when defining components in Angular2 you have multiple types of lifecycle hooks that you can implement such as OnDestroy, NgOnInit, etc.

In every sample piece of code I've seen online about using these hooks, I only ever see them being used one at a time. For instance

```<code>export class ModalComponent implements OnDestroy { ... }
</code>```

or

```<code>export class ModalComponent implements OnChanges { ... }
</code>```

But what if you want to use multiple for a single component? For instance, what if you want specific behavior for OnChanges AND OnDestroy? I've tried the following:

```<code>export class ModalComponent implements OnChanges implements OnDestroy{ ... }
export class ModalComponent implements OnChanges, OnDestroy { ... }
export class ModalComponent implements [OnChanges, OnDestroy] { ... }
export class ModalComponent implements OnChanges and OnDestroy { ... }
</code>```

I'm certain the answer is very simple but I'm having a remarkable amount of trouble finding an answer to this.

Thank you in advance!

答:
You were probably right when you implemented two interfaces with a comma separator.

Here's an example.

```<code>import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-ram-component',
  templateUrl: './ram.component.html',
  styleUrls: ['./ram.component.css']
})

export class RamComponentComponent implements OnInit,OnDestroy,AfterViewInit {

  constructor() { }

  ngOnInit() {
    console.log('On Init');
  }
  ngAfterViewInit(){
    console.log('after view');
  }
  ngOnDestroy(){
    console.log('destroyed!!');
  }
}
</code>```

Please note the import statement has to include all the necessary lifecycle hooks.

```<code> import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
</code>```

Lifecycle Hooks Reference

Body:
I know that when defining components in Angular2 you have multiple types of lifecycle hooks that you can implement such as OnDestroy, NgOnInit, etc.

In every sample piece of code I've seen online about using these hooks, I only ever see them being used one at a time. For instance

export class ModalComponent implements OnDestroy { ... }

or

export class ModalComponent implements OnChanges { ... }

But what if you want to use multiple for a single component? For instance, what if you want specific behavior for OnChanges AND OnDestroy? I've tried the following:

export class ModalComponent implements OnChanges implements OnDestroy{ ... }
export class ModalComponent implements OnChanges, OnDestroy { ... }
export class ModalComponent implements [OnChanges, OnDestroy] { ... }
export class ModalComponent implements OnChanges and OnDestroy { ... }

I'm certain the answer is very simple but I'm having a remarkable amount of trouble finding an answer to this.

Thank you in advance!

Body:
You were probably right when you implemented two interfaces with a comma separator.

Here's an example.

import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-ram-component',
  templateUrl: './ram.component.html',
  styleUrls: ['./ram.component.css']
})

export class RamComponentComponent implements OnInit,OnDestroy,AfterViewInit {

  constructor() { }

  ngOnInit() {
    console.log('On Init');
  }
  ngAfterViewInit(){
    console.log('after view');
  }
  ngOnDestroy(){
    console.log('destroyed!!');
  }
}

Please note the import statement has to include all the necessary lifecycle hooks.

 import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';

Lifecycle Hooks Reference


问:
Second argument to std::vector
Looking at vector, I realized that I have never used the second argument when creating vectors.

```<code>std::vector<int> myInts; // this is what I usually do
std::vector<int, ???> myOtherInts; // but is there a second argument there?
</code>```

Looking at the link above it says that it is for:

Allocator object to be used instead of constructing a new one.

or, as for this one:

Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type T is used, which defines the simplest memory allocation model and is value-independent.

I guess it has to do with something with memory management. However, I am not sure how to use that.

Any pointers regarding this?

答: Allocators (STL) help you to manage memory for your objects in vector class. you may use the custom allocator for different memory model( etc). </p>

Title: Second argument to std::vector

Body:
Looking at vector, I realized that I have never used the second argument when creating vectors.

std::vector<int> myInts; // this is what I usually do
std::vector<int, ???> myOtherInts; // but is there a second argument there?

Looking at the link above it says that it is for:

Allocator object to be used instead of constructing a new one.

or, as for this one:

Allocator: Type of the allocator object used to define the storage allocation model. By default, the allocator class template for type T is used, which defines the simplest memory allocation model and is value-independent.

I guess it has to do with something with memory management. However, I am not sure how to use that.

Any pointers regarding this?


问:
Why do event handlers need to be references and not invocations?
In the React tutorial, it says

Doing onClick={alert('click')} would alert immediately instead of when the button is clicked.

```<code>class Square extends React.Component {
  render() {
    return (
      <button className="square" onClick={() => alert('click')}>
        {this.props.value}
      </button>
    );
  }
}
</code>```

However, I cannot understand why that would be... can anyone clarify this for me please? Why can't you pass a function invocation as a handler?

答:
When you do onClick={alert("click")} that's going to call the alert function and assign the returned value (undefined) to the onClick property. So, what React sees is onClick={undefined} and says: well, that's not a function, why would I add such a handler?

What you want to pass to onClick is a function, not undefined.

Therefore, you have to do: onClick={myFunction} where myFunction can be () => alert("...") as you mentioned, or you can use bind to create a similar function:

```<code>onClick={alert.bind(window, "click")}
</code>```

bind will return a new function which will internally call the alert function with the "click" argument.

A similar case is when you do setTimeout(() => alert("after 1 second"), 1000). setTimeout expects a function. If you do setTimeout(alert("..."), 1000), the alert will be called, indeed, but the setTimeout will receive as first argument undefined (that's what alert returns).

Instead, if you have a function which returns a function, that will work:

```<code>// This will be called first and will return a function
const sayHelloTo = name => {
   // This will be the function passed to `setTimeout`
   return () => alert(`Hello ${name}`);
};
setTimeout(sayHelloTo("Alice"), 1000);
</code>```

You can use it in the same way for the onClick thingy:

```<code>onClick={sayHelloTo("Alice")}
</code>```

This is a very tiny example about what happens in the background (it's just a proof of concept, I'm sure what it actually happens is way better than this):

```<code>const elm = {
  onClick: null,
  // The click method can be invoked manually
  // using `elm.click()` or is natively invoked by the browser
  click () {
     if (typeof this.onClick === "function") {
        this.onClick();
     }
  }
};

// If you do:
elm.onClick = alert("click"); // this calls the alert, and returns undefined
elm.onClick === undefined // true

// But when doing:
elm.onClick = () => alert("click");
typeof elm.onClick // "function"

elm.click(); // this will call the alert
</code>```

Body:
In the React tutorial, it says

Doing onClick={alert('click')} would alert immediately instead of when the button is clicked.

class Square extends React.Component {
  render() {
    return (
      <button className="square" onClick={() => alert('click')}>
        {this.props.value}
      </button>
    );
  }
}

However, I cannot understand why that would be... can anyone clarify this for me please? Why can't you pass a function invocation as a handler?

Body:
When you do onClick={alert("click")} that's going to call the alert function and assign the returned value (undefined) to the onClick property. So, what React sees is onClick={undefined} and says: well, that's not a function, why would I add such a handler?

What you want to pass to onClick is a function, not undefined.

Therefore, you have to do: onClick={myFunction} where myFunction can be () => alert("...") as you mentioned, or you can use bind to create a similar function:

onClick={alert.bind(window, "click")}

bind will return a new function which will internally call the alert function with the "click" argument.

A similar case is when you do setTimeout(() => alert("after 1 second"), 1000). setTimeout expects a function. If you do setTimeout(alert("..."), 1000), the alert will be called, indeed, but the setTimeout will receive as first argument undefined (that's what alert returns).

Instead, if you have a function which returns a function, that will work:

// This will be called first and will return a function
const sayHelloTo = name => {
   // This will be the function passed to `setTimeout`
   return () => alert(`Hello ${name}`);
};
setTimeout(sayHelloTo("Alice"), 1000);

You can use it in the same way for the onClick thingy:

onClick={sayHelloTo("Alice")}

This is a very tiny example about what happens in the background (it's just a proof of concept, I'm sure what it actually happens is way better than this):

const elm = {
  onClick: null,
  // The click method can be invoked manually
  // using `elm.click()` or is natively invoked by the browser
  click () {
     if (typeof this.onClick === "function") {
        this.onClick();
     }
  }
};

// If you do:
elm.onClick = alert("click"); // this calls the alert, and returns undefined
elm.onClick === undefined // true

// But when doing:
elm.onClick = () => alert("click");
typeof elm.onClick // "function"

elm.click(); // this will call the alert


问:
is there a Collection Subscription Inheritance passed onto child templates
Consider below hierarchy of templates,

'A' has 2 template 'B' and 'C'.

'B' has 2 templates 'D' and 'E'.

my question is whether the meteor collection subcription made in template 'A' is available in the helper for template 'E' since 'A' has 'B' and 'B' has 'E'?

NOTE: if YES/NO why?

答:
The data is available as a helper in the child templates if you pass the data to them.

You can do:

```<code>{{> childTemplate post=post}}
</code>```

And then

```<code><template name="childTemplate">
  {{post.title}}
</template>
</code>```

Body:
The data is available as a helper in the child templates if you pass the data to them.

You can do:

{{> childTemplate post=post}}

And then

<template name="childTemplate">
  {{post.title}}
</template>


问:
how to set value from picker to customized cell textfield of particular section?
```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if(indexPath.section==0)
    {
        if(indexPath.row==1)
        {

            static NSString *CellIdentifier = @"custom1TableViewCell";

            custom1TableViewCell *cell2 = (custom1TableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

            if (cell2 == nil)
            {

                cell2 = [[ custom1TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

            }

            NSDictionary *dictionary = [dataArray objectAtIndex:indexPath.section];

            NSArray *array = [dictionary objectForKey:@"data"];
            cell2.language.text = [array objectAtIndex:indexPath.row];

            //for picker

            [cell2.sellanguage setInputView:pickerview];
            cell2.sellanguage.text = selectedLanguage;

            return cell2;
        }

        static NSString *CellIdentifier = @"customTableViewCell";

        customTableViewCell *cell = (customTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

        if (cell == nil)
        {

            cell = [[customTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];

        }

        NSDictionary *dictionary = [dataArray objectAtIndex:indexPath.section];
        NSArray *array = [dictionary objectForKey:@"data"];
        cell.soundfx.text = [array objectAtIndex:indexPath.row];

        return cell;

    }
- (void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component

{

    [pickerview selectRow:row inComponent:0 animated:YES];

    NSLog(@"%@",[languages objectAtIndex:row]);

    selectedLanguage= [languages objectAtIndex:row];

    [[self view] endEditing:YES];
    [self.tableview reloadData];
}
</code>```

答:
```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    // now you can use cell.textLabel.text
    //For Example
    self.textfield.text = cell.textLabel.text;
}
</code>```

I hope this clears your doubt.

Body:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    // now you can use cell.textLabel.text
    //For Example
    self.textfield.text = cell.textLabel.text;
}

I hope this clears your doubt.


问:
java.upcasting
i have this example:

```<code>class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    static void test(One o) {o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new One());
    }
}
</code>```

Results:

```<code>One!!!
One!!!
</code>```

ok, no questions.

than, i try modified my code:

only this method:

```<code>public static void main(String args[])
    {
        test(new Jenia());
        }
</code>```

results:

```<code>One!!!
One!!!
</code>```

ok, we have this results because - here upcasting(Jenia-One).

its all ok too, but, modified again:
 in class Jenia override methodtestOne`:

```<code>public void testOne(){System.out.println("Two!!!");}
</code>```

so i have this code:

```<code>class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    public void testOne(){System.out.println("Two!!!");}

    static void test(One o){o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new Jenia());
    }
}
</code>```

and results:

```<code>Two!!!
One!!!
</code>```

my question: why Two!!! ?? why we not lost override methods?

答: Because all the methods in Java are virtual in terms of C++/C# and all the values passed by reference. So when you call some method, the type of the reference is irrelevant, what is important is the type of the object it points to. In your case the object is of Jenia type, so Jenia method gets called.</p>

Title: java.upcasting

Body:
i have this example:

class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    static void test(One o) {o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new One());
    }
}

Results:

One!!!
One!!!

ok, no questions.

than, i try modified my code:

only this method:

public static void main(String args[])
    {
        test(new Jenia());
        }

results:

One!!!
One!!!

ok, we have this results because - here upcasting(Jenia-One).

its all ok too, but, modified again:
 in class Jenia override methodtestOne`:

public void testOne(){System.out.println("Two!!!");}

so i have this code:

class One
{
    public void testOne(){System.out.println("One!!!");}
    public void testTwo(){System.out.println("One!!!");}
}
public class Jenia extends One
{
    public void testOne(){System.out.println("Two!!!");}

    static void test(One o){o.testOne(); o.testTwo();}
    public static void main(String args[])
    {
        test(new Jenia());
    }
}

and results:

Two!!!
One!!!

my question: why Two!!! ?? why we not lost override methods?


问:
Editable cells in dynamic table
I'm trying to make a dynamic table with variable no. of rows and columns. Table is created but when i click on the cells, they are not editable as i assumed they will be.

$(document).ready(function() {
            $("#createit").click(function() {
                var num_rows = document.getElementById('rows').value;
                var num_cols = document.getElementById('cols').value;
                var tbody = '';
                for (var i = 0; i < num_rows; i++) {
                    tbody += '
';
                    for (var j = 0; j < num_cols; j++) {
                        tbody += '';
                        tbody += 'Cell' + i + j;
                        tbody += '	'
                    }
                    tbody += '
';
                }
                //document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
                $('.editableTable').append(tbody);
            });
        });
        $(".editableTable td").dblclick(function() {
            console.log('clicked');
            var OriginalContent = $(this).text();
            $(this).addClass("cellEditing");
            $(this).html("<select><option>1</option><option>2</option><option >3</option></select>");
            $(this).children().first().focus();
            $(this).bgColor = 'red';

            $(this).children().first().keypress(function(e) {
                if (e.which == 13) {
                    var newContent = OriginalContent;
                    $(this).parent().text(OriginalContent);
                    $(this).parent().removeClass("cellEditing");
                }
            });
            $(this).children().first().blur(function() {
                $(this).parent().text(OriginalContent);
                $(this).parent().removeClass("cellEditing");
            });
        });
        $(".editableTable td").bind('keydown', function(event) {
            if (event.keyCode === 9 || event.keyCode === 13) {
                var tabindex = $(this).attr('tabindex');
                tabindex++; //increment tabindex
                $('[tabindex=' + tabindex + ']').focus().dblclick();
                return false;
            }
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.editableTable {
            border: solid 0px;
            width: 100%;
            text-align: center
        }

        .editableTable td {
            border: solid 0.5px;
            border-color: lightblue;
            min-width: 100px;
        }

        .editableTable .cellEditing {
            padding: 0;
        }

        select {
            border: 0px;
            width: 100%;
        }</code>```

Rows: <input type="text" name="rows" id="rows"/>

    Cols: <input type="text" name="cols" id="cols"/>

    <input name="generate" type="button" value="Create Table!" id='createit' />

```

Same thing i have done before but with a static table. JSFIDDLE https://jsfiddle.net/rbrohitbisht/691rx62k/

Now i want to do the same thing with the dynamic table. What i'm doing wrong here?

答:
use HTML DOM "contentEditable" Property Element Object
  https://stackoverflow.com/a/44380264/3615816

<input type=button value="Enable editing"
onclick="document.getElementById('t1').contentEditable = 'true';alert('You can now edit table')" />

c1	c2

cc1	cc2

<input type=button value="disable editing"
onclick="document.getElementById('t1').contentEditable = 'false'; " />```

Title: Editable cells in dynamic table

Body:
I'm trying to make a dynamic table with variable no. of rows and columns. Table is created but when i click on the cells, they are not editable as i assumed they will be.

$(document).ready(function() {
            $("#createit").click(function() {
                var num_rows = document.getElementById('rows').value;
                var num_cols = document.getElementById('cols').value;
                var tbody = '';
                for (var i = 0; i < num_rows; i++) {
                    tbody += '
';
                    for (var j = 0; j < num_cols; j++) {
                        tbody += '';
                        tbody += 'Cell' + i + j;
                        tbody += '	'
                    }
                    tbody += '
';
                }
                //document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
                $('.editableTable').append(tbody);
            });
        });
        $(".editableTable td").dblclick(function() {
            console.log('clicked');
            var OriginalContent = $(this).text();
            $(this).addClass("cellEditing");
            $(this).html("<select><option>1</option><option>2</option><option >3</option></select>");
            $(this).children().first().focus();
            $(this).bgColor = 'red';

            $(this).children().first().keypress(function(e) {
                if (e.which == 13) {
                    var newContent = OriginalContent;
                    $(this).parent().text(OriginalContent);
                    $(this).parent().removeClass("cellEditing");
                }
            });
            $(this).children().first().blur(function() {
                $(this).parent().text(OriginalContent);
                $(this).parent().removeClass("cellEditing");
            });
        });
        $(".editableTable td").bind('keydown', function(event) {
            if (event.keyCode === 9 || event.keyCode === 13) {
                var tabindex = $(this).attr('tabindex');
                tabindex++; //increment tabindex
                $('[tabindex=' + tabindex + ']').focus().dblclick();
                return false;
            }
        });

.editableTable {
            border: solid 0px;
            width: 100%;
            text-align: center
        }

        .editableTable td {
            border: solid 0.5px;
            border-color: lightblue;
            min-width: 100px;
        }

        .editableTable .cellEditing {
            padding: 0;
        }

        select {
            border: 0px;
            width: 100%;
        }

Rows: <input type="text" name="rows" id="rows"/>

    Cols: <input type="text" name="cols" id="cols"/>

    <input name="generate" type="button" value="Create Table!" id='createit' />

Same thing i have done before but with a static table. JSFIDDLE https://jsfiddle.net/rbrohitbisht/691rx62k/

Now i want to do the same thing with the dynamic table. What i'm doing wrong here?

Body:
use HTML DOM "contentEditable" Property Element Object
  https://stackoverflow.com/a/44380264/3615816

<input type=button value="Enable editing"
onclick="document.getElementById('t1').contentEditable = 'true';alert('You can now edit table')" />

<table id="t1"   border="1">

  <tr><td >c1</td><td >c2</td></tr>
  <tr><td >cc1</td><td >cc2</td></tr>

</table>

<input type=button value="disable editing"
onclick="document.getElementById('t1').contentEditable = 'false'; " />


答:
When you have an event handler it must be a function reference, not a function invocation. This is because internally when the handler is executed, the handler is first evaluated before it can be called. With inline JSX expressions such as when passing an event handler prop, the expression is evaluated when the component is declared, before the handler is called.

Thus, if you pass in an invocation such as alert('click'), it will alert as it is being evaluated. When the event is triggered and the handler is called, it will then attempt to call the return value of alert (which is undefined) -- not good. Instead, you need a function reference, which when evaluated gives you a callable function which is then called as the handler.

Take this pseudocode for an example:

```<code>function on(event, handler) {
    //some event listener function that runs the handler when event happens
    //then we call handler when the event happens:
    handler();
}
</code>```

Imagine if we invoked the function as on('click', alert('test')), then alert('test') would be evaluated and the return value would be passed as the handler, which is undefined. Then you would be trying to call undefined(), not good. Thus, you must pass a function reference, a reference to a callable function.

Title: Why do event handlers need to be references and not invocations?

Body:
When you have an event handler it must be a function reference, not a function invocation. This is because internally when the handler is executed, the handler is first evaluated before it can be called. With inline JSX expressions such as when passing an event handler prop, the expression is evaluated when the component is declared, before the handler is called.

Thus, if you pass in an invocation such as alert('click'), it will alert as it is being evaluated. When the event is triggered and the handler is called, it will then attempt to call the return value of alert (which is undefined) -- not good. Instead, you need a function reference, which when evaluated gives you a callable function which is then called as the handler.

Take this pseudocode for an example:

function on(event, handler) {
    //some event listener function that runs the handler when event happens
    //then we call handler when the event happens:
    handler();
}

Imagine if we invoked the function as on('click', alert('test')), then alert('test') would be evaluated and the return value would be passed as the handler, which is undefined. Then you would be trying to call undefined(), not good. Thus, you must pass a function reference, a reference to a callable function.