Application of bitwise operators in JavaScript

First of all let us revise what bitwise operators are and why you should comprehend them in 2017. Bitwise operators are operators that work on a bit or two bits (comparing them and giving a result based on the comparison) at a time.

AND ( & ) will  be 1 only if both of the bits are 1, otherwise it will be 0.
Example (all combinations): 1&1=1;  1&0=0;  0&1=0;  0&0=0;

OR ( | ) will be 1 if there is a 1 present when comparing two bits,
Example (all combinations): 1|1=1;  1|0=1;  0|1=1;  0|0=0;

XOR ( ^ ) is 1 only if one bit is 1 and the other is 0 no matter the order (1 XOR 0 =1)
(0 XOR 1=1)

NOT ( ~ ) if the bit is 0 it will go to 1 if it is 1 it will go to 0. In this case there is no comparison with other data. If you have an integer, let’s say 5 which is 0101 then the NOT will bring it to 1010.

To see the truth tables go to this website
Practical applications of bitwise operators (real life):
0X1 represents 1 in hexadecimal.


  • We check if the value is odd. If it is, the program returns true it’s not (if it is even) then the program returns false:


(value & 0x1) > 0

Explanation: Let’s say we have a value of 8 and on the other side we have 0x1. We convert them to binary numbers (that’s what the computer only understands at the most bottom level). We write the numbers one below the other and start the calculation from the most right bit to the most left bit (refer to the and operator above)

1000
0001


0000

The result is 0000 which is 0 in denary (decimal ). Zero is not greater than zero so the expression returns false. Which means that the number is even.

JS code:

console.log((8 & 0x1) > 0)
  • Use them for data encryption (encryption is all about bitwise operators)

a = 1903349;
b = 4542345;
c = 5834533;
hash = a ^ b ^ c;

The numbers will be converted to binary and will be hashed (they will be transformed in some boolean XOR equivalent data)

Conclusion:

Bitwise operators are rarely used in JavaScript (as far as I’ve seen in 5 years of coding). I suppose interviewers use them for questions for future employees to see how deep the candidate went with their programming knowledge. Still, it is good to know them because once you see them and maybe have to do something with them you will have the basic knowledge in your head and solving the problem in front of you will require less time and frustration.

So, when doing operation with bitwise operators which are nothing else but boolean operations, always have in mind the truth tables which are easy to understand and learn.

My opinion is, try to avoid them because your code looks incomprehensible to others who may in the future maintain your application. The more clearer you are the better for everyone else.

Mathematics is done by the computer, problem solving not yet

I’ve been doing a lot of maths recently and whenever I come across a problem which I don’t know how to evaluate and solve at the end I ask WolframAlpha (https://www.wolframalpha.com) or Symbolab (https://www.symbolab.com). As you can see if you type any high school – college problem you will almost certainly get a positive result, a solution to the problem. Not only will you get the solution but you will also get the steps towards the solution which is insane.

Let’s go back to year 2000, no let’s got back to year 2010. You had none of this things alive. You were really great-full if you could get a script or a book with solved problems including the steps.

Now let’s see some of the stuff that you can easily do with WolframAlpha or Symbolab

  1. WolframAlpha quadratic equation solverhttp://www.wolframalpha.com/widgets/view.jsp?id=bf424cb7b0dea050a42b9739eb261a3a  We are all familiar with this one, it can be easily programmed and you can find thousands of such example on the Internet and of-course Casio Calculators are the best (the fastest and the easiest) for solving quadratic equations. You get the result instantly and see if an equation has 0, 1 or 2 results.
  2.  WolframAlpha  intersection points of two curves/lineshttp://www.wolframalpha.com/widgets/view.jsp?id=7b9037eb9f5f7493a73df97a38bc58e6  You can use this app to draw any desired function-graph no matter the order. You can draw a parabola, third order equations, of-course, lines (first order equations) etc. You instantly get the x coordinates and if you subscribe and pay (6 dollars per month for students you can see the steps towards the x solution). This can be useful if you don’t want to draw things on paper. As we all know computers will always be much more precise and accurate than humans. Although someone may think that is an easy app to program it certainly is not and takes much effort to achieve such thing.
  3.  WolframAlpha derivatives: http://www.wolframalpha.com/widget/widgetPopup.jsp?p=v&id=f4ccdf86d504bc91f8652fa6d7b76db6&title=+Derivative+Calculator&theme  Put the function from which you want to take the derivative from and you’ll get the result instantly. You can take the n-th derivative up to number 10 if you wish (maybe for Taylor series I cannot think why would you do it for anything else at this time). If you’ve got a function with a lot of x-is and a function which is really big and you know that the probability of making a mistake is high then I suggest you to use this app. Again, computers are “smarter” and cannot make a mistake. Well they can, but they don’t. Although this app is nice I think that this is time when Symbolab kicks in. Symbolab is magnificent at doing this job, also the output looks nice. Here is the link: https://www.symbolab.com/solver/derivative-calculator The greatest thing of all is that you get the steps for free at Symbolab. You don’t have to pay anything. The steps are much more nicer than at WolframAlpha. I think we really have to appreciate such things because the engineers have put great effort into it, I really don’t know how they earn their money to support such platform.
  4. Wolfram alpha Integralshttp://www.wolframalpha.com/calculators/integral-calculator/. Put inside whatever function you want and you will most certainly get the result. Again, I prefer Symbolab over Wolfram generally for all the calculus problems, but for the complex calculus problems WolframAlpha still beats Symbolab. Symbolab integrals link: https://www.symbolab.com/solver/definite-integral-calculator
  5.  WolframAlpha Surface & Integrals: http://www.wolframalpha.com/widgets/view.jsp?id=8ab70731b1553f17c11a3bbc87e0b605  Write in the functions (subtract functions of-course, see Newton-Leibniz rule) that you want to integrate over it and write down the limits for integration for the surface. Now if you are unsure about the limits of the two function then the best thing to do is to go to number 2 on the list and find the intersection points and insert them in the two boxes which represent the limits. Direct solutions (similar to this one) is not offered by Symbolab, however you can always use the definite integration if you know the limits of your integration, after you know them go to number 4 on the list
  6. WolframAlpha Function domain: http://www.wolframalpha.com/widgets/view.jsp?id=b0160688b805d84769cebe1afb71895   We all know how important that is and how many times we’ve searched for the domain whether it’s a function with multiple or just a single variable. There isn’t an equivalent at Symbolab but you don’t really need it. I believe this is one of the easiest problems in mathematics no matter which function is in the game…
  7. Symbolab Limits: https://www.symbolab.com/solver/limit-calculator Limits just kick ass at Symbolabs they can’t be compared to WolframAlpha. The steps are all shown and even the hardest problems are solvable here. The alternative WolframAlpha still deals with the most difficult limits to solve (I believe that the engineers at Symbolab will soon have solution for everything).

The counting goes on and on, almost all calculus types of differential equations can be solved, sequences, Laplace transformations, Fourier series and many others. In 2016 the computer can do a lot of things, consider that another lot of things is not revealed to the public. The reason why I posted so much mathematical stuff is because I’ve realized that we are taught mathematics in a wrong way. Through elementary and high school we are always doing some kind of equations and when we have to apply them on a problem the majority and when I say majority I mean 90% of us do not know how to apply the learned stuff (logarithms, roots, exponential equations, derivatives, limits, differential equations etc.). As we can see, all of this stuff that we are doing in school is solved in a couple of seconds by the computer. The point is, we should not be doing this stuff, well, we should but in low amounts. What we should do is concentrate on PROBLEM SOLVING stuff (word problems). Let’s be honest, word problems are nightmares for most of us. As soon as we see an example, task with a lot of words written people become frightened.

Word problems are indeed hard at the beginning but once our brains gets used to them, we begin to understand them. The most important thing is that we are becoming aware of the tools that we’ve learned in maths and can solve the problem sometimes in many ways. It’s better for us to spend a whole day on solving two word problems then to solve 50 long equations pulling the x out of them. There are multiple reasons why this word problem approach is better than the others but let’s focus on year 2016-2017.

As I’ve said, computers are here to help us and whenever we can use them we should do so to save us time and to put this time into something that computers are unable to do at this moment, but what we are doing is rejecting or partially rejecting the technology and following the education path of our parents/grandparents. Of-course, we should learn how to solve “equation problems” so that we can solve the word problem but the education is exaggerating with these type of problems because it assumes that the word problems will take too much of a time for a pupil to learn/grasp and therefore won’t learn anything or will learn very little but in contrary the pupil/student will benefit hugely out of it because it will try many ways to get to the result and therefore learn how not to solve the problems and how problems should be solved (depends on the type of problem being solved). We can see this kind of problem solving in programming. It takes a lot of time to develop something valuable, there are times when a computer programmer just sits and looks at three lines of code trying to work things out. The same should be applied on children early in school so that they develop a logical thinking habit.

The time of AI will certainly come at some point in the future and God knows what will happen then. I used to have an AI subject at my faculty and was skeptical with this field. I did not believe that something of that kind could ever be build in the future. As my exam was approaching and as I gained more knowledge I found out that I was wrong at the beginning. AI is indeed plausible, however, it will always be rejected from a person who has never done maths, programming and studying the AI (neural networks, deep learning etc.).

AI is basically mathematics trying to simulate a brain. With such concept, researchers are trying to make a software (and already have made quite few) which learns and applies the knowledge afterwards. Every once in a while we can see how a computer (software) outsmarted a human. For instance, the latest achievement  presents a software beating the world champion in “Go” game https://www.youtube.com/watch?v=EOWnzHAgPgE.  Experts could not believe that it happened so soon. This is one of many examples (but one of the most discussed examples recently) where AI algorithms surpass the human even though AI hasn’t yet come near its full potential.

AI will continue to expand, algorithms will appear, new concepts will emerge. We cannot stop it neither should we. Why is that so, why do we want to harm ourselves perhaps? It’s quite easy to answer the question because all the discoveries in the past as well the discoveries which haven’t happened yet are due to people’s CURIOSITY. We are curious on how things work and what things could do once build. Even if a government program against AI is to be introduced there will always be a good amount people digging and trying to build the forbidden (in this case AI).

As soon as we realize and accept the upcoming AI events, the better for all of us.

The summarize this article:

  • Learn how to think and solve problems don’t spend too much time on solving problems which a computer can easily solve such as solving numerous equations as mentioned above. Use On-line tools to speed up your work.
  • Adapt to current technologies
  • Practice daily on your field, no matter what type of field you are involved into.

Državna matura riješeni zadaci- matematika A razina, JESEN 2016. god. (postupak)

Hrvatski:

U prilogu se nalaze riješeni zadaci (Matematika A razina) sa državne mature, jesen 2016.god.
U prvom prilogu se nalazi prvih 15 zadataka dok su u drugom ostali zadaci.

Ukoliko imate kakvih nejasnoća pošaljite mail na eugen.sunic@live.com

Link na maturu, Matematika A razina 2016, ljeto: https://www.ncvvo.hr/drzavna-matura-2015-2016-jesenski-rok/

English

In the attachment below you can find solved problems from the 2016 (autumn) math exam, level A.
Students across the country must pass this exam in order to inscribe them-self to a desired faculty.

If you have any question, refer to eugen.sunic@live.com

Riješeni zadaci s postupkom, 1.dio/solved problems with steps, first part:
MAT A, viša razina, jesen 2016.god. 1.dio

Riješeni zadaci s postupkom, 2.dio/solved problems with steps, second part:

MAT A, viša razina, jesen 2016.god. 2.dio

Državna matura riješeni zadaci- matematika A razina, LJETO 2016. god. (postupak)

Hrvatski:

U prilogu se nalaze riješeni zadaci (Matematika A razina) sa državne mature, ljeto 2016.god.
U prvom prilogu se nalazi prvih 15 zadataka dok u drugom ostali zadaci.

Ukoliko ima kakvih nejasnoća pošaljite mail na eugen.sunic@live.com

Link na maturu, Matematika A razina 2016, ljeto: https://www.scribd.com/doc/316830479/MAT-A-razina-pitanja

English

In the attachment below you can find solved problems from the 2016 (summer) math exam, level A.
Students across the country must pass this exam in order to inscribe them-self to a desired faculty.

If you have any question, refer to eugen.sunic@live.com

Exam link, Mathematics A level, 2016, summer: https://www.scribd.com/doc/316830479/MAT-A-razina-pitanja

Riješeni zadaci s postupkom, 1.dio/solved problems with steps, first part:
MAT A, viša razina, ljeto 2016.god. 1.dio

Riješeni zadaci s postupkom, 2.dio/solved problems with steps, second part:

MAT A, viša razina, ljeto 2016.god. 2.dio

Insert data to database using Java-Android (MySql)

Copy and paste the following class to insert data to mysql database.

If you want to use more POST parameters just concatenate the variable urlParameters with appropriate values and POST variable names.

public class BackgroundWorker extends AsyncTask {
    private Context context;
    //in constructor:
    public BackgroundWorker(Context context){
        this.context=context;
    }
    @Override
    protected String doInBackground(String... params) {

        URL url;
        HttpURLConnection connection = null;
        try {
            //Create connection
            url = new URL(params[0]);
            String urlParameters= URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(params[1], "UTF-8");
            urlParameters += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(params[2], "UTF-8");

            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");

            connection.setRequestProperty("Content-Length", "" +
                    Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");

            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            //Send request
            DataOutputStream wr = new DataOutputStream(
                    connection.getOutputStream());
            wr.writeBytes(urlParameters);
            wr.flush();
            wr.close();

            //Get Response
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
       return null;
    }
        @Override
    protected void onPreExecute() {
        //super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String s) {
        Toast.makeText(context, "Success",
                Toast.LENGTH_LONG).show();
        //super.onPostExecute(s);
    }
}

To call the above class use the following code:

BackgroundWorker backgroundWorker= new BackgroundWorker(this);
backgroundWorker.execute("server_url_with_php_file", "param1_value", "param2_value");

Here is the link to the initial stackoverflow problem: http://stackoverflow.com/questions/38317614/http-post-via-android-java-does-not-work/38318341#38318341

Math function classes (injection, surjection, bijection)

Let’s start with the definition first:

(1) In mathematicsinjectionssurjections and bijections are classes of functions distinguished by the manner in which arguments (input expressions from the domain) and images (output expressions from the codomain) are related or mapped to each other (taken from Wikipedia: https://en.wikipedia.org/wiki/Bijection,_injection_and_surjection).

Now let’s simplify the definition:

In mathematics injectionssurjections and bijections are classes of functions which tell us how functions behave. By applying a class we can easily distinguish a function’s order in most cases (f(x)= x, f(x)=x2 etc.)

(2) Domain and codomain simplified

Domain is a set where x values are stored and the codomain is a set where y values are stored.

(3) Injection: the injection class means that each x value/element of the 2d coordinate system has a corresponding y value of the coordinate system, in other words every x value in a set (this set is called the domain) is connected to an appropriate/corresponding y value in the other set (this set is called the codomain). In order for a function to be injective all of the values from x must be connected to all of the appropriate/corresponding values to y. Injection is also called one to one relationship since every x value MUST match the corresponding y value. If a value remains without a connection in any of the sets (domain & codomain) or if there are multiple connections for example from the x values/elements from the domain to one y value from the codomain (vice versa) then the function is NOT injective.

Proof formula:

proof1_injection

Example picture:

injection_set

(4) Surjection: the surjection class means that each x value/element in the domain of the 2d coordinate system has AT LEAST ONE (but can have multiple, most often two) corresponding values/elements in the codomain. It is important to say that all y values of the coordinate system must be used in order for a function to be surjective. This means that when you look at the function and decide to draw numerous horizontal lines (both negative and positive sections of the coordinate system, y0) the horizontal line that you have drawn will have to touch AT LEAST ONCE the given function. If this is not the case then the function is not surjective.

Proof formula:

proof2_surjection

Example picture:

surjection_set

(5) Bijection: the bijection function class represents the injection and surjection combined, both of these two criteria’s have to be met in order for a function to be bijective. We write the bijection in the following way, Bijection=Injection AND Surjection.

(6) If a function is neither injective, surjective nor bijective, then the function is just called: General function

Example picture:

xsquared

 

(7) A function is not defined if for one value in the domain there exists multiple values in the codomain. For example, if we have one x value on the coordinate system (let x be 3) and for that SAME x we have 2 or more y values, then the given graph is not a function because we don’t know which y values should we use and there must only exist one y value for one x value (surjection principal). See the horizontal and vertical test below (9).

Example picture (not a function):

(8) Note: When defining a function it is important to limit the function (set x border values) because borders depend on the surjectivness, injectivness, bijectivness.

(9) Vertical and Horizontal test lines,

Vertical lines are used to evaluate the existence of a function. This means that they determine if the graph inside a coordinate system is really a function or  isn’t.

Example picture (taken from: http://mathonline.wikidot.com/different-types-of-functions)

vertical-line-test

The picture says it all but let’s add a few words: If a vertical line crosses the graph MORE THAN ONCE, then the graph is NOT A FUNCTION.

Horizontal lines are used to evaluate the function classHorizontal lines actually tell us which class does NOT BELONG TO THE FUNCTION (injection, surjection)

Example picture (taken from: http://mathonline.wikidot.com/different-types-of-functions)

Screen Shot 2014-08-28 at 10.40.11 AM

Changing border-color of HTML input element to red if an error occurs

On November 7th a question was posted on SO where the OP wanted to change the border color of the input elements to red when both inputs didn’t match a condition.

I combined the JavaScript and a little bit of JQuery to solve this.

Here is the code:

var index_one;
var index_two;

    $('#Location, #LocationTo').change(function (e) {

        index_one = $("#Location")[0].selectedIndex;
        index_two = $("#LocationTo")[0].selectedIndex;
    });
    $("#submit").click(function () {
        if ($("#Location>option").eq(index_one).text() == $("#LocationTo>option").eq(index_two).text()) {
            $('#Location, #LocationTo').css("border-color", "red");
        } else {
            $('#Location, #LocationTo').css("border-color", "black");
        }
    });

As you can see, I first fetched the indexes of the selected items and after that gave the index to the eq(index) JQuery function in order to get the element as an object and then get the text via the .text() function. If the same options were selected in both input tags then the red border color would be displayed, otherwise the black default color remains.

If you want to handle all the possible cases then add the following code:

else if($("#Location>option").eq(index_one).text() =="Please Select")
    {
        alert ("Select an option");
    }
      else if($("#LocationTo>option").eq(index_one).text() =="Please Select")
    {
        alert ("Select an option");
    }

Here is the fiddle to see the code in action: http://jsfiddle.net/eugensunic/eg8k4vL7/1/