Friday, April 20, 2018

The reasones why i changed my mac book pro to a windows lapop


Everybody loves MacBooks, i was curious and happy to get a MacBook with touch bar at work, but once i got it, my hate to it started and built up and was increasing day after day.

I finally decided to ex-change it with a windows laptop for the below reasons:

  • Gets very hot most of the time, with just chrome and slack running.
  • Keyboard is awful, key press distance is very little, noisy as well.
  • Touch bar means that i need to do 2 steps for simple tasks like changing the volume or brightness.
  • Touch bar place makes it easy to touch its buttons unintentionally, i found myself touching the mute button or the Siri multiple times when pressing the backspace button.
  • The Siri button is really annoying, i have disabled it and still it comes up with a pop every time it is touched.
  • Touch pad is too big, lots of times my hand was resting on it while i was using it. 
  • I heard it is very stable, but mine was crashing every couple of days. Lots of times i start it to find that it is actually restarting instead of resuming from sleep.
  • Mostly annoying: I need my USB ports, not every thing is Type C. I had a hard drive that i couldn't connect, simply because i left the converter at my office. In addition to USB headphones, etc...
  • OSX lacks lots of simple tasks, coming from a windows. I had to do some tweaks to have some of them. Like: Locking the machine with keyboard shortcut, arranging windows and moving between different screens with keyboard shortcut, Minimising windows, etc...
  • I wasn't able to login multiple time after woking form sleep.
  • Software updates were very frequent and always asking for restart.


What i liked:
  • Display is amazing.
  • Speakers are amazing.
  • Touch pad gestures are nice.


Friday, July 21, 2017

Importing all pfx certificates in a folder

Assuming all pfx have the same password

forfiles /p "E:\Certificates" /m *.pfx /c "cmd /c CERTUTIL -f -p "password" -importpfx @file"

Tuesday, July 11, 2017

Sort the odd numbers in array

Given an array of numbers, it is required to sort ascending odd numbers but even numbers must be on their places.

ex:
{ 5, 3, 2, 8, 1, 4 } should give { 1, 3, 2, 8, 5, 4 }
{ 5, 3, 1, 8, 0 } should give { 1, 3, 5, 8, 0 }

Algorithm:
define sorted list
define another list to save the odd number indexes
Iterate through the array for each item
     if item is even skip it
     if item is odd:
           add it to the sorted list
           add the item index to indexes list
loop through the indexes list, for each index
     save the item from the sorted list into the the numbers array at the that index

Note: the sorted list should support duplicate items

Example implementations

Using a list

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace sortOdd
{
    public class Program
    {
        static void Main(string[] args)
        {
            CollectionAssert.AreEqual(new int[] { 1, 3, 2, 8, 5, 4 }, Program.SortArray(new int[] { 5, 3, 2, 8, 1, 4 }));
            CollectionAssert.AreEqual(new int[] { 1, 3, 5, 8, 0 }, Program.SortArray(new int[] { 5, 3, 1, 8, 0 }));
            CollectionAssert.AreEqual(new int[] { }, Program.SortArray(new int[] { }));
        }

        public static int[] SortArray(int[] array)
        {
            var result = new int[array.Length];
            List<int> sortedOdd = new List<int>();
            var indexes = new List<int>();
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i]%2 == 0)
                    result[i] = array[i];
                else
                {
                    int index = sortedOdd.BinarySearch(array[i]);
                    if (index < 0)
                        sortedOdd.Insert(~index, array[i]);
                    else
                        sortedOdd.Insert(index, array[i]);
                    indexes.Add(i);
                }
            }
            for (int i = 0; i < indexes.Count; i++)
            {
                result[indexes.ElementAt(i)] = sortedOdd.ElementAt(i);
            }
            return result;
        }
    }
}

Using sorted list 

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace sortOdd
{

    public class Program
    {
        static void Main(string[] args)
        {
            CollectionAssert.AreEqual(new int[] { 1, 3, 2, 8, 5, 4 }, Program.SortArray(new int[] { 5, 3, 2, 8, 1, 4 }));
            CollectionAssert.AreEqual(new int[] { 1, 3, 5, 8, 0 }, Program.SortArray(new int[] { 5, 3, 1, 8, 0 }));
            CollectionAssert.AreEqual(new int[] { }, Program.SortArray(new int[] { }));
        }

        public static int[] SortArray(int[] array)
        {
            var result = new int[array.Length];
            var sortedOdd = new SortedSet<int>(new DuplicateKeyComparer<int>());
            var indexes = new List<int>();
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i]%2 == 0)
                    result[i] = array[i];
                else
                {
                    sortedOdd.Add(array[i]);
                    indexes.Add(i);
                }
            }
            for (int i = 0; i < indexes.Count; i++)
            {
                result[indexes.ElementAt(i)] = sortedOdd.ElementAt(i);
            }
            return result;
        }
    }

    public class DuplicateKeyComparer<TKey>:IComparer<TKey> where TKey : IComparable
    {
        public int Compare(TKey x, TKey y)
        {
            int result = x.CompareTo(y);

            if (result == 0)
                return 1;  
            return result;
        }
    }
}

Monday, July 10, 2017

Level order traversal in spiral form

Printing tree in spiral form, or a zigzag form

would print 1 2 3 4 5 6 7
Algorithm

printSpiral(tree)
  set level = tree root
  while level contains nodes
     printLevel(level, ltr)
     set level = getNextLevel(level)
     ltr == !ltr 
Function to get next level
getNextLevel(level)
set nextLevel as empty list
foreach node in level
     if(node.left!=null) nextLevel.add(node.left)
     if(node.right!=null) nextLevel.add(node.right)
Function to print all nodes at a given level
printLevel(level, ltr)
if(!ltr)
    reverse level
foreach node in level
    print node.data

Example code in Java

package com.algorithms.treespiral;

import
java.util.ArrayList;
import
java.util.Collections;

public class
Main {
   
/* Driver program to test the above functions */
   
public static void main(String[] args)
    {
        BinaryTree tree =
new BinaryTree();
       
tree.root = new Node(1);
       
tree.root.left = new Node(2);
       
tree.root.right = new Node(3);
       
tree.root.left.left = new Node(7);
       
tree.root.left.right = new Node(6);
       
tree.root.right.left = new Node(5);
       
tree.root.right.right = new Node(4);
       
System.out.println("Spiral order traversal of Binary Tree is ");
       
tree.printSpiral(tree.root);
   
}
}

class Node
{
   
int data;
   
Node left, right;

    public
Node(int d)
    {
       
data = d;
       
left = right = null;
   
}
}

class BinaryTree
{
    Node
root;

   
/* print spiral order traversal of a tree  */
   
void printSpiral(Node node)
    {
       
boolean ltr = false;
       
ArrayList<Node> layer = new ArrayList<>();
       
layer.add(node);
        while
(layer.size() != 0)
        {
            printLevel(layer
,ltr);
           
layer = getNextLevel(layer);
           
ltr = !ltr;
       
}
    }

   
/* gets the next layer in the tree */
   
ArrayList<Node> getNextLevel(ArrayList<Node> node) {
        ArrayList<Node> nextLayer =
new ArrayList<>();
        for
(Node n:node) {
           
if(n.left != null)
                nextLayer.add(n.
left);
            if
(n.right != null) {
                nextLayer.add(n.
right);
            
}
        }
       
return nextLayer;
   
}

   
/* prints tree level taking direction into account */
   
void printLevel(ArrayList<Node> node, boolean ltr) {
       
if (ltr != true) {
            Collections.reverse(node)
;
       
}
       
for (Node n:node) {
            System.
out.print(n.data + " ");
       
}
    }
}

Wednesday, June 21, 2017

IIS problems

Some commands to help troubleshoot windows hosted web applications 

URL reservations: 

netsh http show urlacl
netsh http delete urlacl url=https://+:443/
netsh http add urlacl url=https://+:443/ user=everyone

Firewall

netsh advfirewall firewall add rule name="IISExpressWeb" dir=in protocol=tcp localport=443 remoteip=any action=allow

Certificates

Show certificates
netsh http show sslcert ipport=0.0.0.0:44347

delete cert
netsh http delete sslcert ipport=0.0.0.0:44347

Add cert
netsh http add sslcert ipport=0.0.0.0:44347 certhash=d4e23174e12ec96e8d3b7cacf7a4f83da9c08e12 appid={214124cd-d05b-4309-9af9-9caa44b2b74a}

Network 
netstat -a -n -o | findstr 443
netstat -ab  | findstr 443

Apppool
Look at the app pools status
c:\Windows\System32\inetsrv\appcmd.exe list apppools

Check event viewer

In my case i found the following error
An error occurred while using SSL configuration for endpoint 127.0.0.1:443.  The error status code is contained within the returned data.


Monday, June 12, 2017

Git tips

git config push.default current
Pushing to the server with he same branch name automatically

Some usefull aliases 
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.cob checkout -b
git config --global alias.st status
git config --global alias.unstage 'reset HEAD --'
git config --global alias.df 'difftool'
git config --global alias.mf 'mergetool'

Sunday, June 4, 2017

DateTime parsing in .NET

Good percentage of bugs and test failures comes from the way date is parsed.
Popular example, a unit test is created, runs on local machine without any problems, then on the test agents, sometimes it passes, and other times fails.
Usually this happens when there is a date stored in UTC for example, then we parse it without specifying date kind, which may change the time value in some cases.

Example below for different ways to parse date, and the effect of that on a time comparison.
Whenever the parsed date kind is local, and the time is adjusted, the comparison is not as we expect.
In the below examples, i am comparing the dates checking if less than 8:40 and expecting all to be true. Some of the them the comparison was giving false, due to time adjustment.

namespace DateParsing
{
    using System.Globalization;
    using System.Xml;

    class Program
    {
        static void Main(string[] args)
        {
            Parse("2017-06-01T08:33:49Z");
            Parse("2017-06-01T08:33:49");
            Parse("2017-06-01T08:00:00.0000000Z");
            ParseByFormat("2017-06-01 08:33:49", "yyyy-MM-dd HH:mm:ss");
            Console.ReadKey();
        }

        private static void Parse(string dateString)
        {
            Console.WriteLine("========== input string is: {0} ===============", dateString);
            var date1 = DateTime.Parse(dateString);
            PrintDate(date1, "Using parse, no date style");
            var date2 = DateTime.Parse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
            PrintDate(date2, "Using parse, Adjust to universal style");
            var date3 = DateTime.Parse(dateString, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
            PrintDate(date3, "Using parse, Assume universal style");
            var date4 = XmlConvert.ToDateTime(dateString, XmlDateTimeSerializationMode.Utc);
            PrintDate(date4, "Using XmlConvert, SerializationMode UTC");
        }

        private static void ParseByFormat(string dateString, string format)
        {
            Console.WriteLine("========== input string is: {0} ===============", dateString);
            var date1 = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
            PrintDate(date1, "Using parse exact, no date style");
            var date2 = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
            PrintDate(date2, "Using parse exact, Adjust to universal style");
            var date3 = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
            PrintDate(date3, "Using parse exact, Assume universal style");
            var date4 = XmlConvert.ToDateTime(dateString, format);
            PrintDate(date4, "Using XmlConvert, SerializationMode not specified");
        }

        static void PrintDate(DateTime date, string format)
        {
            DateTime x = new DateTime(2017, 06, 01, 08, 40, 00);
            Console.WriteLine("Date is {0}, date kind is {1}, {2}", date, date.Kind, format);
            Console.WriteLine("{0} < than {1} is {2} ", date, x, date < x);
        }
    }
}


========== input string is: 2017-06-01T08:33:49Z ===============
Date is 01/06/2017 09:33:49, date kind is Local, Using parse, no date style
01/06/2017 09:33:49 < than 01/06/2017 08:40:00 is False
Date is 01/06/2017 08:33:49, date kind is Utc, Using parse, Adjust to universal style
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True
Date is 01/06/2017 09:33:49, date kind is Local, Using parse, Assume universal style
01/06/2017 09:33:49 < than 01/06/2017 08:40:00 is False
Date is 01/06/2017 08:33:49, date kind is Utc, Using XmlConvert, SerializationMode UTC
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True

========== input string is: 2017-06-01T08:33:49 ===============
Date is 01/06/2017 08:33:49, date kind is Unspecified, Using parse, no date style
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True
Date is 01/06/2017 08:33:49, date kind is Unspecified, Using parse, Adjust to universal style
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True
Date is 01/06/2017 09:33:49, date kind is Local, Using parse, Assume universal style
01/06/2017 09:33:49 < than 01/06/2017 08:40:00 is False
Date is 01/06/2017 08:33:49, date kind is Utc, Using XmlConvert, SerializationMode UTC
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True

========== input string is: 2017-06-01T08:00:00.0000000Z ===============
Date is 01/06/2017 09:00:00, date kind is Local, Using parse, no date style
01/06/2017 09:00:00 < than 01/06/2017 08:40:00 is False
Date is 01/06/2017 08:00:00, date kind is Utc, Using parse, Adjust to universal style
01/06/2017 08:00:00 < than 01/06/2017 08:40:00 is True
Date is 01/06/2017 09:00:00, date kind is Local, Using parse, Assume universal style
01/06/2017 09:00:00 < than 01/06/2017 08:40:00 is False
Date is 01/06/2017 08:00:00, date kind is Utc, Using XmlConvert, SerializationMode UTC
01/06/2017 08:00:00 < than 01/06/2017 08:40:00 is True

========== input string is: 2017-06-01 08:33:49 ===============
Date is 01/06/2017 08:33:49, date kind is Unspecified, Using parse exact, no date style
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True
Date is 01/06/2017 08:33:49, date kind is Unspecified, Using parse exact, Adjust to universal style
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True
Date is 01/06/2017 09:33:49, date kind is Local, Using parse exact, Assume universal style
01/06/2017 09:33:49 < than 01/06/2017 08:40:00 is False
Date is 01/06/2017 08:33:49, date kind is Unspecified, Using XmlConvert, SerializationMode not specified
01/06/2017 08:33:49 < than 01/06/2017 08:40:00 is True

Wednesday, May 31, 2017

string.Format with params trap

Lately i have seen this code

        static void LogError(string error, params object[] details)
        {
            var message = string.Format(error, details);
            Console.WriteLine(message);
        }

The code compiles and runs without problems, and if p is passed as a single string, would work fine. If someone knows that it should be a single string.
If someone else is using the same method he might fall into a trap assuming that the params is optional, which would also compile but would give exception during runtime.

Ex:
        static void Main(string[] args)
        {
            var message = "Error occurred, details: {0}";
            LogError(message, "details");
            LogError(message);
        }

        static void LogError(string error, params object[] details)
        {
            var message = string.Format(error, details);
            Console.WriteLine(message);
        }

It would compile and run, but would give an error

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.

Another developer might assume that he can pass multiple params, which would only take the first one and ignore the others

Ex:
        static void Main(string[] args)
        {
            var message = "Error occurred, details: {0}";
            LogError(message, "details");
            LogError(message, "details", "more details ");
        }

        static void LogError(string error, params object[] details)
        {
            var message = string.Format(error, details);
            Console.WriteLine(message);
        }


Would output:
Error occurred, details: details
Error occurred, details: details

Registering all ocx files

I had an old app that is using windows controls ocx libraries, like comctl32.ocx, comdlg32.ocx And others
The program was complaining about missing comctl32.ocx, then i did register it with the below command, running it in elevated command prompt 
regsvr32 c:\Windows\SysWOW64\comctl32.ocx

Starting the app again it complained about another missing ocx. 


In that case it might be better to register all the ocx files in the SysWOW64 folder by running the below command

forfiles /p "c:\Windows\SysWOW64" /m *.ocx /c "cmd /c regsvr32 @file"

Monday, January 16, 2017

Namespace and extending twitter bootstrap


Using customized bootstrap styles can sometimes conflict with other bootstrap styles that are not customized, for example this could happen if you have a frame and you are loading a web component inside of it inside a page.

Possible solution to avoid conflicts is to namespace twitter bootstrap

Lets take example html with bootstrap styling

<html>
<head>
    <title>My Twitter Bootstrap example</title>
    <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
    <ul class="nav nav-pills" role="tablist">
        <li role="presentation" class="active"><a href="#">Home <span class="badge">42</span></a></li>
        <li role="presentation"><a href="#">Profile</a></li>
        <li role="presentation"><a href="#">Messages <span class="badge">3</span></a></li>
    </ul>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</body>
</html>

To namespace bootstrap styles:
Create a new less file, and paste the below inside. "mybt" below is the custom namespace i am using

.mybt {
    @import "bootstrap-3.3.7/less/bootstrap";
}

After that compile this less file
lessc mybt.less mybt.css

And now after referencing mybt.css the html would use mybt and the bootstrap styles like below

<html>
<head>
    <title>My Twitter Bootstrap example</title>
    <link rel="stylesheet" href="mybt.css">
</head>
<body>
    <ul class="mybt nav nav-pills" role="tablist">
        <li role="presentation" class="mybt active"><a href="#">Home <span class="mybt badge">42</span></a></li>
        <li role="presentation" class="mybt"><a href="#">Profile</a></li>
        <li role="presentation" class="mybt"><a href="#">Messages <span class="mybt badge">3</span></a></li>
    </ul>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
</body>
</html>

Another option is to extend bootstrap styles
to extend it, create new less file with below:

@import "bootstrap-3.3.7/less/bootstrap";

.my-nav:extend(.nav) {}
.my-nav-pills:extend(.nav-pills) {}
.my-badge:extend(.badge) {}

Extending will work if you have only few styles that you are using.