jeudi 1 septembre 2016

Javascript Performance: `if (a in b) {b[a]()}` vs `a in b && b[a]();` vs object traversing

I noticed I can use a && b(); as a shorthand for if(a) {b()} or if(a) b();. The MOST usual case for this indecision is for objects having 4-5 elements.

Question: is there a performance gain/loss for using the shorthand when compared with an iteration of if(){} or regular object traversing for (var i in b) { b[i]() } ?

Uploading data to Firebase with "IF" and UIPickerController

I started coding a few weeks ago and I am trying to load data to my Firebase.database for my app. But the thing is, that I want the data to load/save into different folders/names ("A" & "B") in my database in firebase so that later i can retrieve the data on 2 different scroll views with one scroll view only showing "A" and one only showing "B".

My code is not throwing errors at me, but for some reason it won't upload data. i don't know why it is not working.

Help highly appreciated. Thanks community !!

CODE INCOMING !!!


/// Picker now

// 2 items for the picker.
var data = ["A", "B"]




func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    // Column count: use one column.
    return 1
}

func pickerView(pickerView: UIPickerView,
                numberOfRowsInComponent component: Int) -> Int {

    // Row count: rows equals array length.
    return data.count
}

func pickerView(pickerView: UIPickerView,
                titleForRow row: Int,
                            forComponent component: Int) -> String? {

    // Return a string from the array for this row.
    return data[row]
}

func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    true
}

///Here I try to Upload the image that I picked in UIPickerView

@IBAction func Upload(sender: UIButton){

    func simplePicker(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

        if component == 0 {

            func Upload(){
            _ = UIImage.self
            FIRDatabase.database().reference().childByAutoId().setValue("A")
            }}

        if component == 1 {

            func Upload(){
            _ = UIImage.self
            FIRDatabase.database().reference().childByAutoId().setValue("B")
            }}


    }

}

Google Sheets Script - If or statement

Super quick question. I have this function I want to run on entire workbook, except two specific sheets.

This is my code:

function onEdit(e) {
  var sheet = SpreadsheetApp.getActiveSheet();
  if (sheet.getName() != "Total" || sheet.getName() != "DataRange" ) { 
    someAction();
  }
}

This just does not work, the code runs on all sheets no matter what. This is probably a noob question but.

SSRS Multiple IF SUM based on paramter

I've been struggling with this for a few hours if anyone can help.

=IIF(Parameters!Agent.Value ="Susan Calladine", (Sum(Fields!Susan_Calladine.Value) / Sum(Fields!InvitedToApply.Value), IIF(Parameters!Agent.Value ="Fazaila Pirbhai", (Sum(Fields!Fazaila_Pirbhai.Value) / Sum(Fields!InvitedToApply.Value), IIF(Parameters!Agent.Value ="Claire Willis", (Sum(Fields!Claire_Willis.Value) / Sum(Fields!InvitedToApply.Value),0)))

Basically to calculate specific fields based on the value of the parameter being returend

php if(!$variable) not working

Please forgive me if this is a dumb question, as I am new to php. I did some c++ years ago and are dabbling in c# with Unity.

I am trying to get a working html / js / php contact form working with reCaptcha. The form works well if the captcha is checked, and the 'success' message is displayed. If the captch is not checked, I want to display a message and not send the form email. The code snippet below works insofar as the email is NOT sent if the captcha is not ticked, but it does not display the message. Can anyone help?

$okMessage = 'Contact form successfully submitted. Thank you, we will get back to you soon!';
$captchaMessage = 'There was an error while submitting the form. Please check the captcha box.';
$spamMessage = 'There was an error while submitting the form. Spamers not welcome.';
$captcha = $_POST['g-recaptcha-response'];

try
{
    //Sanitise Inputs
    $emailText = "You have new message from contact form\n=============================\n";
    $emailText .= "First Name: " . @trim(stripslashes($_POST['name'])). "\n";
    $emailText .= "Last Name: " . @trim(stripslashes($_POST['surname'])). "\n";
    $emailText .= "Company: " . @trim(stripslashes($_POST['company'])). "\n";
    $emailText .= "Email: " . @trim(stripslashes($_POST['email'])). "\n";
    $emailText .= "Message: " . @trim(stripslashes($_POST['message'])). "\n";

    if(!$captcha){
        $responseArray = array('type' => 'danger', 'message' => $captchaMessage);
          exit;
        }
        $secretKey = "secret_key";
        $ip = $_SERVER['REMOTE_ADDR'];
        $response=file_get_contents("http://ift.tt/1vh5G4o".$secretKey."&response=".$captcha."&remoteip=".$ip);
        $responseKeys = json_decode($response,true);
        if(intval($responseKeys["success"]) !== 1) {
          $responseArray = array('type' => 'danger', 'message' => $spamMessage);
        } else {
            mail($sendTo, $subject, $emailText, "From: " . $from);
            $responseArray = array('type' => 'success', 'message' => $okMessage);
        }


}

using if statement with req.file for a single file upload

I have a basic web app where i want the users to be able to register with a picture upload in the form, but if they do not have a picture to upload at the current time i want to automatically set a default image that is already stored locally in uploads folder as noimage.png to be called and stored as the profile image of the user. This has been my trial but not working;

var multer = require('multer');


//var uploads = multer({dest: './uploads/'});

var storage = multer.diskStorage({
    destination: function (request, file, callback) {
        callback(null, './uploads');
    },
    filename: function (request, file, callback) {
        console.log(file);
        callback(null, file.fieldname)
    }
});
var upload = multer({ storage: storage });
router.post('/register', upload.single('profileimage'), function(req,res,next){

    `if(req.file.profileimage){
            console.log('uploading File...');

            // File Info
            var profileImageOriginalName = req.files.profileimage.originalname;
            var profileImageName = req.files.profileimage.name;

            var profileImageMime = req.files.profileimage.mimetype;
            var profileImagePath = req.files.profileimage.path;
            var profileImageExt = req.files.profileimage.extension;
            var profileImageSize = req.files.profileimage.size;
        } else {
            // Set a Default Image
            var profileImageName = 'noimage.png';
        }

How can i use multer to handle this?

Store value in variable from an if statement within a switch statement case

I want to have a variable keep track of results from an if statement in every case of a switch statement. The problem is every time my case uses the initial value of the variable - 0, and not value given by the previous case, so I always get myNum = 1. I want to know what is a common solution to this problem.

I also tried this with an array var myArray = [false,false,false,false]; where case 1 changes myArray[0] = true, when if statement in case 2 returns true it changes myArray[1] = true, however the entire array is now [false,true,false,false], i.e. the changes from case 1 are not saved in the variable and it is instead using the initial variable value.

Both cases are the same if I log value to console outside of the switch statement.

$scope.clickItem = function(result){
var myNum = 0;
function addNum() {
  myNum++;
};

switch(currentString) {
    case string1:
    if($scope.img1 === result){
         addNum();
         console.log('myNum is ' + myNum); // <- It's 1
         $scope.currentString = $scope.val2;
     }
     else{
         console.log("Wrong..");
     }
    break;

    case $scope.val2:
    if($scope.img2 === result){
        addNum();
        console.log('myNum is ' + myNum); // <- It's 1 again, when it should be 2.
        $scope.currentString = $scope.val3;
     }
     else{
         console.log("Wrong..");
     }
    break;

    case $scope.val3:
    if($scope.img3 === result){
         addNum();
         $scope.currentString = $scope.val4;
     }
     else{
    console.log("Wrong..");
}
break;
}
...etc