问:
Sending Email using SMTP gmail in CodeIgniter from website
I'm stuck on my problem to send email with codeigniter.

I've already done successful sending gmail, but the problem is the recipient and the sender are the same. I want this email received to me from sender in website,

There is my Controller :

```<code>public function index(){
    $this->sendEmail();
    $this->load->view('content_contact');
}
public function sendEmail(){
    $this->load->helper(array('form', 'url'));
    $this->load->library('email');

    //konfigurasi email
    $config = array();
    $config['charset'] = 'utf-8';
    $config['useragent'] = 'Codeigniter';
    $config['protocol']= "smtp";
    $config['mailtype']= "html";
    $config['smtp_host']= "ssl://smtp.gmail.com";
    $config['smtp_port']= 465;
    $config['smtp_timeout']= "5";
    $config['smtp_user']= "my_email$gmail.com";
    $config['smtp_pass']= "my_pass";
    $config['crlf']="\r\n";
    $config['newline']="\r\n";

    $config['wordwrap'] = TRUE;
    $this->load->view('content_contact');

    $this->email->initialize($config);
    $this->email->from($this->input->post('from'));
    $this->email->to("my_email@gmail.com");
    $this->email->subject($this->input->post('subject'));
    $this->email->message($this->input->post('isi'));

    if($this->email->send()){
        echo "pengiriman email Success";
    }
    else{
        echo "pengiriman email Failed";
    }

}
</code>```

And This is my View : content_contact.php
content_contact.php

答:
use below mentioned solution</p>

```<code>$config = Array(
    'protocol' => 'smtp',
    'smtp_host' => 'ssl://smtp.googlemail.com',
    'smtp_port' => 465,
    'smtp_user' => 'my_email@gmail.com',
    'smtp_pass' => 'yourpassword',
    'mailtype'  => 'html',
    'charset'   => 'utf-8',
    'wordwrap'  => TRUE
);
$this->load->library('email', $config);
</code>```

Body:
I'm stuck on my problem to send email with codeigniter.

I've already done successful sending gmail, but the problem is the recipient and the sender are the same. I want this email received to me from sender in website,

There is my Controller :

public function index(){
    $this->sendEmail();
    $this->load->view('content_contact');
}
public function sendEmail(){
    $this->load->helper(array('form', 'url'));
    $this->load->library('email');

    //konfigurasi email
    $config = array();
    $config['charset'] = 'utf-8';
    $config['useragent'] = 'Codeigniter';
    $config['protocol']= "smtp";
    $config['mailtype']= "html";
    $config['smtp_host']= "ssl://smtp.gmail.com";
    $config['smtp_port']= 465;
    $config['smtp_timeout']= "5";
    $config['smtp_user']= "my_email$gmail.com";
    $config['smtp_pass']= "my_pass";
    $config['crlf']="\r\n";
    $config['newline']="\r\n";

    $config['wordwrap'] = TRUE;
    $this->load->view('content_contact');

    $this->email->initialize($config);
    $this->email->from($this->input->post('from'));
    $this->email->to("my_email@gmail.com");
    $this->email->subject($this->input->post('subject'));
    $this->email->message($this->input->post('isi'));

    if($this->email->send()){
        echo "pengiriman email Success";
    }
    else{
        echo "pengiriman email Failed";
    }

}

And This is my View : content_contact.php
content_contact.php

Body:
use below mentioned solution

$config = Array(
    'protocol' => 'smtp',
    'smtp_host' => 'ssl://smtp.googlemail.com',
    'smtp_port' => 465,
    'smtp_user' => 'my_email@gmail.com',
    'smtp_pass' => 'yourpassword',
    'mailtype'  => 'html',
    'charset'   => 'utf-8',
    'wordwrap'  => TRUE
);
$this->load->library('email', $config);


来源: stackexchange

问:
Laravel Sync Call to undefined method Illuminate\Database\Query\Builder
I try to get several options and several specifications for each of my products.

In order to get several values instead of one I had to make third tables named product_suboptions and product_subspecifications where it gets id of product and id of options + subspecifications

This is my create method:

```<code>$options = Option::all();
$suboptions = Suboption::all();
$specifications = Specification::all();
$subspecifications = Subspecification::all();
return view('admin.products.create', compact('options', 'suboptions', 'specifications', 'subspecifications'));
</code>```

This is my store method:

```<code>public function store(Request $request)
    {
//.........

$product->save();
$product->suboptions()->sync($request->suboptions, false);
$product->subspecifications()->sync($request->subspecifications, false);

return ......//
}
</code>```

This relations in my models:

Product

```<code>public function option(){
     return $this->belongsToMany(Option::class);
  }
  public function suboption(){
     return $this->belongsToMany(Suboption::class);
  }
  public function specification(){
     return $this->belongsToMany(Specification::class);
  }
  public function subspecification(){
     return $this->belongsToMany(Subspecification::class);
  }
</code>```

Option

```<code>public function products(){
     return $this->belongsToMany(Product::class);
  }
</code>```

Suboption

```<code>public function products(){
     return $this->belongsToMany(Product::class);
  }
</code>```

Specification

```<code>public function products(){
     return $this->belongsToMany(Product::class);
  }
</code>```

Subspecification

```<code>public function products(){
     return $this->belongsToMany(Product::class);
  }
</code>```

Now the problem is when i save product it returns this error

BadMethodCallException
  Call to undefined method Illuminate\Database\Query\Builder::suboptions()

and only save my product but nothing in product_suboptions and product_subspecifications tables.

any idea?

答:
SOLVED

The problem was in my form i was trying to get name such as name="suboption_id[]" which i had to get it like name="suboptions[]" now working perfectly.

ContentLicense: CC BY-SA 3.0

Body:
I try to get several options and several specifications for each of my products.

In order to get several values instead of one I had to make third tables named product_suboptions and product_subspecifications where it gets id of product and id of options + subspecifications

This is my create method:

$options = Option::all();
$suboptions = Suboption::all();
$specifications = Specification::all();
$subspecifications = Subspecification::all();
return view('admin.products.create', compact('options', 'suboptions', 'specifications', 'subspecifications'));

This is my store method:

public function store(Request $request)
    {
//.........

$product->save();
$product->suboptions()->sync($request->suboptions, false);
$product->subspecifications()->sync($request->subspecifications, false);

return ......//
}

This relations in my models:

Product

public function option(){
     return $this->belongsToMany(Option::class);
  }
  public function suboption(){
     return $this->belongsToMany(Suboption::class);
  }
  public function specification(){
     return $this->belongsToMany(Specification::class);
  }
  public function subspecification(){
     return $this->belongsToMany(Subspecification::class);
  }

Option

public function products(){
     return $this->belongsToMany(Product::class);
  }

Suboption

public function products(){
     return $this->belongsToMany(Product::class);
  }

Specification

public function products(){
     return $this->belongsToMany(Product::class);
  }

Subspecification

public function products(){
     return $this->belongsToMany(Product::class);
  }

Now the problem is when i save product it returns this error

BadMethodCallException
  Call to undefined method Illuminate\Database\Query\Builder::suboptions()

and only save my product but nothing in product_suboptions and product_subspecifications tables.

any idea?


问:
Pushing a multidimensional array in javascript
Please check down the code below, I want to push an object multiple times into an array and set a specified path. Hope someone can help. TNX!

To keep it simple I just removed all loops and static addressed my array, but still no success and I don't got any idea why:

wrong result:

```<code>let myObject = {
"version": "2.0",
"worker": {
    "todo": []
 }
};
let myObjectArray = new Array();
myObjectArray.push(myObject);
myObjectArray.push(myObject);
myObjectArray[0]["worker"]["todo"] = "test";
console.log(myObjectArray);
</code>```

-> wrong output array

correct result:

```<code>let myObjectArray = [
{
    "version": "2.0",
    "worker": {
        "todo": []
    }
},
{
    "version": "2.0",
    "worker": {
        "todo": []
    }
}
];
myObjectArray[0]["worker"]["todo"] = "test";
console.log(myObjectArray);
</code>```

-> correct output array

答:
You have to use the deep copying here to make sure the 2 objects are treated as separate instance instead of being the references to the same object.

For "deep" copy, use JSON.parse(JSON.stringify(myObject)) so it will look something like:

```<code>myObjectArray.push(JSON.parse(JSON.stringify(myObject)));
</code>```

Body:
Please check down the code below, I want to push an object multiple times into an array and set a specified path. Hope someone can help. TNX!

To keep it simple I just removed all loops and static addressed my array, but still no success and I don't got any idea why:

wrong result:

let myObject = {
"version": "2.0",
"worker": {
    "todo": []
 }
};
let myObjectArray = new Array();
myObjectArray.push(myObject);
myObjectArray.push(myObject);
myObjectArray[0]["worker"]["todo"] = "test";
console.log(myObjectArray);

-> wrong output array

correct result:

let myObjectArray = [
{
    "version": "2.0",
    "worker": {
        "todo": []
    }
},
{
    "version": "2.0",
    "worker": {
        "todo": []
    }
}
];
myObjectArray[0]["worker"]["todo"] = "test";
console.log(myObjectArray);

-> correct output array

Body:
You have to use the deep copying here to make sure the 2 objects are treated as separate instance instead of being the references to the same object.

For "deep" copy, use JSON.parse(JSON.stringify(myObject)) so it will look something like:

myObjectArray.push(JSON.parse(JSON.stringify(myObject)));


问:
Group array by inner value in PHP
I'm quite new in PHP and I'm having problems to even start to solve this issue.

Having this kind of array:

```<code>Array (
   [0] => Array (
          [title] => "Test string"
          [lat] => "40.4211"
          [long] => "-3.70118"
          )
   [1] => Array (
          [title] => "Test string 2"
          [lat] => "10.0"
          [long] => "-23.0"
          )
   [2] => Array (
          [title] => "Test string 3"
          [lat] => "10.0"
          [long] => "-23.0"
          )
   [3] => Array (
          [cust] => "Test string 4"
          [type] => "5.0"
          [level] => "-1.34"
          )
)
</code>```

I would like to create a new inner array for the ones that contains the same lat and long. In the example above the ones of #1 and #2 have the same lat and log (10.0 and -23.0).

```<code>Array (
   [0] => Array (
          [title] => "Test string"
          [lat] => "40.4211"
          [long] => "-3.70118"
          )
   [1] => Array (
            [0] => Array (
                  [title] => "Test string 2"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
            [1] => Array (
                  [title] => "Test string 3"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
          )
   [2] => Array (
          [cust] => "Test string 4"
          [type] => "5.0"
          [level] => "-1.34"
          )
)
</code>```

How can I archieve this? Thanks in advance.

答:
Try this    </p>

```<code>    $result = [];
    foreach ($array as $vlaue) {
        $uniqueKey = $vlaue['lat'] .'_'. $vlaue['long'];
        $result[$uniqueKey][] = $value;
    }

    $result = array_values($result);
</code>```

Title: Group array by inner value in PHP

Body:
I'm quite new in PHP and I'm having problems to even start to solve this issue.

Having this kind of array:

Array (
   [0] => Array (
          [title] => "Test string"
          [lat] => "40.4211"
          [long] => "-3.70118"
          )
   [1] => Array (
          [title] => "Test string 2"
          [lat] => "10.0"
          [long] => "-23.0"
          )
   [2] => Array (
          [title] => "Test string 3"
          [lat] => "10.0"
          [long] => "-23.0"
          )
   [3] => Array (
          [cust] => "Test string 4"
          [type] => "5.0"
          [level] => "-1.34"
          )
)

I would like to create a new inner array for the ones that contains the same lat and long. In the example above the ones of #1 and #2 have the same lat and log (10.0 and -23.0).

Array (
   [0] => Array (
          [title] => "Test string"
          [lat] => "40.4211"
          [long] => "-3.70118"
          )
   [1] => Array (
            [0] => Array (
                  [title] => "Test string 2"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
            [1] => Array (
                  [title] => "Test string 3"
                  [lat] => "10.0"
                  [long] => "-23.0"
                  )
          )
   [2] => Array (
          [cust] => "Test string 4"
          [type] => "5.0"
          [level] => "-1.34"
          )
)

How can I archieve this? Thanks in advance.

Body:
Try this

    $result = [];
    foreach ($array as $vlaue) {
        $uniqueKey = $vlaue['lat'] .'_'. $vlaue['long'];
        $result[$uniqueKey][] = $value;
    }

    $result = array_values($result);


问:
How to Hide Tabbar Top Border color in IOS Xamarin.forms
I have Changed the Tabbar selected text color by using the below code. But I don't know how to hide the tabbar top border color in xamarin.forms ios.</p>

```<code> UITabBar.Appearance.SelectedImageTintColor = UIColor.FromRGB(247, 148, 30);
</code>```

答:
Set this in AppDelegate , it works perfectly on my side.

```<code>UITabBar.Appearance.BackgroundImage = new UIImage();
UITabBar.Appearance.ShadowImage = new UIImage();
</code>```

Body:
I have Changed the Tabbar selected text color by using the below code. But I don't know how to hide the tabbar top border color in xamarin.forms ios.

 UITabBar.Appearance.SelectedImageTintColor = UIColor.FromRGB(247, 148, 30);

Body:
Set this in AppDelegate , it works perfectly on my side.

UITabBar.Appearance.BackgroundImage = new UIImage();
UITabBar.Appearance.ShadowImage = new UIImage();


问:
How we can handle Multiple Type UITableViewCell
I have multiple type cell to show in UITableView.

I have five type of cell in UITableView. all cell show according the different service response data, if service data nil or empty then we will not need to show the cell. so how i can check the number of row and show the cell according the service response.

答:
Swift 3

Let say you have a tableView which has two types of cell. indexPath.row == 0 will show a header cell & rest of cell are info holder cell. For this you need to do the following things

```<code>extension YourControllerName: UITableViewDelegate, UITableViewDataSource {

      func numberOfSections(in tableView: UITableView) -> Int {
         return 1
      }

      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

         return yourDataHolderArray.count
      }

      func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        // Specify the height of cell if the cells height are different
        if indexPath.row == 0 {
            return 30.0
        }
        return 80.0
      }

      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if yourDataHolderArray.count > 0 {

            if indexPath.row == 0 {

                let cell = tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath) as! YourHeaderCell

                return cell
            }
            else {

                let cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath) as! YourInfoCell

                return cell
            }
        }
        return UITableViewCell()
    }
}
</code>```

Hope it helps.

Body:
Swift 3

Let say you have a tableView which has two types of cell. indexPath.row == 0 will show a header cell & rest of cell are info holder cell. For this you need to do the following things

extension YourControllerName: UITableViewDelegate, UITableViewDataSource {

      func numberOfSections(in tableView: UITableView) -> Int {
         return 1
      }

      func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

         return yourDataHolderArray.count
      }

      func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        // Specify the height of cell if the cells height are different
        if indexPath.row == 0 {
            return 30.0
        }
        return 80.0
      }

      func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if yourDataHolderArray.count > 0 {

            if indexPath.row == 0 {

                let cell = tableView.dequeueReusableCell(withIdentifier: "Cell1", for: indexPath) as! YourHeaderCell

                return cell
            }
            else {

                let cell = tableView.dequeueReusableCell(withIdentifier: "Cell2", for: indexPath) as! YourInfoCell

                return cell
            }
        }
        return UITableViewCell()
    }
}

Hope it helps.


问:
How can I find out the current route in Rails?
I need to know the current route in a filter in Rails. How can I find out what it is?

I'm doing REST resources, and see no named routes.

答:
In rails 3 you can access the Rack::Mount::RouteSet object via the Rails.application.routes object, then call recognize on it directly

```<code>route, match, params = Rails.application.routes.set.recognize(controller.request)
</code>```

that gets the first (best) match, the following block form loops over the matching routes:

```<code>Rails.application.routes.set.recognize(controller.request) do |r, m, p|
  ... do something here ...
end
</code>```

once you have the route, you can get the route name via route.name. If you need to get the route name for a particular URL, not the current request path, then you'll need to mock up a fake request object to pass down to rack, check out ActionController::Routing::Routes.recognize_path to see how they're doing it.

Body:
In rails 3 you can access the Rack::Mount::RouteSet object via the Rails.application.routes object, then call recognize on it directly

route, match, params = Rails.application.routes.set.recognize(controller.request)

that gets the first (best) match, the following block form loops over the matching routes:

Rails.application.routes.set.recognize(controller.request) do |r, m, p|
  ... do something here ...
end

once you have the route, you can get the route name via route.name. If you need to get the route name for a particular URL, not the current request path, then you'll need to mock up a fake request object to pass down to rack, check out ActionController::Routing::Routes.recognize_path to see how they're doing it.

ContentLicense: CC BY-SA 2.5


问:
C Programming - How often should realloc be used?
I have a question about dynamic memory allocation.

Context: I'm writing a program that reads a text file of words and counts the frequency with which each word occurs (one word per line).

This particular function reads the file, counts the lines and characters, then dynamically allocates memory to the array of string pointers, an array storing the count of characters for each line and the strings themselves. (The other parts are less directly relevant to my question).

Question: How often should I reallocate memory if I run out of space? I set a constant ("memstart") for setting the initial memory allocation value. In the below code snippet I realloc for every line over the value of "memstart". Would the program process faster if a reallocated a larger block of memory instead of increasing the memory space by 1 "variable type" each time?

What would be best practice for something like this?

Code Snip:

```<code>int read_alloc(FILE* fin, FILE *tmp, char **wdp, int *sz){
    int line_cnt= 0, chr, let=1;
    do{
        chr=getc(fin);
        let++;
        //count characters

        if(chr!=EOF){
            chr=tolower(chr);
            fputc(chr, tmp);
        }
        //convert to lcase and write to temp file

        if ('\n' == chr || chr==EOF){
            sz[(line_cnt)]=((let)*sizeof(char));            //save size needed to store string in array
            *(wdp+(line_cnt))=malloc((let)*sizeof(char));   //allocate space for the string
            if ((line_cnt-1) >= memstart){
                realloc(wdp, (sizeof(wdp)*(memstart+line_cnt)));    //if more space needed increase size
                realloc(sz, (sizeof(sz)*(memstart+line_cnt)));
            }
            line_cnt++;
            let=1;
        }
    } while (EOF != chr);

    return (line_cnt);
}
</code>```

答:
The classic answer is to double each time, but a factor of 1.5 might be better.  The important bit is that you multiply your array size by some factor each time, rather than adding  additional space each time.

Each re-allocation might need to copy the previous array into a new one.  We'd like to minimize these copies.  If we will be adding n items, and we start with an array of size a, increase by a factor of r each re-allocation, to end with a value of n, the sequence of (re-)allocations will be a, ar, ar^2, ar^3, ..., n.  The sum of that sequence is (nr-a)/(r-1).  Thus the total space is of order O(n).

Suppose instead we start with a, and this time add r each time.  The sequence is a, a+r, a+2r, a+3r, ..., n.  The sum of that sequence will be 0.5*((n^2-a^2)/r + a + n).  In this case the total space of order O(n^2).  Much worse!

With a constant factor of 2, the array will be in the worse case 1/2 empty.  That's probably ok.  You can always shrink the allocation when you're done and know the final size.

As pointed out in another answer, there are several bugs in the manner in which you call realloc(), but that wasn't the question.

Body:
I have a question about dynamic memory allocation.

Context: I'm writing a program that reads a text file of words and counts the frequency with which each word occurs (one word per line).

This particular function reads the file, counts the lines and characters, then dynamically allocates memory to the array of string pointers, an array storing the count of characters for each line and the strings themselves. (The other parts are less directly relevant to my question).

Question: How often should I reallocate memory if I run out of space? I set a constant ("memstart") for setting the initial memory allocation value. In the below code snippet I realloc for every line over the value of "memstart". Would the program process faster if a reallocated a larger block of memory instead of increasing the memory space by 1 "variable type" each time?

What would be best practice for something like this?

Code Snip:

int read_alloc(FILE* fin, FILE *tmp, char **wdp, int *sz){
    int line_cnt= 0, chr, let=1;
    do{
        chr=getc(fin);
        let++;
        //count characters

        if(chr!=EOF){
            chr=tolower(chr);
            fputc(chr, tmp);
        }
        //convert to lcase and write to temp file

        if ('\n' == chr || chr==EOF){
            sz[(line_cnt)]=((let)*sizeof(char));            //save size needed to store string in array
            *(wdp+(line_cnt))=malloc((let)*sizeof(char));   //allocate space for the string
            if ((line_cnt-1) >= memstart){
                realloc(wdp, (sizeof(wdp)*(memstart+line_cnt)));    //if more space needed increase size
                realloc(sz, (sizeof(sz)*(memstart+line_cnt)));
            }
            line_cnt++;
            let=1;
        }
    } while (EOF != chr);

    return (line_cnt);
}


问:
How to locally run Heroku app one-off
I am writing an app that runs one-off on Heroku. So my Procfile is empty, I run on Heroku using

```<code>heroku run node index.js
</code>```

For development purposes, I want to run it locally, and it must read the .env file automatically. But

```<code>Heroku local
</code>```

attempts to read Procfile and then do nothing.

How can I run my app locally with heroku cli and make it read .env automatically?

答: use Heroku local:run node index.js

Title: How to locally run Heroku app one-off

Body:
I am writing an app that runs one-off on Heroku. So my Procfile is empty, I run on Heroku using

heroku run node index.js

For development purposes, I want to run it locally, and it must read the .env file automatically. But

Heroku local

attempts to read Procfile and then do nothing.

How can I run my app locally with heroku cli and make it read .env automatically?

Body: use Heroku local:run node index.js


问:
How to define a method called send in a Rails controller?
I am trying to define a method send in my controller:

```<code>class InvoicesController < ApplicationController

  def send
  end

end
</code>```

However, I am getting an error wrong number of arguments (2 for 0) when I do this.

So I assume that send is a reserved word in Rails?

What could be a possible workaround for defining a send method in my controller anyway.

Thanks for any ideas.

答: I would consider calling it post or deliver instead

Body:
I am trying to define a method send in my controller:

class InvoicesController < ApplicationController

  def send
  end

end

However, I am getting an error wrong number of arguments (2 for 0) when I do this.

So I assume that send is a reserved word in Rails?

What could be a possible workaround for defining a send method in my controller anyway.

Thanks for any ideas.


问:
Status of DoFn inside ParDo
Do we have anything which can provide the completion status of DoFn like when the function has finished it's execution?

Can we generate any trigger or anything which can give a fair idea about successful completion of all the steps written inside DoFn function?

Any help will be appreciated.

答:
Within a ParDo you will always know when the function has finished, so assuming you want to know when the entire PCollection has been processed - you can create a new Pcollection after applying the ParDo and then apply subsequent transformation on the new PCollection. E.g. </p>

```<code>PCollection<T> step = ...;
PCollection<T> afterStep = step.apply(ParDo.of( new DoFn<...>(){...}));
afterStep.apply(ParDo.of(new DoFn<...>(){...}));
</code>```

Title: Status of DoFn inside ParDo

Body:
Within a ParDo you will always know when the function has finished, so assuming you want to know when the entire PCollection has been processed - you can create a new Pcollection after applying the ParDo and then apply subsequent transformation on the new PCollection. E.g.

PCollection<T> step = ...;
PCollection<T> afterStep = step.apply(ParDo.of( new DoFn<...>(){...}));
afterStep.apply(ParDo.of(new DoFn<...>(){...}));


问:
Global variable at top of the JavaScript file
Say I declare a global JavaScript variable at the top of a JavaScript file to equal 0

i.e.

```<code>var jVar=0;
</code>```

Then I call a function in the JavaScript to set that variable to 1
ie.

```<code>function setVarToOne(){
    jVar=1;
}
</code>```

If I then reload the page what will the variable equal before the setVarToOne function is called ?

Will the jVar keep the value it was set to in the function or will it be re-initialised to 0?

What I need to understand is, what happens to JavaScript variables when the page is reloaded?

Thanks

答:
Global variables are variables which will be stored throughout the Session.
When you want to store something beyond the session use PHP.
You need PHP for the global variable to be stored.
Copy your code and put it in a php file.
In this file write this,

```<code><?php
session_start();
$_SESSION['JVar'] = 0;
function setVarToOne(){
    $_SESSION['jVar'] = 1;
}
</code>```

the variable will be stored in session all you have to do is pass that value to js by

```<code>echo "<script>var JVar = $_SESSION['jVar']</script>";
?>
</code>```

Body:
Say I declare a global JavaScript variable at the top of a JavaScript file to equal 0

i.e.

var jVar=0;

Then I call a function in the JavaScript to set that variable to 1
ie.

function setVarToOne(){
    jVar=1;
}

If I then reload the page what will the variable equal before the setVarToOne function is called ?

Will the jVar keep the value it was set to in the function or will it be re-initialised to 0?

What I need to understand is, what happens to JavaScript variables when the page is reloaded?

Thanks

Body:
Global variables are variables which will be stored throughout the Session.
When you want to store something beyond the session use PHP.
You need PHP for the global variable to be stored.
Copy your code and put it in a php file.
In this file write this,

<?php
session_start();
$_SESSION['JVar'] = 0;
function setVarToOne(){
    $_SESSION['jVar'] = 1;
}

the variable will be stored in session all you have to do is pass that value to js by

echo "<script>var JVar = $_SESSION['jVar']</script>";
?>


问:
Angular Material 2 Autocomplete, mat-option element doesn't trigger keyup event
I am looking for a way to figure out when an mat-option inside the mat-autocomplete was either clicked or was selected using the enter key.

The click event binding works as expected but the keyup.enter or even just the keyup event doesn't work.

Is this a bug in the library or I am doing something wrong?

```<code><mat-option (click)="onEnter()" (keyup.enter)="onEnter()" *ngFor="let state of filteredStates | async" [value]="state.name">
</code>```

Here's a live example - https://angular-3okq5u.stackblitz.io

Update: Please mention if there's a better way to handle the selection of an option at the <mat-option> element level.

答:
Use onSelectionChange event in options if you want to trigger a function on option change. it will also trigger if you use keyboard to select the auto-complete option which you are trying to achieve here.

```<code><input (keyup.enter)="onEnter($event)" matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
    <mat-autocomplete  #auto="matAutocomplete">
      <mat-option  (onSelectionChange)="onEnter($event)" (click)="onEnter()"  *ngFor="let state of filteredStates | async" [value]="state.name">
        <img style="vertical-align:middle;" aria-hidden src="{{state.flag}}" height="25" />
        <span>{{ state.name }}</span> |
        <small>Population: {{state.population}}</small>
      </mat-option>
    </mat-autocomplete>
</code>```

Update

onSelectionChange event is triggering twice whenever you change the option and it's because of the existing issue in Angular material. Work around for the issue is also given that you should check the event before doing anything inside the function.

```<code> onEnter(evt: any){
    if (evt.source.selected) {
    alert("hello ");
    }
  }
</code>```

Working demo

Body:
I am looking for a way to figure out when an mat-option inside the mat-autocomplete was either clicked or was selected using the enter key.

The click event binding works as expected but the keyup.enter or even just the keyup event doesn't work.

Is this a bug in the library or I am doing something wrong?

<mat-option (click)="onEnter()" (keyup.enter)="onEnter()" *ngFor="let state of filteredStates | async" [value]="state.name">

Here's a live example - https://angular-3okq5u.stackblitz.io

Update: Please mention if there's a better way to handle the selection of an option at the <mat-option> element level.

Body:
Use onSelectionChange event in options if you want to trigger a function on option change. it will also trigger if you use keyboard to select the auto-complete option which you are trying to achieve here.

<input (keyup.enter)="onEnter($event)" matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
    <mat-autocomplete  #auto="matAutocomplete">
      <mat-option  (onSelectionChange)="onEnter($event)" (click)="onEnter()"  *ngFor="let state of filteredStates | async" [value]="state.name">
        <img style="vertical-align:middle;" aria-hidden src="{{state.flag}}" height="25" />
        <span>{{ state.name }}</span> |
        <small>Population: {{state.population}}</small>
      </mat-option>
    </mat-autocomplete>

Update

onSelectionChange event is triggering twice whenever you change the option and it's because of the existing issue in Angular material. Work around for the issue is also given that you should check the event before doing anything inside the function.

 onEnter(evt: any){
    if (evt.source.selected) {
    alert("hello ");
    }
  }

Working demo


问:
How can I combine stdlib logging with py.test
I am using py.test to test some modules of mine that contains quite a bit of stdlib logging. I would of course like for the logging to log to stdout, which is captured by py.test, so that I will get all relevant logging messages if a test fails.

The problem with this is that the logging module ends up trying to log messages to the 'stdout'-object provided by py.test after this object has been discarded by py.test. That is, I get:

```<code>Traceback (most recent call last):
  File "/usr/lib/python2.6/atexit.py", line 24, in _run_exitfuncs
    func(*targs, **kargs)
  File "/usr/lib/python2.6/logging/__init__.py", line 1508, in shutdown
    h.flush()
  File "/usr/lib/python2.6/logging/__init__.py", line 754, in flush
    self.stream.flush()
ValueError: I/O operation on closed file
</code>```

If I turn off capturing with -s, I don't have any problems, but of course that makes the test output unreadable with irrelevant logging.

Can anyone tell me the proper way to integrate stdlib logging with py.test?

(I tried looking at this, where it looks like it should just work without issues, so it didn't help me much)

答:
If you don't mind the logging going nowhere after the objects have been discarded by py.test you could set the module-level variable logging.raiseExceptions to False somewhere early in your modules or tests.

This will make the logging module swallow exceptions that occur in the logging subsystem. (Also a good practice for production systems where you don't want errors in logging crash your system)

You could also use logging.basicConfig() to set logging output to a separate file. But this is probably not what you want.

Body:
I am using py.test to test some modules of mine that contains quite a bit of stdlib logging. I would of course like for the logging to log to stdout, which is captured by py.test, so that I will get all relevant logging messages if a test fails.

The problem with this is that the logging module ends up trying to log messages to the 'stdout'-object provided by py.test after this object has been discarded by py.test. That is, I get:

Traceback (most recent call last):
  File "/usr/lib/python2.6/atexit.py", line 24, in _run_exitfuncs
    func(*targs, **kargs)
  File "/usr/lib/python2.6/logging/__init__.py", line 1508, in shutdown
    h.flush()
  File "/usr/lib/python2.6/logging/__init__.py", line 754, in flush
    self.stream.flush()
ValueError: I/O operation on closed file

If I turn off capturing with -s, I don't have any problems, but of course that makes the test output unreadable with irrelevant logging.

Can anyone tell me the proper way to integrate stdlib logging with py.test?

(I tried looking at this, where it looks like it should just work without issues, so it didn't help me much)


问:
unable to access DB pod External IP from application
I've created two pods top of Azure Kubernetes cluster
1) Application
2) MS SQL server

both pods are exposed via Azure Loadbalancer and both having External IPs. I am unable to use the External IP in my application config file. But I can connect that SQL Server from anywhere. For some reason I am unable to telnet DB IP from Application container.

the connection is getting timeout. but I can ping/telnet the DB's cluster ip. So I have tried to use the DB cluster IP in my config file to check if the connection is successful but no luck.

Could someone help me with this ?

答:
As Suresh said, we should not use public IP address to connect them.

We can refer to this article to create a application and a database, then connect a front end to a back end using a service.


问:
How can I get a div to stick to the bottom of the screen and have the middle content scroll?
I'm trying to have a sticky footer, where the footer is ALWAYS visible and docked to the bottom, while the middle content will scroll as content is added to it.  I am using this method of accomplishing that:

/* Reset */

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

/* Essentials */

.container {
  display: table;
}

.content {
  display: table-row;
  height: 100%;
}

.content-body {
  display: table-cell;
}

.scroller {
  max-height: 100%;
  overflow-y: auto;
}

/* Aestetics */

.container {
  width: 100%;
  height: 100%;
}

.header,
.footer {
  padding: 10px 20px;
  background: #f7f7f7;
}

.scroller {
  padding: 20px;
  background: #e7e7e7;
}

p {
  margin-top: 0;
  margin-bottom: 1rem;
}

p:last-child {
  margin-bottom: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <header class="header">
    <p>This is the header</p>
  </header>
  <section class="content">
    <div class="content-body">
      <div class="scroller">
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
      </div>
    </div>
  </section>
  <footer class="footer">
    <p>This is the footer.</p>
  </footer>
</div></code>```

This works great for Chrome and FF but does not work in IE.  Is there a simple fix for this in IE or does someone know of a better solution?

答:
You can simply consider fixed position like this :

/* Reset */

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

/* Essentials */

.content {
  height: 100%;
}

.scroller {
  max-height: 100%;
  overflow-y: auto;
}

/* Aestetics */

.container {
  width: 100%;
  height: 100%;
}

.header,
.footer {
  position:fixed;
  right:0;
  left:0;
  padding:20px;
  background:#fff;

}

.footer {
 bottom:0;
}
.header {
 top:0;
}

.scroller {
  padding: 20px;
  background: #e7e7e7;
  margin:40px auto;
}

p {
  margin-top: 0;
  margin-bottom: 1rem;
}

p:last-child {
  margin-bottom: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <header class="header">
    <p>This is the header</p>
  </header>
  <section class="content">
    <div class="content-body">
      <div class="scroller">
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
      </div>
    </div>
  </section>
  <footer class="footer">
    <p>This is the footer.</p>
  </footer>
</div></code>```

Body:
I'm trying to have a sticky footer, where the footer is ALWAYS visible and docked to the bottom, while the middle content will scroll as content is added to it.  I am using this method of accomplishing that:

/* Reset */

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

/* Essentials */

.container {
  display: table;
}

.content {
  display: table-row;
  height: 100%;
}

.content-body {
  display: table-cell;
}

.scroller {
  max-height: 100%;
  overflow-y: auto;
}

/* Aestetics */

.container {
  width: 100%;
  height: 100%;
}

.header,
.footer {
  padding: 10px 20px;
  background: #f7f7f7;
}

.scroller {
  padding: 20px;
  background: #e7e7e7;
}

p {
  margin-top: 0;
  margin-bottom: 1rem;
}

p:last-child {
  margin-bottom: 0;
}

This is the header

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the footer.

This works great for Chrome and FF but does not work in IE.  Is there a simple fix for this in IE or does someone know of a better solution?

Body:
You can simply consider fixed position like this :

/* Reset */

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

/* Essentials */

.content {
  height: 100%;
}

.scroller {
  max-height: 100%;
  overflow-y: auto;
}

/* Aestetics */

.container {
  width: 100%;
  height: 100%;
}

.header,
.footer {
  position:fixed;
  right:0;
  left:0;
  padding:20px;
  background:#fff;

}

.footer {
 bottom:0;
}
.header {
 top:0;
}

.scroller {
  padding: 20px;
  background: #e7e7e7;
  margin:40px auto;
}

p {
  margin-top: 0;
  margin-bottom: 1rem;
}

p:last-child {
  margin-bottom: 0;
}

<div class="container">
  <header class="header">
    <p>This is the header</p>
  </header>
  <section class="content">
    <div class="content-body">
      <div class="scroller">
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
        <p>This is the content.</p>
      </div>
    </div>
  </section>
  <footer class="footer">
    <p>This is the footer.</p>
  </footer>
</div>


问:
How to fix shadow on scaled FloatingActionButton using support library 23
I have a FAB on a KitKat device using support library 23. I'm scaling the button for a transition effect (by containing it in a resizing view). This basically works apart from the shadow, which appears in a weird form (see the scaled red button in the screenshot, the blue button is full size).

What actually appears to happen is that the shadow is in 4 "corner" bitmaps that overlap to produce an odd effect.

Does anyone know how this can be fixed?

答:
Use scale properties to resize your floating button. And shadow will be fine</p>

```<code><android.support.design.widget.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="center"
    android:scaleX="0.75"
    android:scaleY="0.75"/>
</code>```

Body:
Use scale properties to resize your floating button. And shadow will be fine

<android.support.design.widget.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="center"
    android:scaleX="0.75"
    android:scaleY="0.75"/>


问:
Picker Error Message on Exit (encountered while discovering extensions: Error Domain=PlugInKit Code=13) With Swift 4 - Xcode 9
Similar to

PhotoPicker discovery error: Error Domain=PlugInKit Code=13

and also to

https://forums.developer.apple.com/thread/82105

BUT I have tried all of these suggestions and still get an error in the debug log. Running Swift 4 XCode 9A235

What was suggest at the various places was ...

some people said add @objc

some people said add internal

some people suggested adding _ and making sure using Any and not
AnyObject

some people said to use didFinishPickingImageWithInfo (this returns
no image for me)

some people said dismsss the picker, others said dismiss self, others
said dismiss both

some said add the 'Privacy... ' to plist (done)

added import Photos

added prior call to force PHPhotoLibrary.requestAuthorization() {
(status) -> Void in ...

I DID NOT get this issues in Swift 3 - previous xcode.
But with Swift 4, I tried everying I saw suggested and I still get the following error

[discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}

The picker works fine and I DO end up selecting an image from photos, but I get this error message on picker exit (cancel or select), every time...

Any suggestions how to stop the error message? Other than the list of things offered at the other two links (summarized above)

my method

```<code>@objc internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    imageSelected = nil

    if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
        imageSelected = editedImage
    } else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
        imageSelected = originalImage
    }

    if  imageSelected != nil {
        handleSelectedImage()   // override in subclass to do something with the returned image
    }
    picker.dismiss(animated: true, completion: nil)   // mess of calling both dismiss to see if it helps - it does not
    dismiss(animated: true, completion: nil)
}
</code>```

答:
I had the same issue and tried every solution I could find, but nothing helped. Just asked myself what could happen to the delegate to not being triggered: deallocation of the delegate!

And that was it in my case! When presenting the UIImagePickerController my instance of class ImagePickerController : NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate
which isn't the presenting view controller, will be deallocated directly. Of course the delegate functions can't be executed anymore.

Just put a breakpoint in deinit (or dealloc in Objective-C world) and see if your delegate is being deallocated.

Body:
Similar to

PhotoPicker discovery error: Error Domain=PlugInKit Code=13

and also to

https://forums.developer.apple.com/thread/82105

BUT I have tried all of these suggestions and still get an error in the debug log. Running Swift 4 XCode 9A235

What was suggest at the various places was ...

some people said add @objc

some people said add internal

some people suggested adding _ and making sure using Any and not
AnyObject

some people said to use didFinishPickingImageWithInfo (this returns
no image for me)

some people said dismsss the picker, others said dismiss self, others
said dismiss both

some said add the 'Privacy... ' to plist (done)

added import Photos

added prior call to force PHPhotoLibrary.requestAuthorization() {
(status) -> Void in ...

I DID NOT get this issues in Swift 3 - previous xcode.
But with Swift 4, I tried everying I saw suggested and I still get the following error

[discovery] errors encountered while discovering extensions: Error Domain=PlugInKit Code=13 "query cancelled" UserInfo={NSLocalizedDescription=query cancelled}

The picker works fine and I DO end up selecting an image from photos, but I get this error message on picker exit (cancel or select), every time...

Any suggestions how to stop the error message? Other than the list of things offered at the other two links (summarized above)

my method

@objc internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    imageSelected = nil

    if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
        imageSelected = editedImage
    } else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
        imageSelected = originalImage
    }

    if  imageSelected != nil {
        handleSelectedImage()   // override in subclass to do something with the returned image
    }
    picker.dismiss(animated: true, completion: nil)   // mess of calling both dismiss to see if it helps - it does not
    dismiss(animated: true, completion: nil)
}


问:
How does variable substitution to extract the current folder's name work in Bash?
I've used the script below to grab the name of the current folder in bash:

```<code>${PWD##*/}
</code>```

This is a trick I saw in this question. However, I don't actually understand what the syntax ##*/ means (except that */ probably means 'any characters up to a slash').

Can anyone explain it? And apologies in advance if this is a dumb question!

答:
From GNU bash manual https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html

${parameter#word}
  ${parameter##word}

The word is expanded to produce a pattern just as in filename expansion (see Filename Expansion). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.

Simple explantion

Assume, parameter, PWD = /home/abc/pqr

Word is the pattern that matches */. Which means /home/abc/. Since pqr
doesnot have a trailing /,  pqr doesnot match that pattern.

From GNU bash manual,

the longest matching pattern (the ‘##’ case) deleted

## means delete the longest matching pattern from parameter. Which means remove /home/abc/ from /home/abc/pqr.

Which gives you pqr

PS: There are no dumb questions

Body:
I've used the script below to grab the name of the current folder in bash:

${PWD##*/}

This is a trick I saw in this question. However, I don't actually understand what the syntax ##*/ means (except that */ probably means 'any characters up to a slash').

Can anyone explain it? And apologies in advance if this is a dumb question!


问:
no module cv on jupyter
I am working on Jupyter Notebook on my windows. I am trying to import module cv and cv2.

import cv
produces this error.

ImportModuleError: No module cv

Similarly for
import cv2
it produces the error :

ImportModuleError: No module cv

Please help me solve this issue.

答:
To install the opencv-python package without the optional contrib modules into python3:

```<code>pip3 install opencv-python --user
</code>```

To install the opencv-python package with the optional contrib modules into python3:

```<code>pip3 install opencv-contrib-python --user
</code>```

Then to import the module:

```<code>import cv2
</code>```

For both of these installations, their pypi sites state: 'This version does not support video related functionality for MacOS and Linux'.

The Pyimagesearch website by Adrian Rosebrock has a tutorial on how to download and compile opencv for Ubuntu with this functionality.

Title: no module cv on jupyter

Body:
To install the opencv-python package without the optional contrib modules into python3:

pip3 install opencv-python --user

To install the opencv-python package with the optional contrib modules into python3:

pip3 install opencv-contrib-python --user

Then to import the module:

import cv2

For both of these installations, their pypi sites state: 'This version does not support video related functionality for MacOS and Linux'.

The Pyimagesearch website by Adrian Rosebrock has a tutorial on how to download and compile opencv for Ubuntu with this functionality.


问:
.htaccess redirect subfolder to HTTPS
I'm trying to write a RewriteRule for my .htaccess file. Specifically, whenever a user accesses a specific subdirectory, I would like it to Rewrite to force an HTTPS connection.

For example, whenever someone accesses: http://www.mydomain.com/subdirectory (and any other sub-directories of that "subdirectory").

I'd like it to rewrite to https://www.mydomain.com/subdirectory

I've tried the following, but it appears to create a loop:

```<code>RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.mydomain.com/subdirectory/$1 [R=301,L]
</code>```

Also, this .htaccess file is placed in the root of my domain.

Any ideas on how to modify my RewriteRule?

Many Thanks!

答:
I would put this into the domain's root directory:</p>

```<code>RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(subdirectory/.*)$ https://www.mydomain.com/$1 [R=301,L]
</code>```

Title: .htaccess redirect subfolder to HTTPS

Body:
I'm trying to write a RewriteRule for my .htaccess file. Specifically, whenever a user accesses a specific subdirectory, I would like it to Rewrite to force an HTTPS connection.

For example, whenever someone accesses: http://www.mydomain.com/subdirectory (and any other sub-directories of that "subdirectory").

I'd like it to rewrite to https://www.mydomain.com/subdirectory

I've tried the following, but it appears to create a loop:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.mydomain.com/subdirectory/$1 [R=301,L]

Also, this .htaccess file is placed in the root of my domain.

Any ideas on how to modify my RewriteRule?

Many Thanks!

Body:
I would put this into the domain's root directory:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(subdirectory/.*)$ https://www.mydomain.com/$1 [R=301,L]


问:
Bootstrap Progress Bar CSS Issuse
I am facing some difficulties with CSS, as i would like to do following things:

Remove spacing between each progress

Remove the thickness of the progress bar

Over all, something like this effects only progress bar thickness and space

between each progress bar

https://i.stack.imgur.com/Z3Y0P.jpg

Using the code below:

jQuery(document).ready(function ($) {

    $('.skillbar').each(function () {
        $(this).find('.skillbar-bar').animate({
            width: $(this).attr('data-percent')
        }, 1500);
    });

    $(".skillbar-title em").html(function(index, old) {
        return old.replace(/(\b\w+)$/, '$1');
    });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.skillbar  {
 position:  relative;
 display:  block;
 margin-top: 50px;
 margin-bottom:  20px;
 width:  100%;
 background:  #ddd;
 height:  42px;
 border-radius:  2px;
 -moz-border-radius:  2px;
 -webkit-border-radius:  2px;
 -webkit-transition:  0.4s linear;
 -moz-transition:  0.4s linear;
 -ms-transition:  0.4s linear;
 -o-transition:  0.4s linear;
 transition:  0.4s linear;
 -webkit-transition-property:  width,  background-color;
 -moz-transition-property:  width,  background-color;
 -ms-transition-property:  width,  background-color;
 -o-transition-property:  width,  background-color;
 transition-property:  width,  background-color;
 }

.skillbar-title  {
 position:  absolute;
 top:  0;
 left:  0;
 font-weight:  bold;
 font-size:  13px;
 color:  #333;
 background:  #6adcfa;
 -webkit-border-top-left-radius:  2px;
 -webkit-border-bottom-left-radius:  2px;
 -moz-border-radius-topleft:  2px;
 -moz-border-radius-bottomleft:  2px;
 border-top-left-radius:  2px;
 border-bottom-left-radius:  2px;
 }

.skillbar-title em  {
 font-size: 14px;
 font-style: italic;
 font-weight: normal;
 color: #999;
 text-transform: lowercase;
 position: relative;
 margin-top: -35px;
 display:  block;
 height:  15px;
 line-height:  25px;
 -webkit-border-top-left-radius:  2px;
 -webkit-border-bottom-left-radius:  2px;
 -moz-border-radius-topleft:  2px;
 -moz-border-radius-bottomleft:  2px;
 border-top-left-radius:  2px;
 border-bottom-left-radius:  2px;
 }

.skillbar-bar  {
 height:  42px;
 width:  0px;
 -webkit-border-top-left-radius:  2px;
 -webkit-border-bottom-left-radius:  2px;
 -moz-border-radius-topleft:  2px;
 -moz-border-radius-bottomleft:  2px;
 border-top-left-radius:  2px;
 border-bottom-left-radius:  2px;
 }

.skillbar-percent  {
 position:  absolute;
 right:  10px;
 top:  0;
 font-size:  12px;
 height:  42px;
 line-height:  42px;
 color:  #444;
 color:  rgba(0, 0, 0, 0.4);
 }

.no-percent .skillbar-percent  {
 display: none;
}

.skillbar-title em span {
 color: #333;
 font-style: normal;
 text-transform: uppercase;
 letter-spacing: 1px;
 margin-left: 3px;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

HTML

50%

CSS

60%

PHP

80%

JQUERY

90%

```

答:
you have to remove height and line-height from .skillbar-percent and .skillbar.
 Also needs to remove line breaks(
).
Reduce height of the .skillbar-bar

Title: Bootstrap Progress Bar CSS Issuse

Body:
I am facing some difficulties with CSS, as i would like to do following things:

Remove spacing between each progress

Remove the thickness of the progress bar

Over all, something like this effects only progress bar thickness and space

between each progress bar

https://i.stack.imgur.com/Z3Y0P.jpg

Using the code below:

jQuery(document).ready(function ($) {

    $('.skillbar').each(function () {
        $(this).find('.skillbar-bar').animate({
            width: $(this).attr('data-percent')
        }, 1500);
    });

    $(".skillbar-title em").html(function(index, old) {
        return old.replace(/(\b\w+)$/, '$1');
    });

});

.skillbar  {
 position:  relative;
 display:  block;
 margin-top: 50px;
 margin-bottom:  20px;
 width:  100%;
 background:  #ddd;
 height:  42px;
 border-radius:  2px;
 -moz-border-radius:  2px;
 -webkit-border-radius:  2px;
 -webkit-transition:  0.4s linear;
 -moz-transition:  0.4s linear;
 -ms-transition:  0.4s linear;
 -o-transition:  0.4s linear;
 transition:  0.4s linear;
 -webkit-transition-property:  width,  background-color;
 -moz-transition-property:  width,  background-color;
 -ms-transition-property:  width,  background-color;
 -o-transition-property:  width,  background-color;
 transition-property:  width,  background-color;
 }

.skillbar-title  {
 position:  absolute;
 top:  0;
 left:  0;
 font-weight:  bold;
 font-size:  13px;
 color:  #333;
 background:  #6adcfa;
 -webkit-border-top-left-radius:  2px;
 -webkit-border-bottom-left-radius:  2px;
 -moz-border-radius-topleft:  2px;
 -moz-border-radius-bottomleft:  2px;
 border-top-left-radius:  2px;
 border-bottom-left-radius:  2px;
 }

.skillbar-title em  {
 font-size: 14px;
 font-style: italic;
 font-weight: normal;
 color: #999;
 text-transform: lowercase;
 position: relative;
 margin-top: -35px;
 display:  block;
 height:  15px;
 line-height:  25px;
 -webkit-border-top-left-radius:  2px;
 -webkit-border-bottom-left-radius:  2px;
 -moz-border-radius-topleft:  2px;
 -moz-border-radius-bottomleft:  2px;
 border-top-left-radius:  2px;
 border-bottom-left-radius:  2px;
 }

.skillbar-bar  {
 height:  42px;
 width:  0px;
 -webkit-border-top-left-radius:  2px;
 -webkit-border-bottom-left-radius:  2px;
 -moz-border-radius-topleft:  2px;
 -moz-border-radius-bottomleft:  2px;
 border-top-left-radius:  2px;
 border-bottom-left-radius:  2px;
 }

.skillbar-percent  {
 position:  absolute;
 right:  10px;
 top:  0;
 font-size:  12px;
 height:  42px;
 line-height:  42px;
 color:  #444;
 color:  rgba(0, 0, 0, 0.4);
 }

.no-percent .skillbar-percent  {
 display: none;
}

.skillbar-title em span {
 color: #333;
 font-style: normal;
 text-transform: uppercase;
 letter-spacing: 1px;
 margin-left: 3px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

HTML

50%

CSS

60%

PHP

80%

JQUERY

90%

Body:
you have to remove height and line-height from .skillbar-percent and .skillbar.
 Also needs to remove line breaks(<br>).
Reduce height of the .skillbar-bar


问:
Display PNG image file with AR.js (Augmented Reality)
I just want to display a PNG file with AR.js (Augmented Reality) on my web browser with a Hiro marker !! But the result is a black box and I don't understand the problem.

Thank you for you help
Benoit

```<code><!DOCTYPE html>
<html>
<!-- include A-Frame obviously -->
<script src="https://aframe.io/releases/0.6.0/aframe.min.js"></script>
<!-- include ar.js for A-Frame -->
<script src="https://jeromeetienne.github.io/AR.js/aframe/build/aframe-ar.js"></script>
<body style='margin : 0px; overflow: hidden;'>
<a-scene embedded arjs>
    <a-assets>
        <img id="transpImage" src="http://www.icone-png.com/png/13/13081.png">
    </a-assets>
    <a-image width="1" height="1" src="#transpImage"></a-image>
    <a-marker-camera preset='hiro'></a-marker-camera>
</a-scene>
</body>
</html>
</code>```

答:
TLDR - three.js/aframe won't let You load an image from an insecure host.

If the image is not on Your server, You probably get a CORS error, which means Your website isn't able to get a response (or gets rejected) trying to obtain the image using XHR. You can read more on this in the a-frame FAQ, and in the asset management subpage.

Make sure, the image is on Your server, or find an image on a secure website (It's a big simplification but most https://* work for me).

A-frame recommends using github as a deployment platform, you could also use glitch.me

Here is my fiddle, where You can see it's not related to AR.js.

Check out the console, You should see:

```<code>Loading mixed (insecure) display content “http://www.icone-png.com/png/13/13081.png” on a secure page[Learn More]
three.js:30486:3 components:texture:error `$s` could not be fetched (Error code: undefined; Response: undefined)
</code>```

confirming all above about the CORS error.

Body:
I just want to display a PNG file with AR.js (Augmented Reality) on my web browser with a Hiro marker !! But the result is a black box and I don't understand the problem.

Thank you for you help
Benoit

<!DOCTYPE html>

Body:
TLDR - three.js/aframe won't let You load an image from an insecure host.

If the image is not on Your server, You probably get a CORS error, which means Your website isn't able to get a response (or gets rejected) trying to obtain the image using XHR. You can read more on this in the a-frame FAQ, and in the asset management subpage.

Make sure, the image is on Your server, or find an image on a secure website (It's a big simplification but most https://* work for me).

A-frame recommends using github as a deployment platform, you could also use glitch.me

Here is my fiddle, where You can see it's not related to AR.js.

Check out the console, You should see:

Loading mixed (insecure) display content “http://www.icone-png.com/png/13/13081.png” on a secure page[Learn More]
three.js:30486:3 components:texture:error `$s` could not be fetched (Error code: undefined; Response: undefined)

confirming all above about the CORS error.

ContentLicense: CC BY-SA 4.0


问:
How to find out which folder Tomcat is installed by brew on MacOS?
I am learning JSP programing which requires Tomcat. I followed some tutorials but failed to install successfully(Probably some step is not clear match to my situation)

Then I found out you can install easily by this command line:

```<code>brew install tomcat
</code>```

It looks install is successful,

My challenge is after install, I don't know where it is on my hard drive. Therefore, can't configure it in IntelliJ.

My question is:

How do I find out where Tomcat is installed by brew on MacOS?

Thanks!

答:
Although the answer of cbst is working. I think it is better to choose the dynamic path to tomcat which is located in

```<code>/usr/local/opt/tomcat
</code>```

The configuration that I would suggest is the following two Tomcat application servers:

Configuration

Application Server 01

```<code>Name: Tomcat latest
Tomcat Home: /usr/local/opt/tomcat/libexec
</code>```

Application Server 02

```<code>Name: Tomcat X.Y
Tomcat Home: /usr/local/opt/tomcat@X.Y/libexec
</code>```

Advantage

When you upgrade tomcat using

```<code>brew upgrade
</code>```

Your tomcat servers are likely to keep working. If the latest version is a major release your specific version Tomcat X.Y will not work anymore, which is good as you have confidence you are running a correct tomcat version. To keep working with a specific tomcat version use

```<code>brew install tomcat@X
</code>```

Body:
I am learning JSP programing which requires Tomcat. I followed some tutorials but failed to install successfully(Probably some step is not clear match to my situation)

Then I found out you can install easily by this command line:

brew install tomcat

It looks install is successful,

My challenge is after install, I don't know where it is on my hard drive. Therefore, can't configure it in IntelliJ.

My question is:

How do I find out where Tomcat is installed by brew on MacOS?

Thanks!

Body:
Although the answer of cbst is working. I think it is better to choose the dynamic path to tomcat which is located in

/usr/local/opt/tomcat

The configuration that I would suggest is the following two Tomcat application servers:

Configuration

Application Server 01

Name: Tomcat latest
Tomcat Home: /usr/local/opt/tomcat/libexec

Application Server 02

Name: Tomcat X.Y
Tomcat Home: /usr/local/opt/tomcat@X.Y/libexec

Advantage

When you upgrade tomcat using

brew upgrade

Your tomcat servers are likely to keep working. If the latest version is a major release your specific version Tomcat X.Y will not work anymore, which is good as you have confidence you are running a correct tomcat version. To keep working with a specific tomcat version use

brew install tomcat@X


问:
How to update ListView without freezing the program
So I have a list of strings (ISBNs), and I need to fill a listview with the objects (Book objects) associated with these strings. The problem is that the function I have to get the Book object using the string takes time, and so to get, say 30 books, the wait approaches 4 or 5 seconds.

One approach I've thought of is to get the Book objects one at a time, and to add them to the list as I get them. But this process will freeze the UI until it's done adding them all. If I try to put this process in a new thread, it won't let me add to the any UI objects (since it's from another thread). If I try to put it in an AsyncTask, I can't access the ListView since it's in the MainActivity class.

There must be a way to dynamically update a UI element, I'm sure I've seen it done. Any suggestions?

EDIT:

This is the code I'm using to actually add items to the list:

```<code>//List view and adapter setup
listView = (ListView) findViewById(R.id.listViewCheckout);
bookAdapter = new SearchBookAdapter(getApplicationContext(), R.layout.search_row_layout);
listView.setAdapter(bookAdapter);

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

    //Get the book
    Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

    //Assign data to the adapter variables
    Bitmap cover = book.getCover();
    String title = book.getTitle();
    String author = book.getAuthor();

    //Add data to the adapter and set the list
    SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
    bookAdapter.add(dataProvider);
    bookAdapter.notifyDataSetChanged();
}
</code>```

答:
Can you make some changes to your code like this it simple it think it will work</p>

```<code>//List view and adapter setup
listView = (ListView) findViewById(R.id.listViewCheckout);
bookAdapter = new SearchBookAdapter(getApplicationContext(), R.layout.search_row_layout);
SearchBookDataProvider dataProvider;
listView.setAdapter(bookAdapter);

 new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] objects) {
                for(int i = 0; i < searches.size(); i++) {

                //Get the book
                Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

                //Assign data to the adapter variables
                Bitmap cover = book.getCover();
                String title = book.getTitle();
                String author = book.getAuthor();

                //Add data to the adapter and set the list
                dataProvider = new SearchBookDataProvider(cover, title, author);
                bookAdapter.add(dataProvider);
                }
            }
            @Override
            protected void onPostExecute(Object o) {
                if (bookAdapter!= null) {
                    bookAdapter.notifyDataSetChanged();
                }
                super.onPostExecute(o);
            }
 }.execute();
</code>```

Body:
So I have a list of strings (ISBNs), and I need to fill a listview with the objects (Book objects) associated with these strings. The problem is that the function I have to get the Book object using the string takes time, and so to get, say 30 books, the wait approaches 4 or 5 seconds.

One approach I've thought of is to get the Book objects one at a time, and to add them to the list as I get them. But this process will freeze the UI until it's done adding them all. If I try to put this process in a new thread, it won't let me add to the any UI objects (since it's from another thread). If I try to put it in an AsyncTask, I can't access the ListView since it's in the MainActivity class.

There must be a way to dynamically update a UI element, I'm sure I've seen it done. Any suggestions?

EDIT:

This is the code I'm using to actually add items to the list:

//List view and adapter setup
listView = (ListView) findViewById(R.id.listViewCheckout);
bookAdapter = new SearchBookAdapter(getApplicationContext(), R.layout.search_row_layout);
listView.setAdapter(bookAdapter);

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

    //Get the book
    Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

    //Assign data to the adapter variables
    Bitmap cover = book.getCover();
    String title = book.getTitle();
    String author = book.getAuthor();

    //Add data to the adapter and set the list
    SearchBookDataProvider dataProvider = new SearchBookDataProvider(cover, title, author);
    bookAdapter.add(dataProvider);
    bookAdapter.notifyDataSetChanged();
}

Body:
Can you make some changes to your code like this it simple it think it will work

//List view and adapter setup
listView = (ListView) findViewById(R.id.listViewCheckout);
bookAdapter = new SearchBookAdapter(getApplicationContext(), R.layout.search_row_layout);
SearchBookDataProvider dataProvider;
listView.setAdapter(bookAdapter);

 new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] objects) {
                for(int i = 0; i < searches.size(); i++) {

                //Get the book
                Book book = BackendFunctions.getBookFromISBN(fbSnapshot, searches.get(i));

                //Assign data to the adapter variables
                Bitmap cover = book.getCover();
                String title = book.getTitle();
                String author = book.getAuthor();

                //Add data to the adapter and set the list
                dataProvider = new SearchBookDataProvider(cover, title, author);
                bookAdapter.add(dataProvider);
                }
            }
            @Override
            protected void onPostExecute(Object o) {
                if (bookAdapter!= null) {
                    bookAdapter.notifyDataSetChanged();
                }
                super.onPostExecute(o);
            }
 }.execute();


问:
URL re-write and asp.net 3.5 webform
how could i do advance url re-write in asp.net3.5. when we post question in stackoverflow then our question is listed as hyperlink like below one.
What is dependency injection?

when we click on link then a dynamic page is show. so i want know if there is a hyperlink which have href like http://mysite.com/130794/what-is-dependency-injection

actualy i want that when user click on above link then user will be redirect to page where url will be shown in address toolbar like http://mysite.com/130794/what-is-dependency-injection. how could i achieve it without touching IIS. how to write the code. please help me with small sample to understand better. thanks

答:
Thomas, check out ASP.NET Routing.

In a nutshell, ASP.NET Routing is a library that was introduced in the .NET Framework 3.5 SP1 that decouples the URL from a physical file. It is used heavily in ASP.NET MVC, but can also be used in WebForms applications. I have authored an article that discusses how to use ASP.NET Routing in an ASP.NET 3.5 SP1 WebForms application: Using ASP.NET Routing Without ASP.NET MVC. It includes a complete working demo you can download and try out on your computer.

From the article:

ASP.NET Routing is a library that was introduced in the .NET Framework 3.5 SP1 that decouples the URL from a physical file; it is used extensively in ASP.NET MVC web applications. With ASP.NET Routing you, the developer, define routing rules that indicate what route patterns map to what physical files. For example, you might indicate that the URL Categories/CategoryName maps to the ShowProductsByCategory.aspx ASP.NET page, passing along the CategoryName portion of the URL. The ASP.NET page could then display the products for that category. With such a mapping, users could view products for the Beverages category by visiting www.yoursite.com/Categories/Beverages rather than visiting the more verbose and less readable www.yoursite.com/ShowProductsByCategory.aspx?CategoryID=1.

While ASP.NET MVC is a great way to get started with ASP.NET Routing, the good news is that these two systems are independent of one another. It's quite possible to use ASP.NET Routing in a traditional ASP.NET Web Forms application. This article shows how to get ASP.NET Routing up and running in a Web Forms application. Read on to learn more!

To use ASP.NET Routing you'll need to be using ASP.NET 3.5 SP1 or ASP.NET 4. In fact, there were a number of enhancements to ASP.NET Routing in ASP.NET 4 to make it easier to use in a WebForms application, so if you can upgrade to ASP.NET 4 that might be helpful.

Happy Programming!

Title: URL re-write and asp.net 3.5 webform


问:
mapping an array of objects and changing the value with on onClick in React
I'm trying to change the value of like within the cardArr objects while using a map() to list each obj.

Below is my code.
Current, it works, but every object shares the same counter since it's not calling from the object. I understand that I'm currently just calling the object property stored in state, but how do I edit the like in each object using a map function?

```<code>import React, { Component } from 'react';

const cardArr = [
{
    id: 1,
    text: "Hey this is a test.",
    img: " ",
    like: 0
},
{
    id: 2,
    text: "If this works I'll call it a day.",
    img: " ",
    like: 0
},
{
    id: 3,
    text: "I'll drink a lot of beer.",
    img: " ",
    like: 0
},
{
    id: 4,
    text: "Cheers",
    img: " ",
    like: 0

}
]

export class Card extends Component {
    constructor(props) {
    super(props);
    this.state = {
      like: 0,
      show: true
    };
     // this.handleClick = this.handleClick.bind(this);

  }

IncrementItem = () => {
    this.setState({ like: this.state.like + 1 });
}
DecreaseItem = () => {
    this.setState({ like: this.state.like - 1 });
}

// handleClick(e) {
//  e.preventDefault();
//  this.IncrementItem();
// }
// handleClick(e) {
//  e.preventDefault();
//  this.DecreaseItem();
// }

render() {

    const cardList = (cardArr.map((card) =>

        <ul>
            <li>
            <div key={card.id}>
                {card.text};
                <img src={card.img}/>
                <p>Like Button</p>
                <button onClick={this.handleClickAdd}>Like</button>
                <p>Dilike Button</p>
                <button onClick={this.DecreaseItem}>Disike</button>
                <p>Likes: {this.state.like}</p>
            </div>
            </li>
        </ul>
        ));

    return(
        <div id='card'>
            {cardList}
        </div>
    )
}
}
</code>```

答:
Instead of pass the like in the state you have use your array and update the like of your element depending on the id.

```<code>import React, { Component } from 'react';

let cardArr = [
{
    id: 1,
    text: "Hey this is a test.",
    img: " ",
    like: 0
},
{
    id: 2,
    text: "If this works I'll call it a day.",
    img: " ",
    like: 0
},
{
    id: 3,
    text: "I'll drink a lot of beer.",
    img: " ",
    like: 0
},
{
    id: 4,
    text: "Cheers",
    img: " ",
    like: 0

}
]

export class Card extends Component {
    constructor(props) {
    super(props);
    this.state = {
       cardArr:cardArr
    };
     // this.handleClick = this.handleClick.bind(this);

  }

IncrementItem = (id) => {
    let cards = this.state.cardArr;
    cards.find(c => c.id === id).like++;
    this.setState({cardArr:cards});
}
DecreaseItem = (id) => {
    let cards = this.state.cardArr;
    cards.find(c => c.id === id).like--;
    this.setState({cardArr:cards});
}

render() {

    this.state.cardArr.map((card) =>

        <ul>
            <li>
            <div key={card.id}>
                {card.text};
                <img src={card.img}/>
                <p>Like Button</p>
                <button onClick={(card.id) => this.handleClickAdd(card.id)}>Like</button>
                <p>Dilike Button</p>
                <button onClick={(card.id) => this.DecreaseItem(card.id)}>Dislike</button>
                <p>Likes: {card.like}</p>
            </div>
            </li>
        </ul>
        );

    return(
        <div id='card'>
            {cardList}
        </div>
    )
}
}
</code>```

Body:
I'm trying to change the value of like within the cardArr objects while using a map() to list each obj.

Below is my code.
Current, it works, but every object shares the same counter since it's not calling from the object. I understand that I'm currently just calling the object property stored in state, but how do I edit the like in each object using a map function?

import React, { Component } from 'react';

const cardArr = [
{
    id: 1,
    text: "Hey this is a test.",
    img: " ",
    like: 0
},
{
    id: 2,
    text: "If this works I'll call it a day.",
    img: " ",
    like: 0
},
{
    id: 3,
    text: "I'll drink a lot of beer.",
    img: " ",
    like: 0
},
{
    id: 4,
    text: "Cheers",
    img: " ",
    like: 0

}
]

export class Card extends Component {
    constructor(props) {
    super(props);
    this.state = {
      like: 0,
      show: true
    };
     // this.handleClick = this.handleClick.bind(this);

  }

IncrementItem = () => {
    this.setState({ like: this.state.like + 1 });
}
DecreaseItem = () => {
    this.setState({ like: this.state.like - 1 });
}

// handleClick(e) {
//  e.preventDefault();
//  this.IncrementItem();
// }
// handleClick(e) {
//  e.preventDefault();
//  this.DecreaseItem();
// }

render() {

    const cardList = (cardArr.map((card) =>

                {card.text};

Like Button

                <button onClick={this.handleClickAdd}>Like</button>

Dilike Button

                <button onClick={this.DecreaseItem}>Disike</button>

Likes: {this.state.like}

        ));

    return(

            {cardList}

    )
}
}

Body:
Instead of pass the like in the state you have use your array and update the like of your element depending on the id.

import React, { Component } from 'react';

let cardArr = [
{
    id: 1,
    text: "Hey this is a test.",
    img: " ",
    like: 0
},
{
    id: 2,
    text: "If this works I'll call it a day.",
    img: " ",
    like: 0
},
{
    id: 3,
    text: "I'll drink a lot of beer.",
    img: " ",
    like: 0
},
{
    id: 4,
    text: "Cheers",
    img: " ",
    like: 0

}
]

export class Card extends Component {
    constructor(props) {
    super(props);
    this.state = {
       cardArr:cardArr
    };
     // this.handleClick = this.handleClick.bind(this);

  }

IncrementItem = (id) => {
    let cards = this.state.cardArr;
    cards.find(c => c.id === id).like++;
    this.setState({cardArr:cards});
}
DecreaseItem = (id) => {
    let cards = this.state.cardArr;
    cards.find(c => c.id === id).like--;
    this.setState({cardArr:cards});
}

render() {

    this.state.cardArr.map((card) =>

        <ul>
            <li>
            <div key={card.id}>
                {card.text};
                <img src={card.img}/>
                <p>Like Button</p>
                <button onClick={(card.id) => this.handleClickAdd(card.id)}>Like</button>
                <p>Dilike Button</p>
                <button onClick={(card.id) => this.DecreaseItem(card.id)}>Dislike</button>
                <p>Likes: {card.like}</p>
            </div>
            </li>
        </ul>
        );

    return(
        <div id='card'>
            {cardList}
        </div>
    )
}
}


答:
I found that variables in this context are not possible.
In MySQL 5.7 Reference Manual, chapter 9.4 User-Defined Variables:

"In a SELECT statement, each select expression is evaluated only when
  sent to the client. This means that in a HAVING, GROUP BY, or ORDER BY
  clause, referring to a variable that is assigned a value in the select
  expression list does not work as expected."

A possible solution (less readable) is to use sub-queries:

```<code>SELECT
       subquery.*,
       subquery._max - subquery._min as _delta
FROM
       (SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(`date_time`)/900)*900) AS _timeslice,
            COUNT(*) AS _count,
            min(`val1`) as _min,
            max(`val1`) as _max,
        FROM `test-table`
        GROUP BY _timeslice) AS subquery;
</code>```

Title: MySQL, How to reuse calculated data in groups

Body:
I would like to reuse calculated data for a group:

# what I would like to obtain:
#_timeslice              _count     _min        _max        _delta
# 2017-11-01T00:00:00Z     4          90         140          50
# 2017-11-01T00:15:00Z     3         100         160          60
# 2017-11-01T00:30:00Z     2         110         130          20
# 2017-11-01T00:45:00Z     4          80         150          70

CREATE TABLE `test-table`
    (`date_time` datetime, `val1` float);

INSERT INTO `test-table`
    (`date_time`,         `val1`)
VALUES

    ('2017-11-01 00:00:00', 140),  # first 15 min
    ('2017-11-01 00:01:00', 110),
    ('2017-11-01 00:02:05',  90),
    ('2017-11-01 00:14:00', 100),

    ('2017-11-01 00:15:00', 100),  # second 15 min
    ('2017-11-01 00:16:00', 160),
    ('2017-11-01 00:28:00', 120),

    ('2017-11-01 00:30:00', 110),  # third 15 min
    ('2017-11-01 00:44:59', 130),

    ('2017-11-01 00:50:00', 120),  # fourth 15 min
    ('2017-11-01 00:55:00', 150),
    ('2017-11-01 00:57:00', 100),
    ('2017-11-01 00:58:00',  80)
;

SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(`date_time`)/900)*900) AS _timeslice,
    COUNT(*) AS _count,
    min(`val1`) as _min,
    max(`val1`) as _max,
    max(`val1`) - min(`val1`) as _delta  # obvious but inefficient because they are recalculated
FROM `test-table`
GROUP BY _timeslice;

SQLFiddle is here: Example

The _delta is inefficient because max and min are recalculated again.

Is there another syntax to avoid this second useless calculation?

Body:
I found that variables in this context are not possible.
In MySQL 5.7 Reference Manual, chapter 9.4 User-Defined Variables:

"In a SELECT statement, each select expression is evaluated only when
  sent to the client. This means that in a HAVING, GROUP BY, or ORDER BY
  clause, referring to a variable that is assigned a value in the select
  expression list does not work as expected."

A possible solution (less readable) is to use sub-queries:

SELECT
       subquery.*,
       subquery._max - subquery._min as _delta
FROM
       (SELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(`date_time`)/900)*900) AS _timeslice,
            COUNT(*) AS _count,
            min(`val1`) as _min,
            max(`val1`) as _max,
        FROM `test-table`
        GROUP BY _timeslice) AS subquery;


答:
You could add position fixed to solve this in IE:

```<code>.header {
  position: fixed; left: 0; top: 0; width: 100%
}
</code>```

Check this updated fiddle:

Title: How can I get a div to stick to the bottom of the screen and have the middle content scroll?

Body:
I'm trying to have a sticky footer, where the footer is ALWAYS visible and docked to the bottom, while the middle content will scroll as content is added to it.  I am using this method of accomplishing that:

/* Reset */

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

/* Essentials */

.container {
  display: table;
}

.content {
  display: table-row;
  height: 100%;
}

.content-body {
  display: table-cell;
}

.scroller {
  max-height: 100%;
  overflow-y: auto;
}

/* Aestetics */

.container {
  width: 100%;
  height: 100%;
}

.header,
.footer {
  padding: 10px 20px;
  background: #f7f7f7;
}

.scroller {
  padding: 20px;
  background: #e7e7e7;
}

p {
  margin-top: 0;
  margin-bottom: 1rem;
}

p:last-child {
  margin-bottom: 0;
}

This is the header

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the content.

This is the footer.

This works great for Chrome and FF but does not work in IE.  Is there a simple fix for this in IE or does someone know of a better solution?

Body:
You could add position fixed to solve this in IE:

.header {
  position: fixed; left: 0; top: 0; width: 100%
}

Check this updated fiddle:


问:
404 page not found - codeigniter Login
Am beginner in codeigniter, and am trying to do a simple login form by referring some online vedios. i did everything . but when i try to login its showing me 404 page not found. Please help me to finsh this

autoload.php

```<code>$autoload['libraries'] = array('database','session');
</code>```

routes.php

```<code>$route['default_controller'] = 'welcome';
</code>```

controllers

welcome.php

```<code><?php defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {

public function __construct(){

    parent::__construct();
        $this->load->helper('url');
        $this->load->model('main_model');
        $this->load->library('session');
        $this->load->library('form_validation');}
public function index()
{
            $this->load->view('welcome_message');
}

function login_user(){
            $this->load->view('welcome_message');

}  function login_validation(){

            $this->load->library('form_validation');
            $this->form_validation->set_rules('username','Username','required');
            $this->form_validation->set_rules('password','Password','required');

            if($this->form_validation->run()){
                // true

                $username = $this->input->post('username');
                $password = $this->input->post('password');

                // model function
                $this->load->model('main_model');

                if($this->main_model->can_login($username, $password)){
                    $session_date = array(
                        'username'=> $username);

                    $this->session->set_userdata($session_date);

                    redirect(base_url() . 'main/enter');
                }else{
                    $this->session->set_flashdata('error','Invalid Username and Password');
                                 redirect(base_url() . 'main/login_user');

                }
            } else{
                //false

                $this->login_user();
            }}function enter(){
if($this->session->userdata('username') !=''){
echo '<h2> Welcome - '.$this->session->userdata('username').'/<h2>';

} else{redirect(base_url() . 'main/login_user');}}}
</code>```

model class

```<code>function can_login($username,$password){
$this->db->where('UserName',$username);
$this->db->where('Password',$password);
  $query=$this->db->get('User');

  if($query->num_rows() > 0){

    return true;

  } else{
   return false;
  }}
</code>```

Whenever i try to login its showing be 404 page not found

login.php

```<code><form method="post" action="<?php echo base_url(); ?>main/login_validation">
            <div class="form-group">
                 <label>Enter Username</label>
                 <input type="text" name="username" class="form-control" />
                 <span class="text-danger"><?php echo form_error('username'); ?></span>
            </div>
            <div class="form-group">
                 <label>Enter Password</label>
                 <input type="password" name="password" class="form-control" />
                 <span class="text-danger"><?php echo form_error('password'); ?></span>
            </div>
            <div class="form-group">
                 <input type="submit" name="insert" value="Login" class="btn btn-info" />
                 <?php
                      echo '<label class="text-danger">'.$this->session->flashdata("error").'</label>';
                 ?>
            </div>
       </form>
</code>```

答:
Never used this framework but to me it seems the problem is either in the redirect or the main/enter controller/action.
To find out var_dump() on the base_url() maybe you calling it wrong maybe its static method of a class or a constant.
Set the session user data somewhere in the code than try going to the main/enter. Maybe does not exist?

Edit:Seems codeingniter redirect does not need base_ur just use

```<code>redirect('/main/enter');
</code>```

Title: 404 page not found - codeigniter Login

Body:
Am beginner in codeigniter, and am trying to do a simple login form by referring some online vedios. i did everything . but when i try to login its showing me 404 page not found. Please help me to finsh this

autoload.php

$autoload['libraries'] = array('database','session');

routes.php

$route['default_controller'] = 'welcome';

controllers

welcome.php

<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {

public function __construct(){

    parent::__construct();
        $this->load->helper('url');
        $this->load->model('main_model');
        $this->load->library('session');
        $this->load->library('form_validation');}
public function index()
{
            $this->load->view('welcome_message');
}

function login_user(){
            $this->load->view('welcome_message');

}  function login_validation(){

            $this->load->library('form_validation');
            $this->form_validation->set_rules('username','Username','required');
            $this->form_validation->set_rules('password','Password','required');

            if($this->form_validation->run()){
                // true

                $username = $this->input->post('username');
                $password = $this->input->post('password');

                // model function
                $this->load->model('main_model');

                if($this->main_model->can_login($username, $password)){
                    $session_date = array(
                        'username'=> $username);

                    $this->session->set_userdata($session_date);

                    redirect(base_url() . 'main/enter');
                }else{
                    $this->session->set_flashdata('error','Invalid Username and Password');
                                 redirect(base_url() . 'main/login_user');

                }
            } else{
                //false

                $this->login_user();
            }}function enter(){
if($this->session->userdata('username') !=''){
echo '
 Welcome - '.$this->session->userdata('username').'/
';

} else{redirect(base_url() . 'main/login_user');}}}

model class

function can_login($username,$password){
$this->db->where('UserName',$username);
$this->db->where('Password',$password);
  $query=$this->db->get('User');

  if($query->num_rows() > 0){

    return true;

  } else{
   return false;
  }}

Whenever i try to login its showing be 404 page not found

login.php

<form method="post" action="<?php echo base_url(); ?>main/login_validation">

                 Enter Username
                 <input type="text" name="username" class="form-control" />
                 <?php echo form_error('username'); ?>

                 Enter Password
                 <input type="password" name="password" class="form-control" />
                 <?php echo form_error('password'); ?>

                 <input type="submit" name="insert" value="Login" class="btn btn-info" />
                 <?php
                      echo ''.$this->session->flashdata("error").'';
                 ?>

       </form>

Body:
Never used this framework but to me it seems the problem is either in the redirect or the main/enter controller/action.
To find out var_dump() on the base_url() maybe you calling it wrong maybe its static method of a class or a constant.
Set the session user data somewhere in the code than try going to the main/enter. Maybe does not exist?

Edit:Seems codeingniter redirect does not need base_ur just use

redirect('/main/enter');


问:
WEBP image fall back
I searched a lot on the internet & can't find the right example or complete tutorial on the web which can full prof. So guys please suggest me some good examples.

I have tried WEBP code on lots or website like use with modernizer, checking browser support, or using the background image.

答:
There is an article on stucox where you can find some examples using webp images with modernizr and fallback images. This should cover your problem.

```<code>/* Result pending */
.js .container {
   background-image: none;
}
/* No JS / WebP not supported */
   .no-js .container,
   .js.no-webp .container {
   background-image: url('image.jpg');
}
/* WebP supported */
   .js.webp .container {
   background-image: url('image.webp');
}
</code>```

http://www.stucox.com/blog/using-webp-with-modernizr/

Title: WEBP image fall back

Body:
There is an article on stucox where you can find some examples using webp images with modernizr and fallback images. This should cover your problem.

/* Result pending */
.js .container {
   background-image: none;
}
/* No JS / WebP not supported */
   .no-js .container,
   .js.no-webp .container {
   background-image: url('image.jpg');
}
/* WebP supported */
   .js.webp .container {
   background-image: url('image.webp');
}

http://www.stucox.com/blog/using-webp-with-modernizr/