问:
Posting a form with google recaptcha via ajax
I have the following 'contact me' form (in a partial) in OctoberCMS

```<code>    <form name="sentMessage" id="contactForm" novalidate>
        <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
                <label>Name</label>
                <input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
                <p class="help-block text-danger"></p>
            </div>
        </div>
        <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
                <label>Email Address</label>
                <input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
                <p class="help-block text-danger"></p>
            </div>
        </div>
        <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
                <label>Phone Number</label>
                <input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
                <p class="help-block text-danger"></p>
            </div>
        </div>
        <div class="row control-group">
            <div class="form-group col-xs-12 floating-label-form-group controls">
                <label>Message</label>
                <textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
                <p class="help-block text-danger"></p>
            </div>
        </div>
        <br>
        <div class="g-recaptcha" id="gcaptcha" data-sitekey="sitekeydataCjaelksjEJlakch"></div>
        <div id="success"></div>
        <div class="row">
            <div class="form-group col-xs-12">
                <button type="submit" class="btn btn-success btn-lg">Send</button>
            </div>
        </div>
    </form>
</code>```

When the user clicks submit - it's handled via javascript (which is what helps with input validation). I'm using JQuery.

The JS looks like this:

```<code>$(function() {
    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var gcaptcha = $("#gcaptcha").data('sitekey');

            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "././mail/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message,
                    gcaptcha: gcaptcha
                },
                cache: false,
                success: function() {
                    // Success message
                    $('#success').html("<div class='alert alert-success'>");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("<strong>Your message has been sent. </strong>");
                    $('#success > .alert-success')
                        .append('</div>');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('</div>');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});
</code>```

The contact_me.php form looks like this:

```<code><?php

// Check for empty fields
if(empty($_POST['name'])        ||
   empty($_POST['email'])       ||
   empty($_POST['phone'])       ||
   empty($_POST['message']) ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
    echo "No arguments Provided!";
    return false;
   }

$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$secret = "alkfejasupersecretkeyalkjeociyseh13987fa9s8df7";
$gcaptcha = $_POST['gcaptcha'];
$remoteip = $_SERVER['REMOTE_ADDR'];

$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$gcaptcha."&remoteip=".$remoteip;
$result = json_decode($url, true);
var_dump($result);
/*
if ($result['success'] == 1) {
    //do mail here
}

// Create the email and send the message
$to = 'myemail@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
*/
?>
</code>```

As you can see - I'm trying to just see if I'm even getting to the contact_me.php form which it doesn't appear I am. Before I had commented it out - the mail never sent - which is why I started playing around trying to see if my data is even hitting the contact_me.php page. I see the success message when submitting - but the data never goes anywhere and no email is ever had.

I can see in Firebug that the data is posting to contact_me - but I can't tell much beyond that. The var_dump doesn't work and I'm in need of further assistance to either better troubleshoot this issue or figure out what isn't working.

答:
After a lot of help from Xorifelse in the comments I realized that the code was probably fine (or at least suitable).

I ended up going a different direction. I updated the form a bit so it looks like this:

```<code><div class="container">
    <div class="row">
        <div class="col-lg-12 text-center">
            <h2>Contact Me</h2>
            <hr class="star-primary">
        </div>
    </div>
    <div class="row">
        <div class="col-lg-8 col-lg-offset-2">
            <form name="sentMessage" id="contactForm" data-request="onSend" data-request-success="alert('We have received your email. Thank you!'); this.reset();" novalidate>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Name</label>
                        <input name="name" type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Email Address</label>
                        <input name="email" type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Phone Number</label>
                        <input name="phone" type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Message</label>
                        <textarea name="contact-msg" rows="5" class="form-control" placeholder="Message" id="contact-msg" required data-validation-required-message="Please enter a message."></textarea>
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <br>
                <div class="g-recaptcha" id="sitekey" data-sitekey="gcaptchasitekey3897vadf834fadf"></div>
                <div id="success"></div>
                <div class="row">
                    <div class="form-group col-xs-12">
                        <button type="submit" class="btn btn-success btn-lg">Send</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
</code>```

Note the 'onSend' data-request parameter.

In the default layout - I put this snippet of PHP to handle the actual processing (the onSend function):

```<code>function onSend()
{
  if(empty(post('name'))        ||
     empty(post('email'))       ||
     empty(post('phone'))       ||
     empty(post('contact-msg')) ||
     empty(post('g-recaptcha-response')) ||
     !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
     {
    echo "Please fill out all required fields.";
    return false;
     }
    // Collect input
    $name = post('name');
    $email = post('email');
    $phone = post('phone');
    $body = post('contact-msg');
    $response = post('g-recaptcha-response');
    $remoteip = $_SERVER['REMOTE_ADDR'];
    $secret = "32supersecretkeyackjaBcjeLCJelahd832CDo";
    $url = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$response."&remoteip=".$remoteip);
    $response = json_decode($url, true);

    // Form Validation
    $validator = Validator::make(
        [
            'name' => $name,
            'email' => $email,
            'phone' => $phone,
            'contact-msg' => $body,
        ],
        [
            'name' => 'required',
            'email' => 'required|email',
            'contact-msg' => 'required',
        ]
    );
    if ($validator->fails())
    {
        $messages = $validator->messages();
        throw new ApplicationException($messages->first());
    }

    // Make sure the captcha is verified before sending
    if (isset($response['success'])&&$response['success']=="true"){
      $to = config('mail.from.address');
      $params = compact('name','email','phone','body');
      Mail::sendTo($to, 'freelance::mail.contact', $params);

      return true;
    }
    else {

      return false;
    }

}
</code>```

I was able to trim down the JS file to this:

```<code>$(function() {

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },

        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});
</code>```

So it provides active validation as the user is typing (which is great).

This method also required a little additional setup on the backend:

You need to create a new 'Mail Template' (code: freelance::mail.contact) in the Settings portion of the backend (and of course, make sure your mail settings are setup)

I would have liked to do a little more JS once the submission is successful - so maybe in the future I'll work that into it - but this is now working as intended.

Body:
I have the following 'contact me' form (in a partial) in OctoberCMS

    <form name="sentMessage" id="contactForm" novalidate>

                Name
                <input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">

                Email Address
                <input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">

                Phone Number
                <input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">

                Message
                <textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>

                <button type="submit" class="btn btn-success btn-lg">Send</button>

    </form>

When the user clicks submit - it's handled via javascript (which is what helps with input validation). I'm using JQuery.

The JS looks like this:

$(function() {
    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var gcaptcha = $("#gcaptcha").data('sitekey');

            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "././mail/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message,
                    gcaptcha: gcaptcha
                },
                cache: false,
                success: function() {
                    // Success message
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Your message has been sent. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('
');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

The contact_me.php form looks like this:

<?php

// Check for empty fields
if(empty($_POST['name'])        ||
   empty($_POST['email'])       ||
   empty($_POST['phone'])       ||
   empty($_POST['message']) ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
    echo "No arguments Provided!";
    return false;
   }

$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
$secret = "alkfejasupersecretkeyalkjeociyseh13987fa9s8df7";
$gcaptcha = $_POST['gcaptcha'];
$remoteip = $_SERVER['REMOTE_ADDR'];

$url = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$gcaptcha."&remoteip=".$remoteip;
$result = json_decode($url, true);
var_dump($result);
/*
if ($result['success'] == 1) {
    //do mail here
}

// Create the email and send the message
$to = 'myemail@gmail.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
*/
?>

As you can see - I'm trying to just see if I'm even getting to the contact_me.php form which it doesn't appear I am. Before I had commented it out - the mail never sent - which is why I started playing around trying to see if my data is even hitting the contact_me.php page. I see the success message when submitting - but the data never goes anywhere and no email is ever had.

I can see in Firebug that the data is posting to contact_me - but I can't tell much beyond that. The var_dump doesn't work and I'm in need of further assistance to either better troubleshoot this issue or figure out what isn't working.

Body:
After a lot of help from Xorifelse in the comments I realized that the code was probably fine (or at least suitable).

I ended up going a different direction. I updated the form a bit so it looks like this:

<div class="container">
    <div class="row">
        <div class="col-lg-12 text-center">
            <h2>Contact Me</h2>
            <hr class="star-primary">
        </div>
    </div>
    <div class="row">
        <div class="col-lg-8 col-lg-offset-2">
            <form name="sentMessage" id="contactForm" data-request="onSend" data-request-success="alert('We have received your email. Thank you!'); this.reset();" novalidate>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Name</label>
                        <input name="name" type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Email Address</label>
                        <input name="email" type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Phone Number</label>
                        <input name="phone" type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Message</label>
                        <textarea name="contact-msg" rows="5" class="form-control" placeholder="Message" id="contact-msg" required data-validation-required-message="Please enter a message."></textarea>
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <br>
                <div class="g-recaptcha" id="sitekey" data-sitekey="gcaptchasitekey3897vadf834fadf"></div>
                <div id="success"></div>
                <div class="row">
                    <div class="form-group col-xs-12">
                        <button type="submit" class="btn btn-success btn-lg">Send</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

Note the 'onSend' data-request parameter.

In the default layout - I put this snippet of PHP to handle the actual processing (the onSend function):

function onSend()
{
  if(empty(post('name'))        ||
     empty(post('email'))       ||
     empty(post('phone'))       ||
     empty(post('contact-msg')) ||
     empty(post('g-recaptcha-response')) ||
     !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
     {
    echo "Please fill out all required fields.";
    return false;
     }
    // Collect input
    $name = post('name');
    $email = post('email');
    $phone = post('phone');
    $body = post('contact-msg');
    $response = post('g-recaptcha-response');
    $remoteip = $_SERVER['REMOTE_ADDR'];
    $secret = "32supersecretkeyackjaBcjeLCJelahd832CDo";
    $url = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$response."&remoteip=".$remoteip);
    $response = json_decode($url, true);

    // Form Validation
    $validator = Validator::make(
        [
            'name' => $name,
            'email' => $email,
            'phone' => $phone,
            'contact-msg' => $body,
        ],
        [
            'name' => 'required',
            'email' => 'required|email',
            'contact-msg' => 'required',
        ]
    );
    if ($validator->fails())
    {
        $messages = $validator->messages();
        throw new ApplicationException($messages->first());
    }

    // Make sure the captcha is verified before sending
    if (isset($response['success'])&&$response['success']=="true"){
      $to = config('mail.from.address');
      $params = compact('name','email','phone','body');
      Mail::sendTo($to, 'freelance::mail.contact', $params);

      return true;
    }
    else {

      return false;
    }

}

I was able to trim down the JS file to this:

$(function() {

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },

        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});

So it provides active validation as the user is typing (which is great).

This method also required a little additional setup on the backend:

You need to create a new 'Mail Template' (code: freelance::mail.contact) in the Settings portion of the backend (and of course, make sure your mail settings are setup)

I would have liked to do a little more JS once the submission is successful - so maybe in the future I'll work that into it - but this is now working as intended.


来源: stackexchange

问:
Assign part of a command's output to a variable in bash?
I have this update script i am working on and i am using ssh to log onto the machine and simply run apt-get update && apt-get upgrade -y. Now the thing is i want to be able to say something like "hostname" updated successfully.

Here's what i have written right now:

```<code>#!/bin/bash

ip=(192.168.1.23 192.168.1.40 192.168.1.41 192.168.1.42 192.168.1.43)
#ssh-key=~/.ssh/id_ed25519

for i in "${ip[@]}"; do {
  ssh -t victor@$i "sudo apt-get update && sudo apt-get upgrade -y"
    if [ $? -eq 0 ]; then
      echo "Update went successfully";
    else
      echo "$(tput smul)$(tput setaf 1)Update failed$(tput rmul)";
      exit 1;
    fi
} done;
</code>```

with the same ssh -t command i was thinking if i could get the hostname and assign it to a variable at the same time i'm using the first ssh session. That is so i dont have to write in my password for the ssh key twice.

So something like this:

```<code>hostname=$"(ssh -t victor@$i hostname && sudo apt-get update && sudo apt-get upgrade -y"
</code>```

And then i just echo $hostname.

答:
Maybe something like

```<code>hostname="$(nmblookup -A <ip>)"
</code>```

and then

```<code>if [ $? -eq 0 ]; then
  echo "$hostname: Update went successfully."
else
  echo "$hostname: Update failed!"
fi
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this update script i am working on and i am using ssh to log onto the machine and simply run apt-get update && apt-get upgrade -y. Now the thing is i want to be able to say something like "hostname" updated successfully.

Here's what i have written right now:

#!/bin/bash

ip=(192.168.1.23 192.168.1.40 192.168.1.41 192.168.1.42 192.168.1.43)
#ssh-key=~/.ssh/id_ed25519

for i in "${ip[@]}"; do {
  ssh -t victor@$i "sudo apt-get update && sudo apt-get upgrade -y"
    if [ $? -eq 0 ]; then
      echo "Update went successfully";
    else
      echo "$(tput smul)$(tput setaf 1)Update failed$(tput rmul)";
      exit 1;
    fi
} done;

with the same ssh -t command i was thinking if i could get the hostname and assign it to a variable at the same time i'm using the first ssh session. That is so i dont have to write in my password for the ssh key twice.

So something like this:

hostname=$"(ssh -t victor@$i hostname && sudo apt-get update && sudo apt-get upgrade -y"

And then i just echo $hostname.

Body:
Maybe something like

hostname="$(nmblookup -A <ip>)"

and then

if [ $? -eq 0 ]; then
  echo "$hostname: Update went successfully."
else
  echo "$hostname: Update failed!"
fi


问:
How to get a specific item inside the key using android
How to only retrieve email addresses inside the key, not all the items. I have an items Name and Email, but I only want to retrieve EMAIL.

example:

```<code>Email: HOTMAIL
Email: GMAIL
</code>```

答:
first make database reference as

```<code>           mReference= FirebaseDatabase.getInstance().getReferenceFromUrl(FIREBASE_URL_USERS);
</code>```

here FREBASE_URL_USERS is a url of users key you can get it from firebase console.
it is a combination of your unique_fiirebase_root_url / User01

then get snapshot of data as

```<code>        mDatabseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            dataSnapshot.getValue("Email");
              // use log to check whetehr you are getting email or not
        @Override
        public void onCancelled(DatabaseError databaseError) {
            // log error and do something
        }
    });
</code>```

Body:
How to only retrieve email addresses inside the key, not all the items. I have an items Name and Email, but I only want to retrieve EMAIL.

example:

Email: HOTMAIL
Email: GMAIL

Body:
first make database reference as

           mReference= FirebaseDatabase.getInstance().getReferenceFromUrl(FIREBASE_URL_USERS);

here FREBASE_URL_USERS is a url of users key you can get it from firebase console.
it is a combination of your unique_fiirebase_root_url / User01

then get snapshot of data as

        mDatabseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            dataSnapshot.getValue("Email");
              // use log to check whetehr you are getting email or not
        @Override
        public void onCancelled(DatabaseError databaseError) {
            // log error and do something
        }
    });


问:
How to make a dynamic method call?
There is a class containing many getters and setters :

```<code>@Entity
@Table(name = "valeur_indicateur")
public class ValeurIndicateur {

    @Id
    @SequenceGenerator(name="s_valeur_indicateur", sequenceName="s_valeur_indicateur", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_valeur_indicateur")
    @Column(name = "val_indi_code")
    private Integer code;

    @ManyToOne
    @JoinColumn(name = "indi_code")
    private Indicateur indicateur;

    @ManyToOne
    @JoinColumn(name = "peri_mes_code")
    private PeriodiciteMesure periodicite_mesure;

    @Column(name = "val_indi_cible_1")
    private String cible_1;

    @Column(name = "val_indi_cible_2")
    private String cible_2;

    @Column(name = "val_indi_cible_3")
    private String cible_3;

    @Column(name = "val_indi_cible_4")
    private String cible_4;

    @Column(name = "val_indi_cible_5")
    private String cible_5;

    @Column(name = "val_indi_cible_6")
    private String cible_6;

    @Column(name = "val_indi_cible_7")
    private String cible_7;

    @Column(name = "val_indi_cible_8")
    private String cible_8;

    @Column(name = "val_indi_cible_9")
    private String cible_9;

    @Column(name = "val_indi_cible_10")
    private String cible_10;

    @Column(name = "val_indi_cible_11")
    private String cible_11;

    @Column(name = "val_indi_cible_12")
    private String cible_12;

    @Column(name = "val_indi_realise_1")
    private String realise_1;

    @Column(name = "val_indi_realise_2")
    private String realise_2;

    @Column(name = "val_indi_realise_3")
    private String realise_3;

    @Column(name = "val_indi_realise_4")
    private String realise_4;

    @Column(name = "val_indi_realise_5")
    private String realise_5;

    @Column(name = "val_indi_realise_6")
    private String realise_6;

    @Column(name = "val_indi_realise_7")
    private String realise_7;

    @Column(name = "val_indi_realise_8")
    private String realise_8;

    @Column(name = "val_indi_realise_9")
    private String realise_9;

    @Column(name = "val_indi_realise_10")
    private String realise_10;

    @Column(name = "val_indi_realise_11")
    private String realise_11;

    @Column(name = "val_indi_realise_12")
    private String realise_12;

    @Column(name = "val_indi_taux")
    private Integer taux;

    public ValeurIndicateur() {
        super();
        // TODO Auto-generated constructor stub
    }

    public ValeurIndicateur(Integer code) {
        super();
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public Indicateur getIndicateur() {
        return indicateur;
    }

    public void setIndicateur(Indicateur indicateur) {
        this.indicateur = indicateur;
    }

    public PeriodiciteMesure getPeriodicite_mesure() {
        return periodicite_mesure;
    }

    public void setPeriodicite_mesure(PeriodiciteMesure periodicite_mesure) {
        this.periodicite_mesure = periodicite_mesure;
    }

    public String getCible_1() {
        return cible_1;
    }

    public void setCible_1(String cible_1) {
        this.cible_1 = cible_1;
    }

    public String getCible_2() {
        return cible_2;
    }

    public void setCible_2(String cible_2) {
        this.cible_2 = cible_2;
    }

    public String getCible_3() {
        return cible_3;
    }

    public void setCible_3(String cible_3) {
        this.cible_3 = cible_3;
    }

    public String getCible_4() {
        return cible_4;
    }

    public void setCible_4(String cible_4) {
        this.cible_4 = cible_4;
    }

    public String getCible_5() {
        return cible_5;
    }

    public void setCible_5(String cible_5) {
        this.cible_5 = cible_5;
    }

    public String getCible_6() {
        return cible_6;
    }

    public void setCible_6(String cible_6) {
        this.cible_6 = cible_6;
    }

    public String getCible_7() {
        return cible_7;
    }

    public void setCible_7(String cible_7) {
        this.cible_7 = cible_7;
    }

    public String getCible_8() {
        return cible_8;
    }

    public void setCible_8(String cible_8) {
        this.cible_8 = cible_8;
    }

    public String getCible_9() {
        return cible_9;
    }

    public void setCible_9(String cible_9) {
        this.cible_9 = cible_9;
    }

    public String getCible_10() {
        return cible_10;
    }

    public void setCible_10(String cible_10) {
        this.cible_10 = cible_10;
    }

    public String getCible_11() {
        return cible_11;
    }

    public void setCible_11(String cible_11) {
        this.cible_11 = cible_11;
    }

    public String getCible_12() {
        return cible_12;
    }

    public void setCible_12(String cible_12) {
        this.cible_12 = cible_12;
    }

    public String getRealise_1() {
        return realise_1;
    }

    public void setRealise_1(String realise_1) {
        this.realise_1 = realise_1;
    }

    public String getRealise_2() {
        return realise_2;
    }

    public void setRealise_2(String realise_2) {
        this.realise_2 = realise_2;
    }

    public String getRealise_3() {
        return realise_3;
    }

    public void setRealise_3(String realise_3) {
        this.realise_3 = realise_3;
    }

    public String getRealise_4() {
        return realise_4;
    }

    public void setRealise_4(String realise_4) {
        this.realise_4 = realise_4;
    }

    public String getRealise_5() {
        return realise_5;
    }

    public void setRealise_5(String realise_5) {
        this.realise_5 = realise_5;
    }

    public String getRealise_6() {
        return realise_6;
    }

    public void setRealise_6(String realise_6) {
        this.realise_6 = realise_6;
    }

    public String getRealise_7() {
        return realise_7;
    }

    public void setRealise_7(String realise_7) {
        this.realise_7 = realise_7;
    }

    public String getRealise_8() {
        return realise_8;
    }

    public void setRealise_8(String realise_8) {
        this.realise_8 = realise_8;
    }

    public String getRealise_9() {
        return realise_9;
    }

    public void setRealise_9(String realise_9) {
        this.realise_9 = realise_9;
    }

    public String getRealise_10() {
        return realise_10;
    }

    public void setRealise_10(String realise_10) {
        this.realise_10 = realise_10;
    }

    public String getRealise_11() {
        return realise_11;
    }

    public void setRealise_11(String realise_11) {
        this.realise_11 = realise_11;
    }

    public String getRealise_12() {
        return realise_12;
    }

    public void setRealise_12(String realise_12) {
        this.realise_12 = realise_12;
    }

    public Integer getTaux() {
        return taux;
    }

    public void setTaux(Integer taux) {
        this.taux = taux;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return code.toString();
    }

}
</code>```

I want to call the setters setCible_ from 1 to 12 :

```<code>@RequestMapping(value = "/insertIndicateur", method = RequestMethod.POST)
public ModelAndView insertIndicateur(@ModelAttribute("indicateur_formulaire") Indicateur indicateur,
                                    @RequestParam int f_objectif,
                                    @RequestParam int f_nature_indicateur,
                                    @RequestParam String f_periodicite_mesure,
                                    @RequestParam String f_type_sortie,
                                    @RequestParam String acteur_saisie,
                                    @RequestParam String acteur_verif,
                                    @RequestParam Map<String, String> params,
                                    HttpServletRequest request, HttpSession session) {

    indicateurDao.insert(indicateur, f_objectif, f_nature_indicateur, f_periodicite_mesure, f_type_sortie, acteur_saisie, acteur_verif);

    ValeurIndicateur valeurIndicateur = new ValeurIndicateur();

    switch(f_periodicite_mesure) {
        case "ANN":
            valeurIndicateur.setCible_1(params.get("val_indi_cible_1"));
            break;
        case "SEM":
            valeurIndicateur.setCible_1(params.get("val_indi_cible_1"));
            valeurIndicateur.setCible_2(params.get("val_indi_cible_2"));
            break;
        case "TRI":
            valeurIndicateur.setCible_1(params.get("val_indi_cible_1"));
            valeurIndicateur.setCible_2(params.get("val_indi_cible_2"));
            valeurIndicateur.setCible_3(params.get("val_indi_cible_3"));
            valeurIndicateur.setCible_4(params.get("val_indi_cible_4"));
            break;
        case "MEN":

            // here I want to loop from 1 to 12 and call dynamically valeurIndicateur.setCible_

            break;
    }

    valeurIndicateur.setIndicateur(indicateur);
    valeurIndicateur.setPeriodicite_mesure(periodiciteMesureDao.get(f_periodicite_mesure));

    valeurIndicateurDao.insert(valeurIndicateur);

    ModelAndView modelView = new ModelAndView("redirect:/elaboration/");

    return modelView;

}
</code>```

Is there a way to dynamically call them ?

答:
If your Object conforms with the JavaBeans specification, then (as you are using Spring), the BeanWrapper interface is probably your best bet:

```<code>BeanWrapper beanWrapper = new BeanWrapperImpl(yourObject);
Arrays.stream(beanWrapper.getPropertyDescriptors())
      .map(PropertyDescriptor::getName)
      .forEach(name-> beanWrapper.setPropertyValue(name, attributes.get(name))
);
</code>```

Note that the JavaBeans property name "foo" points at the methods "setFoo" and "getFoo".

Or, if you want to iterate over the attributes map, do it like this:

```<code>BeanWrapper beanWrapper = new BeanWrapperImpl(yourObject);
attributes.forEach((k,v)->{
    if(beanWrapper.isWritableProperty(k)) beanWrapper.setPropertyValue(k,v);
});
</code>```

Another way without reflection is to have a hard coded map with BiConsumers that call the methods, something like this:

```<code>static final Map<String, BiConsumer<YourClass,String>> PROPERTY_MAP;
static {
    Map<String, BiConsumer<YourClass,String>> map = new HashMap<>();
    map.put("val_indi_cible_1", YourClass::setCible_1);
    map.put("val_indi_cible_2", YourClass::setCible_2);
    map.put("val_indi_cible_3", YourClass::setCible_3);
    map.put("val_indi_cible_4", YourClass::setCible_3);
    map.put("val_indi_cible_5", YourClass::setCible_4);
    map.put("val_indi_cible_6", YourClass::setCible_5);
    // etc.
    PROPERTY_MAP= Collections.unmodifiableMap(map);
}
</code>```

Now, in your method, you can do something like this:

```<code>YourClass yourClass = new YourClass();
attributes.forEach((k, v) -> Optional.ofNullable(PROPERTY_MAP.get(k))
                                     .ifPresent(bc -> bc.accept(yourClass, v)));
</code>```

Explanation:

Iterate over attributes map

For each key, see if there is an associated property

If present, call that property

Advantage: no reflection, decent performance, compile-time safety

Disadvantage: you have to update the property map whenever you add a new method

Title: How to make a dynamic method call?

Body:
There is a class containing many getters and setters :

@Entity
@Table(name = "valeur_indicateur")
public class ValeurIndicateur {

    @Id
    @SequenceGenerator(name="s_valeur_indicateur", sequenceName="s_valeur_indicateur", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="s_valeur_indicateur")
    @Column(name = "val_indi_code")
    private Integer code;

    @ManyToOne
    @JoinColumn(name = "indi_code")
    private Indicateur indicateur;

    @ManyToOne
    @JoinColumn(name = "peri_mes_code")
    private PeriodiciteMesure periodicite_mesure;

    @Column(name = "val_indi_cible_1")
    private String cible_1;

    @Column(name = "val_indi_cible_2")
    private String cible_2;

    @Column(name = "val_indi_cible_3")
    private String cible_3;

    @Column(name = "val_indi_cible_4")
    private String cible_4;

    @Column(name = "val_indi_cible_5")
    private String cible_5;

    @Column(name = "val_indi_cible_6")
    private String cible_6;

    @Column(name = "val_indi_cible_7")
    private String cible_7;

    @Column(name = "val_indi_cible_8")
    private String cible_8;

    @Column(name = "val_indi_cible_9")
    private String cible_9;

    @Column(name = "val_indi_cible_10")
    private String cible_10;

    @Column(name = "val_indi_cible_11")
    private String cible_11;

    @Column(name = "val_indi_cible_12")
    private String cible_12;

    @Column(name = "val_indi_realise_1")
    private String realise_1;

    @Column(name = "val_indi_realise_2")
    private String realise_2;

    @Column(name = "val_indi_realise_3")
    private String realise_3;

    @Column(name = "val_indi_realise_4")
    private String realise_4;

    @Column(name = "val_indi_realise_5")
    private String realise_5;

    @Column(name = "val_indi_realise_6")
    private String realise_6;

    @Column(name = "val_indi_realise_7")
    private String realise_7;

    @Column(name = "val_indi_realise_8")
    private String realise_8;

    @Column(name = "val_indi_realise_9")
    private String realise_9;

    @Column(name = "val_indi_realise_10")
    private String realise_10;

    @Column(name = "val_indi_realise_11")
    private String realise_11;

    @Column(name = "val_indi_realise_12")
    private String realise_12;

    @Column(name = "val_indi_taux")
    private Integer taux;

    public ValeurIndicateur() {
        super();
        // TODO Auto-generated constructor stub
    }

    public ValeurIndicateur(Integer code) {
        super();
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public Indicateur getIndicateur() {
        return indicateur;
    }

    public void setIndicateur(Indicateur indicateur) {
        this.indicateur = indicateur;
    }

    public PeriodiciteMesure getPeriodicite_mesure() {
        return periodicite_mesure;
    }

    public void setPeriodicite_mesure(PeriodiciteMesure periodicite_mesure) {
        this.periodicite_mesure = periodicite_mesure;
    }

    public String getCible_1() {
        return cible_1;
    }

    public void setCible_1(String cible_1) {
        this.cible_1 = cible_1;
    }

    public String getCible_2() {
        return cible_2;
    }

    public void setCible_2(String cible_2) {
        this.cible_2 = cible_2;
    }

    public String getCible_3() {
        return cible_3;
    }

    public void setCible_3(String cible_3) {
        this.cible_3 = cible_3;
    }

    public String getCible_4() {
        return cible_4;
    }

    public void setCible_4(String cible_4) {
        this.cible_4 = cible_4;
    }

    public String getCible_5() {
        return cible_5;
    }

    public void setCible_5(String cible_5) {
        this.cible_5 = cible_5;
    }

    public String getCible_6() {
        return cible_6;
    }

    public void setCible_6(String cible_6) {
        this.cible_6 = cible_6;
    }

    public String getCible_7() {
        return cible_7;
    }

    public void setCible_7(String cible_7) {
        this.cible_7 = cible_7;
    }

    public String getCible_8() {
        return cible_8;
    }

    public void setCible_8(String cible_8) {
        this.cible_8 = cible_8;
    }

    public String getCible_9() {
        return cible_9;
    }

    public void setCible_9(String cible_9) {
        this.cible_9 = cible_9;
    }

    public String getCible_10() {
        return cible_10;
    }

    public void setCible_10(String cible_10) {
        this.cible_10 = cible_10;
    }

    public String getCible_11() {
        return cible_11;
    }

    public void setCible_11(String cible_11) {
        this.cible_11 = cible_11;
    }

    public String getCible_12() {
        return cible_12;
    }

    public void setCible_12(String cible_12) {
        this.cible_12 = cible_12;
    }

    public String getRealise_1() {
        return realise_1;
    }

    public void setRealise_1(String realise_1) {
        this.realise_1 = realise_1;
    }

    public String getRealise_2() {
        return realise_2;
    }

    public void setRealise_2(String realise_2) {
        this.realise_2 = realise_2;
    }

    public String getRealise_3() {
        return realise_3;
    }

    public void setRealise_3(String realise_3) {
        this.realise_3 = realise_3;
    }

    public String getRealise_4() {
        return realise_4;
    }

    public void setRealise_4(String realise_4) {
        this.realise_4 = realise_4;
    }

    public String getRealise_5() {
        return realise_5;
    }

    public void setRealise_5(String realise_5) {
        this.realise_5 = realise_5;
    }

    public String getRealise_6() {
        return realise_6;
    }

    public void setRealise_6(String realise_6) {
        this.realise_6 = realise_6;
    }

    public String getRealise_7() {
        return realise_7;
    }

    public void setRealise_7(String realise_7) {
        this.realise_7 = realise_7;
    }

    public String getRealise_8() {
        return realise_8;
    }

    public void setRealise_8(String realise_8) {
        this.realise_8 = realise_8;
    }

    public String getRealise_9() {
        return realise_9;
    }

    public void setRealise_9(String realise_9) {
        this.realise_9 = realise_9;
    }

    public String getRealise_10() {
        return realise_10;
    }

    public void setRealise_10(String realise_10) {
        this.realise_10 = realise_10;
    }

    public String getRealise_11() {
        return realise_11;
    }

    public void setRealise_11(String realise_11) {
        this.realise_11 = realise_11;
    }

    public String getRealise_12() {
        return realise_12;
    }

    public void setRealise_12(String realise_12) {
        this.realise_12 = realise_12;
    }

    public Integer getTaux() {
        return taux;
    }

    public void setTaux(Integer taux) {
        this.taux = taux;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return code.toString();
    }

}

I want to call the setters setCible_ from 1 to 12 :

@RequestMapping(value = "/insertIndicateur", method = RequestMethod.POST)
public ModelAndView insertIndicateur(@ModelAttribute("indicateur_formulaire") Indicateur indicateur,
                                    @RequestParam int f_objectif,
                                    @RequestParam int f_nature_indicateur,
                                    @RequestParam String f_periodicite_mesure,
                                    @RequestParam String f_type_sortie,
                                    @RequestParam String acteur_saisie,
                                    @RequestParam String acteur_verif,
                                    @RequestParam Map<String, String> params,
                                    HttpServletRequest request, HttpSession session) {

    indicateurDao.insert(indicateur, f_objectif, f_nature_indicateur, f_periodicite_mesure, f_type_sortie, acteur_saisie, acteur_verif);

    ValeurIndicateur valeurIndicateur = new ValeurIndicateur();

    switch(f_periodicite_mesure) {
        case "ANN":
            valeurIndicateur.setCible_1(params.get("val_indi_cible_1"));
            break;
        case "SEM":
            valeurIndicateur.setCible_1(params.get("val_indi_cible_1"));
            valeurIndicateur.setCible_2(params.get("val_indi_cible_2"));
            break;
        case "TRI":
            valeurIndicateur.setCible_1(params.get("val_indi_cible_1"));
            valeurIndicateur.setCible_2(params.get("val_indi_cible_2"));
            valeurIndicateur.setCible_3(params.get("val_indi_cible_3"));
            valeurIndicateur.setCible_4(params.get("val_indi_cible_4"));
            break;
        case "MEN":

            // here I want to loop from 1 to 12 and call dynamically valeurIndicateur.setCible_

            break;
    }

    valeurIndicateur.setIndicateur(indicateur);
    valeurIndicateur.setPeriodicite_mesure(periodiciteMesureDao.get(f_periodicite_mesure));

    valeurIndicateurDao.insert(valeurIndicateur);

    ModelAndView modelView = new ModelAndView("redirect:/elaboration/");

    return modelView;

}

Is there a way to dynamically call them ?

Body:
If your Object conforms with the JavaBeans specification, then (as you are using Spring), the BeanWrapper interface is probably your best bet:

BeanWrapper beanWrapper = new BeanWrapperImpl(yourObject);
Arrays.stream(beanWrapper.getPropertyDescriptors())
      .map(PropertyDescriptor::getName)
      .forEach(name-> beanWrapper.setPropertyValue(name, attributes.get(name))
);

Note that the JavaBeans property name "foo" points at the methods "setFoo" and "getFoo".

Or, if you want to iterate over the attributes map, do it like this:

BeanWrapper beanWrapper = new BeanWrapperImpl(yourObject);
attributes.forEach((k,v)->{
    if(beanWrapper.isWritableProperty(k)) beanWrapper.setPropertyValue(k,v);
});

Another way without reflection is to have a hard coded map with BiConsumers that call the methods, something like this:

static final Map<String, BiConsumer<YourClass,String>> PROPERTY_MAP;
static {
    Map<String, BiConsumer<YourClass,String>> map = new HashMap<>();
    map.put("val_indi_cible_1", YourClass::setCible_1);
    map.put("val_indi_cible_2", YourClass::setCible_2);
    map.put("val_indi_cible_3", YourClass::setCible_3);
    map.put("val_indi_cible_4", YourClass::setCible_3);
    map.put("val_indi_cible_5", YourClass::setCible_4);
    map.put("val_indi_cible_6", YourClass::setCible_5);
    // etc.
    PROPERTY_MAP= Collections.unmodifiableMap(map);
}

Now, in your method, you can do something like this:

YourClass yourClass = new YourClass();
attributes.forEach((k, v) -> Optional.ofNullable(PROPERTY_MAP.get(k))
                                     .ifPresent(bc -> bc.accept(yourClass, v)));

Explanation:

Iterate over attributes map

For each key, see if there is an associated property

If present, call that property

Advantage: no reflection, decent performance, compile-time safety

Disadvantage: you have to update the property map whenever you add a new method


问:
How to resolve error "Cannot find name '_' " using lodash in angular2 app with webpack
Here's how I import lodash in typescript/angular2 app using webpack:

$ npm install lodash --save

$ typings install dt~lodash --save

In webpack.config.js:

```<code>module.exports = {
   plugins: [
      new ProvidePlugin({
         '_' : 'lodash'
</code>```

And it works.

But there's still an error in my editor (Sublime) and in the terminal on runtime : Cannot find name '_'

So, what I'm missing?

In the .ts file where i use lodash I tried to declare it like so:

```<code>declare var _ : LoDashStatic
</code>```

with no luck.

答:
I am not sure how old this issue is but these kind of issues are still happening. I have just added Lodash type definition into my Angular-CLI project and made it work. It was part of an experiment where I wanted some third party libraries to be used inside Angular2. I had to struggle a bit to figure out how it works so here it goes.

The current type definition for Lodash seems having some issue. So I am getting error while compiling. I replaced the content of type definition file with an older version of lodash type definition file and it worked.
Working version is from the path,

https://github.com/borisyankov/DefinitelyTyped

I installed lodash with  typings install dt~lodash --save

Once you add any type definition file, it will get a reference in the base type definition file as shown below.

Now if you miss to refer the base file in tsconfig.json, we won't have the lodash module available in Angular2. You can add it as below,

To use the lodash feature import the module which you can see if you open the type definition file. In case of lodash it's "lodash".

In your components you can import the librabries like,

```<code>import * as $ from 'jquery';
import * as _ from "lodash";
</code>```

and use the features in code,

Eg:

and the result is,

Body:
Here's how I import lodash in typescript/angular2 app using webpack:

$ npm install lodash --save

$ typings install dt~lodash --save

In webpack.config.js:

module.exports = {
   plugins: [
      new ProvidePlugin({
         '_' : 'lodash'

And it works.

But there's still an error in my editor (Sublime) and in the terminal on runtime : Cannot find name '_'

So, what I'm missing?

In the .ts file where i use lodash I tried to declare it like so:

declare var _ : LoDashStatic

with no luck.

Body:
I am not sure how old this issue is but these kind of issues are still happening. I have just added Lodash type definition into my Angular-CLI project and made it work. It was part of an experiment where I wanted some third party libraries to be used inside Angular2. I had to struggle a bit to figure out how it works so here it goes.

The current type definition for Lodash seems having some issue. So I am getting error while compiling. I replaced the content of type definition file with an older version of lodash type definition file and it worked.
Working version is from the path,

https://github.com/borisyankov/DefinitelyTyped

I installed lodash with  typings install dt~lodash --save

Once you add any type definition file, it will get a reference in the base type definition file as shown below.

Now if you miss to refer the base file in tsconfig.json, we won't have the lodash module available in Angular2. You can add it as below,

To use the lodash feature import the module which you can see if you open the type definition file. In case of lodash it's "lodash".

In your components you can import the librabries like,

import * as $ from 'jquery';
import * as _ from "lodash";

and use the features in code,

Eg:

and the result is,


问:
angular 2 [innerHTML] render inside html (not working on angular 2 )
i am using Angular 2 and i try to render the text which i have inside the variable action.render as html code:

```<code><p *ngIf="action.isHtml">
      <div [innerHTML]="{{action.content}}"></div>
</p>
<p *ngIf="!action.isHtml">
      {{action.content}}
</p>
</code>```

the innerHTML doesn't work in my case. is there any other approach with Angular 2? (here is what i get )

this is my action.content

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>
            </title>
            <style type="text/css">
                .cs2654AE3A{text-align:left;text-indent:0pt;margin:0pt 0pt 0pt 0pt}
                .csC8F6D76{color:#000000;background-color:transparent;font-family:Calibri;font-size:11pt;font-weight:normal;font-style:normal;}
            </style>
        </head>
        <body>
            <p class="cs2654AE3A"><span class="csC8F6D76">New claim declaration by HD team 00015371</span></p></body>
    </html>
</code>```

答:
Change your code to this and try again :

```<code><p *ngIf="action.isHtml">
      <div [innerHTML]="action.content"></div>
</p>
<p *ngIf="!action.isHtml">
      {{action.content}}
</p>
</code>```

You should use either innerHTML="{{action.content}}" or [innerHTML]="action.content" but not [innerHTML]="{{action.content}}"

Body:
i am using Angular 2 and i try to render the text which i have inside the variable action.render as html code:

      {{action.content}}

the innerHTML doesn't work in my case. is there any other approach with Angular 2? (here is what i get )

this is my action.content

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>
            </title>

New claim declaration by HD team 00015371

Body:
Change your code to this and try again :

<p *ngIf="action.isHtml">
      <div [innerHTML]="action.content"></div>
</p>
<p *ngIf="!action.isHtml">
      {{action.content}}
</p>

You should use either innerHTML="{{action.content}}" or [innerHTML]="action.content" but not [innerHTML]="{{action.content}}"


问:
Using gitattributes for linguist examples
Are there any concrete examples, in order to detect wrong languages in GitHub via Linguist attributes?

Source: https://github.com/github/linguist

linguist-documentation

linguist-language

linguist-vendored

答:
Examples can be found in Linguist's documentation.
Detecting wrong languages (which's what OP asks) can be achieved by setting linguist-language attributes in the .gitattributes file.

linguist-language

With the following attribute, Linguist detects all .rb files as being Java files.

```<code>*.rb linguist-language=Java
</code>```

linguist-vendored

With the following attribute, Linguist detects files in the special-vendored-path directory (notice the mandatory trailing *) as vendored and excludes them from statistics.

```<code>special-vendored-path/* linguist-vendored
</code>```

linguist-documentation

Without the following attribute, Linguist would detect the file docs/formatter.rb as documentation and exclude it from statistics.

```<code>docs/formatter.rb linguist-documentation=false
</code>```

linguist-detectable

With the following attribute, Linguist counts SQL files in statistics. Without this attribute, only programming and markup languages are counted in statistics.

```<code>*.sql linguist-detectable=true
</code>```

Body:
Examples can be found in Linguist's documentation.
Detecting wrong languages (which's what OP asks) can be achieved by setting linguist-language attributes in the .gitattributes file.

linguist-language

With the following attribute, Linguist detects all .rb files as being Java files.

*.rb linguist-language=Java

linguist-vendored

With the following attribute, Linguist detects files in the special-vendored-path directory (notice the mandatory trailing *) as vendored and excludes them from statistics.

special-vendored-path/* linguist-vendored

linguist-documentation

Without the following attribute, Linguist would detect the file docs/formatter.rb as documentation and exclude it from statistics.

docs/formatter.rb linguist-documentation=false

linguist-detectable

With the following attribute, Linguist counts SQL files in statistics. Without this attribute, only programming and markup languages are counted in statistics.

*.sql linguist-detectable=true

ContentLicense: CC BY-SA 4.0


问:
Qt5: show notification popups
I'm writing an image viewer which allows me to do some actions. As a visual feedback to some actions (like copy/move/delete/..) I'd like to have a decent popup in the middle of my application window which informs about what has been done and which disappears after about a second.

Of course I can just use a Widget and and modify it to fit my needs:

placed in the middle/on top of application window (regardless of layout)

disappears after a given time

no interaction/focus possible - clicking on the notification should be like clicking on what's behind of it

decent style (e.g. transparent and easily readable)

.. I'm just wondering if there's something dedicated for this purpose

(I'm NOT talking about tray notifications which appear near to some task barof the window manager)

答:
You can achieve a nice popup fade in/fade out effect using animation effects in qt ,sample code is given below :

```<code>QGraphicsOpacityEffect* effect=new QGraphicsOpacityEffect();
this->label->setGraphicsEffect(effect);
this->label->setStyleSheet("border: 3px solid gray;border-radius:20px;background-color:#ffffff;color:gray");
this->label->setAlignment(Qt::AlignCenter);
this->label->setText("Your Notification");
QPropertyAnimation* a=new QPropertyAnimation(effect,"opacity");
a->setDuration(1000);  // in miliseconds
a->setStartValue(0);
a->setEndValue(1);
a->setEasingCurve(QEasingCurve::InBack);
a->start(QPropertyAnimation::DeleteWhenStopped);
this->label->show();
connect(this->timer,&QTimer::timeout,this,&Notifier::fadeOut);
this->timer->start(2000); // 1000 ms to make the notification opacity full and 1000 seconds to call the fade out so total of 2000ms.
</code>```

and your fadeout method as:

```<code>void fadeOut(){
    QGraphicsOpacityEffect *effect = new QGraphicsOpacityEffect();
    this->label->setGraphicsEffect(effect);
    QPropertyAnimation *a = new QPropertyAnimation(effect,"opacity");
    a->setDuration(1000); // it will took 1000ms to face out
    a->setStartValue(1);
    a->setEndValue(0);
    a->setEasingCurve(QEasingCurve::OutBack);
    a->start(QPropertyAnimation::DeleteWhenStopped);
    connect(a,SIGNAL(finished()),this->label,SLOT(hide()));
}
</code>```

Title: Qt5: show notification popups

Body:
You can achieve a nice popup fade in/fade out effect using animation effects in qt ,sample code is given below :

QGraphicsOpacityEffect* effect=new QGraphicsOpacityEffect();
this->label->setGraphicsEffect(effect);
this->label->setStyleSheet("border: 3px solid gray;border-radius:20px;background-color:#ffffff;color:gray");
this->label->setAlignment(Qt::AlignCenter);
this->label->setText("Your Notification");
QPropertyAnimation* a=new QPropertyAnimation(effect,"opacity");
a->setDuration(1000);  // in miliseconds
a->setStartValue(0);
a->setEndValue(1);
a->setEasingCurve(QEasingCurve::InBack);
a->start(QPropertyAnimation::DeleteWhenStopped);
this->label->show();
connect(this->timer,&QTimer::timeout,this,&Notifier::fadeOut);
this->timer->start(2000); // 1000 ms to make the notification opacity full and 1000 seconds to call the fade out so total of 2000ms.

and your fadeout method as:

void fadeOut(){
    QGraphicsOpacityEffect *effect = new QGraphicsOpacityEffect();
    this->label->setGraphicsEffect(effect);
    QPropertyAnimation *a = new QPropertyAnimation(effect,"opacity");
    a->setDuration(1000); // it will took 1000ms to face out
    a->setStartValue(1);
    a->setEndValue(0);
    a->setEasingCurve(QEasingCurve::OutBack);
    a->start(QPropertyAnimation::DeleteWhenStopped);
    connect(a,SIGNAL(finished()),this->label,SLOT(hide()));
}


问:
deleting information in my table
Hello I've got my code I just want to delete an specific row but it will delete all when I run my program..?</p>

```<code> <html>
 <body>
 <?php
 $servername = "localhost";
 $username = "root";
 $password = "";
 $dbname = "csedb";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// sql to delete a record
$sql = "DELETE FROM addform WHERE id_stu=$id_stu";

if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
if($sql)
{
header('location:student.php');
}
mysqli_close($conn);
?>
</body>
</html>
</code>```

答:
You need to pass specific id of the row which you want to delete.

```<code>$sql = "DELETE FROM addform WHERE id_stu=id_to_delete";
</code>```

Also, don't forget to look about how to prevent sql injection.

Title: deleting information in my table

Body:
Hello I've got my code I just want to delete an specific row but it will delete all when I run my program..?

 <?php
 $servername = "localhost";
 $username = "root";
 $password = "";
 $dbname = "csedb";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

// sql to delete a record
$sql = "DELETE FROM addform WHERE id_stu=$id_stu";

if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . mysqli_error($conn);
}
if($sql)
{
header('location:student.php');
}
mysqli_close($conn);
?>

Body:
You need to pass specific id of the row which you want to delete.

$sql = "DELETE FROM addform WHERE id_stu=id_to_delete";

Also, don't forget to look about how to prevent sql injection.


问:
OAuth Not Working With Laravel
i am trying to connect my magento 2.0 store from my laravel application, when i make OAuth call from laravel to my magento 2.0 store laravel throws an error Class 'OAuth' not found.

OAuth is installed on my system and code works perfectly out side laravel but when i place code inside of a Laravel controller it throws the error

following is my code of OAuth call that i am making from laravel

```<code>$oAuth = new OAuth($integratoinData->auth_data->consumer_key, $integratoinData->auth_data->consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
        $oAuth->setToken($integratoinData->auth_data->access_token, $integratoinData->auth_data->access_token_secret);

        $oAuth->fetch($integrationCredentials['url']);

        $responseInfo   = $oAuth->getLastResponseInfo();
</code>```

please help me thank you in advance

答:
Try adding '\' when making instance of OAuth:</p>

```<code>$oAuth = new \OAuth($integrato...
</code>```

Title: OAuth Not Working With Laravel

Body:
i am trying to connect my magento 2.0 store from my laravel application, when i make OAuth call from laravel to my magento 2.0 store laravel throws an error Class 'OAuth' not found.

OAuth is installed on my system and code works perfectly out side laravel but when i place code inside of a Laravel controller it throws the error

following is my code of OAuth call that i am making from laravel

$oAuth = new OAuth($integratoinData->auth_data->consumer_key, $integratoinData->auth_data->consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
        $oAuth->setToken($integratoinData->auth_data->access_token, $integratoinData->auth_data->access_token_secret);

        $oAuth->fetch($integrationCredentials['url']);

        $responseInfo   = $oAuth->getLastResponseInfo();

please help me thank you in advance

Body:
Try adding '\' when making instance of OAuth:

$oAuth = new \OAuth($integrato...


问:
How to make text that is outside of the header/footer to repeat for every page in Odoo Qweb report
I need a custom text to repeat on every page in multi page pdf report. The thing is that this custom text is not in the header/footer section. Any idea how this can be accomplished?</p>

答:
Try this code

```<code><template id="report_test">
<t t-call="report.external_layout">
    <t t-foreach="docs" t-as="o">
        <div class="page">
            <!-- Add text you want to repeat every page here -->
            <div class="row">
                <!-- your reprot data print here -->
            </div>
        </div>
    </t>
</t>
</code>```

Body:
Try this code

<template id="report_test">
<t t-call="report.external_layout">
    <t t-foreach="docs" t-as="o">
        <div class="page">
            <!-- Add text you want to repeat every page here -->
            <div class="row">
                <!-- your reprot data print here -->
            </div>
        </div>
    </t>
</t>


问:
Telerik UI controls vs client-side UI with jQuery
I am trying decide on how I want to handle the UI for an external-facing web app. Because it is external, latency caused by page bloat could be an issue.

I have used jQuery some in the past, and I am evaluating the Telerik controls now. I have seen a lot of good recommendations on the Telerik controls, including some on StackOverflow. Indeed they do seem fairly full-featured. I also have no doubt that I can develop the application much more quickly using those controls than I can with jQuery. However, I am worried that they will cause too much bloat on my pages.

Do any of you have experience comparing the performance of these controls against a purely jQuery implementation? Specifically,

Is the RadScriptManager from Telerik really any better than the MS Ajax ScriptManager?

Are there performance issues in general with the Telerik controls?

Is there any plug-in for jQuery that comes close to the grid functionality of RadGrid?

Any other related information would be useful as well.

答:
In case it helps anyone later, I have dumped the Telerik tools and am using jQuery exclusively for now. We'll see if I run into something that I can't do. I was disappointed in the Telerik tools. I had heard so many good things about them, but they didn't work so well for me. Here is what I found when evaluating the Telerik tools.

The Telerik Ajax tools have problems handling master/content page setups. They acknowledge this in their forums, and I guess they are working on it. Quite problematic for me though.

I saw lots of unexpected behaviors and quirks that don't seem to have any documentation. For example, when using the Web20 skin and form decorator, the rounded corners on a fieldset go all to hell when doing Ajax.

The Telerik tools slowed down my dev machine quite a bit and seem to cause problems with my environment. I almost never have crashes or memory violations, and I had four in two days while using these tools. It had probably been a month since my last one before that.

So combine all that with the fact that jQuery is free and lightweight, and the choice was easy. It might take me a little longer initially, but the result will be much better in the end.

OwnerDisplayName: NealS

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: nshaw


问:
Should an object under the @Mock annotation have its constructor called?
I'm trying to create an unit test mocking some dependencies with Mockito.
Here's the main code:

```<code>import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class VolumesPresenterTest {

VolumesPresenter presenter;

@Mock
OrderRepository orderRepository;

@Mock
VolumesRepository volumesRepository;

@Before
public void createPresenter() {
    presenter = new DefaultVolumesPresenter(orderRepository, volumesRepository);
}

@Test
public void testGetVolumes() {
    presenter.getVolumes();
    verify(volumesRepository).getVolumes();
}
}
</code>```

OrderRepository has a single constructor, which receives an Android Context as a param. This is causing the unit test to fail with the following stack trace:

```<code>java.lang.NoClassDefFoundError: android/content/Context

at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
at java.lang.Class.getDeclaredConstructors(Class.java:2020)
at org.mockito.internal.creation.cglib.ClassImposterizer.setConstructorsAccessible(ClassImposterizer.java:85)
at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:71)
at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:49)
at org.mockito.internal.creation.cglib.CglibMockMaker.createMock(CglibMockMaker.java:24)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
at org.mockito.Mockito.mock(Mockito.java:1285)
at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:33)
at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
at org.mockito.internal.configuration.DefaultAnnotationEngine.createMockFor(DefaultAnnotationEngine.java:43)
at org.mockito.internal.configuration.DefaultAnnotationEngine.process(DefaultAnnotationEngine.java:66)
at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:71)
at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:55)
at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:108)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl$1.withBefores(JUnit45AndHigherRunnerImpl.java:27)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:276)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException: android.content.Context
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 39 more

Test ignored.
Process finished with exit code 255
</code>```

I understand that I can't use the android framework on unit tests, but I didn't expect the real constructor of OrderRepository to be called. Being a mocked object, I thought it would just be replaced with some other dumb/mock implementation.

My question is: am I missing anything or the constructors of objects annotated with @Mock are indeed supposed to be called? If so, how can I mock a dependency which expects a Context as a param to its constructor?

答:
OrderRepository has a single constructor, which receives an Android Context as a param. This is causing the unit test to fail with the following stack trace:

```<code>java.lang.NoClassDefFoundError: android/content/Context
</code>```

No!

The error message tells that you have a problem with your classpath.

Body:
I'm trying to create an unit test mocking some dependencies with Mockito.
Here's the main code:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class VolumesPresenterTest {

VolumesPresenter presenter;

@Mock
OrderRepository orderRepository;

@Mock
VolumesRepository volumesRepository;

@Before
public void createPresenter() {
    presenter = new DefaultVolumesPresenter(orderRepository, volumesRepository);
}

@Test
public void testGetVolumes() {
    presenter.getVolumes();
    verify(volumesRepository).getVolumes();
}
}

OrderRepository has a single constructor, which receives an Android Context as a param. This is causing the unit test to fail with the following stack trace:

java.lang.NoClassDefFoundError: android/content/Context

at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2671)
at java.lang.Class.getDeclaredConstructors(Class.java:2020)
at org.mockito.internal.creation.cglib.ClassImposterizer.setConstructorsAccessible(ClassImposterizer.java:85)
at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:71)
at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:49)
at org.mockito.internal.creation.cglib.CglibMockMaker.createMock(CglibMockMaker.java:24)
at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
at org.mockito.Mockito.mock(Mockito.java:1285)
at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:33)
at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
at org.mockito.internal.configuration.DefaultAnnotationEngine.createMockFor(DefaultAnnotationEngine.java:43)
at org.mockito.internal.configuration.DefaultAnnotationEngine.process(DefaultAnnotationEngine.java:66)
at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:71)
at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:55)
at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:108)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl$1.withBefores(JUnit45AndHigherRunnerImpl.java:27)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:276)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException: android.content.Context
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 39 more

Test ignored.
Process finished with exit code 255

I understand that I can't use the android framework on unit tests, but I didn't expect the real constructor of OrderRepository to be called. Being a mocked object, I thought it would just be replaced with some other dumb/mock implementation.

My question is: am I missing anything or the constructors of objects annotated with @Mock are indeed supposed to be called? If so, how can I mock a dependency which expects a Context as a param to its constructor?

Body:
OrderRepository has a single constructor, which receives an Android Context as a param. This is causing the unit test to fail with the following stack trace:

java.lang.NoClassDefFoundError: android/content/Context

No!

The error message tells that you have a problem with your classpath.


问:
Excel 2007 simple copy and paste vba not working in excel 2016
I've put together what is an audit workbook which is supposed to copy and paste some hidden cells to a data storage sheet that is hidden the collective data in the hidden sheet is then used for KPI reports.

The problem is that I've put it together in Excel 2007, in which it works perfectly but now it needs to be used in Excel 2016.

I'm running the macro from a button, if the button is pressed  it copies the data and selects the field in the hidden sheet but doesn't paste, no error dialogues either.

When I step  through the code in the vba editor it works fine, but not from the button despite the button being linked to the code. I'm a bit lost or what to do as I don't know how to correct the code.

Here's the code:

```<code>Sub CopyPhoneAuditToDB()
'
'
' Copy Phone Audit To DB

'
    Application.ScreenUpdating = False
    Sheets("Data Phone").Visible = xlSheetVisible
    Sheets("Data Phone").Unprotect
    Range("E49:T49").Select
    Selection.Copy
    Sheets("Data Phone").Select
    Range("A2").Select
    Cells(Rows.Count, "A").End(xlUp).Offset(1).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveSheet.Protect
    Sheets("Phone Audit").Select
    Range("H5:J5").Select
    Sheets("Data Phone").Visible = xlSheetVeryHidden
    ActiveWorkbook.Save
End Sub
</code>```

答:
Please let me know if this works for you:</p>

```<code>Option Explicit

Sub CopyPhoneAuditToDB()

Application.ScreenUpdating = False

With Sheets("Data Phone")
    .Visible = xlSheetVeryHidden
    .Unprotect
    Sheets("Phone Audit").Range("E49:T49").Copy
    .Cells(.Rows.Count, "A").End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValues, _
        Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    .Protect
End With

With Sheets("Phone Audit")
    .Activate
    .Range("H5:J5").Select
End With

Application.ScreenUpdating = True
ActiveWorkbook.Save

End Sub
</code>```

Body:
I've put together what is an audit workbook which is supposed to copy and paste some hidden cells to a data storage sheet that is hidden the collective data in the hidden sheet is then used for KPI reports.

The problem is that I've put it together in Excel 2007, in which it works perfectly but now it needs to be used in Excel 2016.

I'm running the macro from a button, if the button is pressed  it copies the data and selects the field in the hidden sheet but doesn't paste, no error dialogues either.

When I step  through the code in the vba editor it works fine, but not from the button despite the button being linked to the code. I'm a bit lost or what to do as I don't know how to correct the code.

Here's the code:

Sub CopyPhoneAuditToDB()
'
'
' Copy Phone Audit To DB

'
    Application.ScreenUpdating = False
    Sheets("Data Phone").Visible = xlSheetVisible
    Sheets("Data Phone").Unprotect
    Range("E49:T49").Select
    Selection.Copy
    Sheets("Data Phone").Select
    Range("A2").Select
    Cells(Rows.Count, "A").End(xlUp).Offset(1).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveSheet.Protect
    Sheets("Phone Audit").Select
    Range("H5:J5").Select
    Sheets("Data Phone").Visible = xlSheetVeryHidden
    ActiveWorkbook.Save
End Sub

Body:
Please let me know if this works for you:

Option Explicit

Sub CopyPhoneAuditToDB()

Application.ScreenUpdating = False

With Sheets("Data Phone")
    .Visible = xlSheetVeryHidden
    .Unprotect
    Sheets("Phone Audit").Range("E49:T49").Copy
    .Cells(.Rows.Count, "A").End(xlUp).Offset(1).PasteSpecial Paste:=xlPasteValues, _
        Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    .Protect
End With

With Sheets("Phone Audit")
    .Activate
    .Range("H5:J5").Select
End With

Application.ScreenUpdating = True
ActiveWorkbook.Save

End Sub


问:
Xamarin Android Audio DSP
I am looking for a audio DSP or FFT library which I can use for Xamarin, first and foremost Android, but iOS but also be cool.

I tried using Superpowered, but they only provide a static library which I can not link in the project.
I also tried using JTransforms, which unfortunately wont succesfully bind and is also not an android java library (only general android seem to work, according to xamarin documentation).

At first I tried using Xamarin Android Visualizer, but I want to be able to record/listen for sound and perform audio analysis "simultanously", without playing it back.

So, does anybody know a library, nuget or anything? I am really clueless.

答: Here is how Bryon Baker used Superpowered with Xamarin: http://superpowered.com/working-with-audio-in-xamarin-with-superpowered-audio-engine</p>

Title: Xamarin Android Audio DSP


问:
SQL Exclude Zero from Case Column
I have a query inserting values into a table and am using CASE to determine the value for each row. I was wondering if it is possible at the end of it to then exclude null or zero from the calculated column?

```<code>   CASE
       WHEN Value = 0 THEN Value2
       WHEN Value2 < Value1 THEN Value3
       WHEN Value2 > Value1 THEN Value4
   END AS Final_Value
</code>```

This produces a few hundred thousand rows, of which a good few thousand are now zero or null. Can I exclude these in the same piece of code?

Thanks

答:
Use the where clause:

```<code>select
   ...
 , case
  when value = 0
   then value2
  when value2 < value1
   then value3
  when value2 > value1
   then value4
  end as final_value
from  ...
where case
       when value = 0 then value2
       when value2 < value1 then value3
       when value2 > value1 then value4
   end <> 0
</code>```

Title: SQL Exclude Zero from Case Column

Body:
I have a query inserting values into a table and am using CASE to determine the value for each row. I was wondering if it is possible at the end of it to then exclude null or zero from the calculated column?

   CASE
       WHEN Value = 0 THEN Value2
       WHEN Value2 < Value1 THEN Value3
       WHEN Value2 > Value1 THEN Value4
   END AS Final_Value

This produces a few hundred thousand rows, of which a good few thousand are now zero or null. Can I exclude these in the same piece of code?

Thanks

Body:
Use the where clause:

select
   ...
 , case
  when value = 0
   then value2
  when value2 < value1
   then value3
  when value2 > value1
   then value4
  end as final_value
from  ...
where case
       when value = 0 then value2
       when value2 < value1 then value3
       when value2 > value1 then value4
   end <> 0


问:
How to set a value to display for bound properties in WPF design mode?
My bound contents are showed as empty string in the UI design-mode. I want to display some faked value for those contents but I don't know how to.

Please share if you know how to. Thank you!

答:
You can wrap your content in another property and test if the value is empty. In that case return the fake value you want.</p>

```<code>private string _content;
public string Content
{
    get
    {
        if (_content != "") return _content;
        else return "FAKE";
    }
    set { _content= value; }
}
</code>```

Body:
You can wrap your content in another property and test if the value is empty. In that case return the fake value you want.

private string _content;
public string Content
{
    get
    {
        if (_content != "") return _content;
        else return "FAKE";
    }
    set { _content= value; }
}


问:
creating a form in excel using VBA
I am trying to creat a form in excel using VBA, but I am stuck at the Code. I need to find out the code to enter a data to my worksheet using VBA form . here is the code I am using, but doesn't work..

```<code>Private Sub cmdAdd_Click()

Dim LastRow As Range
Dim DPDIAdhocRequestTable As ListObject

With LastRow

    Cells(1, 2) = RequesterName.Value
    Cells(1, 3) = RequesterPhoneNumber.Value
    Cells(1, 4) = RequesterBureau.Value
    Cells(1, 5) = DateRequestMade.Value
    Cells(1, 6) = DateRequestDue.Value
    Cells(1, 7) = PurposeofRequest.Value
    Cells(1, 8) = ExpectedDataSaurce.Value
    Cells(1, 9) = Timeperiodofdatarequested.Value
    Cells(1, 10) = ReoccuringRequest.Value
    Cells(1, 11) = RequestNumber.Value
    Cells(1, 12) = AnalystAssigned.Value
    Cells(1, 13) = AnalystEstimatedDueDate.Value
    Cells(1, 14) = AnalystCompletedDate.Value
    Cells(1, 15) = SupervisiorName.Value

End With

End Sub
</code>```

can you help me to figure out the correct code for enter command?

thank you so much for your help.

答:
The first problem is that you've created a Range named LastRow but haven't assigned anything to it.

```<code>'Declaration
Dim LastRow As Range
'Assigns the last row based on the last item in Column A
Set LastRow = Range("A" & Rows.Count).End(xlUp).Row
With LastRow
    ...
End With
</code>```

The second issue is a minor syntax error in your With LastRow block.

```<code> With LastRow
      Cells(x,y).Value = "Foo"
 End With
</code>```

Should be

```<code> With LastRow
     .Cells(x,y).Value = "Foo"
 End With
</code>```

Which is essentially the same as saying LastRow.Cells(x,y).Value = "Foo". Without the "." in front of Cells() VBA will not apply the With to that object, and assume you meant ActiveSheet.Cells()

Title: creating a form in excel using VBA

Body:
I am trying to creat a form in excel using VBA, but I am stuck at the Code. I need to find out the code to enter a data to my worksheet using VBA form . here is the code I am using, but doesn't work..

Private Sub cmdAdd_Click()

Dim LastRow As Range
Dim DPDIAdhocRequestTable As ListObject

With LastRow

    Cells(1, 2) = RequesterName.Value
    Cells(1, 3) = RequesterPhoneNumber.Value
    Cells(1, 4) = RequesterBureau.Value
    Cells(1, 5) = DateRequestMade.Value
    Cells(1, 6) = DateRequestDue.Value
    Cells(1, 7) = PurposeofRequest.Value
    Cells(1, 8) = ExpectedDataSaurce.Value
    Cells(1, 9) = Timeperiodofdatarequested.Value
    Cells(1, 10) = ReoccuringRequest.Value
    Cells(1, 11) = RequestNumber.Value
    Cells(1, 12) = AnalystAssigned.Value
    Cells(1, 13) = AnalystEstimatedDueDate.Value
    Cells(1, 14) = AnalystCompletedDate.Value
    Cells(1, 15) = SupervisiorName.Value

End With

End Sub

can you help me to figure out the correct code for enter command?

thank you so much for your help.

Body:
The first problem is that you've created a Range named LastRow but haven't assigned anything to it.

'Declaration
Dim LastRow As Range
'Assigns the last row based on the last item in Column A
Set LastRow = Range("A" & Rows.Count).End(xlUp).Row
With LastRow
    ...
End With

The second issue is a minor syntax error in your With LastRow block.

 With LastRow
      Cells(x,y).Value = "Foo"
 End With

Should be

 With LastRow
     .Cells(x,y).Value = "Foo"
 End With

Which is essentially the same as saying LastRow.Cells(x,y).Value = "Foo". Without the "." in front of Cells() VBA will not apply the With to that object, and assume you meant ActiveSheet.Cells()


问:
OpenCV3 error: "Unable to stop the stream: Inappropriate ioctl for device"
I'm trying to read the frames of an .mov file using OpenCV 3.2 (from the menpo conda channel). I'm using Python 3.5.3 through Anaconda on an Ubuntu 16.04 64-bit setup.

Problem is, I get the following error message from OpenCV when it hits the cap.read() call, and the loop immediately breaks and catches the if num == 0 conditional.

Here's the entirety of the code I'm running:

```<code>import cv2
import numpy as np
import sys

f = sys.argv[1]
cap = cv2.VideoCapture(f)

frames = []
num = 0
while cap.isOpened():
    ret, frame = cap.read()
    if not ret: break
    gframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    frames.append(gframe)
    num += 1
    if num % 100 == 0:
        frames.append(gframe)
    if num % 1000 == 0:
        print(num)

if num == 0:
    print("Something went wrong: no frames found.")
    exit(0)

cap.release()
</code>```

```
user@ubuntu:/data$ python read.py movie.mov
Unable to stop the stream: Inappropriate ioctl for device
Something went wrong: no frames found.
user@ubuntu:/data$
```

I've found a couple of other StackOverflow questions on this topic, but they don't quite translate to my exact circumstance:

This question proposes rebuilding OpenCV (also uses Python 2). That's not an option for me, as I'm trying to do this with Anaconda.

These two questions (here and here) on the OpenCV forums were left without any satisfactory answers.

This one has a lively discussion and a thorough answer, but it's specific to perl.

To that third point--there are quite a few other questions here that have the quote inappropriate ioctl for device but it's hard to see if any of them is directly relevant to this problem.

As a partial aside: I've installed this exact same opencv3 conda package on my macOS machine, and the code I've pasted here works just fine and on exactly the same .mov file I've tried on the Ubuntu machine.

Any ideas?

答:
Solved the problem by getting around it entirely.

Used the opencv-feedstock recipe of OpenCV for conda-forge. In the recipe folder is the build information for conda. I modified the build.sh file, changing the following options:

```<code>-DBUILD_PNG=1
-DBUILD_JPEG=1
-DWITH_CUDA=1
-DWITH_FFMPEG=1
</code>```

ran conda build --numpy 1.12 recipe from the parent directory (had to specify the NumPy version, as the build script requirement lists numpy x.x which means you have to provide the version at runtime), and waited.

Took forever (seriously, a couple hours on a very powerful machine--the time sink is CUDA), but the build eventually completed successfully.

Then it was just a matter of installing the locally-built bz2 archive (conda install --use-local opencv). No more weird ioctl error messages, and the above script worked just fine.

Body:
I'm trying to read the frames of an .mov file using OpenCV 3.2 (from the menpo conda channel). I'm using Python 3.5.3 through Anaconda on an Ubuntu 16.04 64-bit setup.

Problem is, I get the following error message from OpenCV when it hits the cap.read() call, and the loop immediately breaks and catches the if num == 0 conditional.

Here's the entirety of the code I'm running:

import cv2
import numpy as np
import sys

f = sys.argv[1]
cap = cv2.VideoCapture(f)

frames = []
num = 0
while cap.isOpened():
    ret, frame = cap.read()
    if not ret: break
    gframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    frames.append(gframe)
    num += 1
    if num % 100 == 0:
        frames.append(gframe)
    if num % 1000 == 0:
        print(num)

if num == 0:
    print("Something went wrong: no frames found.")
    exit(0)

cap.release()

user@ubuntu:/data$ python read.py movie.mov
Unable to stop the stream: Inappropriate ioctl for device
Something went wrong: no frames found.
user@ubuntu:/data$

I've found a couple of other StackOverflow questions on this topic, but they don't quite translate to my exact circumstance:

This question proposes rebuilding OpenCV (also uses Python 2). That's not an option for me, as I'm trying to do this with Anaconda.

These two questions (here and here) on the OpenCV forums were left without any satisfactory answers.

This one has a lively discussion and a thorough answer, but it's specific to perl.

To that third point--there are quite a few other questions here that have the quote inappropriate ioctl for device but it's hard to see if any of them is directly relevant to this problem.

As a partial aside: I've installed this exact same opencv3 conda package on my macOS machine, and the code I've pasted here works just fine and on exactly the same .mov file I've tried on the Ubuntu machine.

Any ideas?

Body:
Solved the problem by getting around it entirely.

Used the opencv-feedstock recipe of OpenCV for conda-forge. In the recipe folder is the build information for conda. I modified the build.sh file, changing the following options:

-DBUILD_PNG=1
-DBUILD_JPEG=1
-DWITH_CUDA=1
-DWITH_FFMPEG=1

ran conda build --numpy 1.12 recipe from the parent directory (had to specify the NumPy version, as the build script requirement lists numpy x.x which means you have to provide the version at runtime), and waited.

Took forever (seriously, a couple hours on a very powerful machine--the time sink is CUDA), but the build eventually completed successfully.

Then it was just a matter of installing the locally-built bz2 archive (conda install --use-local opencv). No more weird ioctl error messages, and the above script worked just fine.