Base 6 Given a sequence of distinct numbers

Problem : Base 6

Given a sequence of distinct numbers a1, a2, ….. an, an inversion occurs if there are indices i aj .

For example, in the sequence 2 1 4 3 there are 2 inversions (2 1) and (4 3).

The input will be a main sequence of N positive integers. From this sequence, a Derived Sequence will be obtained using the following rule. The output is the number of inversions in the derived sequence.

Rule for forming derived sequence
An integer may be represented in base 6 notation. In base 6, 10305 is 1×64 + 3×62 + 5 =1409. Note that none of the digits in that representation will be more than 5.

The sum of digits in a base 6 representation is the sum of all the digits at the various positions in the representation. Thus for the number 1409, the representation is 10305, and the sum of digits is 1+0+3+0+5=9. The sum of digits may be done in the decimal system, and does not need to be in base 6

The derived sequence is the sum of the digits when the corresponding integer is represented in the base 6 form number will be expressed in base 6, and the derived sequence is the sum of the digits of the number in the base 6 representation.

Input Format:

The first line of the input will have a single integer, which will give N.

The next line will consist of a comma separated string of N integers, which is the main sequence
Output Format:

The number of inversions in the derived sequence formed from the main sequence.
Constraints:

N <= 50

Integers in sequence <= 107

Sample Input and Output

SNo. Input Output
1
5

55, 53, 88, 27, 33

2
2
8
120,21,47,64,72,35,18,98

11

Explanation for example 1:
The number of integers is 5, as specified in the first line. The given sequence is 55, 53, 88, 27, 33.

The base6 representation is 131, 125, 224, 43, 53 The derived sequence is 5,8,8,7,8 (corresponding to the sum of digits). The number of inversions in this is 2, namely (8, 7), (8, 7)

Explanation for example 2:
The base 6 representation of this is 320,33,115,144,200,55,30,242, and the derived sequence (sum of digits) is 5,6,7,9,2,10,3,8. The number of inversions is 11 (5,2), (5,3),(6,2) (6,3), (7,2), (7,3) (9,2),(9,3) (9,8),(10,3), (10,8)
Note:

Please do not use package and namespace in your code. For object oriented languages your code should be written in one class.
Note:

Participants submitting solutions in C language should not use functions from / as these files do not exist in gcc
Note:

For C and C++, return type of main() function should be int.


Source: stackoverflow-php

Canno’t login despite of true values of email and password with mysql

I want to test a login application with mysql by using volley framework and sharedpreferences.
it ok but when I enter a true login and password I had this result “ffgfg” although I entred a true values but I had mlgré que the value of the response is success but I had the intent “Invalid username or password”
ce login et mot de passe existe dans my database

Config.java

public class Config {

//URL to our login.php file
public static final String LOGIN_URL = "http://10.0.3.2/test_volley/login.php";

//Keys for email and password as defined in our $_POST['key'] in login.php
public static final String KEY_EMAIL = "email";
public static final String KEY_PASSWORD = "password";

//If server response is equal to this that means login is successful
public static final String LOGIN_SUCCESS = "success";

//Keys for Sharedpreferences
//This would be the name of our shared preferences
public static final String SHARED_PREF_NAME = "myloginapp";

//This would be used to store the email of current logged in user
public static final String EMAIL_SHARED_PREF = "email";

//We will use this to store the boolean in sharedpreference to track user is loggedin or not
public static final String LOGGEDIN_SHARED_PREF = "loggedin";

}

MainActivity.java

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

//Defining views
private EditText editTextEmail;
private EditText editTextPassword;
private AppCompatButton buttonLogin;

//boolean variable to check user is logged in or not
//initially it is false
private boolean loggedIn = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //Initializing views
    editTextEmail = (EditText) findViewById(R.id.editTextEmail);
    editTextPassword = (EditText) findViewById(R.id.editTextPassword);

    buttonLogin = (AppCompatButton) findViewById(R.id.buttonLogin);

    //Adding click listener
    buttonLogin.setOnClickListener(this);
}

@Override
protected void onResume() {
    super.onResume();
    //In onresume fetching value from sharedpreference
    SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME,Context.MODE_PRIVATE);

    //Fetching the boolean value form sharedpreferences
    loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);

    //If we will get true
    if(loggedIn){
        //We will start the Profile Activity
        Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
        startActivity(intent);
    }
}


private void login(){
    //Getting values from edit texts
    final String email = editTextEmail.getText().toString().trim();
    final String password = editTextPassword.getText().toString().trim();

    //Creating a string request
    StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.LOGIN_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    System.out.println("response " + response);=>success
                    //If we are getting success from server
                    if(response.equalsIgnoreCase(Config.LOGIN_SUCCESS)){

                        //Creating a shared preference
                       SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

                        //Creating editor to store values to shared preferences
                        SharedPreferences.Editor editor = sharedPreferences.edit();

                        //Adding values to editor
                        editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
                        editor.putString(Config.EMAIL_SHARED_PREF, email);

                        //Saving values to editor
                        editor.commit();

                        //Starting profile activity
                        Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
                        startActivity(intent);
                    }else{
                        //If the server response is not success
                        //Displaying an error message on toast
                        Toast.makeText(MainActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    //You can handle error here if you want
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params = new HashMap<>();
            //Adding parameters to request
            params.put(Config.KEY_EMAIL, email);
            params.put(Config.KEY_PASSWORD, password);

            //returning parameter
            return params;
        }
    };

    //Adding the string request to the queue
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

@Override
public void onClick(View v) {
    //Calling the login function
    login();
}

}

login.php

<?php  
 if($_SERVER['REQUEST_METHOD']=='POST'){
 //Getting values 
 $username = $_POST['email'];
 $password = $_POST['password'];

//Creating sql query
 $sql = "SELECT * FROM user_info WHERE email='$username' AND password='$password'";

//importing dbConnect.php script 
require_once('dbConnect.php');

//executing query
$result = mysqli_query($con,$sql);

//fetching result
 $check = mysqli_fetch_array($result);

//if we got some result 
if(isset($check)){
//displaying success 
 echo "success";
}else{
//displaying failure
echo "failure";
}
mysqli_close($con);
}
?>  


Source: stackoverflow-php

Unable to convert Javascript object to Java Model

My Spring controller and client side Javascript code are as follows and for some reason the Javascript object is unable to reach the Spring controller in the Object form. My Controller code is as follows:

@RequestMapping(value = "/addRating", method = RequestMethod.POST, headers = "Accept=application/json")
public EmployeeRating addRating(@ModelAttribute("employeeRating") EmployeeRating employeeRating) {  
    if(employeeRating.getId()==0)
    {
        employeeRatingService.addRating(employeeRating);
    }
    else
    {   
        employeeRatingService.updateRating(employeeRating);
    }

    return employeeRating;
}

My Javascript code below:

$.ajax({
          url: 'https://myrestURL/addRating',
          type: 'POST',
          dataType: 'json',
          data: {
              'id':5,
              'name': 'Name',
              'rating': '1'
          },
          contentType: 'application/json; charset=utf-8',
          success: function (result) {
             // CallBack(result);
             window.alert("Result: " + result);
          },
          error: function (error) {
              window.alert("Error: " + error);
          }
      });

The EmployeeRating object in Java has id, name and rating fields so there’s no mismatch.


Source: stackoverflow-javascript

Sending form from Angular JS to Spring

I have simple application AngularJS and Spring boot. I want to pass whole form pre-filled by user to my app and register . Usually I had no problems – was passing JSON obj with correct structure and presto. However here I just run in cricle.
The form payload is sent to controller, address mapping is correct , but java form content is empty

Payload sent to server:

{"userform":{"name":"a","surname":"a","email":"a@a.com","password":"a","confirmPassword":"a"}}

Here is my html:

There was a problem registering. Please try again.
<form role="form" name="userForm" ng-submit="register()">
<button type="submit" class="btn btn-primary">Submit</button>

Here java script

app.controller('register', function ($scope, $rootScope, $http) {
    $scope.formData = {};
    $scope.register = function () {
        $http.post('/api/register', {userform: $scope.formData}).then(
            function (resposne) {
                console.log("registered");
                console.log(response);
            },
            function (response) {
                console.log("Register error")
            }
        )
      }
});

And here controller:

@RestController
@RequestMapping("/api")
public class ApiController {

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@RequestBody RegisterForm userform) {
        System.out.println("name:" + userform.getName());
        System.out.println("surname:" + userform.getSurname());
        return "OK";
    }
}

and last but not least RegisterForm:

public class RegisterForm {
    private static final String NOT_BLANK_MESSAGE = "Cannot be blank";
    @NotBlank
    @Email(message = "Not email")
    private String email;

    @NotBlank(message = RegisterForm.NOT_BLANK_MESSAGE)
    private String name;

    @NotBlank(message = RegisterForm.NOT_BLANK_MESSAGE)
    private String surname;

    @NotBlank(message = RegisterForm.NOT_BLANK_MESSAGE)
    private String password;

    @NotBlank(message = RegisterForm.NOT_BLANK_MESSAGE)
    private String confirmpassword;

    /*-----GETTERS AND SETTERS HERE----*/
}


Source: stackoverflow-javascript

Converting an image to base64 in angular 2

Converting an image to base64 in angular 2, image is uploaded from local . Current am using fileLoadedEvent.target.result. The problem is, when I send this base64 string through REST services to java, it is not able to decode it. When i try this base64 string with free online encoder-decoder, there also I cannot see decoded image. I tried using canvas also. Am not getting proper result. One thing is sure the base64 string what am getting is not proper one, do I need to add any package for this ? Or in angular 2 is there any perticular way to encode the image to base64 as it was there in angular 1 – angular-base64-upload package.


Source: stackoverflow-javascript

JSP doesn’t show cookie for the first time

I set a cookie in javascript, not in controller and I want to check if that cookie exists in JSP. My cookie is set, but I have to reload the page manually in order to see it in jsp. I did reload method in javascript, but I still have to reload page once more.

JSP:
getting cookie: ${cookie['_sYrV'] } or ${cookie._sYrV }

Javascript:

set_cookie("name","value", 1);
window.onload = function () {
    if (!localStorage.reloadOnce) {
        localStorage.setItem("reloadOnce", "true");
        window.location.reload();
    }
}

var set_cookie = function(name, value, day) {
    var d = new Date();
    d.setTime(d.getTime() + (day * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = name + "=" + value + ";" + expires + ";path=/";
};

What should I do in order to see the cookie in jsp without reloading the page manually?


Source: stackoverflow-javascript

Java Applets – Application/Publisher Show ‘Unknown’ for Signed Applet On Javascript->Java Calls

Our product is running into an issue specific to Java 8. Java 6/7 runs fine.

We have a package of Java applets that multiple customers use, so the domain this package is deployed to is always different. The package is properly signed with the certificate from Verisign.

When the end user launches a page in the browser, the expected dialog with our application name and publisher appears, and asks the end user to accept the security warning. The end user accepts and clicks ‘Do not ask again’ and the page runs fine.

The trouble starts with pages that make Javascript calls into the Java applets. The behavior appears to be random. New security popups appear, asking the end user to accept the certificate again. My understanding is that once the user selects the certificate initially, this should not happen again. Yet it does.

Then also sometimes the popup appears with the application name and publisher set to UNKNOWN. There does not seem to be any reason for this, the applet package is confirmed to be signed correctly and with a valid certificate from Verisign. Yet, it occurs.

I recognize the initial popup is unavoidable but all of these downstream popups, especially those where the application/publisher are UNKNOWN don’t make sense to me, and I’m not sure how to debug this further. The java console trace logs do not clearly show any more details.

Any ideas? Please feel free to ask me more detail if there is something here unclear.


Source: stackoverflow-javascript

Why is my Android app inserting blank records into MySQL database?

Currently I am working on developing an app through Android Studio and working on coding the login and registration capabilities. We send newly registered users’ info to a MySQL database externally (i.e. not locally) through PHP, and also want to log registered users into the app. At the moment, the Android app is not sending the PHP file the information the user types into the text boxes. I put a tracer into the PHP file and it shows that the values are coming up null.

Here is my MainActivity.java:

package android.capstone.registerlogin;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import static android.capstone.registerlogin.R.id.etCreateAccEmail;
import static android.capstone.registerlogin.R.id.etCreateAccPassword;
import static android.capstone.registerlogin.R.id.etCreateAccUsername;


public class MainActivity extends Activity {

    private EditText etUserName, etPassWord, etEmail;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_login);

        etPassWord = (EditText) findViewById(etCreateAccPassword);
        etUserName = (EditText) findViewById(etCreateAccUsername);
        etEmail = (EditText) findViewById(etCreateAccEmail);
        final TextView createAcc = (TextView) findViewById(R.id.tvCreateAcc);
        createAcc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /* creating this intent shows where you're starting and
                where you want to go, we want to get the to the create account page
                called RegisterUser.java
                   first line creates the intent
                 */
                Intent createIntent = new Intent(MainActivity.this, CreateAccount.class);
                //second line makes the intent actually happen .startActivity
                MainActivity.this.startActivity(createIntent);
            }
        });

    }



    public void signup(View v) {
        String UserName = etUserName.getText().toString();
        String PassWord = etPassWord.getText().toString();
        String Email = etEmail.getText().toString();



        Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();

        new SignupActivity(this).execute(UserName, PassWord, Email);
    }


    }

Here is my SignupActivity.java:

package android.capstone.registerlogin;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class SignupActivity extends AsyncTask<String, Void, String> {
    private Context context;

    public SignupActivity(Context context) {
        this.context = context;
    }

    protected void onPreExecute() {

    }

    @Override
    protected String doInBackground(String... arg0) {
        String userName = arg0[0];
        String passWord = arg0[1];
        String eMail = arg0[2];



        String link;
        String data;
        BufferedReader bufferedReader;
        String result;

        try {
            data = "?username=" + URLEncoder.encode(userName, "UTF-8");
            data += "&password=" + URLEncoder.encode(passWord, "UTF-8");
            data += "&email=" + URLEncoder.encode(eMail, "UTF-8");



            link = "http://cgi.soic.indiana.edu/~gabschle/signup.php" + data;
            URL url = new URL(link);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            result = bufferedReader.readLine();
            return result;
        } catch (Exception e) {
            return new String("Exception: " + e.getMessage());
        }
    }

    @Override
    protected void onPostExecute(String result) {
        String jsonStr = result;
        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);
                String query_result = jsonObj.getString("query_result");
                if (query_result.equals("SUCCESS")) {
                    Toast.makeText(context, "Data inserted successfully. Signup successful.", Toast.LENGTH_SHORT).show();
                } else if (query_result.equals("FAILURE")) {
                    Toast.makeText(context, "Data could not be inserted. Signup failed." + jsonStr, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
        }
    }
}

Here is my CreateAccount.java:

package android.capstone.registerlogin;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import static android.capstone.registerlogin.R.id.etCreateAccEmail;
import static android.capstone.registerlogin.R.id.etCreateAccPassword;
import static android.capstone.registerlogin.R.id.etCreateAccUsername;

public class CreateAccount extends Activity {


    private EditText etUserName, etPassWord, etEmail;
    private Button mButton;
    //private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_account);

        etPassWord = (EditText) findViewById(etCreateAccPassword);
        etUserName = (EditText) findViewById(etCreateAccUsername);
        etEmail = (EditText) findViewById(etCreateAccEmail);

        final String UserName = etUserName.getText().toString();
        final String PassWord = etPassWord.getText().toString();
        final String Email = etEmail.getText().toString();


        mButton = (Button) findViewById(R.id.bCreateAccSignUp);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
                new SignupActivity(CreateAccount.this).execute(UserName, PassWord, Email);


            }

            });
        }




    public void signup(View v) {
        String UserName = etUserName.getText().toString();
        String PassWord = etPassWord.getText().toString();
        String Email = etEmail.getText().toString();



        Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
        new SignupActivity(this).execute(UserName, PassWord, Email);
    }
}

Here is my PHP file:

<?php
$con=mysqli_connect("db.soic.indiana.edu","caps16_team19","capstoneteam19","caps16_team19");
if (mysqli_connect_errno($con))
{
   echo '{"query_result":"ERROR"}';
}


$userName = $_GET['username'];
$passWord = $_GET['password'];
$tDate = $_GET['date'];
$tDate = date('Y-m-d');
$eMail =$_GET['email'];

if($eMail == null) {
    echo '{"query_result":"FAILURE"}';
} else {

$result = mysqli_query($con,"INSERT INTO account (username, password, activated, email) VALUES ('$userName', '$passWord', '$tDate','$eMail')");

if($result == true) {
    echo '{"query_result":"SUCCESS"}';
}
else{
    echo '{"query_result":"FAILURE"}';
}
}

mysqli_close($con);
?>

Let me know if you need additional files!
Thanks for your help!


Source: stackoverflow-php