lundi 1 février 2016

How to reference a previous prompt() in JavaScript?

I want to ask a user (through a prompt) if they would rather convert km to miles, or miles to km, within an else if statement. If neither condition is met, I want to go back to the conversion prompt:

var conversion=prompt("Do you want to convert miles to km, or km to miles?");
if (conversion=="miles to km") {
[perform miles conversion here]
} else if (conversion=="km to miles") {
[perform km conversion here]
} else {
**[go back to conversion prompt]**
}

How would you code this line in JavaScript? Thanks.

Complicated Move Script

So to explain my question, here are my sample directories:

C:
  Source
    foldera1.1
      file1.1.txt
    foldera1.2
      file1.2.txt
    folder1.3
      file1.3.txt
  Destination
    foldera
      foldera1

I'm trying to write a script, be it powershell, batch, or VBS, that will move all the file1.x.txt files from the Source directory to the folder foldera1 in the Destination directory without creating 3 different move jobs and specifying ...folder1.1\file1.1.txt, ...folder1.2\file1.2.txt, etc. I am horrible at if/then statements and I'm unsure where I might be able to use wildcards if at all. Since I'm not able to put wildcards in a directory name when pointing to a file's path in a move or robocopy script, I'm at a loss as to where to go from here. Any help with this would be greatly appreciated.

Secondary Facial Condition is not read when facial image is not detected

functional:

User will take a picture using a webcam. When the camera snaps an image, a check page will appear; this page informs the user to hold on while a check condition runs to detect if the image captured is able to detect any facial features and image.

Hence, if check condition is successful, it navigate the user to an option page to either retake the picture or navigate to a new page. Else, it will inform user to smile and navigate to a retake page where, user can only select the retake option to have the image retaken.

What has been done:

Have made use of a faceapp sdk: facepp-sdk.min.js, to create the facial detection. And to also create a check condition if face is detected, option page is shown else, retake page is shown.

Issue:

The check condition is not being called. Hence, at the end, no matter if the image taken has got facial features or the image is a blank image, the option page is always called. However, the detection is functional as if the facial image is detected, the console log is able to log the smile index, gender and approximate age, Else, if no facial image is detected, the console log returns empty.

Hence, what has gone worng? Help pls.

Code: method call to check captured image

//Function call for face detection
function Send() {
  // Send Capture Image to Backend Server
  var canvasServer = document.getElementById("canvas");
  var context = canvasServer.getContext("2d");
  var imageDataURL = canvasServer.toDataURL('image/png');
  var smilesDetected = 0;


  //Send image to server  via ajax    
  var ajax = new XMLHttpRequest();
  ajax.open("POST", "image.do", false);
  ajax.setRequestHeader("Content-Type", "application/upload");
  ajax.send(imageDataURL);

  // Send Capture Image to Face Detection Webservice
  setTimeout(function() {
    console.log("start: " + Date());

    var binary = atob(canvasServer.toDataURL('image/jpeg').split(',')[1]);
    var array = [];
    for (var i = 0; i < binary.length; i++) {
      array.push(binary.charCodeAt(i));
    }
    var blobObject = new Blob([new Uint8Array(array)], {
      type: 'image/jpeg'
    });

    var xhr = new XMLHttpRequest();


    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4) {
        //If API server connection is successful
        if (xhr.status === 200) {
          string_result = xhr.responseText;
          //alert(xhr.responseText);
          if (string_result != "") {
            var ageArray = string_result.split("age");
            var genderArray = string_result.split("gender");
            var smileArray = string_result.split("smiling");

            var age = "";
            var gender = "";
            var smile = "";

            //To get face detection data from server    
            for (i = 0; i < smileArray.length; i++) {
              if (i > 0) {
                age = ageArray[i].substring(ageArray[i].indexOf("value") + 7, ageArray[i].indexOf("},"));
                age = $.trim(age);

                gender = genderArray[i].substring(genderArray[i].indexOf("value") + 8, genderArray[i].indexOf("},") - 1);
                gender = $.trim(gender);
                gender = gender.substring(1, gender.length - 1);

                smile = smileArray[i].substring(smileArray[i].indexOf("value") + 8, smileArray[i].indexOf("}"));
                smile = $.trim(smile);

                console.log("age: |" + age + "|");
                console.log("gender: |" + gender + "|");
                console.log("smile index: |" + smile + "|");

                // Save Face Detection Result to Backend Server
                if (parseFloat(smile) >= 50) {
                  ajax_detection("function.do", "formType=detection&gender=" + gender + "&age=" + age + "&smileIndex=" + smile + "&isSmile=true");

                  smilesDetected++;
                  console.log(smilesDetected);
                } else {
                  ajax_detection("function.do", "formType=detection&gender=" + gender + "&age=" + age + "&smileIndex=" + smile + "&isSmile=false");
                }
              }
            }
          } else {
            console.log('error');
          }
          //Conditional check for face detection

          if (smilesDetected > 2) {
            $('#check_face_page').fadeOut({
              duration: slideDuration,
              queue: false
            });
            $('#check_face_page').animate({
              'left': '1081px'
            }, {
              duration: slideDuration,
              easing: 'easeInOutQuart',
              queue: false
            });
            $('#camera_option_page').fadeIn({
              duration: slideDuration,
              queue: false
            });
            $('#camera_option_page').animate({
              'left': '0px'
            }, {
              duration: slideDuration,
              easing: 'easeInOutQuart',
              queue: false
            });
          } else {
            console.log("Not detected");

            $('#check_face_page').fadeOut({
              duration: slideDuration,
              queue: false
            });
            $('#check_face_page').animate({
              'left': '1081px'
            }, {
              duration: slideDuration,
              easing: 'easeInOutQuart',
              queue: false
            });
            $('#PleaseSmile_page').fadeIn({
              duration: slideDuration,
              queue: false
            });
            $('#PleaseSmile_page').animate({
              'left': '0px'
            }, {
              duration: slideDuration,
              easing: 'easeInOutQuart',
              queue: false,
              complete: function() {

                setTimeout(function() {
                  $('#PleaseSmile_page').fadeOut({
                    duration: slideDuration,
                    queue: false
                  });
                  $('#PleaseSmile_page').animate({
                    'left': '1081px'
                  }, {
                    duration: slideDuration,
                    easing: 'easeInOutQuart',
                    queue: false,
                    complete: function() {
                      $('#Retake_Only_page').fadeIn({
                        duration: slideDuration,
                        queue: false
                      });
                      $('#Retake_Only_page').animate({
                        'left': '0px'
                      }, {
                        duration: slideDuration,
                        easing: 'easeInOutQuart',
                        queue: false
                      });
                    }
                  });
                }, 1300);
              }
            });
          }
          // Get Total Smile Index from Backend Server
          ajax_getTotalSmile("function.do", "formType=getTotalSmile");

          console.log("end: " + Date());
        }
        //IF API server is wrong and unable to connect: set error msg
        else {
          console.log('error');
          console.log("end: " + Date());
        }
      }
    };
    xhr.open('POST', 'http://ift.tt/1nzUnZh', true);
    //xhr.open('POST', 'http:// http://ift.tt/1Tx6L8T', true);
    var fd = new FormData();
    fd.append('img', blobObject);
    xhr.send(fd);
  }, 2000);
}

Code: faceapp-sdk.js

(function() {
  var k = function(d, a) {
    return function() {
      return d.apply(a, arguments)
    }
  };
  this.FacePP = function() {
    function d(a, b, c) {
      var e, f, g, h, l = this;
      this.apiKey = a;
      this.apiSecret = b;
      null == c && (c = {});
      this.sessionCheck = k(this.sessionCheck, this);
      a = {
        apiURL: "http://ift.tt/1nzUljX",
        sessionInterval: 500,
        requestTimeout: 1E4,
        ajaxAdapter: "FormData" in window ? "XMLHttpRequest" : "jQuery",
        concurrency: 2
      };
      for (e in a) null == c[e] && (c[e] = a[e]);
      this.apiURL = c.apiURL.replace(d.RE_TRIM, "");
      this.sessionInterval = c.sessionInterval;
      this.requestTimeout = c.requestTimeout;
      this.requestAdapter = d.adapter[c.ajaxAdapter];
      0 < (g = c.concurrency) && (f = [], h = function() {
        var a, b, c, e;
        0 < g && 0 < f.length && (--g, e = f.shift(), a = e[0], c = e[1], b = e[2], d.prototype.request.call(l, a, c, function(a, c) {
          ++g;
          setTimeout(h, 0);
          b(a, c)
        }))
      }, this.request = function(a, c, b) {
        f.push([a, c, b]);
        h()
      })
    }
    d.RE_TRIM = /^\/+|\/+$/g;
    d.prototype.request = function(a, b, c) {
      b.api_key = this.apiKey;
      b.api_secret = this.apiSecret;
      a = this.apiURL + "/" + a.replace(d.RE_TRIM, "");
      this.requestAdapter(a, b, {
          timeout: this.requestTimeout
        },
        c)
    };
    d.prototype.sessionCheck = function(a, b) {
      var c = this;
      this.request("info/get_session", {
        session_id: a
      }, function(e, f) {
        e ? b(e, f) : "FAILED" === f.status ? b(f.result.error_code || -1, f.result) : "INQUEUE" === f.status ? setTimeout(c.sessionCheck, c.sessionInterval, a, b) : b(null, f.result)
      })
    };
    d.prototype.requestAsync = function(a, b, c) {
      var e = this;
      b.async = "true";
      this.request(a, b, function(a, b) {
        a ? c(a, b) : setTimeout(e.sessionCheck, e.sessionInterval, b.session_id, c)
      })
    };
    d.adapter = {
      jQuery: function(a, b, c, e) {
        var f, g;
        g = 0;
        for (f in b) g +=
          b[f].length || 0;
        jQuery.ajax({
          url: a,
          dataType: "jsonp",
          crossDomain: !0,
          data: b,
          method: 1024 > g ? "GET" : "POST",
          timeout: c.timeout,
          error: function(a) {
            if (a = a.responseText) try {
              a = JSON.parse(a)
            } catch (b) {}
            e((null != a ? a.error_code : void 0) || -1, a)
          },
          success: function(a) {
            e(null, a)
          }
        })
      },
      XMLHttpRequest: function(a, b, c, e) {
        var f, g, d;
        f = !1;
        for (g in b)
          if (b[g] instanceof Blob) {
            f = !0;
            break
          }
        d = new XMLHttpRequest;
        d.onreadystatechange = function() {
          var a;
          if (4 === this.readyState) {
            this.onreadystatechange = null;
            if (a = this.responseText) try {
              a = JSON.parse(a)
            } catch (b) {}
            200 ===
              this.status ? e(null, a) : e(a.error_code || -1, a)
          }
        };
        "timeout" in d && (d.timeout = c.timeout);
        d.open("POST", a, !0);
        if (f) {
          a = new FormData;
          for (g in b) a.append(g, b[g]);
          d.send(a)
        } else {
          d.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
          a = encodeURIComponent;
          c = [];
          for (g in b) c.push("" + a(g) + "=" + a(b[g]));
          d.send(c.join("&"))
        }
      }
    };
    return d
  }()
}).call(this);

Code unreachable when comparing types

Question: My else-statement is unreachable, what am i doing wrong?

very VERY new at programming and i'm trying to compare the type so for example people can't enter strings when i'm asking for integers.

My code is probably pretty bad, if i could get a header what to do and why the if-argument skips the else-part i'd be really happy!

Thanks!

class Program
{
    static void Main(string[] args)
    {            
        int integer = 0;

        start:
        Console.WriteLine("How old are you?: ");
        int svar = int.Parse(Console.ReadLine());

        Utility.CompareTypes(svar, integer);

            if (true)
        {
            Console.WriteLine("Thanks");

        }
            else
            {
                Console.WriteLine("You have to enter a number!");
                goto start;
            }

    }
}

class Utility
{

    public static bool CompareTypes<T01, T02>(T01 type01, T02 type02)
    {
        return typeof(T01).Equals (typeof(T02));
    }

}

:c

How to I check that a string contains only digits and / in python?

I am trying to check that a string contains only / and digits, to use as a form of validation, however I cannot find and way to do both. ATM I have this:

if Variable.isdigit() == False:

This works for the digits but I have not found a way to check also for the slashes.

How to for loop and check a condition such that the inner funtion is called one by one for each [on hold]

I have a python function say as follows :

for server in hostlist:
   if server.port not in safe_port_list:
       print "This is not a good server" 
       notify_subsystem(server.port,server.protocol,server.ip)
   else:
       print "whatever"

And lets say the notify_subsystem is a method which calls some external integration xyz.

The loop is simple and understandable i.e if the server port is not found in safe_port_list ,it will keep checking if condition for each host in one go.

I want something here which will call the notify_subsystem one by one and NOT in one go for all the servers.

   for server in hostlist:
   if server.port not in safe_port_list:
       print "This is not a good server" 
       `something_here`
         notify_subsystem(server.port,server.protocol,server.ip)
   else:
       print "whatever"

I am guessing i need a second loop at that place

When entered right username it directs to else [duplicate]

This question already has an answer here:

I was wondering how come when I enter my username correctly in the console when prompted that it still directs me into the else code or in other words. Says that i have entered the wrong password when correct it's supposed to say welcome.

package com.racecar484.user;

import java.util.Scanner;

class Application extends Game {

    public void calculator1(String args, int num) {
        int numb2, numb3, numb4;

    }

    public static void main(String args[]) {
        int Hotel = 50;
        int day = 1;
        int night = 12;
        int CarRent = 230;
        int Foodservice = 25;
        int cab = 300;
        String name = "Hernandez";
        String $ = "$";
        String Username = null;
        int cash = 500;
        boolean roomvacancy = true;
        boolean roomnotvacant = false;
        String password = null;
        String word;
        int num;
        Scanner in = new Scanner(System.in);
        if (Hotel <= 51 && day < 3) {
            System.out.println("Hello, and welcome to the CrunchGames Login panel.");
            System.out.println("Please enter your username and password down below!");
            Username = in.nextLine();
            System.out.println("Please enter your password.");
            password = in.nextLine();
            System.out.println("Logged in securely.");
            System.out.println("Please press any " + "ENTER" + " to resume.");
            String anykey = in.nextLine();

            System.out.println("System check....");
            System.out.println("System up to date.");
            System.out.println("Initiation sequence.");
            System.out.println("Welcome back to the CrunchGames application " + Username + ".");
            String[] myname = { "Alpha", "Bravo", "Charlie", "Delta" };
            {

            }
        } else {
            System.out.println("System is not up to date or");
            System.out.println(" does not support the version of this app.");
            System.out.println("Please update to a newer O.S or update the Application.");
        }

        System.out.println("Please enter your username and password one more ");
        System.out.println("time to verify that you are indeed the account user");
        String UsernameVerification = in.nextLine();
        if (UsernameVerification != Username) {
            System.out.println("Sorry that is the wrong user name, please try logging in again.");
            System.out.println("Enter your username.");
            String Username2 = in.nextLine();
        } else {
            System.out.println("Enter your password");
            password = in.nextLine();
        }
        System.out.println("Please Verify your password in order to continue.");
        String password2 = in.nextLine();
        if (password2 != password) {
            System.out.println("Password is incorrect, please try again.");
            password = in.nextLine();
            if (password2 == password) {
                System.out.println("Welcome to the CrunchGames Application!");
                System.out.println("Would you like to set up your profile?");
                String profile = in.nextLine();
                String yes = "yes";
                String no = "no";
                if (profile == yes) {
                    System.out.println("404 Page not found, sorry.");
                }
                if (profile == no) {
                    System.out.println("Ok, again welcome!");
                }
            }
        }

    }

    public void test(String[] args) {
        boolean a = true;
        String b = "Hello";
        if (a == true) {
            System.out.println(b);
        }
    }

    // Array
    public void arrays(String[] args, int[] arg) {

        int[] Arr = new int[34];
        Arr[2] = 42;
        System.out.println(Arr[2]);

    }

    {
    }
}