问:
How to use InetOrgPersonContextMapper class
I'm authenticated and authorise to Active Directory by Spring Security.
But can not retrive LDAP attributes, for example MAIL.
I trying use InetOrgPersonContextMapper for it...

```<code>@Bean
public InetOrgPersonContextMapper inetOrgPersonContextMapper(){
    InetOrgPersonContextMapper contextMapper = new InetOrgPersonContextMapper();
    return contextMapper;
}
 @Bean
public LdapAuthenticationProvider ldapAuthenticationProvider(){
    LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(ldapAuthenticator(),ldapAuthoritiesPopulator());
    ldapAuthenticationProvider.setUserDetailsContextMapper(inetOrgPersonContextMapper());
    return ldapAuthenticationProvider;
}
</code>```

but when i trying retrive attributes in controller to i get ClassCastExeption

```<code>Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    InetOrgPerson person = (InetOrgPerson)auth.getPrincipal();
</code>```

Please tell me correct way for reitrive attributes.

答:
I guess it's no better way, but it's working.
If anybody know how can do it better, please tell me.</p>

```<code>@Bean
public UserDetailsContextMapper userDetailsContextMapper(){
    return new LdapUserDetailsMapper(){
        @Override
        public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
            InetOrgPersonContextMapper personContextMapper = new InetOrgPersonContextMapper();
            UserDetails cm = personContextMapper.mapUserFromContext(ctx,username,authorities);
            String MAIL = ((InetOrgPerson)(personContextMapper.mapUserFromContext(ctx,username,authorities))).getMail();
            String FullName = ((InetOrgPerson)(personContextMapper.mapUserFromContext(ctx,username,authorities))).getDisplayName();
            System.out.println("MAIL: " + MAIL + " Full Name: " + FullName);
            return cm;
        }
    };
}
</code>```

Body:
I'm authenticated and authorise to Active Directory by Spring Security.
But can not retrive LDAP attributes, for example MAIL.
I trying use InetOrgPersonContextMapper for it...

@Bean
public InetOrgPersonContextMapper inetOrgPersonContextMapper(){
    InetOrgPersonContextMapper contextMapper = new InetOrgPersonContextMapper();
    return contextMapper;
}
 @Bean
public LdapAuthenticationProvider ldapAuthenticationProvider(){
    LdapAuthenticationProvider ldapAuthenticationProvider = new LdapAuthenticationProvider(ldapAuthenticator(),ldapAuthoritiesPopulator());
    ldapAuthenticationProvider.setUserDetailsContextMapper(inetOrgPersonContextMapper());
    return ldapAuthenticationProvider;
}

but when i trying retrive attributes in controller to i get ClassCastExeption

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    InetOrgPerson person = (InetOrgPerson)auth.getPrincipal();

Please tell me correct way for reitrive attributes.

Body:
I guess it's no better way, but it's working.
If anybody know how can do it better, please tell me.

@Bean
public UserDetailsContextMapper userDetailsContextMapper(){
    return new LdapUserDetailsMapper(){
        @Override
        public UserDetails mapUserFromContext(DirContextOperations ctx, String username, Collection<? extends GrantedAuthority> authorities) {
            InetOrgPersonContextMapper personContextMapper = new InetOrgPersonContextMapper();
            UserDetails cm = personContextMapper.mapUserFromContext(ctx,username,authorities);
            String MAIL = ((InetOrgPerson)(personContextMapper.mapUserFromContext(ctx,username,authorities))).getMail();
            String FullName = ((InetOrgPerson)(personContextMapper.mapUserFromContext(ctx,username,authorities))).getDisplayName();
            System.out.println("MAIL: " + MAIL + " Full Name: " + FullName);
            return cm;
        }
    };
}


来源: stackexchange

问:
Prevent validation when you have hide field Codeigniter
I am doing an airline reservation and I have 2 radio button.

1) One way

2) Round Trip

The things that I've done is when I select the Round Trip, all the fields are there(Depart, return and number of passengers) but I when select One way radio button the return field should hide.

In my controller, I have validation that all fields are required. The problem is, whenever I tried to search in One Way(the return field is hidden) it gives me an "Return field is required" error

Question: How can I prevent the validation in return field when I choice the One Way radio button?

View

```<code><div class="pure-u-1-1 searchcontainer center">
            <div class="pure-u-1-1 findcheaptxt">
               <span>Find Cheap Flights</span>
            </div>
            <div class="pure-u-1-1 radiobtn">
               <form action="">
                  <input type="radio" name="flight_type"  value="one_way" class="onew" style=""  >One Way
                  <input type="radio" name="flight_type" class="roundw" style="" checked>Round Trip
               </form>
            </div>

            <form method="post" enctype="multipart/form-data" action="<?= base_url() .'User/search'?>">
            <?= validation_errors(); ?>
            <div class="pure-u-1-1 fromto">
               <div class="pure-u-1-1">
                  <label for="from" class="margin2px">From</label>

                  <select name="flight_from">
                    <option value="">-- Please select depature --</option>
                    <?php foreach($countries as $country):?>
                        <option value ="<?= $country->country_name?>" ><?= $country->country_name?></option>
                    <?php endforeach?>

                  </select>

               </div>
                <div class="pure-u-1-1">
                  <label for="to" class="tomargin">To</label>
                  <!-- <input type="text" class="fromto"><br> -->
                  <select class="fromto" name="flight_to">
                    <option value="">-- Please select destination --</option>
                    <?php foreach($countries as $country):?>
                        <option value ="<?= $country->country_name?>" ><?= $country->country_name?></option>
                    <?php endforeach?>
                  </select>
                </div>
               <div class="pure-u-1-1 dr" name ="depart">
                  <label for="depart" class="drr">Depart</label>
                  <input type="date" id="depart" name="depart" class="departreturn">

               </div>
                <div class="pure-u-1-1 dr" id="try">
                  <label for="return" class="drr">Return</label>
                  <input type="date" id="return" name="return" class="departreturn"><br>

                  </div>
            </div>

            <div class="pure-u-1-1 personfield">
                <!--  <div class="pure-u-1-5 margin">
                    Adult<br>
                    <input type="text" name="" class="person">
                 </div>
                 <div class="pure-u-1-5 margin">
                    Seniors<br>
                    <input type="text" name="" class="person">
                 </div>
                 <div class="pure-u-1-5 margin">
                    Children<br>
                    <input type="text" name="" class="person">
                 </div>
                 <div class="pure-u-1-5">
                    Class<br>
                    <input type="text" name="" class="person">
                 </div> -->
                  <div class="pure-u-1-5 margin">
                    Number of Passengers<br>
                    <input type="text" name="no_of_passengers" class="person">
                 </div>

            </div>
                 <div class="pure-u-1-1 center">
                      <button class="submitbtn">Search Now</button>
               </form>
            </div>
         </div>
      </div>
</code>```

Controller

```<code>public function search()
{
    $data['countries'] = $this->CrudModel->get('countries');
    $this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');
    $this->form_validation->set_rules('flight_from', 'Select depature', 'required|trim');
    $this->form_validation->set_rules('flight_to', 'Select Destination', 'required|trim');

    if ($_POST['flight_type'] == 'round_trip')
    {
        $this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');
        $this->form_validation->set_rules('return', 'Date of return', 'required|trim');
        $this->form_validation->set_rules('no_of_passengers', 'Number of Passengers', 'required');
        if ($this->form_validation->run() == FALSE)
        {
            $this->index();

        }
        else
        {
            $search_result = array(
                $flight_from = $_POST['flight_from'],
                $flight_to = $_POST['flight_to'],
                $depart = $_POST['depart'],
                $return = $_POST['return'],
                $no_of_passengers = $_POST['no_of_passengers']
            );
            $data['search_result'] = $this->CrudModel->search('flight',$flight_from,$flight_to,$depart,$return,$no_of_passengers);
            $this->load->view('partials/header');
            $this->load->view('partials/nav');
            $this->load->view('result',$data);
        }

    }
    else
    {
        $this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');
        $this->form_validation->set_rules('no_of_passengers', 'Number of Passengers', 'required');
        if ($this->form_validation->run() == FALSE)
        {
            $this->index();

        }
        else {
            $search_result = array(
                $flight_from = $_POST['flight_from'],
                $flight_to = $_POST['flight_to'],
                $depart = $_POST['depart'],
                $no_of_passengers = $_POST['no_of_passengers']
            );
        $data['search_result'] = $this->CrudModel->search('flight',$flight_from,$flight_to,$depart,$no_of_passengers);
        $this->load->view('partials/header');
        $this->load->view('partials/nav');
        $this->load->view('result',$data);
        }

    }
}
</code>```

My ajax/js when hiding the return field

```<code> <script type="text/javascript">
$(document).on('change', 'input:radio[name=flight_type]', function(){
    $('div[id^="try"]').toggle(); // hide all DIVs begining with "my_radio_"
    $('#' + $(this).attr('id') + '_text').show(); // show the current one
});
</script>
</code>```

答:
You have to pass flight_type parameters in post request. Then your code will be something like this describe below.

```<code>$this->form_validation->set_rules('flight_from', 'Select depature', 'required|trim');
$this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');

if($this->input->post('flight_type')== 'roundw'):
    $this->form_validation->set_rules('flight_to', 'Select Destination', 'required|trim');
    $this->form_validation->set_rules('return', 'Date of return', 'required|trim');
endif:
</code>```

Let me know if it not works for you.

ContentLicense: CC BY-SA 3.0

Body:
I am doing an airline reservation and I have 2 radio button.

1) One way

2) Round Trip

The things that I've done is when I select the Round Trip, all the fields are there(Depart, return and number of passengers) but I when select One way radio button the return field should hide.

In my controller, I have validation that all fields are required. The problem is, whenever I tried to search in One Way(the return field is hidden) it gives me an "Return field is required" error

Question: How can I prevent the validation in return field when I choice the One Way radio button?

View

               Find Cheap Flights

               <form action="">
                  <input type="radio" name="flight_type"  value="one_way" class="onew" style=""  >One Way
                  <input type="radio" name="flight_type" class="roundw" style="" checked>Round Trip
               </form>

            <form method="post" enctype="multipart/form-data" action="<?= base_url() .'User/search'?>">
            <?= validation_errors(); ?>

                  From

                  <select name="flight_from">
                    <option value="">-- Please select depature --</option>
                    <?php foreach($countries as $country):?>
                        <option value ="<?= $country->country_name?>" ><?= $country->country_name?></option>
                    <?php endforeach?>

                  </select>

                  To

                  <select class="fromto" name="flight_to">
                    <option value="">-- Please select destination --</option>
                    <?php foreach($countries as $country):?>
                        <option value ="<?= $country->country_name?>" ><?= $country->country_name?></option>
                    <?php endforeach?>
                  </select>

                  Depart
                  <input type="date" id="depart" name="depart" class="departreturn">

                  Return
                  <input type="date" id="return" name="return" class="departreturn">

                    Number of Passengers

                    <input type="text" name="no_of_passengers" class="person">

                      <button class="submitbtn">Search Now</button>
               </form>

Controller

public function search()
{
    $data['countries'] = $this->CrudModel->get('countries');
    $this->form_validation->set_error_delimiters('
', '
');
    $this->form_validation->set_rules('flight_from', 'Select depature', 'required|trim');
    $this->form_validation->set_rules('flight_to', 'Select Destination', 'required|trim');

    if ($_POST['flight_type'] == 'round_trip')
    {
        $this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');
        $this->form_validation->set_rules('return', 'Date of return', 'required|trim');
        $this->form_validation->set_rules('no_of_passengers', 'Number of Passengers', 'required');
        if ($this->form_validation->run() == FALSE)
        {
            $this->index();

        }
        else
        {
            $search_result = array(
                $flight_from = $_POST['flight_from'],
                $flight_to = $_POST['flight_to'],
                $depart = $_POST['depart'],
                $return = $_POST['return'],
                $no_of_passengers = $_POST['no_of_passengers']
            );
            $data['search_result'] = $this->CrudModel->search('flight',$flight_from,$flight_to,$depart,$return,$no_of_passengers);
            $this->load->view('partials/header');
            $this->load->view('partials/nav');
            $this->load->view('result',$data);
        }

    }
    else
    {
        $this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');
        $this->form_validation->set_rules('no_of_passengers', 'Number of Passengers', 'required');
        if ($this->form_validation->run() == FALSE)
        {
            $this->index();

        }
        else {
            $search_result = array(
                $flight_from = $_POST['flight_from'],
                $flight_to = $_POST['flight_to'],
                $depart = $_POST['depart'],
                $no_of_passengers = $_POST['no_of_passengers']
            );
        $data['search_result'] = $this->CrudModel->search('flight',$flight_from,$flight_to,$depart,$no_of_passengers);
        $this->load->view('partials/header');
        $this->load->view('partials/nav');
        $this->load->view('result',$data);
        }

    }
}

My ajax/js when hiding the return field

Body:
You have to pass flight_type parameters in post request. Then your code will be something like this describe below.

$this->form_validation->set_rules('flight_from', 'Select depature', 'required|trim');
$this->form_validation->set_rules('depart', 'Date of flight', 'required|trim');

if($this->input->post('flight_type')== 'roundw'):
    $this->form_validation->set_rules('flight_to', 'Select Destination', 'required|trim');
    $this->form_validation->set_rules('return', 'Date of return', 'required|trim');
endif:

Let me know if it not works for you.


问:
document.getElementById giving Null by JS not by HTML
When I am defining my input tag in html and accessing in JS by id then I am getting my tag.

HTML Code:

```<code><input class="easyui-combobox" name="language" style="width:30%;" id= "XX">
</code>```

JS Code:

```<code>var cc = document.getElementById("XX");
</code>```

Here things are fine.

But When I am creating from javascript and trying to access I am getting. I want dynamic So I need to create from JS.

JS Code:

```<code>var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
</code>```

Here I am getting null after applying this:

```<code>var cc = document.getElementById("XX");
</code>```

答:
You have not appended your element </p>

```<code>var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);

var cc = document.getElementById("XX");
console.log(cc);
</code>```

Body:
When I am defining my input tag in html and accessing in JS by id then I am getting my tag.

HTML Code:

<input class="easyui-combobox" name="language" style="width:30%;" id= "XX">

JS Code:

var cc = document.getElementById("XX");

Here things are fine.

But When I am creating from javascript and trying to access I am getting. I want dynamic So I need to create from JS.

JS Code:

var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";

Here I am getting null after applying this:

var cc = document.getElementById("XX");

Body:
You have not appended your element

var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);

var cc = document.getElementById("XX");
console.log(cc);


问:
Why does these 2 similar for loop have different results when adding ActionListener into JButton?
Originally I have a JFrame have 3 buttons: which button 0 prints 0 when clicked, button 1 prints 1 and so on:

```<code>JFrame jframe=new JFrame();
jframe.getContentPane().setLayout(new GridLayout(3,1));
for(int i=0;i<3;i++){
    final int j=i;
    JButton jbutton=new JButton(""+j);
    jframe.getContentPane().add(jbutton);
    jbutton.setPreferredSize(new Dimension(100,100));
    jbutton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            System.out.println(""+j);
        }
    });
}
jframe.setVisible(true);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
</code>```

I want to reduce 1 line due to the final variable, and hence refactor the for-loop as this:

```<code>JFrame jframe=new JFrame();
jframe.getContentPane().setLayout(new GridLayout(3,1));
for(final int[] arr={0};arr[0]<3;arr[0]++){
    JButton jbutton=new JButton(""+arr[0]);
    jframe.getContentPane().add(jbutton);
    jbutton.setPreferredSize(new Dimension(100,100));
    jbutton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            System.out.println(""+arr[0]);
        }
    });
}
jframe.setVisible(true);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
</code>```

but this time all buttons print 3 even the button index is still 0,1,2, what is the reason?

答:
After the loop ends, i[0] is 3. The ActionListeners all hold a reference to i and will read the same value for i[0] which is 3.

```<code>jbutton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        System.out.println(""+arr[0]);
    }
});
</code>```

If you want to correct this, assign the value of i[0] to a local final variable and us that for the output like:

```<code>for(int[] arr = {0}; arr[0] < 3; arr[0]++) {
    final int val = arr[0];
    ...
    jbutton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            System.out.println("" + val);
        }
    });
}
</code>```

Body:
Originally I have a JFrame have 3 buttons: which button 0 prints 0 when clicked, button 1 prints 1 and so on:

JFrame jframe=new JFrame();
jframe.getContentPane().setLayout(new GridLayout(3,1));
for(int i=0;i<3;i++){
    final int j=i;
    JButton jbutton=new JButton(""+j);
    jframe.getContentPane().add(jbutton);
    jbutton.setPreferredSize(new Dimension(100,100));
    jbutton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            System.out.println(""+j);
        }
    });
}
jframe.setVisible(true);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

I want to reduce 1 line due to the final variable, and hence refactor the for-loop as this:

JFrame jframe=new JFrame();
jframe.getContentPane().setLayout(new GridLayout(3,1));
for(final int[] arr={0};arr[0]<3;arr[0]++){
    JButton jbutton=new JButton(""+arr[0]);
    jframe.getContentPane().add(jbutton);
    jbutton.setPreferredSize(new Dimension(100,100));
    jbutton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            System.out.println(""+arr[0]);
        }
    });
}
jframe.setVisible(true);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

but this time all buttons print 3 even the button index is still 0,1,2, what is the reason?

Body:
After the loop ends, i[0] is 3. The ActionListeners all hold a reference to i and will read the same value for i[0] which is 3.

jbutton.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        System.out.println(""+arr[0]);
    }
});

If you want to correct this, assign the value of i[0] to a local final variable and us that for the output like:

for(int[] arr = {0}; arr[0] < 3; arr[0]++) {
    final int val = arr[0];
    ...
    jbutton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            System.out.println("" + val);
        }
    });
}


问:
C++ and DirectShow
I'm just getting started with DirectShow programming, and the 'C' nature of the DirectShow API is making my skin crawl. Endless return codes instead of exceptions, addref/release all over the place, functions taking pointer to pointers...

Are there any 'C++ friendly' wrappers for DirectShow programming that hide all the COM ugliness underneath.?

答:
If you don't find a wrapper then you can possibly benefit from the coding pattern discussed in my blog entry "B true, or B thrown! (Using the >> throwing pattern)".

Example from that blog entry (this can easily be adapted for COM, and in fact I first "invented" it for COM usage):

```<code>std::ostream& operator<<( std::ostream& stream, wchar_t const s[] )
{
    Size const  nBytes      = wcstombs( 0, s, 0 );
    (nBytes >= 0)
        || throwX( "wcstombs failed to deduce buffer size" );

    Size const              bufSize     = nBytes + 1;
    std::vector< char >     buf( bufSize );

    // The count of bytes written does not include terminating nullbyte.
    wcstombs( &buf[0], s, bufSize )
        >> Accept< IsNonNegative >()
        || throwX( "wcstombs failed to convert string" );

    return (stream << &buf[0]);
}
</code>```

There is some discussion at the blog, evidently everybody has his or her own preference for suitable operators etc., so I'm just throwing in the general principle here.

Oh, should add, instead of AddRef and Release calls, just use some COM smart pointer. There are so many of them around (e.g. in ATL/MFC, and the "intrinsic" one for Visual C++) that it's just pick and choose the one you like. Or create your own e.g. based on boost::intrusive_ptr.

Cheers & hth.,

ContentLicense: CC BY-SA 2.5

Title: C++ and DirectShow

Body:
If you don't find a wrapper then you can possibly benefit from the coding pattern discussed in my blog entry "B true, or B thrown! (Using the >> throwing pattern)".

Example from that blog entry (this can easily be adapted for COM, and in fact I first "invented" it for COM usage):

std::ostream& operator<<( std::ostream& stream, wchar_t const s[] )
{
    Size const  nBytes      = wcstombs( 0, s, 0 );
    (nBytes >= 0)
        || throwX( "wcstombs failed to deduce buffer size" );

    Size const              bufSize     = nBytes + 1;
    std::vector< char >     buf( bufSize );

    // The count of bytes written does not include terminating nullbyte.
    wcstombs( &buf[0], s, bufSize )
        >> Accept< IsNonNegative >()
        || throwX( "wcstombs failed to convert string" );

    return (stream << &buf[0]);
}

There is some discussion at the blog, evidently everybody has his or her own preference for suitable operators etc., so I'm just throwing in the general principle here.

Oh, should add, instead of AddRef and Release calls, just use some COM smart pointer. There are so many of them around (e.g. in ATL/MFC, and the "intrinsic" one for Visual C++) that it's just pick and choose the one you like. Or create your own e.g. based on boost::intrusive_ptr.

Cheers & hth.,


问:
Remove margin for the div for which width is given in percentage
In styled components of React JS, I have given the width for div in percentage to make it responsive....
But the div is getting margin at right which is making the alignment disturbed.
How to get rid of this margin.

```<code>export const BannerHeaderText = styled.h1`
    width: 46.5%;
    height: 64px;
    font-size: 28px;
    font-weight: 600;
    line-height: 1.14;
    `
export const BannerParagraph = styled.p`
    width: 51.4%;
    height: 40px;
    margin-top: 8px;
    font-size: 16px;
    line-height: 1.5;
    color: #000000;
    opacity: 0.38;
    `
</code>```

I am getting the width as I needed.

```<code><BannerParagraphBlock>

                <BannerHeaderText>
                    Solveing the most common problems in marketing
                </BannerHeaderText>

                <BannerParagraph>
                    Exquisite codially mr happiness of neglected distrusts.
                    Boisterous impossible unaffected he me everything.
                </BannerParagraph>

                <SeeAllProductsButton>{message.SayEffectHomePageSeeAllProductsButton.value}</SeeAllProductsButton>

            </BannerParagraphBlock>
</code>```

Missed Data

BannerHeaderText is h1 and BannerParagrap is p
BannerParagraphBlock is section

答:
In the beginning of your CSS code reset your margins for the
 tag. Then later you can give the margins as required. This is how it looks like,

```<code>    div{
        margin:0;
        padding:0;
    }
</code>```

Hopefully this will work!

Body:
In styled components of React JS, I have given the width for div in percentage to make it responsive....
But the div is getting margin at right which is making the alignment disturbed.
How to get rid of this margin.

export const BannerHeaderText = styled.h1`
    width: 46.5%;
    height: 64px;
    font-size: 28px;
    font-weight: 600;
    line-height: 1.14;
    `
export const BannerParagraph = styled.p`
    width: 51.4%;
    height: 40px;
    margin-top: 8px;
    font-size: 16px;
    line-height: 1.5;
    color: #000000;
    opacity: 0.38;
    `

I am getting the width as I needed.

<BannerParagraphBlock>

                <BannerHeaderText>
                    Solveing the most common problems in marketing
                </BannerHeaderText>

                <BannerParagraph>
                    Exquisite codially mr happiness of neglected distrusts.
                    Boisterous impossible unaffected he me everything.
                </BannerParagraph>

                <SeeAllProductsButton>{message.SayEffectHomePageSeeAllProductsButton.value}</SeeAllProductsButton>

            </BannerParagraphBlock>

Missed Data

BannerHeaderText is h1 and BannerParagrap is p
BannerParagraphBlock is section

Body:
In the beginning of your CSS code reset your margins for the <div> tag. Then later you can give the margins as required. This is how it looks like,

    div{
        margin:0;
        padding:0;
    }

Hopefully this will work!


问:
Showing Response Status - Uploading Image using JQuery
What I'm trying to do is download some image from a URL then upload it to WordPress post, my form below:

```<code><form method="post" id="upload">
<?php foreach($data as $row): ?>

<label>File Name</label>
<input type="text" id="filename_<?php echo $row->id;?>" name="data[<?php echo $row->id;?>][filename]" value="<?php echo $file_name;?>" />

<label>Title</label>
<input type="text" id="title_<?php echo $row->id;?>" name="data[<?php echo $row->id;?>][title]" value="<?php echo $title;?>" />

<?php endforeach;?>
<button name="act" value="savepost">Save</button>
</form>
<!-- showing result here -->
<div id="result"></div>
</code>```

So, then when click Save button... the action will call function prc_upload()

```<code>function prc_upload() {
   $posts = $_POST['data'];
   foreach ($posts as $post) {
   $filename  = $post['filename'];
   $title     = $post['title'];
   // Process uplaoding here
   // Process uplaoding here
   // Process uplaoding here
   if (!$fileSaved) {
      $result = $filename.' Can not saved !!';
   } else {
      $result = filename' Saved Succesfuly!!';
   }
}
</code>```

How to use jquery to show response result when Save button clicked..

答:
append your img  to html

like

```<code>$($post).each(function(){
$('#placeIDwhereYouWantToShowImg').append('<img src='+this.imgsrc+' class="if any"/>')
})
</code>```

Body:
What I'm trying to do is download some image from a URL then upload it to WordPress post, my form below:

<form method="post" id="upload">
<?php foreach($data as $row): ?>

File Name
<input type="text" id="filename_<?php echo $row->id;?>" name="data[<?php echo $row->id;?>][filename]" value="<?php echo $file_name;?>" />

Title
<input type="text" id="title_<?php echo $row->id;?>" name="data[<?php echo $row->id;?>][title]" value="<?php echo $title;?>" />

<?php endforeach;?>
<button name="act" value="savepost">Save</button>
</form>

So, then when click Save button... the action will call function prc_upload()

function prc_upload() {
   $posts = $_POST['data'];
   foreach ($posts as $post) {
   $filename  = $post['filename'];
   $title     = $post['title'];
   // Process uplaoding here
   // Process uplaoding here
   // Process uplaoding here
   if (!$fileSaved) {
      $result = $filename.' Can not saved !!';
   } else {
      $result = filename' Saved Succesfuly!!';
   }
}

How to use jquery to show response result when Save button clicked..

Body:
append your img  to html

like

$($post).each(function(){
$('#placeIDwhereYouWantToShowImg').append('<img src='+this.imgsrc+' class="if any"/>')
})


问:
Unit testing with stubs and mocks
I'm trying to write tests for some classes. The classes I want to test use different repositories to to get and save things from my database.

A simplified example

```<code>public class MyClass
{
    private readonly IGroupRepository _groupRepo;

  public MyClass(IGroupRepository groupRepo){
    _groupRepo = groupRepo;
  }

  public void Execute(PersonInfo personInfo, string id){
  var group = _groupRepo.GetById(id);

  var person = group.Persons.First(p=> p.Id == personInfo.Id);

  person.FirstName = personInfo.FirstName;
  person.LastName = personInfo.LastName;

  _groupRepo.Save(group);
  }
}
</code>```

What I want to do is make sure that what is saved into the db is correct.

So I have a unit test like this:

```<code>[TestMethod]
public void TestMethod(){
    var groupId = "ABC";
    var personId = 1;

    ver personInfo = new PersonInfo()
    {
      Id = personId,
      FirstName = "Sam",
      LastName = "Smith"
    }

    var groupStub = new Mock<IGroupRepository>;
    groupStub.Setup(x=> x.GetById(groupId)).Returns(new Group(){
            Id = groupId,
            Persons = List<Person>()
            {
                new Person()
                {
                    Id = personId,
                    FirstName = "George",
                    LastName = "Bolton",
                }
            }
        }
    });

    var myClass = new MyClass();
    myClass.Execute(personInfo, groupId);

    var group = groupStub.GetById(groupId);
    var person = group.Persons.First(p=> p.Id == personId);

    Assert.AreEqual(personInfo.FirstName, person.FirstName);
}
</code>```

I thought this was fine, but then I was reading more up on it and I read that you are not supposed to assert on a sub, which I think I'm doing in my assert statement? I'm getting info from the stub, then using Assert on the result?

So I'm not sure if this is the correct way to test. If not, why and what is the correct way?

答:
It is not recommended that you should be testing what is saved into
  the database is correct. It is more of integration testing than unit
  testing, and it goes beyond the scope of you class.

There could be many reasons for data not getting saved properly in db, but your class is behaving as it should be, for example network issue, but then failing your UT will not be correct.

Instead you should test your class for scenarios where how your class behaves when database insertions fails, or if some exception occurs. And then use your mocking framework to mock repository with those expectations and assert accordingly in tests of your class.

Some good readings here and here

Title: Unit testing with stubs and mocks

Body:
I'm trying to write tests for some classes. The classes I want to test use different repositories to to get and save things from my database.

A simplified example

public class MyClass
{
    private readonly IGroupRepository _groupRepo;

  public MyClass(IGroupRepository groupRepo){
    _groupRepo = groupRepo;
  }

  public void Execute(PersonInfo personInfo, string id){
  var group = _groupRepo.GetById(id);

  var person = group.Persons.First(p=> p.Id == personInfo.Id);

  person.FirstName = personInfo.FirstName;
  person.LastName = personInfo.LastName;

  _groupRepo.Save(group);
  }
}

What I want to do is make sure that what is saved into the db is correct.

So I have a unit test like this:

[TestMethod]
public void TestMethod(){
    var groupId = "ABC";
    var personId = 1;

    ver personInfo = new PersonInfo()
    {
      Id = personId,
      FirstName = "Sam",
      LastName = "Smith"
    }

    var groupStub = new Mock<IGroupRepository>;
    groupStub.Setup(x=> x.GetById(groupId)).Returns(new Group(){
            Id = groupId,
            Persons = List<Person>()
            {
                new Person()
                {
                    Id = personId,
                    FirstName = "George",
                    LastName = "Bolton",
                }
            }
        }
    });

    var myClass = new MyClass();
    myClass.Execute(personInfo, groupId);

    var group = groupStub.GetById(groupId);
    var person = group.Persons.First(p=> p.Id == personId);

    Assert.AreEqual(personInfo.FirstName, person.FirstName);
}

I thought this was fine, but then I was reading more up on it and I read that you are not supposed to assert on a sub, which I think I'm doing in my assert statement? I'm getting info from the stub, then using Assert on the result?

So I'm not sure if this is the correct way to test. If not, why and what is the correct way?


答:
The proper way is to get the event source, and then you do not need final int

```<code>    public static void main(String [] args)
    {
        JFrame jframe=new JFrame();
        jframe.getContentPane().setLayout(new GridLayout(3,1));
        for(int i=0;i<3;i++){
            JButton jbutton=new JButton(""+ i);
            jframe.getContentPane().add(jbutton);
            jbutton.setPreferredSize(new Dimension(100,100));
            jbutton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    JButton myButton = (JButton)e.getSource();
                    System.out.println(""+ myButton.getText());
                }
            });
        }
        jframe.setVisible(true);
        jframe.pack();
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
</code>```

Title: Why does these 2 similar for loop have different results when adding ActionListener into JButton?

Body:
The proper way is to get the event source, and then you do not need final int

    public static void main(String [] args)
    {
        JFrame jframe=new JFrame();
        jframe.getContentPane().setLayout(new GridLayout(3,1));
        for(int i=0;i<3;i++){
            JButton jbutton=new JButton(""+ i);
            jframe.getContentPane().add(jbutton);
            jbutton.setPreferredSize(new Dimension(100,100));
            jbutton.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    JButton myButton = (JButton)e.getSource();
                    System.out.println(""+ myButton.getText());
                }
            });
        }
        jframe.setVisible(true);
        jframe.pack();
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }


答:
You need to append input element to document </p>

```<code>var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);
</code>```

Title: document.getElementById giving Null by JS not by HTML

Body:
You need to append input element to document

var input = document.createElement("input");
input.className = 'easyui-combobox';
input.style = 'width:30%';
input.id = "XX";
document.body.appendChild(input);


问:
Potential Null dereferencing
I am using an open-source json parser, but while compiling its giving me dereferencing warnings.

MyProject/Classes/SBJSON.m:403:13 Potential null dereference.  According to coding standards in 'Creating and Returning NSError Objects' the parameter 'error' may be null

```<code>- (BOOL)scanValue:(NSObject **)o error:(NSError **)error
{
skipWhitespace(c);

switch (*c++) {
    case '{':
        return [self scanRestOfDictionary:(NSMutableDictionary **)o error:error];
        break;
    case '[':
        return [self scanRestOfArray:(NSMutableArray **)o error:error];
        break;
    case '"':
        return [self scanRestOfString:(NSMutableString **)o error:error];
        break;
    case 'f':
        return [self scanRestOfFalse:(NSNumber **)o error:error];
        break;
    case 't':
        return [self scanRestOfTrue:(NSNumber **)o error:error];
        break;
    case 'n':
        return [self scanRestOfNull:(NSNull **)o error:error];
        break;
    case '-':
    case '0'...'9':
        c--; // cannot verify number correctly without the first character
        return [self scanNumber:(NSNumber **)o error:error];
        break;
    case '+':
        *error = err(EPARSENUM, @"Leading + disallowed in number");
        return NO;
        break;
    case 0x0:
        *error = err(EEOF, @"Unexpected end of string");
        return NO;
        break;
    default:
        *error = err(EPARSE, @"Unrecognised leading character");
        return NO;
        break;
}

NSAssert(0, @"Should never get here");
return NO;
}
</code>```

here it shows dereferencing at error.

答:
It complains that the error parameter might be NULL (in case the caller choses to pass NULL). Then, the statement

```<code>*error = err(EPARSENUM, @"Leading + disallowed in number");
</code>```

will crash. A reported work-around is to put an if statement around the assignment:

```<code>if(error){
    *error = err(EPARSENUM, @"Leading + disallowed in number");
}
</code>```

Title: Potential Null dereferencing

Body:
I am using an open-source json parser, but while compiling its giving me dereferencing warnings.

MyProject/Classes/SBJSON.m:403:13 Potential null dereference.  According to coding standards in 'Creating and Returning NSError Objects' the parameter 'error' may be null

- (BOOL)scanValue:(NSObject **)o error:(NSError **)error
{
skipWhitespace(c);

switch (*c++) {
    case '{':
        return [self scanRestOfDictionary:(NSMutableDictionary **)o error:error];
        break;
    case '[':
        return [self scanRestOfArray:(NSMutableArray **)o error:error];
        break;
    case '"':
        return [self scanRestOfString:(NSMutableString **)o error:error];
        break;
    case 'f':
        return [self scanRestOfFalse:(NSNumber **)o error:error];
        break;
    case 't':
        return [self scanRestOfTrue:(NSNumber **)o error:error];
        break;
    case 'n':
        return [self scanRestOfNull:(NSNull **)o error:error];
        break;
    case '-':
    case '0'...'9':
        c--; // cannot verify number correctly without the first character
        return [self scanNumber:(NSNumber **)o error:error];
        break;
    case '+':
        *error = err(EPARSENUM, @"Leading + disallowed in number");
        return NO;
        break;
    case 0x0:
        *error = err(EEOF, @"Unexpected end of string");
        return NO;
        break;
    default:
        *error = err(EPARSE, @"Unrecognised leading character");
        return NO;
        break;
}

NSAssert(0, @"Should never get here");
return NO;
}

here it shows dereferencing at error.

Body:
It complains that the error parameter might be NULL (in case the caller choses to pass NULL). Then, the statement

*error = err(EPARSENUM, @"Leading + disallowed in number");

will crash. A reported work-around is to put an if statement around the assignment:

if(error){
    *error = err(EPARSENUM, @"Leading + disallowed in number");
}


答:
You should not test the logic of another module/class that is being used in the class you are implementing Unit test.

You should only test/verify that the call to that module is being invoked or not as your business logic says. You should only concentrate on the Business logic of that class only for what you are writing unit testcases.

Here in your case IGroupRepository is another module/class and not the one for which you are writing unit tests. Instead if you want to verify that data is being saved or not then you should include that in another test case which you are implementing for IGroupRepository.

However writing unit tests for data saving is not recommended and it is considered as part of integration test.

Title: Unit testing with stubs and mocks


问:
Delphi XE10.x FireDAC - Error lost connection to MySQL server during query
I am building this simple query using following code:

```<code>FDQuery1.SQL.Text := 'INSERT INTO album SET customer_id=' + Chr(39) + IntToStr(CustomerID) + Chr(39) + ',lab_id=' + Chr(39) + IntToStr(LabID) + Chr(39) +
        ', album_name_c = ' + Chr(39) + ProjectFolderName + Chr(39) +
        ', album_name_s = ' + Chr(39) + ProjectFolderNameOnServer + Chr(39) +
        ' ,album_size=' + Chr(39) + txtAlbumSize.Text + Chr(39) +
        ', album_paper=' + Chr(39) + txtPaperFinish.Text + Chr(39) +
        ', album_cover=' + Chr(39) + txtCover.Text + Chr(39) +
        ', album_binding=' + Chr(39) + txtBinding.Text + Chr(39) +
        ', album_coating=' + Chr(39) + txtCoating.Text + Chr(39) +
        ', starts_from=' + Chr(39) + BoolToStr(chkRight.Checked) + Chr(39) +
        '; SELECT LAST_INSERT_ID() AS RecID;';
</code>```

But when I call FDQuery1.OpenOrExecute I get error message as stated in subject of this post.

Current query length is around 299 characters.

I read somewhere on internet that the Query length should be less than 255 characters, so I have also tried to shorten the query but keep its length below 255 characters.

But still I get the same error message.

What wrong am I doing here please guide me.

TIA

Yogi Yang

答:
Ok finally I found the actual problem and solved it...

It so happens that the dumb FireDAC's Query component does not support query in the format stated in original post. I had to build traditional Insert query as per SQL norms.

Though query with SET keyword is supported by MySQL and I have been using it in my PHP projects so there is not question of the query being wrong.

Ok what I did with suggestion/help of other developers in another forum was build a parameterized query and use it like below:

```<code>FDQuery1.SQL.Text := 'INSERT INTO album(customer_id, album_name_c, album_name_s, album_size, album_paper, album_cover, album_binding, album_coating, starts_from, total_files, lab_id, upload_date, album_uploaded) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?);';

        FDQuery1.Params.Items[0].AsInteger := CustomerID;
        FDQuery1.Params.Items[1].AsString := ProjectFolderName;
        FDQuery1.Params.Items[2].AsString := ProjectFolderNameOnServer;
        FDQuery1.Params.Items[3].AsString := AlbumSize;
        FDQuery1.Params.Items[4].AsString := PaperFinish;
        FDQuery1.Params.Items[5].AsString := Cover;
        FDQuery1.Params.Items[6].AsString := Binding;
        FDQuery1.Params.Items[7].AsString := Coating;

        if chkLeft.Checked then
          FDQuery1.Params.Items[8].AsString := '1'
        else
          FDQuery1.Params.Items[8].AsString := '0';

        if chkRight.Checked then
          FDQuery1.Params.Items[8].AsString := '2'
        else
          FDQuery1.Params.Items[8].AsString := '0';

        FDQuery1.Params.Items[9].AsInteger := lstFiles.Count;
        FDQuery1.Params.Items[10].AsInteger := LabID;
        FDQuery1.Params.Items[11].AsDate := Now;
        FDQuery1.Params.Items[12].AsString := '1';

        FDQuery1.Execute;
</code>```

Thanks to this parameterized query I did not have to add single quotes to varchar and data fields data using Chr(39).

I hope this will help other developers solve similar problems that they may face.

Regards,

Yogi Yang

Body:
I am building this simple query using following code:

FDQuery1.SQL.Text := 'INSERT INTO album SET customer_id=' + Chr(39) + IntToStr(CustomerID) + Chr(39) + ',lab_id=' + Chr(39) + IntToStr(LabID) + Chr(39) +
        ', album_name_c = ' + Chr(39) + ProjectFolderName + Chr(39) +
        ', album_name_s = ' + Chr(39) + ProjectFolderNameOnServer + Chr(39) +
        ' ,album_size=' + Chr(39) + txtAlbumSize.Text + Chr(39) +
        ', album_paper=' + Chr(39) + txtPaperFinish.Text + Chr(39) +
        ', album_cover=' + Chr(39) + txtCover.Text + Chr(39) +
        ', album_binding=' + Chr(39) + txtBinding.Text + Chr(39) +
        ', album_coating=' + Chr(39) + txtCoating.Text + Chr(39) +
        ', starts_from=' + Chr(39) + BoolToStr(chkRight.Checked) + Chr(39) +
        '; SELECT LAST_INSERT_ID() AS RecID;';

But when I call FDQuery1.OpenOrExecute I get error message as stated in subject of this post.

Current query length is around 299 characters.

I read somewhere on internet that the Query length should be less than 255 characters, so I have also tried to shorten the query but keep its length below 255 characters.

But still I get the same error message.

What wrong am I doing here please guide me.

TIA

Yogi Yang

Body:
Ok finally I found the actual problem and solved it...

It so happens that the dumb FireDAC's Query component does not support query in the format stated in original post. I had to build traditional Insert query as per SQL norms.

Though query with SET keyword is supported by MySQL and I have been using it in my PHP projects so there is not question of the query being wrong.

Ok what I did with suggestion/help of other developers in another forum was build a parameterized query and use it like below:

FDQuery1.SQL.Text := 'INSERT INTO album(customer_id, album_name_c, album_name_s, album_size, album_paper, album_cover, album_binding, album_coating, starts_from, total_files, lab_id, upload_date, album_uploaded) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?);';

        FDQuery1.Params.Items[0].AsInteger := CustomerID;
        FDQuery1.Params.Items[1].AsString := ProjectFolderName;
        FDQuery1.Params.Items[2].AsString := ProjectFolderNameOnServer;
        FDQuery1.Params.Items[3].AsString := AlbumSize;
        FDQuery1.Params.Items[4].AsString := PaperFinish;
        FDQuery1.Params.Items[5].AsString := Cover;
        FDQuery1.Params.Items[6].AsString := Binding;
        FDQuery1.Params.Items[7].AsString := Coating;

        if chkLeft.Checked then
          FDQuery1.Params.Items[8].AsString := '1'
        else
          FDQuery1.Params.Items[8].AsString := '0';

        if chkRight.Checked then
          FDQuery1.Params.Items[8].AsString := '2'
        else
          FDQuery1.Params.Items[8].AsString := '0';

        FDQuery1.Params.Items[9].AsInteger := lstFiles.Count;
        FDQuery1.Params.Items[10].AsInteger := LabID;
        FDQuery1.Params.Items[11].AsDate := Now;
        FDQuery1.Params.Items[12].AsString := '1';

        FDQuery1.Execute;

Thanks to this parameterized query I did not have to add single quotes to varchar and data fields data using Chr(39).

I hope this will help other developers solve similar problems that they may face.

Regards,

Yogi Yang


问:
Does jqgrid support tooltips on header cells (and grouped header cells)
I am using jqgrid and I want to have a tooltip that is a different value for each column heading (i want to put in the description in to a tooltip) for each column name.  In my case I am using the treegrid but my question applies to both the treegrid and the regular jqgrid.

Is this possible? Again, I am looknig to do this for every column header (both regular and grouped header cols)

答:
To add tooltip just call this methode on loadcomplete:</p>

```<code>addToolTipForColumnheader('YourGridID');

function addToolTipForColumnheader(gridID){
    var columnNameList=$('#'+gridID)[0].p.colNames;
    for (var i = 0; i < columnNameList.length; i++){
        var columnName=$('#'+gridID)[0].p.colModel[i].name;
        $('#'+gridID+'_'+columnName).attr("title", $('#'+gridID)[0].p.colNames[i]);
    }
}
</code>```

Body:
To add tooltip just call this methode on loadcomplete:

addToolTipForColumnheader('YourGridID');

function addToolTipForColumnheader(gridID){
    var columnNameList=$('#'+gridID)[0].p.colNames;
    for (var i = 0; i < columnNameList.length; i++){
        var columnName=$('#'+gridID)[0].p.colModel[i].name;
        $('#'+gridID+'_'+columnName).attr("title", $('#'+gridID)[0].p.colNames[i]);
    }
}


问:
Remove Doubleqoutes and insert a character
I have the two paragraphs below in a multiline textbox and I want to:

Replace the numbers 1 and 2 with Q1 and Q2, and

Remove all the quotes.

According to Forbes & Hawranik (found in Kulig & Williams, 2012), which of the following is a unique characteristic of rural residents
  with dementia?

A.    They are less likely to have an adult child to assist them with care.   B.  They experience a delay in dementia diagnosis.  C.  There is
  a greater reluctance in accepting specialized care.   D.  They tend to
  have a later onset of dementia than their urban counterparts.

A nurse speaks at a staff development in-service. Which statement by a nurse participant shows the need for education?

A.    “I know that the consequences of discrimination are still present
  and they're linked to health disparities.” B. “I'm sure the percentage
  of client-care hours that we spend working with minority clients is
  bound to increase.” C.    “Some may erroneously assume that there are few
  health disparities because Canada has a universal health care system.”
  D.    “It's inaccurate to link the prevalence of particular diseases with
  particular minority groups.”

I have tried this code but it is not working:

```<code>For i = 0 To Val(textcon.Lines.Count) - 1

  If textcon.Lines(i).Contains(Chr(34)) Then
    MyStringBuilder.Replace(Chr(34), "#")
  End If
next
</code>```

答:
Try this(For Simple Double Quotes):

```<code>For i = 0 To Val(TextBox1.Lines.Count) - 1
       If TextBox1.Lines(i).Contains(Chr(34)) Then
            TextBox1.Text = TextBox1.Text.Replace(Chr(34), "")
       End If
Next
TextBox1.Text = TextBox1.Text.Replace("1.", "Q1 ")
TextBox1.Text = TextBox1.Text.Replace("2.", "Q2 ")
</code>```

Try this(For Curly Double Quotes):

```<code>For i = 0 To Val(TextBox1.Lines.Count) - 1
     TextBox1.Text = TextBox1.Text.Replace(Chr(148), "")
     TextBox1.Text = TextBox1.Text.Replace(Chr(147), "")
Next
TextBox1.Text = TextBox1.Text.Replace("1.", "Q1 ")
TextBox1.Text = TextBox1.Text.Replace("2.", "Q2 ")
</code>```

There are different types of Double Quotation marks, you can refereed the character code from here

Try with this content:(I've change the Curly Quotes to Straight Quotes)

```<code>1. According to Forbes & Hawranik (found in Kulig & Williams, 2012), which of the following is a unique characteristic of rural residents with dementia?
    A. They are less likely to have an adult child to assist them with care. B. They experience a delay in dementia diagnosis. C. There is a greater reluctance in accepting specialized care. D. They tend to have a later onset of dementia than their urban counterparts.

2. A nurse speaks at a staff development in-service. Which statement by a nurse participant shows the need for education?

A. "I know that the consequences of discrimination are still present and they're linked to health disparities." B. "I'm sure the percentage of client-care hours that we spend working with minority clients is bound to increase." C. "Some may erroneously assume that there are few health disparities because Canada has a universal health care system." D. "It's inaccurate to link the prevalence of particular diseases with particular minority groups."
</code>```

Body:
I have the two paragraphs below in a multiline textbox and I want to:

Replace the numbers 1 and 2 with Q1 and Q2, and

Remove all the quotes.

According to Forbes & Hawranik (found in Kulig & Williams, 2012), which of the following is a unique characteristic of rural residents
  with dementia?

A.    They are less likely to have an adult child to assist them with care.   B.  They experience a delay in dementia diagnosis.  C.  There is
  a greater reluctance in accepting specialized care.   D.  They tend to
  have a later onset of dementia than their urban counterparts.

A nurse speaks at a staff development in-service. Which statement by a nurse participant shows the need for education?

A.    “I know that the consequences of discrimination are still present
  and they're linked to health disparities.” B. “I'm sure the percentage
  of client-care hours that we spend working with minority clients is
  bound to increase.” C.    “Some may erroneously assume that there are few
  health disparities because Canada has a universal health care system.”
  D.    “It's inaccurate to link the prevalence of particular diseases with
  particular minority groups.”

I have tried this code but it is not working:

For i = 0 To Val(textcon.Lines.Count) - 1

  If textcon.Lines(i).Contains(Chr(34)) Then
    MyStringBuilder.Replace(Chr(34), "#")
  End If
next

Body:
Try this(For Simple Double Quotes):

For i = 0 To Val(TextBox1.Lines.Count) - 1
       If TextBox1.Lines(i).Contains(Chr(34)) Then
            TextBox1.Text = TextBox1.Text.Replace(Chr(34), "")
       End If
Next
TextBox1.Text = TextBox1.Text.Replace("1.", "Q1 ")
TextBox1.Text = TextBox1.Text.Replace("2.", "Q2 ")

Try this(For Curly Double Quotes):

For i = 0 To Val(TextBox1.Lines.Count) - 1
     TextBox1.Text = TextBox1.Text.Replace(Chr(148), "")
     TextBox1.Text = TextBox1.Text.Replace(Chr(147), "")
Next
TextBox1.Text = TextBox1.Text.Replace("1.", "Q1 ")
TextBox1.Text = TextBox1.Text.Replace("2.", "Q2 ")

There are different types of Double Quotation marks, you can refereed the character code from here

Try with this content:(I've change the Curly Quotes to Straight Quotes)

1. According to Forbes & Hawranik (found in Kulig & Williams, 2012), which of the following is a unique characteristic of rural residents with dementia?
    A. They are less likely to have an adult child to assist them with care. B. They experience a delay in dementia diagnosis. C. There is a greater reluctance in accepting specialized care. D. They tend to have a later onset of dementia than their urban counterparts.

2. A nurse speaks at a staff development in-service. Which statement by a nurse participant shows the need for education?

A. "I know that the consequences of discrimination are still present and they're linked to health disparities." B. "I'm sure the percentage of client-care hours that we spend working with minority clients is bound to increase." C. "Some may erroneously assume that there are few health disparities because Canada has a universal health care system." D. "It's inaccurate to link the prevalence of particular diseases with particular minority groups."


问:
How do I programmatically create a new KeyStore?
I'm trying to programmatically create a new keystore in Java. The following code:

```<code>KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.setCertificateEntry("alias", cert);
</code>```

throws a Uninitialized KeyStore exception.

答:
I use this code, it works, hope it can help.</p>

```<code>public static KeyStore createKeyStore() throws Exception {
    File file = new File("/Users/keyserverstore.keystore");
    KeyStore keyStore = KeyStore.getInstance("JKS");
    if (file.exists()) {
        // if exists, load
        keyStore.load(new FileInputStream(file), "123456".toCharArray());
    } else {
        // if not exists, create
        keyStore.load(null, null);
        keyStore.store(new FileOutputStream(file), "123456".toCharArray());
    }
    return keyStore;
}
</code>```

Body:
I'm trying to programmatically create a new keystore in Java. The following code:

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.setCertificateEntry("alias", cert);

throws a Uninitialized KeyStore exception.

Body:
I use this code, it works, hope it can help.

public static KeyStore createKeyStore() throws Exception {
    File file = new File("/Users/keyserverstore.keystore");
    KeyStore keyStore = KeyStore.getInstance("JKS");
    if (file.exists()) {
        // if exists, load
        keyStore.load(new FileInputStream(file), "123456".toCharArray());
    } else {
        // if not exists, create
        keyStore.load(null, null);
        keyStore.store(new FileOutputStream(file), "123456".toCharArray());
    }
    return keyStore;
}


问:
Remove double quoted string from text file?
I'm working on some text files, i have to remove a specific string

```<code>ex: "1234_NAME=TRUE", (including double quotes and comma)
</code>```

Using Vim editor if i pass

```<code>:%s/"1234_NAME=TRUE",//g
</code>```

But In this way i will be doing manually. But i want to automate the job by using some script.

I tried using sed tool, but it failed.

```<code>sed 's/"1234_NAME=TRUE",//g' hello.txt
</code>```

I'm not expert on scripting. i know command is not correct. what is the solution for the above command.

And one more question:

Instead of passing file names manually, can we add a small loop which will take all text files in a directory one by one and remove the string.

Answer as suggested by @codeforester require some fix:

```<code>for file in *.txt
do
   [[ -f "$file" ]] || continue
</code>```

semicolon was the issue.

and Thanks to @SlePort for the answer.

Regards,

GBiradar

答:
This might work for you:

```<code>sed -i.bak 's/"1234_NAME=TRUE",//g' *.txt
</code>```

-i for in place editing

.bak: the extension of the backed up files

Body:
I'm working on some text files, i have to remove a specific string

ex: "1234_NAME=TRUE", (including double quotes and comma)

Using Vim editor if i pass

:%s/"1234_NAME=TRUE",//g

But In this way i will be doing manually. But i want to automate the job by using some script.

I tried using sed tool, but it failed.

sed 's/"1234_NAME=TRUE",//g' hello.txt

I'm not expert on scripting. i know command is not correct. what is the solution for the above command.

And one more question:

Instead of passing file names manually, can we add a small loop which will take all text files in a directory one by one and remove the string.

Answer as suggested by @codeforester require some fix:

for file in *.txt
do
   [[ -f "$file" ]] || continue

semicolon was the issue.

and Thanks to @SlePort for the answer.

Regards,

GBiradar

Body:
This might work for you:

sed -i.bak 's/"1234_NAME=TRUE",//g' *.txt

-i for in place editing

.bak: the extension of the backed up files


问:
How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?
I cd into the directory where all the pem/key files are and run the following:

```<code>aws iam upload-server-certificate
    --server-certificate-name certificate_name
    --certificate-body file://webservercertificate.pem
    --private-key file://server.key
    --certificate-chain file://certificate_chain_file.pem
</code>```

I get the following error:

A client error (InvalidClientTokenId) occurred when calling the
  UploadServerCertificate operation: The security token included in the
  request is invalid.

I have 1 'user' in 'users'. That user has been assigned the following permissions:

```<code>IAMFullAccess IAMReadOnlyAccess IAMUserSSHKeys
</code>```

I've downloaded the credentials for this user and put them into my user variables

```<code>AWS_ACCESS_KEY ****
AWS_SECRET_KEY ****
</code>```

I have 1 role on my elastic beanstalk  aws-elasticbeanstalk-ec2-role

答: You are somehow using wrong AWS Credentials (AccessKey and SecretKey) of AWS Account. So make sure they are correct else you need to create new and use them - in that case may be @Prakash answer is good for you</p>

Body:
I cd into the directory where all the pem/key files are and run the following:

aws iam upload-server-certificate
    --server-certificate-name certificate_name
    --certificate-body file://webservercertificate.pem
    --private-key file://server.key
    --certificate-chain file://certificate_chain_file.pem

I get the following error:

A client error (InvalidClientTokenId) occurred when calling the
  UploadServerCertificate operation: The security token included in the
  request is invalid.

I have 1 'user' in 'users'. That user has been assigned the following permissions:

IAMFullAccess IAMReadOnlyAccess IAMUserSSHKeys

I've downloaded the credentials for this user and put them into my user variables

AWS_ACCESS_KEY ****
AWS_SECRET_KEY ****

I have 1 role on my elastic beanstalk  aws-elasticbeanstalk-ec2-role


问:
Promises in JavaScript not executing propertly
I have this series of steps that needs to be completed in order:

Validate an object

Fetch an image URL using Bing's image search API

Add the found URLs to the object

Make a post request and send the object

A sample object looks like:

```<code>`{
    options: [{
      text: 'Pizza',
      votes: 0,
      imageURL: ""
    }, {
      text: 'Hot Dog',
      votes: 0,
      imageURL: ""
    }]
  };`
</code>```

Because the order in this series, I am using promises to make sure everything goes in the order specified above. So far I have:

  function validatePoll() {
    var isValid = true;
    for (var i = 0; i < $scope.poll.options.length; i++) {
      if (!$scope.poll.options[i].text) {
        isValid = false;
        break;
      }
    }
    return isValid;
  }

  let promiseURL = function(searchTerm) {
    return new Promise(function(resolve, reject) {
      $http.get('https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=' + searchTerm + '&count=1&offset=0&mkt=en-us&safeSearch=Strict', {
        headers: {
          'Ocp-Apim-Subscription-Key': 'XXXXXXXXXXXXXXXXXXXXXXXXXX'
        }
      }).success(function(response) {
        console.log(response);
        resolve(response);
      }).error(function (err, status) {
        reject(err);
      })
    })
  };

  let fetchImageURL = function() {
    for(var i = 0; i < $scope.poll.options.length; i++) {
      console.log(promiseURL($scope.poll.options[i].text));
    }
  }

  $scope.submitChoice = function() {
    var isValid = validatePoll();
    if(isValid) {
      fetchImageURL();
    } else {
      console.log("Not Valid Poll");
    }
  }```

But what ends up happening is the console.log(promiseURL($scope.poll.options[i].text)); in the fetchImageURL returns an unresolved promise instead of the response string I want instead. How might I be able to fix the code to ensure that:

A call to promiseURL is made with the proper argument

A response is received and can be parsed

The parsed information can be added to the imageURL property in the polls object

答:
Promises are usually used as follows:

```<code>promise.then(function(result) {
  console.log(result); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"
});
</code>```

Where the promise itself looks like:

```<code>var promise = new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…

  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});
</code>```

It doesn't look like, in your loop, you're calling then on promiseURL($scope.poll.options[i].text).  Try doing something like:

```<code>for(var i = 0; i < $scope.poll.options.length; i++) {
  promiseURL($scope.poll.options[i].text).then(function(result) {
      console.log(result); // "Stuff worked!"
  });
}
</code>```

See https://developers.google.com/web/fundamentals/getting-started/primers/promises for a great primer on promises.

Body:
I have this series of steps that needs to be completed in order:

Validate an object

Fetch an image URL using Bing's image search API

Add the found URLs to the object

Make a post request and send the object

A sample object looks like:

`{
    options: [{
      text: 'Pizza',
      votes: 0,
      imageURL: ""
    }, {
      text: 'Hot Dog',
      votes: 0,
      imageURL: ""
    }]
  };`

Because the order in this series, I am using promises to make sure everything goes in the order specified above. So far I have:

  function validatePoll() {
    var isValid = true;
    for (var i = 0; i < $scope.poll.options.length; i++) {
      if (!$scope.poll.options[i].text) {
        isValid = false;
        break;
      }
    }
    return isValid;
  }

  let promiseURL = function(searchTerm) {
    return new Promise(function(resolve, reject) {
      $http.get('https://api.cognitive.microsoft.com/bing/v5.0/images/search?q=' + searchTerm + '&count=1&offset=0&mkt=en-us&safeSearch=Strict', {
        headers: {
          'Ocp-Apim-Subscription-Key': 'XXXXXXXXXXXXXXXXXXXXXXXXXX'
        }
      }).success(function(response) {
        console.log(response);
        resolve(response);
      }).error(function (err, status) {
        reject(err);
      })
    })
  };

  let fetchImageURL = function() {
    for(var i = 0; i < $scope.poll.options.length; i++) {
      console.log(promiseURL($scope.poll.options[i].text));
    }
  }

  $scope.submitChoice = function() {
    var isValid = validatePoll();
    if(isValid) {
      fetchImageURL();
    } else {
      console.log("Not Valid Poll");
    }
  }

But what ends up happening is the console.log(promiseURL($scope.poll.options[i].text)); in the fetchImageURL returns an unresolved promise instead of the response string I want instead. How might I be able to fix the code to ensure that:

A call to promiseURL is made with the proper argument

A response is received and can be parsed

The parsed information can be added to the imageURL property in the polls object

Body:
Promises are usually used as follows:

promise.then(function(result) {
  console.log(result); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"
});

Where the promise itself looks like:

var promise = new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…

  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

It doesn't look like, in your loop, you're calling then on promiseURL($scope.poll.options[i].text).  Try doing something like:

for(var i = 0; i < $scope.poll.options.length; i++) {
  promiseURL($scope.poll.options[i].text).then(function(result) {
      console.log(result); // "Stuff worked!"
  });
}

See https://developers.google.com/web/fundamentals/getting-started/primers/promises for a great primer on promises.


问:
how to start a next activity after clicking on viewpager?
my HomeActivity.java :

```<code>    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    FragmentManager fm = getSupportFragmentManager();
    SlidingImage_Adapter pagerAdapter = new SlidingImage_Adapter(fm);
    pager.setAdapter(pagerAdapter);
}

private Boolean exit=false;
@Override
public void onBackPressed() {
    if (exit) {
        finish();
    } else {
        Toast.makeText(this, "Tekan lagi untuk keluar.",
                Toast.LENGTH_SHORT).show();
        exit = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                exit = false;
            }
        }, 3 * 1000);
    }
    ;
}
</code>```

this is for connecting between Homeact and image_model

my SlidingImage_adapter.java :

```<code>@Override
public Fragment getItem(int arg0) {
    ImageModel myFragment = new ImageModel();
    Bundle data = new Bundle();
    data.putInt("current_page", arg0+1);
    myFragment.setArguments(data);
    return myFragment;
}
@Override
public int getCount() {
    return Page_Count;
}
</code>```

this is to take the pict from .xml that i make (layout1.xml, layout2.xml, etc)

my Image_Model.java

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle data = getArguments();
    mCurrentPage = data.getInt("current_page", 0);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = null;
    if (mCurrentPage == 1) {
        v = inflater.inflate(R.layout.layout1, container, false);
    } else if (mCurrentPage == 2) {
        v = inflater.inflate(R.layout.layout2, container, false);
    } else if (mCurrentPage == 3) {
        v = inflater.inflate(R.layout.layout3, container, false);
    }
    return v;
}
</code>```

答:
Inside your Image_Model.java

```<code>        @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle data = getArguments();
        mCurrentPage = data.getInt("current_page", 0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = null;
        if (mCurrentPage == 1) {
            v = inflater.inflate(R.layout.layout1, container, false);
        } else if (mCurrentPage == 2) {
            v = inflater.inflate(R.layout.layout2, container, false);
        } else if (mCurrentPage == 3) {
            v = inflater.inflate(R.layout.layout3, container, false);
        }
       v.setOnClickListener(this);
        return v;
    }

@Override
public void onClick(View v){
Intent i=new Intent(getContext(), YouActivity.class);
getContext.startActivity(i);
}
</code>```

Body:
my HomeActivity.java :

    ViewPager pager = (ViewPager) findViewById(R.id.pager);
    FragmentManager fm = getSupportFragmentManager();
    SlidingImage_Adapter pagerAdapter = new SlidingImage_Adapter(fm);
    pager.setAdapter(pagerAdapter);
}

private Boolean exit=false;
@Override
public void onBackPressed() {
    if (exit) {
        finish();
    } else {
        Toast.makeText(this, "Tekan lagi untuk keluar.",
                Toast.LENGTH_SHORT).show();
        exit = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                exit = false;
            }
        }, 3 * 1000);
    }
    ;
}

this is for connecting between Homeact and image_model

my SlidingImage_adapter.java :

@Override
public Fragment getItem(int arg0) {
    ImageModel myFragment = new ImageModel();
    Bundle data = new Bundle();
    data.putInt("current_page", arg0+1);
    myFragment.setArguments(data);
    return myFragment;
}
@Override
public int getCount() {
    return Page_Count;
}

this is to take the pict from .xml that i make (layout1.xml, layout2.xml, etc)

my Image_Model.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle data = getArguments();
    mCurrentPage = data.getInt("current_page", 0);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = null;
    if (mCurrentPage == 1) {
        v = inflater.inflate(R.layout.layout1, container, false);
    } else if (mCurrentPage == 2) {
        v = inflater.inflate(R.layout.layout2, container, false);
    } else if (mCurrentPage == 3) {
        v = inflater.inflate(R.layout.layout3, container, false);
    }
    return v;
}

Body:
Inside your Image_Model.java

        @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle data = getArguments();
        mCurrentPage = data.getInt("current_page", 0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = null;
        if (mCurrentPage == 1) {
            v = inflater.inflate(R.layout.layout1, container, false);
        } else if (mCurrentPage == 2) {
            v = inflater.inflate(R.layout.layout2, container, false);
        } else if (mCurrentPage == 3) {
            v = inflater.inflate(R.layout.layout3, container, false);
        }
       v.setOnClickListener(this);
        return v;
    }

@Override
public void onClick(View v){
Intent i=new Intent(getContext(), YouActivity.class);
getContext.startActivity(i);
}


答:
CComPtr is a pretty handy one,

Beyond that you just have to live with things like the HRESULTS.  I rather prefer them to exceptions ... find them much easier to work with ... each to their own.

Title: C++ and DirectShow

Body:
I'm just getting started with DirectShow programming, and the 'C' nature of the DirectShow API is making my skin crawl. Endless return codes instead of exceptions, addref/release all over the place, functions taking pointer to pointers...

Are there any 'C++ friendly' wrappers for DirectShow programming that hide all the COM ugliness underneath.?


问:
How to trigger another controller on AngularJS?
I don't want to share data between controller. I just want to trigger controller C when i click either tab A or tab B.

```<code><body ng-controller="MainController">
   <div class="div1" ng-controller="ControllerA" ng-click="changeTab('tab1')">
    ...
   </div>
   <div class="div2" ng-controller="ControllerB" ng-click="changeTab('tab2')">
    ...
   </div>
   <div class="div3" ng-controller="ControllerC">
    ...
   </div>
</body>
</code>```

How this can be done ? Any idea ?

答:
You can use events, where $scope.$parent.$broadcast is a closest path between sibling controllers:

angular.module('app', [])
.controller('ControllerA', ['$scope', function($scope){
     $scope.changeTab = function(tab){
         $scope.$parent.$broadcast('myevent', tab);
     }
}])
.controller('ControllerC', ['$scope', function($scope){
    $scope.counter = 0;
     $scope.$on('myevent', function(event, tab){
         $scope.tab = tab;
         $scope.counter++;
     });
}])```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//code.angularjs.org/snapshot/angular.min.js"></script>

<body ng-app="app">
  <div class="div1" ng-controller="ControllerA" ng-click="changeTab('tab1')">
    Click ControllerA
   </div>
   <div class="div2" ng-controller="ControllerC">
     ControllerB({{tab}}): {{counter}}
   </div>
</body></code>```

Body:
I don't want to share data between controller. I just want to trigger controller C when i click either tab A or tab B.

    ...

    ...

    ...

How this can be done ? Any idea ?

Body:
You can use events, where $scope.$parent.$broadcast is a closest path between sibling controllers:

angular.module('app', [])
.controller('ControllerA', ['$scope', function($scope){
     $scope.changeTab = function(tab){
         $scope.$parent.$broadcast('myevent', tab);
     }
}])
.controller('ControllerC', ['$scope', function($scope){
    $scope.counter = 0;
     $scope.$on('myevent', function(event, tab){
         $scope.tab = tab;
         $scope.counter++;
     });
}])

<script src="//code.angularjs.org/snapshot/angular.min.js"></script>

<body ng-app="app">
  <div class="div1" ng-controller="ControllerA" ng-click="changeTab('tab1')">
    Click ControllerA
   </div>
   <div class="div2" ng-controller="ControllerC">
     ControllerB({{tab}}): {{counter}}
   </div>
</body>


问:
how to delete the key from dict when concat data frames in python
I need to join pandas dataframes that are stored in dictionary.
For example:
in the dic, for each key, it has a data frame as corresponding value

this is my code, but it has a little bit difference from my goal:

pd.concat(dic, axis = 1)

Appreciate!

I was wondering if anyone could help me to delete the key from the new dataframe?
I am using python

答:
I think you need MultiIndex.droplevel:

```<code>df = pd.concat(dic, axis = 1)
df.columns = df.columns.droplevel(0)
print (df)
     colorApple colorYellow
Date
1/3        red1        red2
3/5     yellow1     yellow2
</code>```

Body:
I think you need MultiIndex.droplevel:

df = pd.concat(dic, axis = 1)
df.columns = df.columns.droplevel(0)
print (df)
     colorApple colorYellow
Date
1/3        red1        red2
3/5     yellow1     yellow2


问:
How do I animate Google charts?
In script tags i added following code and i am unable to animate it. kindly suugest

  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Sales', 'Expenses'],
      ['2004',  1000,      400],
      ['2005',  1170,      460],
      ['2006',  660,       1120],
      ['2007',  1030,      540]
    ]);

    var options = {
      title: 'Company Performance',
       animation: {
          duration: 1000,
          easing: 'out'
      },
      vAxis: {title: 'Year',  titleTextStyle: {color: 'red'}, minValue:0, maxValue:1000}
    };
    var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
```

chart is loading but i am unable to animate it. animating at the time of loading

答:
```<code>var data = google.visualization.arrayToDataTable( chartArr );

var options = {
  sliceVisibilityThreshold: .0,
  pieHole: 0.3,
  legend: 'none',
  pieSliceText: 'label',
  height:500,
  width : "100%",
  is3D: true,
  animation:{
    duration: 5000,
    easing: 'out',
    startup: true //This is the new option
  },
};

var chart = new google.visualization.PieChart(document.getElementById('ethnicityChartInq'));

chart.draw(data, options);

// initial value
var percent = 0;
// start the animation loop
var handler = setInterval(function(){
    // values increment
    percent += 1;
    // apply new values
    data.setValue(0, 1, percent);
    data.setValue(1, 1, 100 - percent);

    // update the pie
    chart.draw(data, options);
    // check if we have reached the desired value
    if (percent > 74)
        // stop the loop
        clearInterval(handler);
}, 30);
</code>```

Title: How do I animate Google charts?

Body:
In script tags i added following code and i am unable to animate it. kindly suugest

  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Sales', 'Expenses'],
      ['2004',  1000,      400],
      ['2005',  1170,      460],
      ['2006',  660,       1120],
      ['2007',  1030,      540]
    ]);

    var options = {
      title: 'Company Performance',
       animation: {
          duration: 1000,
          easing: 'out'
      },
      vAxis: {title: 'Year',  titleTextStyle: {color: 'red'}, minValue:0, maxValue:1000}
    };
    var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }

chart is loading but i am unable to animate it. animating at the time of loading


问:
Odd nhibernate question about changing a PK to just an Id field in Mapping
So I need to copy rows for 2 tables from one db to another.

I want to be able to do identity insert, one way is to change the column to not be PK.

if I mark the pk not a pk but just a column, can I still map it as an ID?

Thanks,

E-

答: Yes, you can map your PK property as an assigned identifier.</p>


答:
HTML headings are block-level elements.
From MDN

A block-level element occupies the entire space of its parent element (container), thereby creating a "block."

In your case you can do this to make the heading center-aligned

```<code>h1.heading {
    margin-right: auto;
    margin-left: auto;
}
</code>```

You can see in the code-snippet below that the heading (in red border) is center-aligned.

h1.heading {
  margin-right: auto;
  margin-left: auto;
  border: 1px solid red;
  width: 352px;
}

p {
  color: #777;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1 class="heading">Solving the most common problems in marketting</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p></code>```

Title: Remove margin for the div for which width is given in percentage

Body:
In styled components of React JS, I have given the width for div in percentage to make it responsive....
But the div is getting margin at right which is making the alignment disturbed.
How to get rid of this margin.

export const BannerHeaderText = styled.h1`
    width: 46.5%;
    height: 64px;
    font-size: 28px;
    font-weight: 600;
    line-height: 1.14;
    `
export const BannerParagraph = styled.p`
    width: 51.4%;
    height: 40px;
    margin-top: 8px;
    font-size: 16px;
    line-height: 1.5;
    color: #000000;
    opacity: 0.38;
    `

I am getting the width as I needed.

<BannerParagraphBlock>

                <BannerHeaderText>
                    Solveing the most common problems in marketing
                </BannerHeaderText>

                <BannerParagraph>
                    Exquisite codially mr happiness of neglected distrusts.
                    Boisterous impossible unaffected he me everything.
                </BannerParagraph>

                <SeeAllProductsButton>{message.SayEffectHomePageSeeAllProductsButton.value}</SeeAllProductsButton>

            </BannerParagraphBlock>

Missed Data

BannerHeaderText is h1 and BannerParagrap is p
BannerParagraphBlock is section

Body:
HTML headings are block-level elements.
From MDN

A block-level element occupies the entire space of its parent element (container), thereby creating a "block."

In your case you can do this to make the heading center-aligned

h1.heading {
    margin-right: auto;
    margin-left: auto;
}

You can see in the code-snippet below that the heading (in red border) is center-aligned.

h1.heading {
  margin-right: auto;
  margin-left: auto;
  border: 1px solid red;
  width: 352px;
}

p {
  color: #777;
}

<h1 class="heading">Solving the most common problems in marketting</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>


问:
Firefox Profile for Portable Firefox - Excel VBA in Selenium
Hi I am using firefox potable version which works fine. However I am not able to set the profile as the profile directory is being ignored. Would if anyone has used this.

Declarations as under

```<code> Private assert As New assert
 Private driver As New Selenium.FirefoxDriver
 Private elms As Selenium.WebElements
 Private elm As Selenium.WebElement
</code>```

Portable Firefox Location. as per the help. I also tried to to put profile directory after set binary, but still the results are same.

```<code> driver.SetProfile ("G:\Software - Portable\FirefoxPortable37\Data\profile")
 driver.SetBinary ("G:\Software -Portable\FirefoxPortable37\FirefoxPortable.exe")
</code>```

This runs the firefox portable version 37, but ignores the profile with extensions.

答:
After lot of experiment I found that adding a true at the end works. So the code looks like </p>

```<code> driver.SetBinary ("X:\Path\FirefoxPortable37\Data\profile"),True
</code>```

Body:
Hi I am using firefox potable version which works fine. However I am not able to set the profile as the profile directory is being ignored. Would if anyone has used this.

Declarations as under

 Private assert As New assert
 Private driver As New Selenium.FirefoxDriver
 Private elms As Selenium.WebElements
 Private elm As Selenium.WebElement

Portable Firefox Location. as per the help. I also tried to to put profile directory after set binary, but still the results are same.

 driver.SetProfile ("G:\Software - Portable\FirefoxPortable37\Data\profile")
 driver.SetBinary ("G:\Software -Portable\FirefoxPortable37\FirefoxPortable.exe")

This runs the firefox portable version 37, but ignores the profile with extensions.

Body:
After lot of experiment I found that adding a true at the end works. So the code looks like

 driver.SetBinary ("X:\Path\FirefoxPortable37\Data\profile"),True


问:
how to retrieve the values from servlet to jsp using json
I'm new to use json and ajax. Please someone help me on how to append the values to the option tag. The values are getting printed on the page itself than inside the option tag. I have seen so many examples but do not understand.

Retrieveservlet :

```<code>protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   // TODO Auto-generated method stub

   System.out.println("action is called inside dropdown");
   ViewValuesInDB daoobj = new ViewValuesInDB();
   ArrayList<String> list = new ArrayList<String>();
   String json = null;
   try {
       list = daoobj.makeConnection();
       System.out.println(list);
       if(null == list){
           System.out.println("list is null");
       }
       else{
           System.out.println("list has values");
       }
       System.out.println("size of ids list :"+list.size());

       /*using json*/
       json = new Gson().toJson(list);
       System.out.println(json);

       response.setContentType("application/json");
       response.getWriter().write(json);

    }catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
</code>```

my jsp code :

```<code><script>
    $(document).ready(function() {
        $.get("Retrieveservlet", function(responseJson) {
            ('#dropDownId').append($('<option>').text(value)('value'));
        });
    });
</script>
<body>
    <label for="dropDownId">Country*:</label>
    <select id="dropDownId">
    </select>
</body>
</code>```

答:
This code works and appending in the dropdown but the values are getting displayed at the top of the page too.Can someone give me solution for this?</p>

```<code>    <script>
        $(document).ready(function() {
            $.get("Retrieveservlet", function(json) {
                /*  x = json[0];
                 alert(x); */
                var myselect = $('#dropDownId');
                $.each(json, function(index, key) {
                    myselect.append($('<option></option>').val(key).html(key));
                });
                //$('#dropDownId').append(myselect.html());
            });
        });
    </script>
</code>```

Body:
I'm new to use json and ajax. Please someone help me on how to append the values to the option tag. The values are getting printed on the page itself than inside the option tag. I have seen so many examples but do not understand.

Retrieveservlet :

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   // TODO Auto-generated method stub

   System.out.println("action is called inside dropdown");
   ViewValuesInDB daoobj = new ViewValuesInDB();
   ArrayList<String> list = new ArrayList<String>();
   String json = null;
   try {
       list = daoobj.makeConnection();
       System.out.println(list);
       if(null == list){
           System.out.println("list is null");
       }
       else{
           System.out.println("list has values");
       }
       System.out.println("size of ids list :"+list.size());

       /*using json*/
       json = new Gson().toJson(list);
       System.out.println(json);

       response.setContentType("application/json");
       response.getWriter().write(json);

    }catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

my jsp code :

    Country*:
    <select id="dropDownId">
    </select>

Body:
This code works and appending in the dropdown but the values are getting displayed at the top of the page too.Can someone give me solution for this?

    <script>
        $(document).ready(function() {
            $.get("Retrieveservlet", function(json) {
                /*  x = json[0];
                 alert(x); */
                var myselect = $('#dropDownId');
                $.each(json, function(index, key) {
                    myselect.append($('<option></option>').val(key).html(key));
                });
                //$('#dropDownId').append(myselect.html());
            });
        });
    </script>


问:
Is GIT a good solution for large projects like Laravel?
When a team work on a Laravel project, they usually edit route file, the same controllers and views. Resulting in thousands of merging conflicts. And resolving them is time consuming. Is there a way of preventing these conflicts?.

答:
What is git?

Git is a mature, actively maintained open source project. A staggering number of software projects rely on Git for version control, including commercial projects as well as open source. Git is an example of a DVCS (hence Distributed Version Control System). Rather than having only one single place for the full version history of the software as is common in the once-popular version control systems like CVS or Subversion (also known as SVN), in Git, every developer's working copy of the code is also a repository that can contain the full history of all changes.

In addition to being distributed, Git has been designed with performance, security and flexibility in mind.

When to use git?

For example, say a developer, Alice, makes changes to source code, adding a feature for the upcoming 2.0 release, then commits those changes with descriptive messages. She then works on a second feature and commits those changes too. Naturally, these are stored as separate pieces of work in the version history. Alice then switches to the version 1.3 branch of the same software to fix a bug that affects only that older version. The purpose of this is to enable the Alice's team to ship a bug fix release, version 1.3.1, before version 2.0 is ready. Alice can then return to the 2.0 branch to continue working on new features for 2.0 and all of this can occur without any network access and is therefore fast and reliable. She could even do it on an airplane. When she is ready to send all of the individually committed changes to the remote repository, Alice can "push" them in one command.

What are the advantages of git?

Git has a lot of usage and advantage but few are below that may clear to you when and why to use git

Git is a version control system or stagging for open source project. You can control your project by creating version step by step.

If an issue has been aroused after changes it is possible in git to restore a previous version to ignore all those changes and bugs.

We create a project on git as origin master and then make clones in different machines when working as a team project. When we 'push' our changes from different clones on different machines git merge all those changes in one origin master. So we don't need to bother about how to merge changes from different clones in one project folder.

How to resolve merge conflicts in git?

May this be help full to you to understand how to solve easily merges conflicts problem in git. The best tool for this purpose is git-mergetool Run merge conflict resolution tools to resolve merge conflicts in git projects.

Use git mergetool to run one of several merge utilities to resolve merge conflicts. It is typically run after git merges.

If one or more  parameters are given, the merge tool program will be run to resolve differences on each file (skipping those without conflicts). Specifying a directory will include all unresolved files in that path. If no  names are specified, git mergetool will run the merge tool program on every file with merge conflicts.

Backup in git mergetool git mergetool creates *.orig backup files while resolving merges. These are safe to remove once a file has been merged and its git mergetool session has completed.

Setting the mergetool.keepBackup configuration variable to false causes git mergetool to automatically remove the backup as files are successfully merged.

For further study about git mergetool please see the link:
https://www.git-tower.com/learn/git/ebook/en/command-line/advanced-topics/merge-conflicts

I think this may be helpful to you.

ContentLicense: CC BY-SA 4.0


问:
PouchDB basic auth does not work with sync gateway
When I try to sync from PouchDB to couchbase server using sync gateway I am getting following error:

XMLHttpRequest cannot load http://localhost:4984/test/. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

I try to set the header even then I am not able to get rid of this error.
Here is my sync gateway config file

```<code>sync-gateway-config.json::

    {
        "log":["*"],
        "databases": {
            "buildercycle": {
                "server":"http://localhost:8091",
                "bucket": "default",
                "users": {
                    "GUEST": {
                        "disabled": false,
                        "admin_channels": ["*"]
                    }
                },
                "sync":`function(doc, oldDoc) {
                      if (doc.type == "sports"){
                        channel(doc.type);
                        access(doc.owner,doc.type);

                      } else  {
                        channel(doc.type);
                       access(doc.owner,doc.type);
                      }
                }`

            }
        },
        "CORS": {
            "Origin": ["http://localhost:8000","http://localhost:8083", "http://localhost:4985"],
            "LoginOrigin": ["http://localhost:8000","http://localhost:8083","http://localhost:4985"],
            "Headers": ["Content-Type"],
            "MaxAge": 17280000
        }
    }

    I am trying to sync my PouchDB in following way:
    remoteCouch="http://"+user+":"+pass+"@localhost:4984/buildercycle";
                            console.log(remoteCouch);
      var opts = {live: true,withCredentials: true};
      db.sync(remoteCouch,opts,'error');

    i am passing user(user1) and password(password) which is defined in following sync_gateway admin URL
</code>```

http://localhost:4985/_admin/db/test/users

I am unable to pin point the error, Please help

答:
Add authorization in headers

"Headers": ["Content-Type","authorization"],

I think cors header is not getting set properly in your case.

Body:
When I try to sync from PouchDB to couchbase server using sync gateway I am getting following error:

XMLHttpRequest cannot load http://localhost:4984/test/. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

I try to set the header even then I am not able to get rid of this error.
Here is my sync gateway config file

sync-gateway-config.json::

    {
        "log":["*"],
        "databases": {
            "buildercycle": {
                "server":"http://localhost:8091",
                "bucket": "default",
                "users": {
                    "GUEST": {
                        "disabled": false,
                        "admin_channels": ["*"]
                    }
                },
                "sync":`function(doc, oldDoc) {
                      if (doc.type == "sports"){
                        channel(doc.type);
                        access(doc.owner,doc.type);

                      } else  {
                        channel(doc.type);
                       access(doc.owner,doc.type);
                      }
                }`

            }
        },
        "CORS": {
            "Origin": ["http://localhost:8000","http://localhost:8083", "http://localhost:4985"],
            "LoginOrigin": ["http://localhost:8000","http://localhost:8083","http://localhost:4985"],
            "Headers": ["Content-Type"],
            "MaxAge": 17280000
        }
    }

    I am trying to sync my PouchDB in following way:
    remoteCouch="http://"+user+":"+pass+"@localhost:4984/buildercycle";
                            console.log(remoteCouch);
      var opts = {live: true,withCredentials: true};
      db.sync(remoteCouch,opts,'error');

    i am passing user(user1) and password(password) which is defined in following sync_gateway admin URL

http://localhost:4985/_admin/db/test/users

I am unable to pin point the error, Please help