Monday, December 28, 2015

Testing on BrowserStack locally

If you login with a BrowserStack account, you can test your local work on emulators. Note for Safari on a Mac, you have to use specific ports.

"For now, Safari 8 on Yosemite allows Local testing via a limited number of ports. The ports that are most easy to remember are 80,3000, 4000, 5000, 8000 and 8080." - StackOverFlow post

So this for example works:

Wednesday, December 2, 2015

Clear Location Settings Cross-Browser

Let's say you are either developing or testing a website you are building that saves your location, and you already told it to save some day in the past. Interestingly every browser has its own way to clear location settings. Here's a quick reference of the big 4 Windows browsers (Chrome, IE, Edge, and Firefox).

On Chrome: Go to the settings from the hamburger menu. Click Content Settings.

On Microsoft Edge: Open the menu labeled with the 3 dots (...), hit Show More, and you will see the dropdown has the Location permissions.

On Internet Explorer: Click the gear and go to Internet Options, then Privacy tab.

On Firefox: First right click anywhere inside of the page, then select View Page Info. Then select the tab for Permissions.

Thursday, November 12, 2015

SQL Server: Save Database Locally

If you have a database up in the cloud or elsewhere and want to make a local copy, you start by opening up SQL Server Management Studio (this is 2014 but should be the same/similar for other versions).

Login to your local server. I used SQL Express, so my login is Windows Authentication and the server name is localhost/SQLEXPRESS. Also make sure this is running if you check in your Services on your machine.

Login to your online server. You need those credentials from your company or whatnot.

Now, start by right clicking on Datbases on your online server and hitting Export Data-tier application.

Hit Next.
Save locally somewhere. I just made a Db folder under my C drive to make it easy to find. It will save a BACPAC file.

Now, right click on Databases on your local server and hit Import Data-tier application. Find your BACPAC file you just made.

Find the BACPAC file you saved.

Hit Next and finish up with this dialog and you should have a local copy imported into your local server.

Add your local DB to your connection string config file.

Installing SQL Server && .NET 3.5 on Windows 10

Recently at work, I upgraded to Windows 10. Obviously, I needed SQL Server. Interestingly all versions I tried (2012, 2014, and 2016) are dependent on .NET 3.5. Even more interestingly, Windows 8 and Windows 10 do not come stock with .NET 3.5.

Anytime I tried to install SQL server, I would get a missing .NET 3.5 error.

When I try to install .NET 3.5 I had the following error: 0x800f081f missing source files.

I tried this and it failed, many times:
  1. Open a command prompt with administrator user rights (Run as Administrator) in DOS BOX type gpedit.msc
  2. Local Computer Policy -> Admin Templates -> System -> Specify settings for Optional Component install and component repair (way near the bottom of the right frame)
  3. Check the “Contact Windows Update Directly” box and set policy to Enabled.
  4. Close gpedit
  5. *Try this: Type in the dos box: DISM /Online /Enable-Feature /FeatureName:NetFx3 /All
  6. Or check in Control Panel and you can now check the .net 3.5 box and it should download
(I also tried using a USB drive with the source files and that failed.)

What did work for me:
  1. On this page (note screenshot above with photo):, hit Download Media Creation Tool.
  2. On my Windows 10 laptop, I opened this file, made a .ISO of my windows 10.
  3. I mounted said .ISO onto the E: drive (right click .ISO and click Mount).
  4. I ran command prompt as an admin.
  5. Then I ran this in command prompt (Replace E with whatever your mounted drive for Windows ends up being).
DISM /Online /Enable-Feature /FeatureName:NetFx3 /Source:E:\sources\sxs /All /LimitAccess

.. and it made me restart. And then it appeared to work. For some reason having it mounted locally worked.

On top of this, I was installing SQL Server 2014 and ran into another snag. I got stuck on Install watsonx86_cpu32_action, for a long long time.. suspected somethng was wrong and read a website here. Based on the suggestions, I went into Task Manager and had to End Task on some Windows Installer processed under the Background Processes.. and then it caused it to get past the watson freeze.

Wednesday, November 11, 2015

Angular JS: $.emit and $.on

In Angular, you sometimes need the scope/functions of another controller to be triggered by something in one controller.

For example, say you have a controller for a navigation page (Controller 1) and a Map page (controller 2) that contains changing maps. You want the navigation page to have a button that changes the map, but all of your stuff to control the Map page is in the Map controller. You can't hit those scope items or those methods.

So, you can have an onclick on the button on the Navigation page that hits the Controller 1 changeMap functions, which will $.emit 'changeMap' out.. where in Controller 2 there is an event listener $.on waiting for this to be triggered, and it will reroute you to the changeMap_Handler.

Controller 1: Navigation Page Controller
        $scope.changeMap = function () {
            $rootScope.$emit('changeMap', { fromState: $ });
Controller 2: Map Page Controller
    $rootScope.$on("changeMap", changeMap_Handler);  // passes it to the handler function

    // here is the handler function
    function changeMap_Handler(event, attrs) {
        $scope.changingMap = true;
        $rootScope.changingMap  = $scope.changingMap ;
        if (attrs.fromState === "someStateVariable") {
            $scope.variable = true;

Tuesday, November 3, 2015

Wednesday, September 2, 2015

Xamarin Test Cloud: How to deploy your tests

Step 1: Go to

Step 2: Login and see your dashboard.

Step 3: Click "New Test Run" on the top right. Click which type of app you want to run tests for first.

Step 4: Select devices you want to run the test on.

Step 5: Test series is how your tests will be organized on your dashboard. You can order them by the number of test runs you plan to execute. So if you are only doing 5 or so devices, it is nice to label it small. Then you can do medium and large depending on your audience.

Step 6: Take this code, fill in the details for your application (apk file, assembly directory..).. the part I blue marked out is my API key and my email address (which you will have filled in for your test run). Then go into the Apple terminal and put it in.. submit it, and your tests will be added to Test Cloud! You can login and see your runs on their website.

You can put "--category "smoke"", or whatever attribute is above your tests to only run certain ones. If you look at my previous Xamarin post, I mentioned you can have
[Category("smoke")]  // attribute for sending only certain tests
public void TestNameHere()

And you add it to the Terminal code at the end like this..!
mono packages/Xamarin.UITest.1.0.0/tools/test-cloud.exe submit ../something.ipa APIKEYHERE --devices f37a5aa9 --series "small" --locale "en_US" --user --assembly-dir StuffHere/bin/Debug --category "smoke"
Or for Windows command prompt, something like this and change api key to the one given to you:
Users\ctenn\Desktop\testcloud\testcloud\AAA\packages\Xamarin.UITest.1.0.0\tools\test-cloud.exe submit CCApp\testcloud\com.AAA_TESTCLOUD_14_2.apk APIKEYHERE --devices d3939da0 --series "weekend" --locale "en_US" --app-name "AAA" --user --assembly-dir CCApp\testcloud\AAA\AAA\bin\Debug
NOTE 1: You can also use Xamarin studio, go into your Test explorer, right click (or double tap whichever it is) the test you want.. and then click to submit it to Test Cloud. (I am just a stubborn web developer who lives off of Windows and Visual Studio).

NOTE 2: General expectations for how well applications will work on devices depends heavily on the device. Goal is to find out your audience and what types of phones they use to cover the vast majority of them. It is best to get the top say 10-20 devices working as close to 100% as you can. Then work to try and support bigger audience. When you get to the 40 newest devices point, you will start seeing massive fails in performance based on their capacity to deal with new applications and you can't really expect them to work perfectly. Chances are you will have difficulty supporting more than the top 80 realistically based on those phone's ability to perform and their memory.

Sunday, August 30, 2015

Xamarin and UI Automated Tests via Test Cloud

Xamarin is used to build, test, and monitor mobile applications. There is a Xamarin Studio IDE for development, and Test Cloud for testing your application across thousands of devices, and Xamarin Insights for monitoring. You do have to pay for these services and this is good for enterprise development for apps to be released on the app store that need to be as bug free as possible.

I will be focusing on UI Automated Tests and Test Cloud. The purpose of this post is to do a basic overview of what it can do and a little kickstart into how to use Xamarin for Automated UI Testing.

UI Automated Tests are tests that perform the manual taps / scrolls / typing / other interactions a person would normally have to do (QA). These are usually the more tedious interactions and many places would save a lot of time and stress by automating these tests. It allows for QA to do their more difficult specific work and remove the manual time consuming stuff. It also sniffs out differences in different platforms and a large scope of devices. The scope of these tests are basically anything you can do with direct interaction on the phone manually, doesn't involve only the back-end (use unit tests here), and can be performed while the mobile application is being run. You have the choice of using Calabash or C# as a language for development -- at this point when I have spoken with the Xamarin team, the functionalities of both languages are now about equal and you can choose one or the other (in the past you had good coverage with C#, but full coverage using Calabash). Calabash is basically the framework with all the methods and whatnot defined for you to use to perform the testing. Now the C# Xamarin.UITest assembly has the same methods open for use too.

Let's start with how to set up a suite for testing. Purchase Xamarin licenses. Startup a new empty C# solution. Add NuGet packages for Xamarin.UITest and nunit.framework. Now you can separate some folder structure into Global, Pages, and Tests. In this main directory, you will also want to make a new class and call it AppInitializer or something like this. HERE is the Xamarin documentation for starting an app. You will get your api key from Xamarin, and the other constants are your local builds. You can choose to use an emulator or a physical device for testing.
public static class AppInitializer
        const string apiKey = "YOUR_API_KEY";
        const string apkPath = "YOUR LOCAL FILE";
        const string appFile = "YOUR LOCAL FILE";
        const string bundleId = "YOUR BUNDLE ID";

        public static IApp StartApp(Platform platform)
            IApp app;
            if (platform == Platform.Android)
                app = ConfigureApp
           // can add another if / else here for iOS

            return app;
You will need a base abstract class, let's just call it Setup.cs for now..this is how you will cause the app to hit the AppInitalizer.StartApp() function every time before you run a test. You will inherit from this base class on each new Test class.
public abstract class Setup
        protected IApp app;
        protected Platform platform;

        protected AbstractSetup(Platform platform)
            this.platform = platform;

        public virtual void BeforeEachTest()
            app = AppInitializer.StartApp(platform);
            if (platform == Platform.iOS)
                // implement here

            if (platform == Platform.Android)
                // implement here


            app.Screenshot("On Home Page");

        public void ResetApp()
            new GlobalPage(app, platform)
So, back to the 3 sections:
  • Global: you can put methods you will use throughout the whole app, enums, a methods for swiping from left or right, things you will just need all the time no matter what page you are on and so you can avoid code duplication.
  • Pages: for each page in your app you plan to test, you should have a page for it with relevant properties and methods it will need. Let's say the mobile developers named their Main Logo iOS-main-logo and Android-main-logo.. the page is a good place to map these to YOUR testing property name, such as simply mainLogo. Now this makes ease for you to deal with any tapping on this mainLogo in your testing app and it is already mapped to both the Android and iOS versions. You can write basic functions like, TapLogoGoHome() into this page so no matter what you can call this function in the tests without needed to rewrite it over and over again.
  • Tests: Below is an example of a test. You have to have a [Test] attirbute. You can optionally have a "category" attribute which means that you can run a specific "playlist" of tests for example if you don't want to run them all every time. You will use this when sending it to Test Cloud and specify the cateogory of tests to run: in this example it can be smoke or secondCategory. You can add a test to as many lists as you like, just keeping adding them on a new line.
        public void SwipeOpenSideMenuAndGoHome()
            string tapOrSwipe = "swipe";

            new GlobalPage(app, platform)

            new SideMenuPage(app, platform)

            new HomePage(app, platform);
On GlobalPage, you will find the OpenSideMenu method, which does the actual .Tap() function.
    public class GlobalPage : BasePage
        protected string menuButton;

        public GlobalPage(IApp app, Platform platform)
            : base(app, platform)
            if (OnAndroid)
                menuButton = "MenuButton";
            if (OniOS)
                menuButton = "y";

        public void OpenSideMenu(string TapOrSwipe = "tap")
            app.WaitFor(isOpen, timeout: TimeSpan.FromSeconds(5));
Using the REPL is necessary to get the elements on the page needed to tap/scroll to get the test working. What you do is call app.Repl() inside of your code, you right click your test and put in Debug test and drop a breakpoint on your app.Repl line. After you hit it, step forward once.. and you will see a little pop up. Type "tree" with no quotation marks and this will give you a layout of everything on the page. SEE the Xamarin Repl tree explanation. Repl specifically spits out what is on the page you are on. You need the IDs (so ask your developers to ID everything in a logical fashion!) to find out what you need to tap and whatnot. You get it from the Repl, not from going through their codebase as this is much faster. If you find something you are not sure about, you can go into the Repl console box and type queries into like app.Flash(c=>c.Class("EditText")) and it will flash the item (blink so you can see it) and so you can tell if it is the right element or not. Sometimes there is no ID, now you have to grab the item some other way such as getting a Child(), Parent(), Descendant(), Sibling(), etc and the index of it (to see which number element it is). This can be good/bad.. it requires maintenance for if the index number or structure changes, but sometimes in a face paced environment without IDs there is no other choice. With app.Query(); you can get things like a count or the text from an element.
// for IDE Xamarin Studio or Visual Studio
stuffOnScreen = app.Query(x => x.Id(ListView).Child()).Count();
var currResult = app.Query(x => x.Id(ListView).Child(stuffOnScreen - 1).Descendant())[2].Text;

// for Repl() tree to find your element
app.Flash(x => x.Button())

// Everything on the page

// One element on the page by index

// total things on page

// Certain matching element on page
app.query(x => x.Id("refresher") 

// Flashes and finds something on the page. 
app.Flash(x => x.Id("bill_iconImageButton"))

// Tap action on page

/// note that sometimes the Next button
/// is on the keyboard, 
/// so this...
app.Flash(x => x.Id("Next"))

// brings back nothing
// but! doing this in the Repl..

// moves the page for you out of the keyboard and onto the next page. 
// Therefore.. add this to your test method 

Last minute tips.. use the Object Browser on the Xamarin.UITest assembly a lot with the Xamarin doucmentation, it makes a lot more sense that way. The Xamarin developers and support are great and there for you if you need it! You can use emulators or physical devices. If you normally work on OSX or don't mind it, it is easier because you can run everything (Android emulators/iOS emulators or physical devices for both) in one place and use Xamarin Studio which is fully integrated. If you are like me.. you can try doing Windows and Visual Studio to run Android and develop everything there (you CANNOT emulate iOS here unless you have a nearby Apple computer and can use it as a building environment by connecting to it.. or..), then move the files over to the OSX/Xamarin Studio environment to run the iOS tests. Likely you will have to tweak the IDs of everything in iOS and debug the tests all over again as iOS behaves differently and things are likely labeled differently, too. Good luck!

Friday, July 31, 2015

LINQ cleanup

Just a little example of some code cleanup.. it's a-OK to break out a logic into something long to get it working and give it some thought. It's great to take your work and make it better using tools like LINQ to make it easier to read and less space. There are times it is not worth it to make it smaller if its harder to read, however. Also, it can be good to cleanup code you see in large projects to make things neater!

Here is one example with 2 pieces of code for looking up a username.. you can search it by first name, last name, or both. Likely for usability the future holds a sorting feature too!

Before lots of LINQ: After putting if/else cases into "or" inside .Where of LINQ:

Tuesday, July 28, 2015

Get; Set;

Taking a step backwards from my normal posts to some more basics.. I wanted to explain Get; Set; on properties to anyone new to software. I felt like some of the descriptions online were a little non-user friendly and wanted to help clarify it. This is done in C#, but the concepts are the same idea with other languages.

        public class Person
            public string Name { get; set; }
            // Let's investigate this one
            public string Phone { get; set; }

        // This is called an auto-implemented property. What does this really mean?
        public string Phone { get; set; }

        // This is the longhand / what really happens / the manual way to do this. 
        private string phone;
        public string Phone
            get { return phone; }
            set { phone = value; }

        // Now what is THIS doing? Example time..
        // Make a Person1 of type Person. 
        Person Person1 = new Person();

        // Add a value to the property of Person. 
        Person1.Phone = "123-4567"; // **#1 see below

        // phone field
        private string phone; 
        // phone property
        public string Phone // **#1 hits this first, causing you to enter the braces..
            get { return phone; } // #3 returns little case phone, which has been assigned to value as property Phone
            set { phone = value; } // #2 sets the magical VALUE to little case phone

        // So now if we ask for..
        // thingy will be "123-4567";
        var thingy = Person1.Phone;

        // where do we get value from????
        // "The word value references the value that client code is attempting to assign to the property." - MSDN
        // In other words.. Microsoft took care of it for you.
        // You try to access and set a property, it knows to assign that to "value"

        // With this version, you can make a new property based on other properties / customization
        // not there is only a get here. Its like a read only value
        public string PhoneString
                string phoneNumString = "";
                // null safe it! 
                if (Person.Phone == null) return string.Empty;

                // if there's an area code, add it on! 
                if (!string.IsNullOrWhiteSpace(Person.Phone.AreaCode))
                    phoneNumString = "(" + Person.Phone.AreaCode + ") " + Person.Phone.PhoneNumber;
                else phoneNumString = Person.Phone.PhoneNumber; // if not, no biggie. 

                // if there's an extension, add it on too! 
                if (!string.IsNullOrWhiteSpace(Person.Phone.Extension)) phoneNumString += "ext." + Person.Phone.Extension;
                return phoneNumString;

        // So, running with the example above... here's what you can and can't do.. 
        // NOPE. Can't set this. There is only a get. 
        Person1.Phonestring = "(813)123-4567 ext. 1000"; // This will fail and throw you an error. ANGRY RED SQUIGGLYS. 

        // But! You can do this. And then... 
        Person1.AreaCode = "813";
        Person1.Phone = "123-4567";
        Person1.Extension = "1000";

        //  result = "(813)123-4567 ext. 1000"
        var result = Person1.Phonestring;

Monday, July 27, 2015

Cool APIs

Little side applications are fun to make. Try thinking of add-ons to your favorite current apps/websites to make them even better and you can make your own project! Or these are great tools to incorporate to make something else new and cool. I love adding JS libraries and APIs from other people and places to make use of the awesome things people put out into the web to share.

Of course, Google. Google drive? Email self a document = upload to drive? Oh the million possible projects using Google..

Unfortunately, google does not have a free API for translating anymore (you have to pay..).. but Microsoft does! I used this in my AnkiTranslate project. Good for if you want to work with multiple languages or make study aids to learn another language.

Can I say wheel of lunch? Lunch picker? Thing to do picker?

Practice stock market = $$$.. if you can get good at it.

And more..

LINQ Eager and Lazy Loading

Here's a little bit on using Linq and the ways to get data out via Eager / Lazy loading and LINQ methods vs operators. The explanations are in the code comments below.

using System.Data.Entity;
using System.Linq;
using EFFundamental;

namespace ConsoleApplication1
    class Program
        // How to query against entity data model
        static void Main(string[] args)

        // using LINQ operator
        // Lazy loading = fetch only main data and have to make subsequent calls to get related data. 
        // Use when you know related data is not required at all or at the time of the call. 
        private static void LinqOperatorLazyLoading()
            var context = new CHEntities();
            var query = from c in context.council_member 
                        where c.end_dtm != null
                        select c;
            var result = query.ToList();

           // note Lazy loading is by default, on.  If you want to change this..
           // context.ContextOptions.LazyLoadingEnabled = false;

        // using LINQ operator
        // Eager loading = explicitly fetching all the data related in one call.
        // Good if all your stuff is not too large or you are unsure of what pieces of data you will need. 
        // If it is a large amount of data.. slower but more complete. 
        private static void LinqOperatorEagerLoading()
            var context = new CHEntities();
            var query = from c in context.council_member.Include("address") // the .Include is what makes it Eager loading (these are the "extra" objects )
                                                        .Include(x => x.council_lku) // to use lambdas, make sure to add: using System.Data.Entity;
                        where c.end_dtm != null
                        select c;
            var result = query.FirstOrDefault();

        // using LINQ methods .WHERE etc.. 
        private static void LinqMethods()
            var context = new CHEntities();
            var result = context.Compliance_Notes.Where(x => x.last_updated_by == "ctenn").ToList();

        private static void ProjectionQuery()
            var context = new CHEntities();
            var query = from c in context.council_member.Include("address")
                        where c.end_dtm != null
                        // anonymous type and 2 of its properties. new object selecting only the properties you want. 
                        select new

Thursday, July 9, 2015

Project Euler 8: Largest product in a series (C#)

The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832.


Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?

Uncomfortably large 1000 digit number is getting stored as a string to begin with.. it's just too big to fit into the regular number types. Thought was I could either iterate through all possible sets of 13 then see if 0 is part of the set. If 0 is part of the set, obviously the product will be 0 which is less than a set without 0.. so just get rid of those possibilities. If we can get a product out of it that isn't 0, we are going to parse each string into its digit using LINQ then aggregate it into a product. Then compare the product to the last highest product. If it is higher, set the current highest product to the new product.

            Stopwatch stopwatch = new Stopwatch();
            string thousandDigitNum =
                "/*insert giant number here from their website*/";

            string thirteenDigitString = null;
            long newProduct = 0;
            long currHighestProduct = 0;

            for (int i = 0; i < (thousandDigitNum.Length -13); i++)
                thirteenDigitString = thousandDigitNum.Substring(i, 13);
                if (thirteenDigitString.Contains("0")) continue;
                newProduct = thirteenDigitString.Select(digit => long
                        .Aggregate((a, b) => a*b);
                if (newProduct > currHighestProduct) currHighestProduct = newProduct;


            Console.WriteLine("The highest value is: " + currHighestProduct + ". And the time elapsed is:" + stopwatch.Elapsed);

23514624000 is the solution.

Friday, July 3, 2015

Project Euler 7: 10,001 prime number (Java)

This one is interesting, if you think about it.. question is if there is a formula?

Well.. I looked for a formula for it and according to my favies wikipedia: "In number theory, a formula for primes is a formula generating the prime numbers, exactly and without exception. No such formula which is efficiently computable is known. A number of constraints are known, showing what such a "formula" can and cannot be.".. so "efficiently" iterate it is! You could iterate yourself to death going through every possibility.. or try and find a better way to iterate, just less.

I figured.. welp. Let's say we have the number 100. It breaks down into 1 x 100, 2 x 50, 4 x 25, 5 x 20, 10 x 10.. and stops there. The first number always goes up, second one always goes down. If they meet, they reverse.. and we are repeating ourselves. BUT you can try this, no matter what .. at least one of the pair of numbers is less than half. So we will ALWAYS catch the pair of multiples if we check all the numbers up to half. So what I am doing for example 100 is seeing if any number from 1-50 will divide evenly into it. The minute its divisible by any of those numbers iterating from 1 to 50, its not prime, doesn't get added to my magic list of numbers, and the loop continues to check 101.. and so on.

1031 ms to calculate is about a second, which fits into most of your attention spans out there.. so I'll take it :).

Point to note and something that was COOL. You can use (int)Math.ceil(num/2.0) to get a rounded up version of your number (ceil = ceiling, you can do Math.floor to get it rounded down.. floor is down whee). BAD thing. Don't forget your cast depending on the type of numbers being used!!!

import java.util.ArrayList;
import java.util.List;

 * Created by Crystal on 6/29/2015.

public class Program {
    public static void main(String[] args) {
        // Project Euler #7
        // What is the 10,001st prime number if we consider 2 the first prime number?

        long start = System.nanoTime();

        int num = 2;
        int halfNum = 0;
        boolean isPrime = true;

        List primeNumbersArr = new ArrayList() {};

        while (primeNumbersArr.size() < 10001){
            isPrime = true;

            if(num % 2 == 0 || num % 3 == 0 || num % 5 == 0) {

            halfNum = (int)Math.ceil(num/2.0);

            int i = 2;
            for (; i < halfNum; i++){
                if (num % i == 0){
                    isPrime = false;

            if (isPrime == true) primeNumbersArr.add(num);

        long stop = System.nanoTime();

        System.out.println(primeNumbersArr.get(10000)  + " is the solution calculated in a time of " + (stop - start) / 1000000 + "ms");


104743 is the solution calculated in a time of 1031ms.

Project Euler 6: sums and squares (Java)

So, I've taken to trying out IntelliJ and Java for some project euler problems and then will start making small apps in there. It's been fun, these puzzles are a good way to get a quick intro into Java. There are definitely some minor differences, but for the most part navigating the IDE and not having my shortcuts be the same has been the largest challenge. There is a free 1 year subscription to IntelliJ and Resharper (for C#) if you have a student email address ending in .edu, so I recommend giving it a shot!!!

import java.util.ArrayList;
import java.util.List;

 * Created by Crystal on 6/29/2015.

public class Program {
    public static void main(String[] args) {
        // Project Euler #6: Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum
        // Starting value, set x to 100
        long start = System.nanoTime();

        int x = 100;

        int sumOfSquares = (x * (x + 1) * (2 * x + 1)) / 6;
        int sum = 0;
        for (int i = 1; i <= x; i++)sum += i;

        long stop = System.nanoTime();

        System.out.println(sum*sum - sumOfSquares + " is the solution calculated in a time of " + (stop - start) / 1000000 + "ms");

25164150 is the solution calculated in a time of 0ms.

Friday, June 19, 2015

Code Project: AnkiTranslate

CLICK HERE to see the full app on GitHib.

Coming out of a medical background, I can't say I'm one for memorizing much of anything (memorizing hundreds of pages/slides at a time taught me 2 things: #1 amazing time management skills, #2 you forget everything you don't directly apply and use often).. BUT I will say that for learning a language you need to memorize vocabulary and that Anki is the tool out there to help you. Anki is simple and free, its flash cards that you make and that do spaced repetition (it hits you with cards you missed at a time interval you can set that is good for you). However, I wrote hours and hours of notes and cards and well, that's no fun.

In a language, I've seen most people say you need about 2000-5000 words to be conversational. And a lot of English speakers speak around 15,000-20,000 words. And crazy specialized folks who go deep into an area (could be medicine, science, whatever).. may know 30,000 or so words. So let's stick with 2000-5000 words... if I am FAST and can make 1 Anki card a minute, I will spend 5000 hours making flash cards.. which is 83 hours. Yes, yes making the cards *might* help me learn it a little more. But I do think flipping through the cards for 83 hours I could be done with at least a good portion of the cards and be speaking / interacting with people instead of still making more cards.

I could spend said 83 hours making a TON of flashcards for random vocabulary. Or I could spend 2 hours making a little app, drop it on github for anyone to use / see, and get to program a little :D.. and drop my time making flash cards down to about 30 seconds). I can find plenty of lists of top / most common 100 or 1000 or such English words, drop this into the program and get flashcards off of a simple copy and paste.

Using the app: input a text file of words you want to translate out and separate each word to translate with a newline (or edit the app to deal with CSV or whatever format or all formats..).. let AnkiTranslate know which language you are starting with and which one you want outputted.. and then..

Output: you will get a text file you can import into Anki that will make your flash cards. Anki has the front of the card, separated by a tab, the back of the card, then a new line for a new card. So as such the format of the output will be your initial word, a tab, the translated word, and a newline for a new card.

Caveat: This is good for vocabulary and short phrases. Expect that a translator will, well, mess up grammar and make you sound funny if you try and translate a ton of phrases. My purpose is to use this to get mass amount of pure one word vocabulary down, then I will study grammar and sentence strucutre on its own and put together the words I learn from this. Sometimes the meaning of the word won't be the one you think of, it happens.. but it'd happen anyways using a translator. If I get 95% of the words right off a translator, that's still pretty good and I'll fix them when I use it wrong and am corrected :P.

Here's the fun: planning. I decided on a WPF because it's easy for me to navigate as I've worked on projects with it before, the UI is simple and looks nice (I say nice relatively, it works, I don't care about design as much as function and logistical use), so on the CS code behind of main window I made a plan.. I usually *try* my best to bullet out a good order of what I am working on, and it almost always partially turns out that way:
namespace AnkiTranslate
    /// Interaction logic for MainWindow.xaml
    public partial class MainWindow : Window
        public MainWindow()
        private void Translate_Click(object sender, RoutedEventArgs e)
            // use native windows importer for file

            // display file path on textbox

            // parse file into string

            // google translate API work

            // parse translator API work + initial values into anki format

            // native windows save file location option

            // export .txt file

            // display success message on textbox
And when I dropped some text boxes onto a window it looks like this:

I ran into a snag and realized that Google does not offer free translating at all anymore, but Microsoft does. I went to the Microsoft Translator API and followed the directions there, it was easy to plug right into my app. This is the expanded version of my initial plan.
namespace AnkiTranslate
    /// Interaction logic for MainWindow.xaml
    public partial class MainWindow
        public MainWindow()

            Languages languageChoices = new Languages();

        private void ComboBoxFrom_Loaded(object sender, RoutedEventArgs e) { ComboboxDoWork(sender); }

        private void ComboBoxTo_Loaded(object sender, RoutedEventArgs e) { ComboboxDoWork(sender); }

        private void ComboboxDoWork(object sender)
            var comboBox = sender as ComboBox;

            if (comboBox == null) return;
            comboBox.ItemsSource = ConfigClass.Languages;
            comboBox.SelectedIndex = 0;

        private void Translate_Click(object sender, RoutedEventArgs e)
            ConfigClass.LanguageTranslatedFrom = ((ConfigClass.ComboboxItem) lanFromComboBox.SelectedValue).Value;
            ConfigClass.LanguageToTranslateTo = ((ConfigClass.ComboboxItem) lanToComboBox.SelectedValue).Value;

            var openFileDialog = new OpenFileDialog {Filter = "Text Files (.txt)|*.txt", FilterIndex = 1, Multiselect = true};
            bool? userConfirmation = openFileDialog.ShowDialog();

            if (userConfirmation != true) return;
            string file = openFileDialog.FileName;

                ConfigClass.TextToTranslate = File.ReadAllText(file);
                MsgBoxLabel.Content = file;
            catch (IOException) { throw new Exception("Something went wrong, eh?"); }

            ConfigClass.TranslatedText = new MicrosoftTranslator().Translate();

            // DOWORK to make anki format
            string[] textToTranslateArray = ConfigClass.TextToTranslate.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
            string[] translatedTextArray = ConfigClass.TranslatedText.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
            string finalText = "";

            for (int i = 0; i < textToTranslateArray.Length - 1; i++)
                finalText += textToTranslateArray[i] + "\t" + translatedTextArray[i] + System.Environment.NewLine;

            var saveDialog = new SaveFileDialog { Filter = "Text Files (.txt)|*.txt", FilterIndex = 1};
            bool? userSaveConfirmation = saveDialog.ShowDialog();

            if (userSaveConfirmation != true) return;
            string savePath = @saveDialog.FileName;

            File.WriteAllText(savePath, finalText);
            MsgBoxLabel.Content = "Successfully saved to: " + saveDialog.FileName;

Since it's a small app, I just hardcoded in some languages (feel free to adjust as needed to whichever you are learning). The website that has a list of all possible languages is here:
namespace AnkiTranslate
    public class Languages
        // full list of supported languages here:
        public void Populate()
            var en = new ConfigClass.ComboboxItem { Text = "English", Value = "en" };
            var es = new ConfigClass.ComboboxItem { Text = "Spanish", Value = "es" };
            var bg = new ConfigClass.ComboboxItem { Text = "Bulgarian", Value = "bg" };
            var cn = new ConfigClass.ComboboxItem { Text = "Chinese", Value = "zh-CHS" };
            var tlh = new ConfigClass.ComboboxItem { Text = "Klingon", Value = "tlh" };

            ConfigClass.Languages = new List {en, es, bg, cn, tlh};

I also made a ConfigClass to hold some global variables instead of passing around local ones to my different functions.

namespace AnkiTranslate
    public class ConfigClass
        public static string TextToTranslate { get; set; }
        public static string LanguageTranslatedFrom { get; set; }
        public static string TranslatedText { get; set; }
        public static string LanguageToTranslateTo { get; set; }

        public static List Languages { get; set; }

        public class ComboboxItem
            public string Text { get; set; }
            public string Value { get; set; }
            public override string ToString()
                return Text;

You can see below with the variables clientId and strTranslatorAccessUri , I am referencing the ConfigurationManager.AppSettings which is hitting my App.config file keys that I added. This is the actual work going to the Microsoft API and returning translated text.

namespace AnkiTranslate
    public class MicrosoftTranslator
        public string Translate()
            string clientId = ConfigurationManager.AppSettings["clientID"];
            //string clientSecret = ConfigurationManager.AppSettings["clientSecret"];
            string strTranslatorAccessUri = ConfigurationManager.AppSettings["strTranslatorAccessURI"]; 

            String strRequestDetails = string.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=", HttpUtility.UrlEncode(clientId), HttpUtility.UrlEncode(clientSecret));

            System.Net.WebRequest webRequest = System.Net.WebRequest.Create(strTranslatorAccessUri);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "POST";

            byte[] bytes = System.Text.Encoding.ASCII.GetBytes(strRequestDetails);
            webRequest.ContentLength = bytes.Length;

            using (var outputStream = webRequest.GetRequestStream()) outputStream.Write(bytes, 0, bytes.Length);

            System.Net.WebResponse webResponse = webRequest.GetResponse();

            var serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(AdmAccessToken));

            //Get deserialized object from JSON stream 
            AdmAccessToken token = (AdmAccessToken)serializer.ReadObject(webResponse.GetResponseStream());
            if (token == null) throw new ArgumentNullException("token");

            string headerValue = "Bearer " + token.access_token;

            // User input text to translate plus chosen TO and FROM languages 
            string uri = "" +
                HttpUtility.UrlEncode(ConfigClass.TextToTranslate) + "&from=" + ConfigClass.LanguageTranslatedFrom + "&to=" + ConfigClass.LanguageToTranslateTo;
            System.Net.WebRequest translationWebRequest = System.Net.WebRequest.Create(uri);
            translationWebRequest.Headers.Add("Authorization", headerValue);
            System.Net.WebResponse response = null;
            response = translationWebRequest.GetResponse();
            Stream stream = response.GetResponseStream();

            Encoding encode = Encoding.GetEncoding("utf-8");
            var translatedStream = new StreamReader(stream, encode);
            System.Xml.XmlDocument xTranslation = new System.Xml.XmlDocument();

            return xTranslation.InnerText;

The finished product looks like the following:

If you do get to use this app, here's a good sample of the top 1000 words and how useful they are by example:

Also, this is *perfect* for the app to translate to another language.. 1000 words separated by a new line.

Here's my use of the app and the output file (plugs right into Anki and I get my deck! Whoo hoo! 80 hours to play more games..): 1000 most common vocabulary words in English / Bulgarian

If you want to try it out yourself, have a go! (I just uploaded the release version to Google Drive so you can download from there. If anyone actually wants to use this and doesn't program / wants me to add more languages just ping me on the contact form and I can add the rest..) Download

Tuesday, June 2, 2015

Life Learning Optimization

I wanted to make some comments on learning, perhaps it will help someone out who is struggling with learning quickly and how it occurs. I've done everything in my life to optimize how I learn and I have been pretty successful in helping others as I've spent years tutoring for almost every science / math / topic / exam.

Learning quickly usually means you "care" more (in some way are more motivated, curious, or passionate than others), work harder, work smarter per your time, or spend more time thinking / working through things throughout your day. Honestly though, people do have a "knack" for learning certain things in certain ways. I will also go so far as to say there's a "knack" for memorizing vs. computing thought. By all means you can be born good at both or get good at both, but usually you have a personality and tendency to like/dislike one or the other and it will force your thinking patterns to be "better" at one naturally. There are visual-, tactile-, audio- types of people and others. You can get better at each one, but there are some that you will be better at without as much effort as the others.

It can make you incredibly unhappy to spend all your thought/time doing things you don't want to or doing things you like the wrong way. Don't do it. Life is too short. You might think you are terrible at something, but be going about it the wrong way. For example, I am a visual learner. I learn very well and very fast writing, reading, drawing concept maps, reviewing, testing myself, and reviewing more all visually. You would think I was terrible at something if you made me try and do all of it by listening to audio only (as many times as I wanted) and being able to only talk to people with no writing allowed. I'm the same person, learning the same topics, but some methods make things stick better.

Sometimes you have the leisure and time to improve at a learning skill. If you are mostly visual and keep working at audio, you will be able to become better at both! However, if you're pressed for time and performance (say.. medical student) you are probably better off figuring out how you learn and overusing that to death so you get some time to sleep. Learning is about learning yourself and what makes you understand the best (in a good amount of time with a worthwhile retention).

Other factors in learning are awakeness (did you sleep enough?), happiness with life, overall health (diet / exercise help), background knowledge (in the same, or other seemingly unrelated things), self-confidence, openness (are you fighting learning it? do you hate your class or teacher?), and good habits (do you habitually distract yourself or did you form good habits at sitting and focusing over the years?). Background knowledge in learning, critical thinking, or being familiar with a topic helps a lot.

I've seen people waste unimaginable amounts of time on other thoughts and it cuts into their learning time. Many of them never realized the problem and became frustrated. For example here are a few (look out for these, see if any sound like you..):
  • Thinking about things happening in the day.
  • Thinking about how every last little thing works.. then getting hung up on it.
  • Thinking about how boring things are.
  • Thinking about how much they hate what they are doing.
  • Thinking about how something is named in a dumb way.
  • Thinking/worrying about what someone else thought of them that day.
  • Thinking/worrying about failure.
  • Thinking about how to get through and just scrape past some class / school / graduation date.
  • Thinking about what they will do in the future (which to some extent is productive, as it can be planning and motivating for the current task).
  • Thinking about whether they will get a call / text / message / whatever.
  • Thinking about how to display some status update on social media.
  • Thinking about said random noise / shuffling / movement in room.
  • Thinking about how many pages they read or how far they are getting in the book.. without actually reading the book.
If you said you had 1 hour of time to work on Algebra.. and you did any or a lot of the above.. your 1 hour is now worth say 15 minutes. That's a lot of thought going into stuff not Algebra.

How to fix some of the above things.. make sure after every page (or paragraph / sentence) you actually comprehended, can summarize, and remember what was written. If you don't remember things you read, record yourself speaking the page and listen to it. If you hate audio, either get Dragon or transcribe audio yourself. If you don't map memory to typing, then write it out, or vice versa. Repetition and quizzing yourself helps. Believe in yourself and don't worry about other people. Also don't get hung up on something too long, one nitty gritty detail won't kill you and obsessing over it gets emotional and wastes time. Sometimes its better to write it down, address it later when you know more, or go out into the world and ask someone online/in person to share some of their knowledge with you. Don't worry about "telling" other people on social media or real life how many chapters you read so you sound good. No one cares how much you read if you didn't learn. Learn for YOU.

You are made up of your years. Your years are made up of your months. Your months of days. Your days of hours. And your hours of minutes and seconds.. how you spend them with your actions and thoughts. If you waste your thoughts on garbage (listed above), it will take you a very long time to get through things when you learn them. I don't advocate not addressing these things, they are important but in their own time. If your job is to be a student and to study, or you made yourself a goal to learn something.. then make sure your time is spend smartly working on the task at hand, in the present. Having a plan in mind, an approximate flexible schedule (don't be too hard on yourself if you don't make it, count the positives and don't let things hold you back!), and a goal help immensely.

I've been told I am a fast learner. Sure? I'm smart but no genius child. I am a very hard worker, extremely goal oriented, and very good at focusing at the task at hand. I hate garbage thoughts (negative feelings, negative things from other people, not believing, worry, unnecessary life drama, emotional or irrational reactions). I don't have any form of social media.. the most I have is this blog for software, one for food (my hobby is cooking), and LinkedIn.. I feel most other social media provides more unnecessary distraction than good, but it's just my opinion (however, there are times where it will HELP your career a lot if you are a public speaker, actor/actress, athlete, traveler/have friends at a distance, etc..). I try my best not to worry about others or let them take time away from my thoughts. Of course, I'm human and do care very much what a few people close to me think, but other than that I don't waste time on drama/life garbage. I can blatantly ignore my surroundings, to the point of likely unhealthy if some event were to occur behind me. I can be called "spacey".. I'm there, but I'm not. If you leave me alone a couple minutes I'll have started thinking or planning out something else in my head I was working on before.. for example working through a puzzle, rehashing as many words I can think of from a language I'm learning, finding another way to approach something, or walking through a concept map of something I've learned. Your idle time is A LOT of your day. Your time spent walking, exercising, traveling, driving, sitting, etc.. and if you took all that time, you can get very good at what you already do "quickly" relative to someone else who is thinking about their Facebook post.

You don't have to do this with your time, only do it if you want to.. do what makes you happy. If you enjoy social media, art, history, science.. anything then spend your time on it! This post if for if you are trying to learn and not sure why you may not be getting the results you want. Not everyone wants to learn a ton of stuff. For some, life is a comfortable place and relaxing is important. For others success and moving up. But, for me.. I like to learn. I'm good at learning and it makes me happy so just sharing some mistakes and advice if you too enjoy learning.

Sunday, May 31, 2015

The Internet

The Internet is a physical wire that connects everyone together, often called the network of networks. It's not magic, a fluffy cloud, or abstract. Communication can be made between things connected to this main wire. The effort to make the initial communication between computer networks began in the 1960's by the US Government. ARPANET was made with collaboration with the UK and France, and it was the interconnection of regional academic networks during the 1980's. Commercialization of the Internet was during the 1990's and marked the beginning of the modern version of the Internet we know today, full of blogs, shopping, academic research, services, and more.

The Internet protocol suite is usually referenced as TCP/IP (Transmission Control Protocol / Internet Protocol), because those are the main protocols. A protocol is nothing more than a set of rules on how to do things. The TCP/IP says how to transfer data (rules for how to packetize, address, transmit, route and receive). I'm going to borrow from Wikipedia for their organizational chart below on the data flow between two internet host computers (A and B).

Servers connect directly to the Internet wire. It is easy to visualize the connection between one server to another as a simple view. The big picture is that there are millions and millions of connections onto this wire.

Since this Internet wire is a physical wire, underground and whatnot, how does it work internationally? It's the same deal.. you put a big wire undersea and wire it up to the one in your country. Interesting stories HERE and HERE about the idea of someone trying to cut the Internet wire undersea. There is a point at the ocean called a landing station where the wire will originate. About every 50 miles or so, there is an amplifier undersea that helps to amplify the signal.
Each server has harddrives. Harddrives contain the content of websites. If you are working at a company as a software engineer, you will typically work on your projects locally then publish to their server (the harddrives of their server as shown above!).
Usually there will be a local copy of your project, something in between for QA testing (UAT: User Acceptance Testing), then the final copy will move to production. Similarly, there will be multiple sets of databases, one for each layer.

If you do work from home, you will likely need to use a VPN for secure access. Photo below from PC Mag.
Each server has its own address called an IP address, it's just like a physical address for homes (each one must have its own unique identifier for its "location"). The World Wide Web (www, W3) is an set of linked hypertext documents and is a layer built on top of the domain system you can reach via the Internet. There are secure websites (https) and unsecure ones (http). Http uses Port 80 and Https uses TCP Port 443 by default, so the communications are different. A port is a communication end point for a host's operating system and differentiates different applications. Think about all the wires going in and out of a large wall outlets, imagine if there were a thousand or so. You would number each one, and one would be for your microwave, computer, hair dryer, etc etc.. those could be thought of as an anaology different "sockets" to be differentiated for different functions). The number is more of a convention to keep things less confusing and so there are defaults for each one.

The reason https is actually secure is due to its use of another protocol called Secure Sockets Layer (SSL) to move data. See chart below from
You, the client, are indirectly connected to the Internet via an Internet Service Provider (ISP) such as Verizon, Cox, Comcast, etc... You are connected to the ISP via Digital subscriber line (DSL). There are many choices for how Internet is provided from fiber optics, satellite, cable, etc.
LAN, WAN, and WLAN are different amounts of connectivity. LAN is a Local Area Network between computers in a home, office, school, or other small area. A WAN is a Wide Area Network spanning a geographical region. And, a WLAN is Wireless Local Area Network (WLAN).. so basically a LAN but using wireless. Wifi is wireless Internet. A router can send out radio signals that can be transmitted and received by phones, computers laptops..
Let's say you want to login to Google to reach your Gmail account. You can send an email to someone else.
Once you send your email to someone, say using Yahoo for Hotmail, the Google servers will contact the Yahoo servers (pink line).

Friday, May 8, 2015

How to Start Programming

I've been asked for recommendations to go the self-taught route for someone with no programming experience,! It starts with the basics and intro, but most of it is up to you :)! As long as you are building things you are interested in and enjoy it, you will pick up skills along the way that make foundations and are always relevant to things you work on in the future. I suggest beginning in this order, starting with web development. As opposed to doing web, you could also try and do application type of development, but here is a good start for web development.

#1. HTML

#2. CSS

Do these to practice:

#3. JavaScript - complete this course, email / text / call me if you get stuck

#4. jQuery

**ABOVE is for a web developer

Microsoft Visual Studio -- download this program to do C# work

#5. C# concepts-- go through all these concepts and understand them. Kinda go through these and #6 at the same time and try using Visual Studio

#6 C# video tutorial set --

#7. SQL: go through these basic commands (there's a lot more than this though, ask me about it when you get to this point)

Then be able to do simple problems from Project Euler.

Contoso Univ App:

Sites I cannot live without:
Stack Overflow - The best open source community to ask questions and see what others have asked.
GitHub - you can upload your own work or pull down others code to see how things are made!
Code Project - GREAT tutorials and articles on specific topics.

Sunday, March 29, 2015

Daily Code Puzzles

Here is a giant list of great sites to practice some puzzles for fun! You can do them when you want or make a goal to do one or a few a day. My current plan is to do one reddit daily planner when I can (ideally once a day, but hard to do with work schedule.. and *cough* DOTA 2!).

I suggest making a solution for your work and organizing it by puzzle #. I put each puzzle # in a file labeled 0-50, 51-100, 101-50, etc.. then picked a naming convention and I make one class page for each problem then make an instance of it in the console app and pass in whatever variable (if there is one) from the main console program.cs. Pick one, two sites at the most and stick with it for awhile. It's harder to keep to a goal when it becomes too much so start small! Take a look at my setup!
My Reddit Github repository

Monday, March 16, 2015

Project Euler - Smallest Multiple

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? (LCM of 1 to 20)

public class Euler5
        List> allFactors = new List>();
        List finalFactors = new List();

        public long Solve(int start, int end)
            for (int i = start; i <= end; i++)
                var factor = FindFactors(i);

            foreach (var factorsList in allFactors) 
                foreach (var factor in factorsList)
                    if (!finalFactors.Contains(factor)) finalFactors.Add(factor);
                    int countCurrent = factorsList.Where(x => x == factor).Count();
                    while (countCurrent > finalFactors.Where(x => x == factor).Count())

            return finalFactors.Aggregate(1, (a, b) => a * b);

        private List FindFactors(int num)
            List result = new List();

            while (num % 2 == 0)
                num /= 2;

            int factor = 3;
            while (factor * factor <= num)
                if (num % factor == 0)
                    num /= factor;
                else factor += 2;

            if (num > 1) result.Add(num);
            return result;

Tuesday, March 3, 2015

Project Euler - Largest palindrome product

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. Find the largest palindrome made from the product of two 3-digit numbers.

    public class Euler4_Palindrome
        int product;
        string productString;
        string reversedProductString;
        List palindromeList = new List();

        public int Solve() 
            for (int i = 999; i > 99; i--)
                for (int j = 999; j > 99; j--)
                    product = i * j;

                    productString = product.ToString();
                    reversedProductString = Reverse(productString);
                    if (productString == reversedProductString) palindromeList.Add(product); 
            return palindromeList.Last();

        public static string Reverse(string s)
            char[] charArray = s.ToCharArray();
            return new string(charArray);

Saturday, February 28, 2015

Project Euler - Largest prime factor

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?

public class LargestPrimeFactor
        List factorsList = new List();
        bool isPrime = true;
        public long FactorNumber(long number)
            double sqroot = Math.Sqrt(number);
            for (long i = 1; i < sqroot; i++)
                if (number % i == 0) 
                    for (long j = 2; j < i; j++)
                        if (i % j == 0) 
                            isPrime = false;

                    if (isPrime == true) 

                        bool secondaryIsPrime = true;
                        for (int k = 2; k < (number / i); k++)
                            if ((number / i) % k == 0) 
                                secondaryIsPrime = false;
                        if (secondaryIsPrime == true) factorsList.Add(number / i);
                        secondaryIsPrime = true;
                    isPrime = true;

            long[] factorsArray = factorsList.ToArray();
            return factorsArray[factorsArray.Length - 1];

My comments: So, this was a very interesting problem to do. Solving the problem for small numbers took me about 2 minutes. HOWEVER, realizing that my computer was brute forcing it and trying to deal with the larger number and NOT coming to a solution withing a reasonable time (10+ mins is about when I gave up on waiting) made me realize I needed to change how it was working. By making it iterate fewer times the brute force gives a "instant" answer if you only have to iterate up to the square root of the number in question. So for example, let's say we have a number 64. The square root is 8. So we can iterate only up to 8 and find out that 1, 2, 4, and 8 are the only factors.. and we can get the other side of the factor by diving the number (64) over those 4 values. So we know that 1 goes with 64, 2 goes with 32, 4 goes with 16, and 8 goes with 8.. and then from there we can only take the ones of those that are prime. As opposed to just iterating from 1 to n, which takes a very very long time and is extremely inefficient.

Good practice: Abstract class vs. Interface

Abstract class: Like a Noun! A group of similar things you can group together with one word. Can have implementation of methods and/or declared non-implemented methods. May or may not include abstract methods. However, if you have an abstract method, it does have to be inside of an abstract class (Got it? Just like rectangle is a square, but square is not a rectangle). A non-abstract class derived from an abstract class (abstract class itself cannot be instantiated) must include actual implementations of all inherited abstract methods and accessors.

Abstract Class Example
    abstract class Pokemon
        // Properties
        protected int myLevel;
        public abstract int Level {get; set;}
        // Going to make this an abstract int just to show the difference
        protected int myHP;
        public abstract int HP {get; set;}

        // Can have methods that are DECLARED but NOT IMPLEMENTED
        abstract public int HPCalculator();

        // Can have methods that are IMPLEMENTED. These two are also NON-ABSTRACT
        public int Attack()
            return enemyHP - attackDamage;
        public int Heal(object potion)
            return myHP + potionAmount; 

    class Pikachu : Pokemon
        public override int Level
                return myLevel;
                myLevel = value;

        public override int HP
                return myHP;
                myHP = value;

        public override int HPCalculator()
            return Level * 5;

    static void Main(string[] args)
        // You can nickname your Pikachu! Let's call him KetchumChu.
        Pikachu KetchumChu = new Pikachu();
        // Set Level property
        KetchumChu.Level = 34;

        // His HP is going to end up being 34*5 = 170 HP.
        KetchumChu.HP = HPCalculator();

        // BATTLE!!! 

Interface: Like a Verb (Action)! Things that your class can do. The whole Interface must be implemented in the classes that implement it, you cannot pick an choose pieces you have to take the whole thing (all or nothing!)

Bare minimum blueprint instructions of what has to be inherited at a minimum. NO IMPLEMENTATION. You want a house? You need a floor, 4 walls, and a roof. You do have to implement every single thing mentioned in the interface. So don't put a chimney and fireplace in your interface if you live in Florida.

Interface Example:
interface IAmCuteInterface
    // These are DECLARED but NOT IMPLEMENTED in the interface.
    void MakeCuteFace();

interface IAmThunderTypeInterface
    // These are DECLARED but NOT IMPLEMENTED in the interface.
    void Thundershock();

// this new class can implement as many interfaces as it wants!! You HAVE TO implement everything from both interfaces now. 
class Pikachu : IAmCuteInterface, IAmThunderTypeInterface
    // Explicit interface member implementation:  
    void IAmCuteInterface.MakeCuteFace()
        // Method implementation.

    void IAmThunderTypeInterface.Thundershock(object potion)
        // Method implementation. Zzzzzap. 

    static void Main()
        // Declare an interface instance.
        Pikachu KetchumChu= new ImplementationClass();

        // Using the thundershock method. 

        // Cheeky ain't he?

Don't put in extra stuff that some things will need and other won't, put in things that you know every single thing would need. For a car to work.. you need tires, an engine, and brakes. Don't add an electric motor to your IDriveable, you don't have to have an electric motor. You can specify that later. You know you don't want to ever instantiate a "car" as no one really has just "generic car" they have their Ford Mustang, Tesla, Corvette, whatever.

You can inherit many interfaces! As many as you like! You can make many separate interfaces for different components and inherit what you need out of it. Let's say we have multiple interfaces.. one each for hands, feet, head, ears, fur, tail, scales, wings:

  • Lizard implements hands, feet, head, tail, scales
  • Cat implements hands, feet, head, ears, fur, tail
  • Bird implements feet, tail, and wings
  • Fire breathing dragon implements hands, feet, head, ears, tail, scales, wings
Summary: You use abstract classes and interfaces to add functionality, increase code re-useability/reduce repetitive code, and streamline functionality. Yes you could avoid using these completely, but your code would eventually get very repetitive and you will find yourself doing a lot of extra and unnecessary work. Don't put in extra stuff into either, just the bare minimum that has to fit into whatever inherit/implements the abstract class/interface. If you find yourself wanting to only take pieces of an abstract class or an interface, try breaking them up into difference classes/interfaces, there was probably a better way to design (plan ahead :) ?). Use an abstract class as a base when you are making many similar things that you can group together (i.e. mammals) and use interfaces (as many as you want!) for small functional parts.

Takeaway from examples: Based on my example.. Pokemon makes a great base class. Every type of Pokemon from Pikachu to Charizard will have HP and be able to Attack() and can Heal(). However, NOT every Pokemon is considered cute or a thunder type.. so these make great Interfaces. Some Pokemon are BOTH cute and thunder type like Pikachu and thus can inherit both interfaces. Pikachu can take the one base class Pokemon, plus both interfaces as seen below:
class Pikachu : Pokemon, IAmCuteInterface, IAmThunderTypeInterface