问:
CollapsingToolbarLayout - Dim/Blur the background image
I've got a collapsing toolbar with an imageview. When extended, it looks like this:

When collapsed, it looks like this:

I know that according to the guidelines, the toolbar should be of the primary color while collapsed, but i like the way i've set it up, and would like to keep it like that.

However, obviously, the toolbar title won't be visible if the image has a lot of white in it. So, is there a way i can blur/dim the background so that the toolbar title is visible at all times?

Edit: The image in question, is loaded from the internet using Picasso.

答:
You can use scrim for this. create gradient file in drawable folder.

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
    android:angle="-90"
    android:startColor="#00000000"
    android:centerColor="#00000000"
    android:endColor="#4d000000"
    android:type="linear" />
</shape>
</code>```

After creating the above file add an extra view to your layout like this

```<code><FrameLayout>
<ImageView>
<View
android:background="@drawable/nameOfAboveFile"/>
<TexTView>
</FrameLayout>
</code>```

Body:
You can use scrim for this. create gradient file in drawable folder.

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
    android:angle="-90"
    android:startColor="#00000000"
    android:centerColor="#00000000"
    android:endColor="#4d000000"
    android:type="linear" />
</shape>

After creating the above file add an extra view to your layout like this

<FrameLayout>
<ImageView>
<View
android:background="@drawable/nameOfAboveFile"/>
<TexTView>
</FrameLayout>


来源: stackexchange

问:
Codeigniter login system issue loging
I got a table "usuarios" which contains the following information:

(id, username, name, lastname, password, type, status, date), right?

Take a look:

My personal goal is to make a login system which allows me to clasify those WHO are ADMIN from those who are just simple users... I mean, if a row of the table contains type = 0 it is an ADMIN and if type = 1 it is a simple user.
So,in the login system if i write for example ADMIN 1234 and this data corresponds to an ADMIN user from the table "users"; when i press "login" it must open an exclusive page only for ADMINs.. The same but for those who are "simple" users.

The system must validate if i write wrongs usernames/passwords and if the username corresponds to an active member (status = 1 active, status = 0 not active). No empty fields while login

No matter what i write in "username" and "password" in the login system.. when i click on "login" i always get this message and nothing happens:

And these are the users registered in my database:

Here is my code:
Controller files (2 files: "dashboard" and "login")
Dashboard:

```<code>    <?php

        Class dashboard extends CI_Controller{

         public function __construct(){
             parent::__construct();
             $this->load->model('m_login');
         $this->auth->cek_auth();

        }

        public function index(){
            $ambil_akun = $this->m_login->ambil_user($this->session->userdata('usuario'));
            $data = array(

              'user' =>$ambil_akun,

              );

            $stat = $this->session->userdata('lvl');
            if($stat=='s_admin'){
              $this->load->view('dashboard_admin', $data);

            }else{

              $this->load->view('dashboard_user', $data);

            }

        }

  public function login(){

    $session = $this->session->userdata('isLogin');
    if($session == FALSE)
    {

      $this->load->view('login_form');

    }else
    {

      redirect('dashboard');

    }

  }

  public function logout(){

    $this->session->sess_destroy();
    redirect('login', 'refresh');

  }

}

?>
</code>```

Login:

```<code>    <?php

        Class Login extends CI_Controller{

        public function __construct(){
             parent::__construct();
             $this->load->model("m_login");

        }

        public function index(){
            $session = $this->session->userdata('isLogin');
            if($session == FALSE)
            {

                $this->load->view('login_form');

            }else
            {

                redirect('dashboard');

            }

        }

        public function do_login()
        {

            $usuario=$this->input->post('uname');
            $contrasena=$this->input->post('pass');

            $cek=$this->m_login->cek_user($contrasena, md5($contrasena));
            if(count($cek) == 1){

                foreach ($cek as $cek) {

                    $tipo=$cek['tipo'];
                    $estado=$cek['estado'];
                    $nombre=$cek['nombre'];

                }

                if($estado =='0'){

                    $this->session->set_userdata(array(

                        'isLogin'=>TRUE,
                        'uname'=>$usuario,
                        'lvl'=>$tipo,
                        'estado'=>$estado

                    ));
                    redirect('dashboard', 'refresh');

                }
                else{

                    echo "<script>alert('YOUR ACCOUNT IS NOT ACTIVE')</script>";
                    redirect('login','refresh');

                }

                }else{

                    echo "<script>alert('USERNAME OR PASSWORD INVALID!')</script>";
                    redirect('login','refresh');

                }

}

}

?>
</code>```

The model file (m_login):

```<code>    <?php

    class m_login extends CI_Model{

        public function __construct(){

         parent::__construct();
         $this->tbl="usuarios";

        }

    public function cek_user($usuario="", $contrasena="")
    {

        $query=$this->db->get_where($this->tbl, array('usuario'=>$usuario, 'contrasena'=>$contrasena));
        $query=$query->result_array();
        return $query;
    }

    public function ambil_user($nombre)
    {

        $query=$this->db->get_where($this->tbl, array('nombre'=> $nombre));
        $query=$query->result_array();
        if(query){

            return $query[0];

        }

    }

}

?>
</code>```

And my view files:
login_form:

```<code>    <!DOCTYPE html>
<html lang="">

    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

    </head>

        <body>
            <div class="container">
            <h3>Login</h3>
            <hr>
            <form action="<?php echo base_url('login/do_login')?>" method="POST">
                <div class="form-group">
                    <label for="cari">USERNAME</label>
                    <input type="text" name="usuario" id="usuario" class="form-control"><?php echo form_error('usuario');?>

                </div>

                <div class="form-group">
                    <label for="cari">PASSWORD</label>
                    <input type="password" name="contrasena" id="contrasena" class="form-control"><?php echo form_error('contrasena');?>

                </div>

                <input class="btn btn-primary" type="submit" value="Login">
                <input class="btn btn-primary" type="reset" value="Reset">

            </form>
                </div>

        </body>
</html>
</code>```

dashboard_admin:

```<code>Hi!<b><?php echo $user['nombre'];?></b>YOU ARE AN ADMINISTRATOR! > [<a href= '<?php echo base_url('dashboard/logout');?>'>LOGOUT</a>]
</code>```

dashboard_user:

```<code>Hi!<b><?php echo $user['nombre'];?></b>YOU ARE A SIMPLE USER! > [<a href= '<?php echo base_url('dashboard/logout');?>'>LOGOUT</a>]
</code>```

Dont know what to do now :/

答:
You must to return an object instead object array in your model, then you don't have encrypted password on your database.

You may use tank_auth: https://konyukhov.com/soft/tank_auth/

ContentLicense: CC BY-SA 3.0

Title: Codeigniter login system issue loging

Body:
I got a table "usuarios" which contains the following information:

(id, username, name, lastname, password, type, status, date), right?

Take a look:

My personal goal is to make a login system which allows me to clasify those WHO are ADMIN from those who are just simple users... I mean, if a row of the table contains type = 0 it is an ADMIN and if type = 1 it is a simple user.
So,in the login system if i write for example ADMIN 1234 and this data corresponds to an ADMIN user from the table "users"; when i press "login" it must open an exclusive page only for ADMINs.. The same but for those who are "simple" users.

The system must validate if i write wrongs usernames/passwords and if the username corresponds to an active member (status = 1 active, status = 0 not active). No empty fields while login

No matter what i write in "username" and "password" in the login system.. when i click on "login" i always get this message and nothing happens:

And these are the users registered in my database:

Here is my code:
Controller files (2 files: "dashboard" and "login")
Dashboard:

    <?php

        Class dashboard extends CI_Controller{

         public function __construct(){
             parent::__construct();
             $this->load->model('m_login');
         $this->auth->cek_auth();

        }

        public function index(){
            $ambil_akun = $this->m_login->ambil_user($this->session->userdata('usuario'));
            $data = array(

              'user' =>$ambil_akun,

              );

            $stat = $this->session->userdata('lvl');
            if($stat=='s_admin'){
              $this->load->view('dashboard_admin', $data);

            }else{

              $this->load->view('dashboard_user', $data);

            }

        }

  public function login(){

    $session = $this->session->userdata('isLogin');
    if($session == FALSE)
    {

      $this->load->view('login_form');

    }else
    {

      redirect('dashboard');

    }

  }

  public function logout(){

    $this->session->sess_destroy();
    redirect('login', 'refresh');

  }

}

?>

Login:

    <?php

        Class Login extends CI_Controller{

        public function __construct(){
             parent::__construct();
             $this->load->model("m_login");

        }

        public function index(){
            $session = $this->session->userdata('isLogin');
            if($session == FALSE)
            {

                $this->load->view('login_form');

            }else
            {

                redirect('dashboard');

            }

        }

        public function do_login()
        {

            $usuario=$this->input->post('uname');
            $contrasena=$this->input->post('pass');

            $cek=$this->m_login->cek_user($contrasena, md5($contrasena));
            if(count($cek) == 1){

                foreach ($cek as $cek) {

                    $tipo=$cek['tipo'];
                    $estado=$cek['estado'];
                    $nombre=$cek['nombre'];

                }

                if($estado =='0'){

                    $this->session->set_userdata(array(

                        'isLogin'=>TRUE,
                        'uname'=>$usuario,
                        'lvl'=>$tipo,
                        'estado'=>$estado

                    ));
                    redirect('dashboard', 'refresh');

                }
                else{

                    echo "";
                    redirect('login','refresh');

                }

                }else{

                    echo "";
                    redirect('login','refresh');

                }

}

}

?>

The model file (m_login):

    <?php

    class m_login extends CI_Model{

        public function __construct(){

         parent::__construct();
         $this->tbl="usuarios";

        }

    public function cek_user($usuario="", $contrasena="")
    {

        $query=$this->db->get_where($this->tbl, array('usuario'=>$usuario, 'contrasena'=>$contrasena));
        $query=$query->result_array();
        return $query;
    }

    public function ambil_user($nombre)
    {

        $query=$this->db->get_where($this->tbl, array('nombre'=> $nombre));
        $query=$query->result_array();
        if(query){

            return $query[0];

        }

    }

}

?>

And my view files:
login_form:

    <!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">

Login

            <form action="<?php echo base_url('login/do_login')?>" method="POST">

                    USERNAME
                    <input type="text" name="usuario" id="usuario" class="form-control"><?php echo form_error('usuario');?>

                    PASSWORD
                    <input type="password" name="contrasena" id="contrasena" class="form-control"><?php echo form_error('contrasena');?>

                <input class="btn btn-primary" type="submit" value="Login">
                <input class="btn btn-primary" type="reset" value="Reset">

            </form>

dashboard_admin:

Hi!<?php echo $user['nombre'];?>YOU ARE AN ADMINISTRATOR! > [<a href= '<?php echo base_url('dashboard/logout');?>'>LOGOUT]

dashboard_user:

Hi!<?php echo $user['nombre'];?>YOU ARE A SIMPLE USER! > [<a href= '<?php echo base_url('dashboard/logout');?>'>LOGOUT]

Dont know what to do now :/


问:
Equivalent of shell 'cd' command to change the working directory?
cd is the shell command to change the working directory.

How do I change the current working directory in Python?

答:
You can change the working directory with:

import os

os.chdir(path)
```

There are two best practices to follow when using this method:

Catch the exception (WindowsError, OSError) on invalid path.  If the exception is thrown, do not perform any recursive operations, especially destructive ones.  They will operate on the old path and not the new one.

Return to your old directory when you're done.  This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in his answer.

Changing the current working directory in a subprocess does not change the current working directory in the parent process.  This is true of the Python interpreter as well.  You cannot use os.chdir() to change the CWD of the calling process.

OwnerDisplayName: Peter

ContentLicense: CC BY-SA 4.0

Body:
You can change the working directory with:

import os

os.chdir(path)

There are two best practices to follow when using this method:

Catch the exception (WindowsError, OSError) on invalid path.  If the exception is thrown, do not perform any recursive operations, especially destructive ones.  They will operate on the old path and not the new one.

Return to your old directory when you're done.  This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in his answer.

Changing the current working directory in a subprocess does not change the current working directory in the parent process.  This is true of the Python interpreter as well.  You cannot use os.chdir() to change the CWD of the calling process.

OwnerDisplayName: sludge

LastEditorDisplayName: sludge


问:
What separates a content management system from just a bunch of web pages?
I have a website that has related pages.  They have links that point back and forth to one another but I have no integrated system, nor do I know what that would mean.

What is the minimum code that a group of web pages must have to be considered a Content Management System (CMS).  Is it that all the settings are in the database and the pages are generated somehow?  Is there some small snippet that all my pages could share that makes them a CMS, database or not?

Thanks.  I was also hoping not to have to study a giant CMS to see what makes it a CMS .  After maybe a basic understanding I would know what I was looking for.

edit:  here's why I ask about code.  Whenever I have looked at a CMS, and maybe they aren't all the same, I saw that to develop a module you always had to inherit from certain classes and had some necessary code.  I didn't know if there was some magic model that I just don't get that all cms makers understand.

edit:  perhaps my question is more about being extendable or pluggable.  What would a minimum look like?  Is it possible to show that here?

edit:  how about this?  Is something a CMS if it is not extendable and/or pluggable?

答:
Without dragging you into a theoretical explanation of what a CMS is and what it's not, perhaps some tutorials on the building methodology of a CMS will help you better understand.

http://css-tricks.com/php-for-beginners-building-your-first-simple-cms/

http://www.intranetjournal.com/php-cms/

ContentLicense: CC BY-SA 2.5


问:
detecting installer iptables and firewalld with if conditions / bash
Creating script to detect

installer (yum or apt-get)

iptables

firewalld

Current system:

Debian 8

iptables NOT installed

firewalld NOT installed

Theoretically it must be working, but missing something:

```<code>#!/bin/bash
installer_check () {
  if [[ $(apt-get -V >/dev/null 2>&1) -eq 0 ]]; then
    installer=apt
  elif [[ $(yum --version >/dev/null 2>&1) -eq 0 ]]; then
    installer=yum
  fi
}

frw_det_yum () {
  if [[ $(rpm -qa iptables >/dev/null 2>&1) -ne 0 ]]; then
    ipt_status_y=installed_none
  elif [[ $(rpm -qa firewalld >/dev/null 2>&1) -ne 0 ]]; then
    frd_status_y=installed_none
  fi
}

frw_det_apt () {
  if [[ $(dpkg -s iptables >/dev/null 2>&1) -ne 0 ]]; then
    ipt_status_a=installed_none
  elif [[ $(dpkg -s firewalld >/dev/null 2>&1) -ne 0 ]]; then
    frd_status_a=installed_none
  fi
}

echo "checking installer"
installer_check
echo -e "$installer detected"

if [ "$installer" = "yum" ]; then
  echo "runing firewallcheck for yum"
  frw_det_yum
  echo $ipt_status
fi

if  [ "$installer" = "apt" ]; then
  echo "checking installer for apt"
  frw_det_apt
  echo $frd_status_a
fi
</code>```

output I'm getting:

```<code>~# ./script
checking installer
apt detected
checking installer for apt
</code>```

So in this current system I'm not getting any value for $frd_status_a

答:
You expect the body of the following to be invoked if firewalld is not installed:

```<code>if [[ $(dpkg -s firewalld >/dev/null 2>&1) -ne 0 ]]; then
  frd_status_a=installed_none
fi
</code>```

However, let's look at what this actually does:

redirect stdout and stderr of the command dpkg -s firewalld to /dev/null

capture the stdout of that command, and compare it numerically to the value 0

If the stdout of that command (which has no stdout because you redirected it) has a numeric value other than 0, then we set the flag.

Of course that flag will never be set, no matter what the dpkg command does when it's invoked, and no matter what its output is.

Consider instead:

```<code>if ! dpkg-query -l firewalld; then
  frd_status_a=installed_none
fi
</code>```

Body:
Creating script to detect

installer (yum or apt-get)

iptables

firewalld

Current system:

Debian 8

iptables NOT installed

firewalld NOT installed

Theoretically it must be working, but missing something:

#!/bin/bash
installer_check () {
  if [[ $(apt-get -V >/dev/null 2>&1) -eq 0 ]]; then
    installer=apt
  elif [[ $(yum --version >/dev/null 2>&1) -eq 0 ]]; then
    installer=yum
  fi
}

frw_det_yum () {
  if [[ $(rpm -qa iptables >/dev/null 2>&1) -ne 0 ]]; then
    ipt_status_y=installed_none
  elif [[ $(rpm -qa firewalld >/dev/null 2>&1) -ne 0 ]]; then
    frd_status_y=installed_none
  fi
}

frw_det_apt () {
  if [[ $(dpkg -s iptables >/dev/null 2>&1) -ne 0 ]]; then
    ipt_status_a=installed_none
  elif [[ $(dpkg -s firewalld >/dev/null 2>&1) -ne 0 ]]; then
    frd_status_a=installed_none
  fi
}

echo "checking installer"
installer_check
echo -e "$installer detected"

if [ "$installer" = "yum" ]; then
  echo "runing firewallcheck for yum"
  frw_det_yum
  echo $ipt_status
fi

if  [ "$installer" = "apt" ]; then
  echo "checking installer for apt"
  frw_det_apt
  echo $frd_status_a
fi

output I'm getting:

~# ./script
checking installer
apt detected
checking installer for apt

So in this current system I'm not getting any value for $frd_status_a

Body:
You expect the body of the following to be invoked if firewalld is not installed:

if [[ $(dpkg -s firewalld >/dev/null 2>&1) -ne 0 ]]; then
  frd_status_a=installed_none
fi

However, let's look at what this actually does:

redirect stdout and stderr of the command dpkg -s firewalld to /dev/null

capture the stdout of that command, and compare it numerically to the value 0

If the stdout of that command (which has no stdout because you redirected it) has a numeric value other than 0, then we set the flag.

Of course that flag will never be set, no matter what the dpkg command does when it's invoked, and no matter what its output is.

Consider instead:

if ! dpkg-query -l firewalld; then
  frd_status_a=installed_none
fi


问:
What am i doing wrong in this procedure query?
I am not so familiar with MySQL, i tried creating a MySQL procedure that SELECTS two fields from a table, assign them to a variable then use the value of those variables to update another field in a different table, so far, this is the code i have but when i run it i get this error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET @amnt = (SELECTinitial_paymentFROMphWHEREpayment_status= 'unconf' at line 5

This is my code:

```<code>DELIMITER //
CREATE PROCEDURE check_for_days()
BEGIN
    SET @i = (SELECT COUNT(*) FROM `ph` WHERE `payment_status` = 'unconfirmed' && TIMESTAMPDIFF(DAY, `date_paired`, NOW()) > 2) ;

    label1:WHILE @i>0
        SET @amnt = (SELECT `initial_payment` FROM `ph` WHERE `payment_status` = 'unconfirmed' && TIMESTAMPDIFF(DAY, `date_paired`, NOW()) > 2 LIMIT 1);
        SET @id_to_cred = (SELECT `to_pay_id` FROM `ph` WHERE `payment_status` = 'unconfirmed' && TIMESTAMPDIFF(DAY, `date_paired`, NOW()) > 2 LIMIT 1);
        UPDATE `gh` SET `remaining_to_get` = + @amnt WHERE `u_id` = @id_to_cred;
        DELETE FROM `ph` WHERE `payment_status` = 'unconfirmed' && TIMESTAMPDIFF(DAY, `date_paired`, NOW()) > 2 LIMIT 1;
        SET @i = @i - 1;
    END WHILE label1;
END
DELIMITER ;
</code>```

答:
For you syntax error:

```<code>label1:WHILE @i>0
  SET @amnt
</code>```

where is DO

```<code>label1:WHILE @i>0 DO
      SET @amnt`
</code>```

Body:
I am not so familiar with MySQL, i tried creating a MySQL procedure that SELECTS two fields from a table, assign them to a variable then use the value of those variables to update another field in a different table, so far, this is the code i have but when i run it i get this error:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET @amnt = (SELECTinitial_paymentFROMphWHEREpayment_status= 'unconf' at line 5

This is my code:

DELIMITER //
CREATE PROCEDURE check_for_days()
BEGIN
    SET @i = (SELECT COUNT(*) FROM `ph` WHERE `payment_status` = 'unconfirmed' && TIMESTAMPDIFF(DAY, `date_paired`, NOW()) > 2) ;

    label1:WHILE @i>0
        SET @amnt = (SELECT `initial_payment` FROM `ph` WHERE `payment_status` = 'unconfirmed' && TIMESTAMPDIFF(DAY, `date_paired`, NOW()) > 2 LIMIT 1);
        SET @id_to_cred = (SELECT `to_pay_id` FROM `ph` WHERE `payment_status` = 'unconfirmed' && TIMESTAMPDIFF(DAY, `date_paired`, NOW()) > 2 LIMIT 1);
        UPDATE `gh` SET `remaining_to_get` = + @amnt WHERE `u_id` = @id_to_cred;
        DELETE FROM `ph` WHERE `payment_status` = 'unconfirmed' && TIMESTAMPDIFF(DAY, `date_paired`, NOW()) > 2 LIMIT 1;
        SET @i = @i - 1;
    END WHILE label1;
END
DELIMITER ;

Body:
For you syntax error:

label1:WHILE @i>0
  SET @amnt

where is DO

label1:WHILE @i>0 DO
      SET @amnt`


问:
Set NSScrollView to not editable
I was wondering how to take care that my NSScrollView is not editable by the user, but i didn't find a way, there is no option in IB, nor do I find an appropriate method of the NSSCrollView class.

A previous post suggested to implement a delegate method

```<code>- (BOOL)textShouldBeginEditing:(NSText *)aTextObject
</code>```

to return false, but this didn't work for me yet.
No solution was given on the previous question.

(I also tried selecting the TextView everything it doesn't display an option 'editable' i just downloaded the new Xcode so the version shouldn't be a problem)

答:
what is inside the scrollView that you want to prevent editing of?

what views have you got embedded in the scrollView? you need to find the view embedded in the scrollView that you want to prevent editing on, and call setEditable:NO on it.

Title: Set NSScrollView to not editable

Body:
I was wondering how to take care that my NSScrollView is not editable by the user, but i didn't find a way, there is no option in IB, nor do I find an appropriate method of the NSSCrollView class.

A previous post suggested to implement a delegate method

- (BOOL)textShouldBeginEditing:(NSText *)aTextObject

to return false, but this didn't work for me yet.
No solution was given on the previous question.

(I also tried selecting the TextView everything it doesn't display an option 'editable' i just downloaded the new Xcode so the version shouldn't be a problem)


问:
Xamarin.Forms NavigationPage
I want to create a NavigationPage but I'm doing something wrong. Here's my stacktrace message: "Sequence contains no elements." Can someone help me pinpoint what's wrong with my code? I uploaded an image of an error I'm getting.

This is the code-behind for the xaml page:

```<code>namespace Quickies
{
public partial class QuickiesPage : NavigationPage
  {
    public QuickiesPage()
    {
        InitializeComponent();
    }
  }
}
</code>```

Here's my "App" class

```<code>namespace Quickies
{
public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        MainPage = new NavigationPage (new QuickiesPage());
    }
</code>```

答:
Navigation page constructor accepts Xamarin.Forms.Page object. You are trying to send a Navigation Page object.
You can either do :

```<code>public partial class QuickiesPage : ContentPage
</code>```

or (since I am not sure what you are trying to do)

```<code>MainPage = new QuickiesPage ();
</code>```

Title: Xamarin.Forms NavigationPage

Body:
I want to create a NavigationPage but I'm doing something wrong. Here's my stacktrace message: "Sequence contains no elements." Can someone help me pinpoint what's wrong with my code? I uploaded an image of an error I'm getting.

This is the code-behind for the xaml page:

namespace Quickies
{
public partial class QuickiesPage : NavigationPage
  {
    public QuickiesPage()
    {
        InitializeComponent();
    }
  }
}

Here's my "App" class

namespace Quickies
{
public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        MainPage = new NavigationPage (new QuickiesPage());
    }

Body:
Navigation page constructor accepts Xamarin.Forms.Page object. You are trying to send a Navigation Page object.
You can either do :

public partial class QuickiesPage : ContentPage

or (since I am not sure what you are trying to do)

MainPage = new QuickiesPage ();


问:
Change label text for a few seconds before returning to original text
Basically I am trying to implement an animation that will replace a label's text for a few seconds before returning to the original text. I have managed to get the label to change text and fade out after 3 seconds, however I can't figure out how to return the text to the original state after the animation is complete.

Here is what I currently have:

```<code>    @IBAction func fade() {
    userMessageLabel.alpha = 100
    UIView.beginAnimations(nil, context: nil)
    UIView.setAnimationDuration(3)
    userMessageLabel.text = "Name is not valid!"
    userMessageLabel.alpha = 0
    UIView.commitAnimations()
}
</code>```

I need the text label to return to "Please enter your first name"

Any help would be much appreciated.

答:
I solved this problem by using a delay:

```<code>userMessageLabel.text = "Name is not valid!"
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
  userMessageLabel.text = "Please enter your first name"
}
</code>```

My solution includes a slight simplification of the delay from this answer

You seem to already know how to animate text to fade out or in.  If desired, add animation code into the asyncAfter delay function

Body:
Basically I am trying to implement an animation that will replace a label's text for a few seconds before returning to the original text. I have managed to get the label to change text and fade out after 3 seconds, however I can't figure out how to return the text to the original state after the animation is complete.

Here is what I currently have:

    @IBAction func fade() {
    userMessageLabel.alpha = 100
    UIView.beginAnimations(nil, context: nil)
    UIView.setAnimationDuration(3)
    userMessageLabel.text = "Name is not valid!"
    userMessageLabel.alpha = 0
    UIView.commitAnimations()
}

I need the text label to return to "Please enter your first name"

Any help would be much appreciated.

Body:
I solved this problem by using a delay:

userMessageLabel.text = "Name is not valid!"
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
  userMessageLabel.text = "Please enter your first name"
}

My solution includes a slight simplification of the delay from this answer

You seem to already know how to animate text to fade out or in.  If desired, add animation code into the asyncAfter delay function


问:
How to implement authenticated routes in React Router 4?
I was trying to implement authenticated routes but found that React Router 4 now prevents this from working:

```<code><Route exact path="/" component={Index} />
<Route path="/auth" component={UnauthenticatedWrapper}>
    <Route path="/auth/login" component={LoginBotBot} />
</Route>
<Route path="/domains" component={AuthenticatedWrapper}>
    <Route exact path="/domains" component={DomainsIndex} />
</Route>
</code>```

The error is:

Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored

In that case, what's the correct way to implement this?

It appears in react-router (v4) docs, it suggests something like

```<code><Router>
    <div>
    <AuthButton/>
    <ul>
        <li><Link to="/public">Public Page</Link></li>
        <li><Link to="/protected">Protected Page</Link></li>
    </ul>
    <Route path="/public" component={Public}/>
    <Route path="/login" component={Login}/>
    <PrivateRoute path="/protected" component={Protected}/>
    </div>
</Router>
</code>```

But is it possible to achieve this while grouping a bunch of routes together?

After some research, I came up with this:

```<code>import React, {PropTypes} from "react"
import {Route} from "react-router-dom"

export default class AuthenticatedRoute extends React.Component {
  render() {
    if (!this.props.isLoggedIn) {
      this.props.redirectToLogin()
      return null
    }
    return <Route {...this.props} />
  }
}

AuthenticatedRoute.propTypes = {
  isLoggedIn: PropTypes.bool.isRequired,
  component: PropTypes.element,
  redirectToLogin: PropTypes.func.isRequired
}
</code>```

Is it correct to dispatch an action in render()? It feels wrong. It doesn't really seem correct with componentDidMount or some other hook, either.

答:
You're going to want to use the Redirect component. There's a few different approaches to this problem. Here's one I like, have a PrivateRoute component that takes in an authed prop and then renders based on that props.

```<code>function PrivateRoute ({component: Component, authed, ...rest}) {
  return (
    <Route
      {...rest}
      render={(props) => authed === true
        ? <Component {...props} />
        : <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
    />
  )
}
</code>```

Now your Routes can look something like this

```<code><Route path='/' exact component={Home} />
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<PrivateRoute authed={this.state.authed} path='/dashboard' component={Dashboard} />
</code>```

If you're still confused, I wrote this post that may help -
Protected routes and authentication with React Router v4

Body:
I was trying to implement authenticated routes but found that React Router 4 now prevents this from working:

<Route exact path="/" component={Index} />
<Route path="/auth" component={UnauthenticatedWrapper}>
    <Route path="/auth/login" component={LoginBotBot} />
</Route>
<Route path="/domains" component={AuthenticatedWrapper}>
    <Route exact path="/domains" component={DomainsIndex} />
</Route>

The error is:

Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored

In that case, what's the correct way to implement this?

It appears in react-router (v4) docs, it suggests something like

<Router>

    <AuthButton/>

<Link to="/public">Public Page</Link>

<Link to="/protected">Protected Page</Link>

    <Route path="/public" component={Public}/>
    <Route path="/login" component={Login}/>
    <PrivateRoute path="/protected" component={Protected}/>

</Router>

But is it possible to achieve this while grouping a bunch of routes together?

After some research, I came up with this:

import React, {PropTypes} from "react"
import {Route} from "react-router-dom"

export default class AuthenticatedRoute extends React.Component {
  render() {
    if (!this.props.isLoggedIn) {
      this.props.redirectToLogin()
      return null
    }
    return <Route {...this.props} />
  }
}

AuthenticatedRoute.propTypes = {
  isLoggedIn: PropTypes.bool.isRequired,
  component: PropTypes.element,
  redirectToLogin: PropTypes.func.isRequired
}

Is it correct to dispatch an action in render()? It feels wrong. It doesn't really seem correct with componentDidMount or some other hook, either.

Body:
You're going to want to use the Redirect component. There's a few different approaches to this problem. Here's one I like, have a PrivateRoute component that takes in an authed prop and then renders based on that props.

function PrivateRoute ({component: Component, authed, ...rest}) {
  return (
    <Route
      {...rest}
      render={(props) => authed === true
        ? <Component {...props} />
        : <Redirect to={{pathname: '/login', state: {from: props.location}}} />}
    />
  )
}

Now your Routes can look something like this

<Route path='/' exact component={Home} />
<Route path='/login' component={Login} />
<Route path='/register' component={Register} />
<PrivateRoute authed={this.state.authed} path='/dashboard' component={Dashboard} />

If you're still confused, I wrote this post that may help -
Protected routes and authentication with React Router v4


问:
How to add a "open git-bash here..." context menu to the windows explorer?
How to add a context (aka right click) menu to the windows explorer that, when clicked, opens the git-bash console in the current explorer folder?</p>

答:
As, @Shaswat Rungta said: "I think the question is more about how to add it after the installation is over."

On my PC(Windows 7) I think that the command "Git Bash here" disappeard after I installed Visual Studio 2017.

I fixt this by downloading and installing Git again.

NOTE: "When installing Git for Windows the context menu options are not 'on' by default. You will have to select them during the install." – @nbushnell
(I did this)


问:
JavaScript Globals - Method Handling
I have multiple global arrays that a single method performs operations on. The method will only need to operate on one array at a time. I would like to accomplish this by passing a parameter to the method and then let the method decide which array it needs to modify based on that parameter. For example,

```<code>var globalarray1;
var globalarray2;

Operate(globalarray1);

function Operate(globalarray){
   globalarray.push("test");
}
</code>```

Of course, the code above only changes the value of the array local to the scope of the method. I know I can do something like this:

```<code>var globalarray1;
var globalarray2;

Operate(1);

function Operate(flag){
   if (flag == 1){
      globalarray1.push("test1");
   }
   else if (flag == 2){
      globalarray2.push("test2")
   }
}
</code>```

However, it just doesn't feel right. How can I change the value of the globals using parameters in a single method without using a bunch of conditional statements?

答: .push is a mutator method, and would change the array passed by the method since objects are passed by reference and not value in ECMAScript. So the first way is correct.

Title: JavaScript Globals - Method Handling

Body:
I have multiple global arrays that a single method performs operations on. The method will only need to operate on one array at a time. I would like to accomplish this by passing a parameter to the method and then let the method decide which array it needs to modify based on that parameter. For example,

var globalarray1;
var globalarray2;

Operate(globalarray1);

function Operate(globalarray){
   globalarray.push("test");
}

Of course, the code above only changes the value of the array local to the scope of the method. I know I can do something like this:

var globalarray1;
var globalarray2;

Operate(1);

function Operate(flag){
   if (flag == 1){
      globalarray1.push("test1");
   }
   else if (flag == 2){
      globalarray2.push("test2")
   }
}

However, it just doesn't feel right. How can I change the value of the globals using parameters in a single method without using a bunch of conditional statements?


问:
How to retrieve End-of-Line from a div content editable in jquery?
So Basically I have:

```<code> <div id="hey" contenteditable="true"></div>
</code>```

Which is used as a Text Box. Now the problem is that when you Try inputting something like:

```<code>Hello
How are you
</code>```

(Notice: it contains an End-of-Line after hello). But the output I'm getting is as HelloHow are you But I want it to be as

```<code>Hello
How are you
</code>```

Jsfiddle Test: https://jsfiddle.net/zcyg8q2u/

You can just type two line in the textbox and press the submit button and see the result by yourself.

Much regards

答:
You can use the html() method instead of text(). It will keep the formatting:

```<code>$('#button').on('click', function(){
    var text = $('#hey').html();
    $('#textspan').html(text);
});
</code>```

https://jsfiddle.net/zax8tkxq/

If you plan to save the results in a database and don't want to take care of the sanitization, then another option would be to use a textarea:

```<code><span id="textspan"></span>
<textarea id="hey"></textarea>
<input type="button" id="button" value="Submit" />
</code>```

And add the following CSS property to your container:

```<code>white-space: pre;
</code>```

https://jsfiddle.net/7ngurg3q/

Body:
So Basically I have:

Which is used as a Text Box. Now the problem is that when you Try inputting something like:

Hello
How are you

(Notice: it contains an End-of-Line after hello). But the output I'm getting is as HelloHow are you But I want it to be as

Hello
How are you

Jsfiddle Test: https://jsfiddle.net/zcyg8q2u/

You can just type two line in the textbox and press the submit button and see the result by yourself.

Much regards

Body:
You can use the html() method instead of text(). It will keep the formatting:

$('#button').on('click', function(){
    var text = $('#hey').html();
    $('#textspan').html(text);
});

https://jsfiddle.net/zax8tkxq/

If you plan to save the results in a database and don't want to take care of the sanitization, then another option would be to use a textarea:

<span id="textspan"></span>
<textarea id="hey"></textarea>
<input type="button" id="button" value="Submit" />

And add the following CSS property to your container:

white-space: pre;

https://jsfiddle.net/7ngurg3q/


问:
Convert Fixed format Rpg code to free format
Hi I need to convert fixed format code to Free format as per my companies coding standard instructions. I dont even understand what the below means except that some date movement and conversions are happening..

```<code>C     *ISO          MOVE      BCEXDT        MDYDATE
C                   MOVE      MDYDATE       PEXPDATT
C     *ISO          MOVE      BCSTDT        MDYDATE
C                   MOVE      MDYDATE       PSTRDAT
</code>```

Field definitions below:

```<code>BCEXDT         8S 0
BCSTDT         8S 0
D  MDYDATE        S               D   DATFMT(*MDY)
</code>```

答:
Nobody else is going to be able to tell you what is going on either; without the definitions of the source and target fields.

That's why IBM depreciated the MOVE op-code from free-form.

Body:
Hi I need to convert fixed format code to Free format as per my companies coding standard instructions. I dont even understand what the below means except that some date movement and conversions are happening..

C     *ISO          MOVE      BCEXDT        MDYDATE
C                   MOVE      MDYDATE       PEXPDATT
C     *ISO          MOVE      BCSTDT        MDYDATE
C                   MOVE      MDYDATE       PSTRDAT

Field definitions below:

BCEXDT         8S 0
BCSTDT         8S 0
D  MDYDATE        S               D   DATFMT(*MDY)


问:
Image is not responsive inside carousel using ng2-bootstrap
Anybody know why is the image inside first carousel not responsive?
And how to make it responsive like the second one (Normal Bootstrap version) below. First one was created using ng2-bootstrap

Here is the html I have:

```<code><h1>ng2-bootstrap carousel</h1>
<carousel>
    <slide>
        <img class="first-slide" src="http://placehold.it/800x400" alt="First slide" class="center-block">
        <div class="container">
            <div class="carousel-caption">
                <h1>Example headline.</h1>
                <p>Descr1</p>
                <p><a class="btn btn-lg btn-primary" href="#" role="button">Sign up today</a></p>
            </div>
        </div>
    </slide>
    <slide>
        <img class="second-slide" src="http://placehold.it/800x400" alt="Second slide" class="center-block">
        <div class="container">
            <div class="carousel-caption">
                <h1>Another example headline.</h1>
                <p>Descr2.</p>
                <p><a class="btn btn-lg btn-primary" href="#" role="button">Learn more</a></p>
            </div>
        </div>
    </slide>
</carousel>

<h1>Normal Bootstrap carousel</h1>

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
      <!-- Indicators -->
      <ol class="carousel-indicators">
        <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
        <li data-target="#carousel-example-generic" data-slide-to="1"></li>
        <li data-target="#carousel-example-generic" data-slide-to="2"></li>
      </ol>

      <!-- Wrapper for slides -->
      <div class="carousel-inner">
        <div class="item active">
          <img src="http://placehold.it/800x400" alt="...">
          <div class="carousel-caption">
            <h2>Heading</h2>
          </div>
        </div>
        <div class="item">
          <img src="http://placehold.it/800x400" alt="...">
          <div class="carousel-caption">
            <h2>Heading</h2>
          </div>
        </div>
        <div class="item">
          <img src="http://placehold.it/800x400" alt="...">
          <div class="carousel-caption">
            <h2>Heading</h2>
          </div>
        </div>
      </div>

      <!-- Controls -->
      <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left"></span>
      </a>
      <a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right"></span>
      </a>
    </div>
</code>```

答:
Image treatment for responsive design:

Image scale down-up

```<code>img {
width: 100%;
height: auto;
}
</code>```

Image scale down but no up

```<code>img {
max-width: 100%;
height: auto;
}
</code>```

Background mantain proportion and scale by one axis

```<code>width: 100%;
height: 400px;
background-repeat: no-repeat;
background-size: contain;
background-image: url('img.jpg');
</code>```

Background deforms but adapt to container

```<code>width: 100%;
height: 400px;
background-image: url('img.jpg');
background-size: cover;
</code>```

Body:
Anybody know why is the image inside first carousel not responsive?
And how to make it responsive like the second one (Normal Bootstrap version) below. First one was created using ng2-bootstrap

Here is the html I have:

ng2-bootstrap carousel

<carousel>
    <slide>

Example headline.

Descr1

Sign up today

    </slide>
    <slide>

Another example headline.

Descr2.

Learn more

    </slide>
</carousel>

Normal Bootstrap carousel

Heading

Heading

Heading

Body:
Image treatment for responsive design:

Image scale down-up

img {
width: 100%;
height: auto;
}

Image scale down but no up

img {
max-width: 100%;
height: auto;
}

Background mantain proportion and scale by one axis

width: 100%;
height: 400px;
background-repeat: no-repeat;
background-size: contain;
background-image: url('img.jpg');

Background deforms but adapt to container

width: 100%;
height: 400px;
background-image: url('img.jpg');
background-size: cover;


问:
How do I change the trigger for a modal form from a button to a link?
Please, I kindly need some assistance with a modal form implementation.

The code below was adapted from W3Schools, however, I have a problem changing the modal trigger from a button (as per below, in the full code body) to link.

I have tried replacing the button trigger with:

```<code><a href="id01">Change Password</a>
</code>```

But it won’t work. Upon clicking the link, it requests a non-existent URL. Can some please advise me on how to solve this?

The full code is below:

```<code><div id='changePasswordModalButton'>
                    <!-- Button to open the modal Change Password form -->
                    <button onclick="document.getElementById('id01').style.display = 'block'">Change Password</button>
                </div>

                <!-- The Modal -->
                <div id="id01" class="modal">
                    <span onclick="document.getElementById('id01').style.display = 'none'" class="close" title="Close Modal">×</span>
                    <!-- Modal Content -->
                    <form class="modal-content animate" action="/action_page.php">
                        <div class="container">
                            <label><b>Current Password*</b></label>
                            <input type="password" name="currentPassword" placeholder="Enter your current password" value="" required/>
                            <label><b>New Password*</b></label>
                            <input type="password" name="currentPassword" placeholder="Enter new password" value="" required/>
                            <label><b>Confirm New Password*</b></label>
                            <input type="password" name="currentPassword" placeholder="Confirm new password" value="" required/>
                            <button type="submit">Update Password</button>
                            <div class="container" style="background-color:#f1f1f1">
                                <button type="button" onclick="document.getElementById('id01').style.display = 'none'" class="cancelbtn">Cancel</button>
                            </div>
                            <div id="mandatoryFields">
                                <h4>* Mandatory Fields</h4>
                            </div>
                        </div>
                    </form>
                </div>

                <script>
                    // Get the modal
                    var modal = document.getElementById('id01');
                    // When the user clicks anywhere outside of the modal, close it
                    window.onclick = function (event) {
                        if (event.target === modal) {
                            modal.style.display = "none";
                        }
                    };
                </script>
</code>```

答:
The default action for a click on a link is to follow the link. You will need to prevent that default using Event.preventDefault()

```<code>window.onclick = function (event) {
  if (event.target === modal) {
    event.preventDefault();
    modal.style.display = "none";
  }
};
</code>```

See: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

You should also consider attaching the event handler to the target instead of the window.

```<code>// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
modal.onclick = function (event) {
    event.preventDefault();
    modal.style.display = "none";
};
</code>```

And the modern syntax would be:

```<code>// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
modal.addEventListener( 'click', function (event) {
    event.preventDefault();
    modal.style.display = "none";
}, false);
</code>```

See: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Body:
Please, I kindly need some assistance with a modal form implementation.

The code below was adapted from W3Schools, however, I have a problem changing the modal trigger from a button (as per below, in the full code body) to link.

I have tried replacing the button trigger with:

Change Password

But it won’t work. Upon clicking the link, it requests a non-existent URL. Can some please advise me on how to solve this?

The full code is below:

                    <button onclick="document.getElementById('id01').style.display = 'block'">Change Password</button>

                    ×

                    <form class="modal-content animate" action="/action_page.php">

                            Current Password*
                            <input type="password" name="currentPassword" placeholder="Enter your current password" value="" required/>
                            New Password*
                            <input type="password" name="currentPassword" placeholder="Enter new password" value="" required/>
                            Confirm New Password*
                            <input type="password" name="currentPassword" placeholder="Confirm new password" value="" required/>
                            <button type="submit">Update Password</button>

                                <button type="button" onclick="document.getElementById('id01').style.display = 'none'" class="cancelbtn">Cancel</button>

* Mandatory Fields

                    </form>

Body:
The default action for a click on a link is to follow the link. You will need to prevent that default using Event.preventDefault()

window.onclick = function (event) {
  if (event.target === modal) {
    event.preventDefault();
    modal.style.display = "none";
  }
};

See: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

You should also consider attaching the event handler to the target instead of the window.

// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
modal.onclick = function (event) {
    event.preventDefault();
    modal.style.display = "none";
};

And the modern syntax would be:

// Get the modal
var modal = document.getElementById('id01');
// When the user clicks anywhere outside of the modal, close it
modal.addEventListener( 'click', function (event) {
    event.preventDefault();
    modal.style.display = "none";
}, false);

See: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener


问:
how to get particular metadata tags from files using apache tika
I have some files in a folder(sample.pdf, sample.html etc) and i am using following Apache tika command to extract metadata.

```<code>java -jar tika-app.jar -m -j /sample/sample.pdf > test.txt
</code>```

after executing this command i am able to get all the metadata tags for sample.pdf file, but my requirement is to get particular tags like author, title etc. please suggest me how to use Apache tika to get particular metadata tags.

Thanks

答:
You can extract metadata Names as follow (my example is for parsing XML file, you can simply change it to PDF parser or use auto detect parser:</p>

```<code>//detecting the file type
BodyContentHandler handler = new BodyContentHandler(-1);
Metadata metadata = new Metadata();
File inFile = new File("example.xml");
FileInputStream inputstream = new FileInputStream(inFile);
ParseContext pcontext = new ParseContext();

//Xml parser
XMLParser xmlparser = new XMLParser();
xmlparser.parse(inputstream, handler, metadata, pcontext);

System.out.println("Metadata of the document:");
String[] metadataNames = metadata.names();//Now we have all the metadata tags here

for(String name : metadataNames) {
    if (name == "Your Particular Tag"){ //here you can check if the tag names are the particular ones you need and do what you want with them
        System.out.println(name + ": " + metadata.get(name));
    }
}
</code>```

Body:
I have some files in a folder(sample.pdf, sample.html etc) and i am using following Apache tika command to extract metadata.

java -jar tika-app.jar -m -j /sample/sample.pdf > test.txt

after executing this command i am able to get all the metadata tags for sample.pdf file, but my requirement is to get particular tags like author, title etc. please suggest me how to use Apache tika to get particular metadata tags.

Thanks

Body:
You can extract metadata Names as follow (my example is for parsing XML file, you can simply change it to PDF parser or use auto detect parser:

//detecting the file type
BodyContentHandler handler = new BodyContentHandler(-1);
Metadata metadata = new Metadata();
File inFile = new File("example.xml");
FileInputStream inputstream = new FileInputStream(inFile);
ParseContext pcontext = new ParseContext();

//Xml parser
XMLParser xmlparser = new XMLParser();
xmlparser.parse(inputstream, handler, metadata, pcontext);

System.out.println("Metadata of the document:");
String[] metadataNames = metadata.names();//Now we have all the metadata tags here

for(String name : metadataNames) {
    if (name == "Your Particular Tag"){ //here you can check if the tag names are the particular ones you need and do what you want with them
        System.out.println(name + ": " + metadata.get(name));
    }
}


问:
Laravel 5.4 hasManyTrough 'Call to undefined method Illuminate\Database\Query\Builder::hasManyTrough()'
I am struggling to see, where I went wrong. It seams easy, I followed Laravel instructions https://laravel.com/docs/5.4/eloquent-relationships#has-many-through , but clearly I need someone more familar with this sort of code as whenever I try to fetch $stagingsystem-stagesubtype I get error

BadMethodCallException with message 'Call to undefined method >Illuminate\Database\Query\Builder::hasManyTrough()'

Can someone help?

StagingSystems

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStagingSystemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('staging_systems', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('staging_systems');
    }
}
</code>```

StageName

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStageNamesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('stage_names', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('staging_system_id')->unsigned();
            $table->foreign('staging_system_id')->references('id')->on('staging_systems');

            $table->string('name')->unique;
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('stage_names');
    }
}
</code>```

StageSubType

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStageSubTypesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('stage_sub_types', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('stage_name_id')->unsigned();
            $table->foreign('stage_name_id')->references('id')->on('stage_names');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('stage_sub_types');
    }
}
</code>```

MODELS

StagingSystem

```<code><?php

namespace App;

use App\StagingSystem;
use Illuminate\Database\Eloquent\Model;

class StagingSystem extends Model
{
    protected $guarded = ['id'];

    public function stagename()
    {
        return $this->hasMany('App\StageName');
    }

    public function stagesubtype()
    {
        return $this->hasManyTrough('App\StageSubType','App\StageName');
    }

}
</code>```

StageName

```<code><?php

namespace App;

use App\StageName;
use Illuminate\Database\Eloquent\Model;

class StageName extends Model
{
  protected $guarded = ['id'];

    public function stagingsystem()
    {
        return $this->belongsTo('App\StagingSystem','id');
    }

    public function stagesubtype()
    {
        return $this->hasMany('App\StageSubType');
    }

}
</code>```

StageSubType

```<code><?php

namespace App;

use App\StageSubType;
use Illuminate\Database\Eloquent\Model;

class StageSubType extends Model
{
      protected $guarded = [
        'id'
    ];

    public function stagename()
    {
        return $this->belongsTo('App\StageName');
    }

     public function stagingsystem()
    {
        return $this->belongsTo('App\StagingSystem');
    }

}
</code>```

答: You have mistyped HasManyThrough as hasManyTrough.

Body:
I am struggling to see, where I went wrong. It seams easy, I followed Laravel instructions https://laravel.com/docs/5.4/eloquent-relationships#has-many-through , but clearly I need someone more familar with this sort of code as whenever I try to fetch $stagingsystem-stagesubtype I get error

BadMethodCallException with message 'Call to undefined method >Illuminate\Database\Query\Builder::hasManyTrough()'

Can someone help?

StagingSystems

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStagingSystemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('staging_systems', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('staging_systems');
    }
}

StageName

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStageNamesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('stage_names', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('staging_system_id')->unsigned();
            $table->foreign('staging_system_id')->references('id')->on('staging_systems');

            $table->string('name')->unique;
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('stage_names');
    }
}

StageSubType

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateStageSubTypesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('stage_sub_types', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('stage_name_id')->unsigned();
            $table->foreign('stage_name_id')->references('id')->on('stage_names');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('stage_sub_types');
    }
}

MODELS

StagingSystem

<?php

namespace App;

use App\StagingSystem;
use Illuminate\Database\Eloquent\Model;

class StagingSystem extends Model
{
    protected $guarded = ['id'];

    public function stagename()
    {
        return $this->hasMany('App\StageName');
    }

    public function stagesubtype()
    {
        return $this->hasManyTrough('App\StageSubType','App\StageName');
    }

}

StageName

<?php

namespace App;

use App\StageName;
use Illuminate\Database\Eloquent\Model;

class StageName extends Model
{
  protected $guarded = ['id'];

    public function stagingsystem()
    {
        return $this->belongsTo('App\StagingSystem','id');
    }

    public function stagesubtype()
    {
        return $this->hasMany('App\StageSubType');
    }

}

StageSubType

<?php

namespace App;

use App\StageSubType;
use Illuminate\Database\Eloquent\Model;

class StageSubType extends Model
{
      protected $guarded = [
        'id'
    ];

    public function stagename()
    {
        return $this->belongsTo('App\StageName');
    }

     public function stagingsystem()
    {
        return $this->belongsTo('App\StagingSystem');
    }

}


问:
Popover not showing in button inside table row
I have a table being built via the map function of JavaScript (ReactJS).

On the last column, I should be having buttons that are meant to open a popover that will (eventually) hold some information. This cell is being done like this:

```<code><td>
    <div>
        <button className="btn btn-primary"
                tabIndex="0"
                role="button"
                data-toggle="popover"
                data-trigger="focus"
                title="Details"
                data-content="Testing, Testing">
               <b>IN PIT</b>
         </button>
    </div>
</td>
</code>```

So far, the said button appears, but no popover whatsoever. I'm not using npm or anything of the sorts since I'm not a front-end-designer myself, and that doesn't seem trivial to setup. I just want something "good enough" for testing purposes.

What am I missing?

答: The names of your attributes imply that you are expecting bootstrap (an external library) to be loaded and attach to the element to provide functionality, is bootstrap included in a script tag on the page? Those attributes don't do anything themselves, they are just tags to attach actions to. Add a bootstrap cdn tag inside the bottom of the body tag to address.</p>

Body:
I have a table being built via the map function of JavaScript (ReactJS).

On the last column, I should be having buttons that are meant to open a popover that will (eventually) hold some information. This cell is being done like this:

        <button className="btn btn-primary"
                tabIndex="0"
                role="button"
                data-toggle="popover"
                data-trigger="focus"
                title="Details"
                data-content="Testing, Testing">
               IN PIT
         </button>

So far, the said button appears, but no popover whatsoever. I'm not using npm or anything of the sorts since I'm not a front-end-designer myself, and that doesn't seem trivial to setup. I just want something "good enough" for testing purposes.

What am I missing?


问:
When to call notify in RecyclerView.Adapter?
Will notify* methods in RecyclerView.Adapter run view's callbacks in UI thread automagically or have I to explicitly switch from my job's thread?

答: Whenever you interact with a View in android you must do it on the UI thread. This includes recyclerviews and their adapters.


问:
Borders around a CALayer mask
I'll start off showing you what I need the end product to look like.

I'm using a cocoapod called BAFluidView that basically simulates the motion of fluid in a container. The developer provided a guide(see the "Use As a Layer" section) showing how you could add a mask to the fluidView's layer for an effect.

So far, I can mask the fluiview with any UIImage I add to the project.  I am, however, facing a problem trying to add a white border around the outline of the water droplet and could use any help I can get.

Thanks very much!

答:
This is what I would call the "brute force" method. Create an image to use as the mask and create a second image to use as the outline.

Note: these images have alpha channels, so it may not be clear unless/until you download them. The checkerboard images shows how they look in GIMP.

Mask Image (which I took from the BAFluidView example):

 -

White outline image (trust me, it's here... just click below):

 -

and the code:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // load mask and outline
    UIImage *maskingImage = [UIImage imageNamed:@"blueDrop"];
    UIImage *outlineImage = [UIImage imageNamed:@"whiteOutlineThin"];

    // define rect equal to size of mask image
    CGRect rfv = CGRectMake(0, 0, maskingImage.size.width, maskingImage.size.height);

    // instantiate BAFluidView
    BAFluidView *fluidView = [[BAFluidView alloc] initWithFrame:rfv startElevation:@0.3];
    fluidView.fillColor = [UIColor colorWithHex:0x092eee];
    [fluidView fillTo:@0.90];
    [fluidView startAnimation];

    // if you want the "droplet" filled with a color
    //  fluidView.backgroundColor = [UIColor yellowColor];

    // instantiate a couple CALayer objects
    CALayer *maskingLayer = [CALayer layer];
    CALayer *outlineLayer = [CALayer layer];

    // set size to match mask
    maskingLayer.frame = rfv;
    outlineLayer.frame = rfv;

    // set mask layer content to mask image
    [maskingLayer setContents:(id)[maskingImage CGImage]];

    // give the mask layer to BAFluidView
    [fluidView.layer setMask:maskingLayer];

    // set outline layer content to outline image
    [outlineLayer setContents:(id)[outlineImage CGImage]];

    // create a "container" view
    UIView *containerView = [[UIView alloc] initWithFrame:rfv];

    // add the outline layer
    [containerView.layer addSublayer:outlineLayer];

    // add the BAFluidView
    [containerView addSubview:fluidView];

    // add the container view to the screen / main view
    [self.view addSubview:containerView];

    // position the view with constraints...
    containerView.translatesAutoresizingMaskIntoConstraints = NO;

    [containerView.widthAnchor constraintEqualToConstant:rfv.size.width].active = YES;
    [containerView.heightAnchor constraintEqualToConstant:rfv.size.height].active = YES;
    [containerView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = YES;
    [containerView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = YES;

}
</code>```

Screen-cap of the result:

You could automate it, and make the process a bit more "elegant" and flexible, by using just the Mask image and generating the outline on-the-fly via code - scale the mask image up by a little bit and then mask it with the original sized image, for example.

Title: Borders around a CALayer mask

Body:
This is what I would call the "brute force" method. Create an image to use as the mask and create a second image to use as the outline.

Note: these images have alpha channels, so it may not be clear unless/until you download them. The checkerboard images shows how they look in GIMP.

Mask Image (which I took from the BAFluidView example):

 -

White outline image (trust me, it's here... just click below):

 -

and the code:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // load mask and outline
    UIImage *maskingImage = [UIImage imageNamed:@"blueDrop"];
    UIImage *outlineImage = [UIImage imageNamed:@"whiteOutlineThin"];

    // define rect equal to size of mask image
    CGRect rfv = CGRectMake(0, 0, maskingImage.size.width, maskingImage.size.height);

    // instantiate BAFluidView
    BAFluidView *fluidView = [[BAFluidView alloc] initWithFrame:rfv startElevation:@0.3];
    fluidView.fillColor = [UIColor colorWithHex:0x092eee];
    [fluidView fillTo:@0.90];
    [fluidView startAnimation];

    // if you want the "droplet" filled with a color
    //  fluidView.backgroundColor = [UIColor yellowColor];

    // instantiate a couple CALayer objects
    CALayer *maskingLayer = [CALayer layer];
    CALayer *outlineLayer = [CALayer layer];

    // set size to match mask
    maskingLayer.frame = rfv;
    outlineLayer.frame = rfv;

    // set mask layer content to mask image
    [maskingLayer setContents:(id)[maskingImage CGImage]];

    // give the mask layer to BAFluidView
    [fluidView.layer setMask:maskingLayer];

    // set outline layer content to outline image
    [outlineLayer setContents:(id)[outlineImage CGImage]];

    // create a "container" view
    UIView *containerView = [[UIView alloc] initWithFrame:rfv];

    // add the outline layer
    [containerView.layer addSublayer:outlineLayer];

    // add the BAFluidView
    [containerView addSubview:fluidView];

    // add the container view to the screen / main view
    [self.view addSubview:containerView];

    // position the view with constraints...
    containerView.translatesAutoresizingMaskIntoConstraints = NO;

    [containerView.widthAnchor constraintEqualToConstant:rfv.size.width].active = YES;
    [containerView.heightAnchor constraintEqualToConstant:rfv.size.height].active = YES;
    [containerView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = YES;
    [containerView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = YES;

}

Screen-cap of the result:

You could automate it, and make the process a bit more "elegant" and flexible, by using just the Mask image and generating the outline on-the-fly via code - scale the mask image up by a little bit and then mask it with the original sized image, for example.


问:
How to get the value of the hidden field next to the clicked checkbox?
I've this two elements next to each other. The hidden field contains the ID of the record. When the user check/uncheck the checkbox, I should be able to retrieve the record's ID.

```<code><asp:CheckBox ID="ckEdit" runat="server" CssClass="ckEditClass" />
<asp:HiddenField ID="hfEdit" Value='<%# Eval("ID") %>' runat="server" />
</code>```

This is what I'm trying to do:

```<code>$(".ckEditClass").on("click", function () {
    var hidden = $(this).parent().parent().children(":hidden")
    alert(hidden.val());
 })
</code>```

I'm getting undefined.

EDIT

The above code is from Visual Studio. However, when I look at F12, I see a  around the checkbox. Hope this information will help.

```<code><td>
    <span class="ckEditClass">
          <asp:CheckBox ID="ckEdit" runat="server" CssClass="ckEditClass" />
    </span>
    <asp:HiddenField ID="hfEdit" Value='<%# Eval("ID") %>' runat="server" />
</td>
</code>```

答:
You can try this way

```<code>$(".ckEditClass").on("click", function () {
   var hidden= $(this).next(input[type="hidden"]);
   alert(hidden.val());
});
</code>```

It will check next component of given type and will return it. Then you can alert its value.

Hope it helps

Body:
I've this two elements next to each other. The hidden field contains the ID of the record. When the user check/uncheck the checkbox, I should be able to retrieve the record's ID.

<asp:CheckBox ID="ckEdit" runat="server" CssClass="ckEditClass" />
<asp:HiddenField ID="hfEdit" Value='<%# Eval("ID") %>' runat="server" />

This is what I'm trying to do:

$(".ckEditClass").on("click", function () {
    var hidden = $(this).parent().parent().children(":hidden")
    alert(hidden.val());
 })

I'm getting undefined.

EDIT

The above code is from Visual Studio. However, when I look at F12, I see a  around the checkbox. Hope this information will help.

          <asp:CheckBox ID="ckEdit" runat="server" CssClass="ckEditClass" />

    <asp:HiddenField ID="hfEdit" Value='<%# Eval("ID") %>' runat="server" />

Body:
You can try this way

$(".ckEditClass").on("click", function () {
   var hidden= $(this).next(input[type="hidden"]);
   alert(hidden.val());
});

It will check next component of given type and will return it. Then you can alert its value.

Hope it helps


问:
Angular, Calling a function with ng-click work only once with ng-route
I add a ng-click inside a ng-repeat, i want to get the single item in the loop, it work well but only once.

```<code>ng-repeat="item in Playlist.item" ng-click="getSingleItem(item)"
</code>```

in my controller

$scope.getSingleItem = function (item) {
    console.log(item);
  }

If i click i get the item object in my console log, this click is a href and send me to the next page with ng-route.
But if i go back and click the same link or another link, it won't work.

it fire only once.

UPDATE!
i just find out that with my own href directive and the ng-click it work only once, but if i just add a $timeout in my own directive it will work.

答:
You have an error in your HTML code. You're missing a comma in that line.
This should be:

ng-repeat="item in Playlist.item" ng-click="getSingleItem(item)"

Body:
I add a ng-click inside a ng-repeat, i want to get the single item in the loop, it work well but only once.

ng-repeat="item in Playlist.item" ng-click="getSingleItem(item)"

in my controller

$scope.getSingleItem = function (item) {
    console.log(item);
  }

If i click i get the item object in my console log, this click is a href and send me to the next page with ng-route.
But if i go back and click the same link or another link, it won't work.

it fire only once.

UPDATE!
i just find out that with my own href directive and the ng-click it work only once, but if i just add a $timeout in my own directive it will work.


问:
Javascript: How to get/select all object with same keys?
I have object like this:

```<code>[
  {
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  },
  {
    "id": 3,
    "name": "App 3",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app3",
    "kat": "tei"
  },
  {
    "id": 4,
    "name": "App 4",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app4",
    "kat": "tei"
  },
  {
    "id": 5,
    "name": "App 5",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app5",
    "kat": "tei"
  }
]
</code>```

How i get/select all object with same keys (kat) in javascript?

example i want to get all object with kat=tkj will return:

```<code>[{
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  }]
</code>```

Thanks for your help ^_^

答:
Try alert($('[id=x1]').length);

here x1 is id.

and loop using $("[x1]").each(function(){}

Body:
I have object like this:

[
  {
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  },
  {
    "id": 3,
    "name": "App 3",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app3",
    "kat": "tei"
  },
  {
    "id": 4,
    "name": "App 4",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app4",
    "kat": "tei"
  },
  {
    "id": 5,
    "name": "App 5",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app5",
    "kat": "tei"
  }
]

How i get/select all object with same keys (kat) in javascript?

example i want to get all object with kat=tkj will return:

[{
    "id": 1,
    "name": "App 1",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app1",
    "kat": "tkj"
  },
  {
    "id": 2,
    "name": "App 2",
    "desc": "Donec rutrum congue leo eget malesuada. Curabitur aliquet quam id dui posuere blandit. Nulla quis lorem ut libero malesuada feugiat. Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat.",
    "nick": "app2",
    "kat": "tkj"
  }]

Thanks for your help ^_^


问:
Visual Studio - Can I open aspx and code file with one action?
Right now, I don't have the "Show All Files" option selected - that means I only see the .aspx files in my web application project, and don't see the .vb or .designer.vb files.

I can open the code by right-clicking on the aspx, and selecting "View Code", but it would be really nice if there was a way to double-click on the aspx file and have it open both the aspx and the aspx.vb.

Is this possible?

答:
F7 will show the code behind when you're in the design view

Shift + F7 will show the design view when you're in code behind

thats the fastest way to switch and I think the best way to achieve your goal of switching between files.

if you mean you want a split screen that isn't possible - at least without extensions

Edit: I just discovered that you can single click (or otherwise select via the keyboard) on the item itself in the solution explorer and hit either F7 or Shift+F7 there to directly open the code or designer directly. No double click needed. Never realized that before ;-)


问:
model.$setValidity don't work for $asyncValidators
I'm using the same code as in this question angularjs: custom directive to check if a username exists

I have code like this:

```<code>export default function(rpc) {
    return {
        restrict: 'AE',
        require: 'ngModel',
        link: function(scope, elm, attr, model) {
            rpc.then((service) => {
                model.$asyncValidators.usernameExists = function() {
                    return service.username_taken(model.$viewValue).then((taken) => {
                        console.log(!taken);
                        model.$setValidity('usernameExists', !taken);
                    });
                };
            });
        }
    };
};

import angular from 'angular';
import usernameExists from './usernameExists';

var module = angular.module('directives', [])
    .directive('usernameExists', usernameExists);

export default module;
</code>```

template:

```<code><form name="register">
    <div>
        <label for="username">username:</label>
        <input type="text" id="username" name="username" placeholder="username"
               ng-model="ctrl.username" ng-model-options="{ debounce: 1000 }"
               username-exists />
        <div ng-if="register.username.$error.usernameExists">username already exists</div>
    </div>
</form>
</code>```

and when I type username that exists I've get http request and I've get false in console but the input is valid and I don't get error message. If I type username that don't exists I've got true from console and the same the input is valid. What is going on? The code is the same as in the answer to the question I linked.

答:
It seems that $timeout is required even if it's 0:

```<code>function usernameExists(rpc, $timeout) {
    return {
        restrict: 'AE',
        require: 'ngModel',
        link: function(scope, elm, attr, model) {
            rpc.then((service) => {
                model.$asyncValidators.usernameExists = function() {
                    return service.username_taken(model.$viewValue).then((taken) => {
                        console.log(!taken);
                        $timeout(() => {
                            model.$setValidity('usernameExists', !taken);
                        }, 0);
                    });
                };
            });
        }
    };
}
</code>```

the other option is to use model.$validators.usernameExists if you're returning a promise:

```<code>function usernameExists(rpc, $timeout) {
    return {
        restrict: 'AE',
        require: 'ngModel',
        link: function(scope, elm, attr, model) {
            rpc.then((service) => {
                model.$validators.usernameExists = function() {
                    return service.username_taken(model.$viewValue).then((taken) => {
                        model.$setValidity('usernameExists', !taken);
                    });
                };
            });
        }
    };
}
</code>```

Body:
I'm using the same code as in this question angularjs: custom directive to check if a username exists

I have code like this:

export default function(rpc) {
    return {
        restrict: 'AE',
        require: 'ngModel',
        link: function(scope, elm, attr, model) {
            rpc.then((service) => {
                model.$asyncValidators.usernameExists = function() {
                    return service.username_taken(model.$viewValue).then((taken) => {
                        console.log(!taken);
                        model.$setValidity('usernameExists', !taken);
                    });
                };
            });
        }
    };
};

import angular from 'angular';
import usernameExists from './usernameExists';

var module = angular.module('directives', [])
    .directive('usernameExists', usernameExists);

export default module;

template:

<form name="register">

        username:
        <input type="text" id="username" name="username" placeholder="username"
               ng-model="ctrl.username" ng-model-options="{ debounce: 1000 }"
               username-exists />

username already exists

</form>

and when I type username that exists I've get http request and I've get false in console but the input is valid and I don't get error message. If I type username that don't exists I've got true from console and the same the input is valid. What is going on? The code is the same as in the answer to the question I linked.

Body:
It seems that $timeout is required even if it's 0:

function usernameExists(rpc, $timeout) {
    return {
        restrict: 'AE',
        require: 'ngModel',
        link: function(scope, elm, attr, model) {
            rpc.then((service) => {
                model.$asyncValidators.usernameExists = function() {
                    return service.username_taken(model.$viewValue).then((taken) => {
                        console.log(!taken);
                        $timeout(() => {
                            model.$setValidity('usernameExists', !taken);
                        }, 0);
                    });
                };
            });
        }
    };
}

the other option is to use model.$validators.usernameExists if you're returning a promise:

function usernameExists(rpc, $timeout) {
    return {
        restrict: 'AE',
        require: 'ngModel',
        link: function(scope, elm, attr, model) {
            rpc.then((service) => {
                model.$validators.usernameExists = function() {
                    return service.username_taken(model.$viewValue).then((taken) => {
                        model.$setValidity('usernameExists', !taken);
                    });
                };
            });
        }
    };
}


答:
If I understand correctly, you want to change this button:

```<code><button onclick="document.getElementById('id01').style.display = 'block'">Change Password</button>
</code>```

with a link.

To do it, the steps are:

replace button with a (but keep all the attributes)

add an href attribute. Since you won't use it, let's make it point to the current page using #.

prevent the link's default behavior (i.e. to try to open a page on click) by adding a return false at the end of the onclick attribute.

The result is:

```<code> <a href="#"
    onclick="document.getElementById('id01').style.display = 'block'; return false">Change Password
 </a>
</code>```

Note that using an onclick attribute is not the best way to go. A better way would be to use an event listener, as you did for the close event:

```<code>document.getElementById("myLink").addEventListener("click", function(event){
    event.preventDefault(); // instead of "return false"
    document.getElementById('id01').style.display = 'block';
});
</code>```

Using this solution, don't forget to remove the onclick attribute and to add an id to your link:

```<code> <a href="#" id="myLink">Change Password</a>
</code>```

See https://www.w3schools.com/jsref/event_preventdefault.asp and https://www.w3schools.com/jsref/event_onclick.asp for more details.

Title: How do I change the trigger for a modal form from a button to a link?

Body:
If I understand correctly, you want to change this button:

<button onclick="document.getElementById('id01').style.display = 'block'">Change Password</button>

with a link.

To do it, the steps are:

replace button with a (but keep all the attributes)

add an href attribute. Since you won't use it, let's make it point to the current page using #.

prevent the link's default behavior (i.e. to try to open a page on click) by adding a return false at the end of the onclick attribute.

The result is:

 <a href="#"
    onclick="document.getElementById('id01').style.display = 'block'; return false">Change Password
 </a>

Note that using an onclick attribute is not the best way to go. A better way would be to use an event listener, as you did for the close event:

document.getElementById("myLink").addEventListener("click", function(event){
    event.preventDefault(); // instead of "return false"
    document.getElementById('id01').style.display = 'block';
});

Using this solution, don't forget to remove the onclick attribute and to add an id to your link:

 <a href="#" id="myLink">Change Password</a>

See https://www.w3schools.com/jsref/event_preventdefault.asp and https://www.w3schools.com/jsref/event_onclick.asp for more details.


答:
Not sure if you have posted the correct code, your ng-click should be placed outside ng-repeat,</p>

```<code>ng-repeat="item in Playlist.item" ng-click="getSingleItem(item)"
</code>```

Title: Angular, Calling a function with ng-click work only once with ng-route

Body:
Not sure if you have posted the correct code, your ng-click should be placed outside ng-repeat,

ng-repeat="item in Playlist.item" ng-click="getSingleItem(item)"


问:
add image beside woocommerce product description in tab
I am trying to place an image next to the product description in the tabs of woocommerce. The code I am trying to use is this:

```<code>add_action('woocommerce_template_product_description', 'badge', 25);
        function badge() {
        echo '<div class="badge"><img src="URL" style="width:175px;height:175px;"></div>';
        }
</code>```

I have not had any luck in getting it to display, and am thinking that the 'woocommerce_template_product_description' maybe the problem - I'm sure if I am targeting the product description correctly. I think tabs are increasing the complexity of the solution.

Using the code below the image displays next to the product summary.

```<code>add_action('woocommerce_single_product_summary', 'badge', 25);
        function badge() {
        echo '<div class="badge"><img src="URL" style="width:175px;height:175px;"></div>';
        }
</code>```

I would appreciate some help is solving this problem.

答:
After much head scratching I think I might have figured it out. This code seems to work:</p>

```<code>add_filter( 'woocommerce_product_tabs', 'magva_badge', 98 );
       function magva_badge( $tabs ) {

       $tabs['description']['callback'] = 'woo_custom_description_tab_content'; // Custom description callback

       return $tabs;
   }

    function woo_custom_description_tab_content() {
        woocommerce_product_description_tab(); echo '<div class="magva_badge"><img src="https://www.magva.com/wp-content/uploads/2015/10/made_in_ireland.png" style="width:175px;height:175px;"></div>';
       }
</code>```

Body:
I am trying to place an image next to the product description in the tabs of woocommerce. The code I am trying to use is this:

add_action('woocommerce_template_product_description', 'badge', 25);
        function badge() {
        echo '

';
        }

I have not had any luck in getting it to display, and am thinking that the 'woocommerce_template_product_description' maybe the problem - I'm sure if I am targeting the product description correctly. I think tabs are increasing the complexity of the solution.

Using the code below the image displays next to the product summary.

add_action('woocommerce_single_product_summary', 'badge', 25);
        function badge() {
        echo '

';
        }

I would appreciate some help is solving this problem.

Body:
After much head scratching I think I might have figured it out. This code seems to work:

add_filter( 'woocommerce_product_tabs', 'magva_badge', 98 );
       function magva_badge( $tabs ) {

       $tabs['description']['callback'] = 'woo_custom_description_tab_content'; // Custom description callback

       return $tabs;
   }

    function woo_custom_description_tab_content() {
        woocommerce_product_description_tab(); echo '<div class="magva_badge"><img src="https://www.magva.com/wp-content/uploads/2015/10/made_in_ireland.png" style="width:175px;height:175px;"></div>';
       }


问:
Working with sql server metadata in c#
Are there any tools out there that encapsulate the retrieval of SQL Server metadata into a nice object model?

My immediate needs are to gather these things from SQL Server 2000-2008 R2:

Databases

Tables

Foreign key constraints

Triggers

So, maybe given a SqlConnection object, I could do things like this:

```<code>var dbs = conn.GetDatabases();
var db = dbs.Single(x => x.Name == "AdventureWorks");
var tables = db.GetTables();
var triggers = db.GetAllTriggers();
</code>```

Of course, those examples would be very convenient, but any sort of object model would be better than what I'm doing now. Before I build my own, is there anything out there?

答: You might want to look at SQL Server Management Objects.</p>

Title: Working with sql server metadata in c#

Body:
Are there any tools out there that encapsulate the retrieval of SQL Server metadata into a nice object model?

My immediate needs are to gather these things from SQL Server 2000-2008 R2:

Databases

Tables

Foreign key constraints

Triggers

So, maybe given a SqlConnection object, I could do things like this:

var dbs = conn.GetDatabases();
var db = dbs.Single(x => x.Name == "AdventureWorks");
var tables = db.GetTables();
var triggers = db.GetAllTriggers();

Of course, those examples would be very convenient, but any sort of object model would be better than what I'm doing now. Before I build my own, is there anything out there?


问:
IntelliJ build wrong JAR: Could not find or load main class
I have a simple example

public class FileSystemReadFile {
    public static void main(String[] args) throws IOException {
        System.out.println("Reading the file" + args[0]);
    }
}
```

which is created in IntelliJ where I want to build JAR file; So what I did:

Added Artifact with dependencies (presumably I have some);

Ensure that MANIFEST.MF is located in src\main\resources\META-INF\ as it is already mentioned somewhere here on the site.

Run Artifact build which gave me JAR file in out folder and I run that jar file that said me "Could not find or load main class"
 java <name>.jar

You may see that main class is added into MANIFEST and location of manifest is also fine.

When I open that created JAR file, I see the same MANIFEST content, I see lots of dependency modules, but I don't see my class!

I suspect that is a cause. Any ideas?

答:
If you include any signed JARs in your app and then use IntelliJ to build artifacts, it will extract the JARS and bundle them with your compiled output.

This then causes a JAVA security exception. I've seen this with Eclipse Paho and Bouncy Castle which are signed.

You can check if any of the library JARs you are using are signed using the jarsigner tool.

```<code>jarsigner -verify -verbose  <path to library JAR>
</code>```

Change your IntelliJ artifact setup so that these get bundled as libraries instead of being extracted. Extraction invalidates the certificate as you'd expect.

Try creating a dummy project with just Main. Add 1 library JAR (that you are trying to build with) at a time. Build an output JAR each time until Main breaks. That's how I found this.

IntelliJ should warn you.....

Body:
I have a simple example

public class FileSystemReadFile {
    public static void main(String[] args) throws IOException {
        System.out.println("Reading the file" + args[0]);
    }
}

which is created in IntelliJ where I want to build JAR file; So what I did:

Added Artifact with dependencies (presumably I have some);

Ensure that MANIFEST.MF is located in src\main\resources\META-INF\ as it is already mentioned somewhere here on the site.

Run Artifact build which gave me JAR file in out folder and I run that jar file that said me "Could not find or load main class"
 java <name>.jar

You may see that main class is added into MANIFEST and location of manifest is also fine.

When I open that created JAR file, I see the same MANIFEST content, I see lots of dependency modules, but I don't see my class!

I suspect that is a cause. Any ideas?

Body:
If you include any signed JARs in your app and then use IntelliJ to build artifacts, it will extract the JARS and bundle them with your compiled output.

This then causes a JAVA security exception. I've seen this with Eclipse Paho and Bouncy Castle which are signed.

You can check if any of the library JARs you are using are signed using the jarsigner tool.

jarsigner -verify -verbose  <path to library JAR>

Change your IntelliJ artifact setup so that these get bundled as libraries instead of being extracted. Extraction invalidates the certificate as you'd expect.

Try creating a dummy project with just Main. Add 1 library JAR (that you are trying to build with) at a time. Build an output JAR each time until Main breaks. That's how I found this.

IntelliJ should warn you.....