Map groups to parent products using nested subqueries I have the following tables

productstbl
===========================================
SegmentCode CategoryId ParentId
============================================

-----------------------------------------------------
categoriestbl

==================
CategoryId  name
====================

---------------------------------------------------------

Groupstbl

=====================
GroupId name
=====================

---------------------------------------------------------
CategoriesGroupsInfo

=======================
id  CategoryId  GroupId
=======================

---------------------------------------------------------

the logic goes like this: I want to map groups to parent products (root node which have parentid = 0)
and the subproducts of that parent will inherit theses groups by default.

The levels of products are unlimited, for example:

1   Basic foods (root node )
    1.1 Baked goods
        1.1.1 American breads
              1.1.1.1 Adobe bread
    1.2 Breads

2 Prepared foods(root node )
    2.1 Appetizers
    2.2 Condiments
    2.3 Confectionery

Note that I know the root node of any product through first char of segmentcode.

For example,  root node of  1.1.1.1 Adobe bread will have segment code 1 which is Basic foods.

Groups are only applied for root nodes and to know the subproducts have to match first number of segment code.

Here is my query it do the work but the execution plan is a headache.

 select * from productstbl
    where substring(SegmentCode,1,1)
    like ( select substring(SegmentCode,1,1)
           from categoriestbl where CatID in(
           select CatID from CategoriesGroupsInfo where GroupID = 1))

Is there any alternative query?

I think the formatting of your code could use some improvements :

select *
from productstbl
where substring(SegmentCode,1,1) like
(
    select substring(SegmentCode,1,1)
    from categoriestbl
    where CatID in
    (
        select CatID
        from CategoriesGroupsInfo
        where GroupID = 1
    )
)

Selecting every column can be expensive; I would recommend to optimize the query to select only the columns you need.

You could also potentially improve the performance (though not necessarily the execution plan) by creating a stored procedure, so the SQL engine wouldn't have to recalculate the execution plan on each call. This also make it much easier to call it from application code.

As far as improving the execution plan, you could modify the database to add indexing to SegmentCode, or add some columns to contain the individual segment codes (if that is feasible).

Short of changing the database, you could use #TempTables and add indexes on the column(s). That would increase I/O but may improve the execution plan.

On another note, you could most likely change like to in since you are comparing a single character with another. like is mostly used for string comparisons using wildcards, which are very expensive and you are not doing.


Overlapping rectangles - multidimensional arrays Task: You are given two rectangles.For each rectangle you are given its bottom-left and top-right points. Check if they overlap. If they do, check for bottom-left and top-right points of the overlapping area.

I decided to solve this by using multidimensional arrays. Using object might make it more transaprent tho. Is there anything, that I could change (especially in terms of task approach, code bugs, code style and performance ) ?

I came up with following code:
Method wich checks if the give rectangles overlap

    public static bool Overlapping(int[][] firstRectangle, int[][] secondRectangle)
    {
        bool XOverlapping = secondRectangle[0][0] <= firstRectangle[1][0] &&
        firstRectangle[0][0] <= secondRectangle[1][0];
        bool YOverlapping = secondRectangle[0][1] <= firstRectangle[1][1] &&
        firstRectangle[0][1] <= secondRectangle[1][1];
        if (XOverlapping && YOverlapping)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

Method which checks for bottom-left and top-right points of the overlapping area.

 public static void GetOverlappingArea(int[][] firstRectangle, int[][] secondRectangle)
    {
        if (Overlapping(firstRectangle, secondRectangle))
        {
            int startXOverlapping = Math.Max(firstRectangle[0][0], secondRectangle[0][0]);
            int endXOverlapping = Math.Min(firstRectangle[1][0], secondRectangle[1][0]);
            int startYOverlapping = Math.Max(firstRectangle[0][1], secondRectangle[0][1]);
            int endYOverlapping = Math.Min(firstRectangle[1][1], secondRectangle[1][1]);
            Console.WriteLine("Left down corner: (" + startXOverlapping + " , " + startYOverlapping + "), Upper right corner: (" + endXOverlapping + " , " + endYOverlapping + ")");
        }
        else
        {
            Console.WriteLine("Rectangles do not overlap");
        }
    }

My test method

        static void Main(string[] args)
    {
        int[][] FirstRectangle = new[] { new[] { 2, 4 }, new[] { 8, 7 } };
        int[][] SecondRectangle = new[] { new[] { 5, 7 }, new[] { 10, 15 } };
        GetOverlappingArea(FirstRectangle, SecondRectangle);
    }

Class selection

First, I believe a multidimensional array is not good enough for describing rectangles. For instance, it's easy to forget what dimension responsible for what direction:

int[][] FirstRectangle = new[] { new[] { 2, 4 }, new[] { 8, 7 } };

What exactly is 2, 4, 8 and 7?
You have to remember. It's a bad design.

Instead you could use the built-in Rectangle struct or reinvent the wheel - write your own type.
In the latter case, it makes sense to move processing methods into your type.

Naming

I personally think that a method name should describe what the method do and what it returns.

So my suggestion is to rename methods Overlapping → IsOverlapping and GetOverlappingArea → PrintOverlappingArea.
Alternatively you could keep the name GetOverlappingArea (or Overlap, OverlapWith) and modify its code to create and return a new Rectangle instance which contains data of overlapping area. This method could be useful in the future.

Local variables should be named using camelCase: xOverlapping, yOverlapping.

Other notes

Instead of

if (XOverlapping && YOverlapping)
{
    return true;
}
else
{
    return false;
}

You could just

return XOverlapping && YOverlapping;

Summarizing

public class Rectangle
{
    public readonly int Left;
    public readonly int Right;
    public readonly int Top;
    public readonly int Bottom;

    public Rectangle(int left, int right, int top, int bottom)
    {
        Left = left;
        Right = right;
        Top = top;
        Bottom = bottom;
    }

    public bool IsOverlapping(Rectangle other)
    {
        bool xOverlapping = other.Left <= Right && Left <= other.Right;
        bool yOverlapping = other.Top <= Bottom && Top <= other.Bottom;
        return xOverlapping && yOverlapping;
    }

    public Rectangle OverlapWith(Rectangle other)
    {
        if (!IsOverlapping(other))
        {
            return null;
        }

        int left = Math.Max(Left, other.Left);
        int right = Math.Min(Right, other.Right);
        int top = Math.Max(Top, other.Top);
        int bottom = Math.Min(Bottom, other.Bottom);

        return new Rectangle(left, right, top, bottom);
    }

    public override string ToString()
    {
        return $"Left={Left}, Right={Right}, Top={Top}, Bottom={Bottom}";
    }
}

TODO

What else should be done?

It always make sense to validate all input arguments in all public methods and constructors.
If you plan to compare rectangles with each other, it makes sense to implement IEquatable<Rectangle> interface and override the GetHashCode() method and optionally define == and != operators.


Storing a fetched list of printers in Angular I have a need to store data retrieved my ASP.NET Web Api to stop making redundant API calls for the same data when I navigate through my Angular page.  On my API I have a database which stores a list of printers known to the PC and stores some basic information about them.  Here is the model:

export class Printer
{
    id: number;
    name: string;
    active: boolean;
    blacklisted: boolean;
    default: boolean;
}

This printer data is consumed by several components and as I previously had it each time I needed this data I had to request it from my backend.  Here is my attempt reducing redundant API calls:

import { Injectable } from '@angular/core';
import { Printer } from '../models/printer';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { catchError, tap } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';

@Injectable()
export class PrintersService {
  private static readonly apiUrl = "/api/printers";
  private static printers: Observable<Printer[]> = undefined;

  constructor(private http: HttpClient) { }

  getPrinters(refresh: boolean = false): Observable<Printer[]> {
    if (refresh || PrintersService.printers === undefined) {
      this.log("Observable<Printer[]> is undefined or the method requested to refresh");
      this.apiGET();
    } else {
      this.log("Observable<Printer[]> is cached, no API call will be made");
    }

    return PrintersService.printers;
  }

  /*
    Not sure how to get this method to work, I need to get a single
    observable object from my observable array of objects.  For now I'm
    just having everyone retrieve the list and then just search that list
    manually, but it would be really nice if I could just make a call for
    a single object instead of getting the whole mess.

    getPrinter(id: number, refresh: boolean = false): Observable<Printer> {
    if (refresh || PrintersService.printers === undefined) {
      this.apiGET();
    }

    var result: Observable<Printer> = of(null);
    PrintersService.printers.subscribe((printers) => {
      var target = printers.find(p => p.id === id);
      result = of(target);
    });

    return result;
  }*/

  updatePrinter(printer: Printer) {
   PrintersService.printers.subscribe(printers => {
      printers.forEach((element, index) => {
        if (element.id === printer.id) {
          printers[index] = printer;
          this.http.put(PrintersService.apiUrl, printer).pipe(
            tap(_ => this.log(`Updated printer id=${printer.id}`)),
            catchError(this.handleError<any>('updatePrinter'))
          );
        }
      });
    });
  }

  private apiGET(): boolean {
    this.log("GET: " + PrintersService.apiUrl);
    PrintersService.printers = this.http.get<Printer[]>(PrintersService.apiUrl);
    return PrintersService.printers === undefined;
  }

  private handleError<T> (operation = 'operation', result?: T) {
    return (error: any): Observable<T> => {
      console.error(error);
      this.log(`${operation} failed: ${error.message}`);
      return of(result as T);
    }
  }

  private log(message: string) {
    console.log('PrintersService: ' + message);
  }
}

From my initial testing with this service, it seems to work well.  API calls are being made only when the data needs to be retrieved.  My main concern with all of this is there is a more appropriate way to do this in Angular.  I'm new to front-end stuff, let alone Angular and I don't know what best practices are for this particular scenario.  This is how I'd handle it if I were writing a desktop app, granted I definitely need something in there that causes the data to refresh every now and then.

"Caching" an Observable

PrintersService is by default a singleton in Angular just like any other service (This is thanks to the way dependency injection container works in Angular). This means you don't need to have the class fields as static. Make them instance fields instead:

private readonly apiUrl = "/api/printers";
private printers: Observable<Printer[]> = undefined;

updatePrinter(printer: Printer) {
  this.printers.subscribe(printers => {
    printers.forEach((element, index) => {
      if (element.id === printer.id) {
        printers[index] = printer;
        this.http.put(this.apiUrl, printer).pipe(
          tap(_ => this.log(`Updated printer id=${printer.id}`)),
          catchError(this.handleError<any>('updatePrinter'))
        );
      }
    });
  });
}

private apiGET(): boolean {
  this.log("GET: " + this.apiUrl);
  this.printers = this.http.get<Printer[]>(PrintersService.apiUrl);
  return PrintersService.printers === undefined;
}

Caching Pattern

I commonly see the following pattern for "caching" observables in various code bases:

const CACHE_SIZE = 1;

this.cache$ = this.requestJokes().pipe(
  shareReplay(CACHE_SIZE)
);

It will not very nicely with the code you have because the pattern addresses the GET calls assuming there's no mutation to the list of Jokes (Printers in your case) such as PUTs, POSTs or DELETEs.

Alternative 1: Observable as BehaviorSubject

You can use a BehaviorSubject<Printer[]> to deal with the state manually. BehaviorSubject is an observable and an observer at the same time. It has methods next(newValue) and getValue() which make manual state control possible.

Alternative 2: More advanced state management

I've been where you are many times. The complexity of manual observable/behaviour subject led me to a conclusion the approach is not scaling well. It holds me back from actually progressing on feature work itself.

My recommendation is to look at a state management library like @ngrx/store. The library ideas revolve around a few concepts one which is Store. The store represents the state of your application that is exposed as an observable. The operations that change (update) the stored are written in a special way (via so called "reducers").

In my experience, the apps written with @NgRx are simpler in building and even simpler in maintenance. You'll need invest some time in picking up the library's approach, API, and so on but the overall entry barrier is relatively low.

Side notes

Use interface instead of class if possible.
Do not use keywords as field names if possible, (i.e. default).
Use is* or are* in member names to denote the boolean nature of the member. (I've seen word "default" used as a verb with the meaning of reset to default(s)).

export interface Printer
{
  id: number;
  name: string;
  isActive: boolean;
  isBlacklisted: boolean;
  isDefault: boolean;
}


An iterable implementation of LinkedList I am curious as to what improvements to my code can be suggested.

package concepts;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedList<M> implements Iterable<LinkedListNode<M>> {

    public static class LinkedListIterator<O> implements Iterator<LinkedListNode<O>> {
        private LinkedListNode<O> curNode;

        public LinkedListIterator(LinkedList<O> linkedList) {
            curNode = linkedList.head;
        }

        @Override
        public boolean hasNext() {
            if (curNode != null) {
                return true;
            } else {
                return false;
            }
        }

        @Override
        public LinkedListNode<O> next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            } else {
                LinkedListNode<O> temp = curNode;
                curNode = curNode.next;
                return temp;
            }

        }

    }

    public LinkedListNode<M> head;

    public boolean add(M newData) {
        LinkedListNode<M> newNode = new LinkedListNode<M>();
        newNode.data = newData;
        if (head == null) {
            head = newNode;
        } else {
            LinkedListIterator<M> it = new LinkedListIterator<M>(this);
            LinkedListNode<M> lastNode = null;
            while (it.hasNext()) {
                lastNode = it.next();
            }
            if (lastNode != null) {
                lastNode.next = newNode;
            } else {
                throw new IllegalStateException();
            }
        }
        return true;
    }

    @Override
    public Iterator<LinkedListNode<M>> iterator() {
        return new LinkedListIterator<M>(this);
    }

}

Here is the LinkedListNode implementation:

package concepts;

public class LinkedListNode<N> {
    public N data;
    public LinkedListNode<N> next;
}

Antipattern

It's not a good idea to expose the internal list nodes, and this is why:

public static void main(String[] args) {
    LinkedList<Integer> list = new LinkedList<>();
    list.add(123);
    // Make a loop:
    list.head.next = list.head;
    int i = 0;

    for (LinkedListNode<Integer> node : list) {
        ++i;

        if (i == 100) {
            break;
        }
    }

    System.out.println("i = " + i);
}

As the above snippet demonstrates, a user may restructure your linked list into a cycle in which iteration will never terminate. So the moral here is that:

hide implementation from the user!

First of all, make head a private field. Then, reimplement the iterator that iterates over values and not the internal nodes holding those values.

Additional field tail would not hurt, while keeping your add method a constant time operation.

Summa summarum

All in all, I had this in mind:

package concepts;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class LinkedListCR<E> implements Iterable<E> {

    private static final class LinkedListNode<E> {
        private E element;
        private LinkedListNode<E> next;

        LinkedListNode(E element) {
            this.element = element;
        }
    }

    private class LinkedListIterator implements Iterator<E> {

        private LinkedListNode<E> nextNodeToReturn = head;

        @Override
        public boolean hasNext() {
            return nextNodeToReturn != null;
        }

        @Override
        public E next() {
            if (!hasNext()) {
                throw new NoSuchElementException("Iterator exceeded.");
            }

            E ret = nextNodeToReturn.element;
            nextNodeToReturn = nextNodeToReturn.next;
            return ret;
        }

    }

    private LinkedListNode<E> head;
    private LinkedListNode<E> tail;

    public void add(E element) {
        LinkedListNode<E> newnode = new LinkedListNode<>(element);

        if (head == null) {
            head = newnode;
            tail = newnode;
        } else {
            tail.next = newnode;
            tail = newnode;
        }
    }

    @Override
    public Iterator<E> iterator() {
        return new LinkedListIterator();
    }

    public static void main(String[] args) {
        LinkedListCR<String> list = new LinkedListCR<>();
        list.add("hello");
        list.add("world");
        list.add("y'all");

        for (String s : list) {
            System.out.print(s + " ");
        }

        System.out.println();
    }
}

Hope that helps.


Guess how many are in the jar game in Java I'm reading up on java and have completed a fairly simple console game.

I'm unsure on my own structure when considering maintainability, separation of concerns and best practices.

Any tips or suggestions is appreciated.

import java.io.*;
import java.util.Scanner;
import java.util.*;

class Prompter {
    private static Scanner scanner = new Scanner(System.in);

    public Prompter() {}

    public static String getInput(String title) {
        System.out.print(title);
        String input = scanner.nextLine();

        return input;
    }

    public static void getReadyforGame() {
        String line;

        do {
            System.out.print("Ready? (press ENTER to start guessing): ");

        } while ((line = scanner.nextLine( )).length( ) > 0);
    }

    public static void getGuess(Jar jar) {
        System.out.print("\nGuess: ");
        int answer = scanner.nextInt();

        while (answer != jar.getNumberToGuess()) {
            jar.incrementNumberOfGuesses();

            System.out.print("Guess: ");
            answer = scanner.nextInt();
        }

    }

    public static void printResult(Jar jar) {
        System.out.println("\nCongratulations - you guessed that there are " +
                            jar.getNumberToGuess() + " lentils in the jar! It took you " +
                            jar.getNumberOfGuesses() + " guess(es) to get it right.\n");
    }

}

class Jar {
    private String itemName;
    private int numberOfItems;
    private int numberToGuess;
    private int numberOfGuesses;

    public Jar(String itemName, int numberOfItems) {
        this.itemName = itemName;
        this.numberOfItems = numberOfItems;
        this.numberToGuess = new Random().nextInt(numberOfItems) + 1;
        this.numberOfGuesses = 1;
    }

    public String getItemName() {
        return itemName;
    }

    public int getNumberOfItems() {
        return numberOfItems;
    }

    public int getNumberToGuess() {
        return numberToGuess;
    }

    public int getNumberOfGuesses() {
        return numberOfGuesses;
    }

    public void incrementNumberOfGuesses() {
        ++numberOfGuesses;
    }
}

class Admin {
    private Prompter prompter;

    public Admin () {}

    public Jar setupGame() {
        System.out.print("ADMINISTRATOR SETUP\n" +
                         "===========================\n\n");

        boolean success     = false;
        int numberOfItems   = 0;
        String itemName     = prompter.getInput("Name of items in the jar: ");

        while (!success) {
            try {
                numberOfItems   = Integer.parseInt(prompter.getInput("Maximum of lentils in the jar: "));
                success = true;
            } catch (Exception e) {
                System.out.println("Number of items was invalid");
            }
        }

        return new Jar(itemName, numberOfItems);
    }
}

class Player {
    private Prompter prompter;

    public Player() {}

    public void playGame(Jar jar) {

        System.out.print("\n\nPLAYER\n" +
                         "===========================\n" +
                         "Your goal is to guess how many lentils are in the jar. Your guess should be between 1 and " + jar.getNumberOfItems() + "\n\n");

        prompter.getReadyforGame();

        prompter.getGuess(jar);

        prompter.printResult(jar);
    }
}

class Game {
    private Admin admin;
    private Player player;
    private Prompter prompter;
    private Jar jar;

    public Game() {}

    public void start() {
        admin = new Admin();
        player = new Player();

        jar = admin.setupGame();

        player.playGame(jar);

    }
}

class Test {
    public static void main(String[] args) {
        Game game = new Game();

        game.start();

    }
}

Javadoc, Javadoc, Javadoc

import java.io.*;

Wildcard imports are sub-optimal. You never know what exactly is imported and it might conflict with other imports.

Classes should all be declared in their own files, this smells like you have all in one file.

class Test {

The main class should ideally be public. I also prefer to have Main somewhere in the name (or as name).

class Game {
    ....
    private Prompter prompter;

It is declared but never used.

You always create a new instance of Prompter but it only contains static methods. So either you make it a static helper class (and always invoke the methods statically) or you make it an instance class. I'd opt for an instance class.

String line;

do {
    System.out.print("Ready? (press ENTER to start guessing): ");
} while ((line = scanner.nextLine( )).length( ) > 0);

Why you need a line variable at all here?

Your logic is split over all the classes, each class has a little piece of the puzzle and the flow is just as far stretched. It is very hard to follow the actual program flow because you have to piece it together from all over the place.

Ideally, you'd have the main class, a class containing the actual logic and some helper classes. The main class would kick off your logic class, which would contain some setup code and the actual logic for the game logic.

Consider this pseudo-code:

class Main
    static void main()
        new Game().start()

class Game
    void start()
        setupPlayers()
        setupJar()

        do
            echo "Guess! "
        while getAnswer() != jarCount

Something like this. Abstract the details away behind methods but keep the main logic in one place, so that it is easy to follow the program flow.

  Your main method should tell me what your application does, not how it does it.

On a related note, Your classes are encapsulating state that does not need to be in its own class. Jar is only used once, there speaks nothing against having these four variables in your Game class. Same for the Player class, which only contains a method which would be better in the Game class.

You have filleted the code into too many classes, all this could be done in one well organized class.

I have to say, with a few exceptions, your naming is always spot on and awesome! Good job.


Keeping history of Django model (by using memoization?) I'm working on a Django project for which I'll need to store the historic information of many models.
So far, I'm using the following strategy:

Memoize the relevant values in __init__.
When saving, check if a relevant value has changed.
If a relevant value has changed, save memoized values into a "history" model.

My code goes as follows:
from django.db import models
from core.models import User

class Spam(models.Model):
    user= models.OneToOneField(User, on_delete=models.PROTECT, related_name='spam')
    ham = models.CharField(max_length=10)
    eggs = models.IntegerField()

    def __init__(self, *args, **kwargs):
        super(Spam, self).__init__(*args, **kwargs)
        self.__relevant_fields = ['ham', 'eggs']
        self._memoize()

   def _memoize(self):
       for f in self.__relevant_fields:
           setattr(self, '__prev_%s' % f, getattr(self, f))

   def _get_prev_value(self, f):
       return getattr(self, '__prev_%s' % f)

   def _dirty_field(self, f) -> bool:
       return getattr(self, '__prev_%s' % f) != getattr(self, f)

   def _dirty(self) -> bool:
       return any([self._dirty_field(f) for f in self.__relevant_fields])

   def _save_history(self):
       history = dict()
       for f in self.__relevant_fields:
           history[f] = self._get_prev_value(f)
       self.user.spam_history.create(**history)

   def save(self, *args, **kwargs):
       super(Spam, self).save(*args, **kwargs)
       if self._dirty():
           self._save_history()

class SpamHistory(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='spam_history')
    ham = models.CharField(max_length=10)
    eggs = models.IntegerField()

Although this approach works, there are some things that make me uncomfortable:

I need to do this for many models, so I'm repeating myself a lot! I'm looking into inheritance, mixins or the like, but so far I haven't found a right way to make it work.
Is this the best approach to achieve what I want? Considering that I will need to fetch historic records frequently, I need the "history" model for each model I need to keep history from.

So, my specific questions are:

Am I implementing a good strategy for keeping the history of my model(s)?
Is there a way to improve this strategy by using an inheritance or mixin strategy?

Ok, after googling a bit more, I found a possible solution: django-simple-history:
from django.db import models
from core.models import User
from simple_history.models import HistoricalRecords

class Spam(models.Model):
    user = models.OneToOneField(User, on_delete=models.PROTECT, related_name='spam')
    ham = models.CharField(max_length=10)
    eggs = models.IntegerField()
    history = HistoricalRecords()

This seems to do exactly what I need to do. I'll test it.


Reverse all the words in a given string I have read this and I want to know how the solution that I came up with in my interview compares with the top solution.

public static String reverseWords(String s) {
    if (s == null) return null;
    else if (s.equals("")) return "";
    else {
        s = s.trim();
        int index;
        for (index = 0; index < s.length(); index++) {
            if (s.charAt(index) == ' ') break;
        }
     String res = reverseWords(s.substring(index)) + " " + s.substring(0, index);
        return res.trim();
    }
}

My code is more space inefficient, as I was concatenating instead of appending, so I created many copies of new strings. What about time complexity though? They both seem to be in \$O(n)\$ time, but I'm not sure about the constant factors.

Also, how does split() specifically perform against charAt()? I knew about the split() operation, but I opted for charAt() because I thought that split() was more expensive (wasn't sure; but I think it does some regex processing, which may be expensive). Should I have opted for split() instead?

Some comments.

It is safer to swap the order when compare - even if you have already checked for null:

else if ("".equals(s)) return "";

Even better 1-liner:

if (s == null || "".equals(s)) return s;

What if you have other separators then space - like tabs, new-lines, \r etc?

if (s.charAt(index) == ' ')

Use regex to match all white-spaces:

// global
Pattern p = Pattern.compile("\\s+");

Actually - just think about it - your solution is not working for such cases, maybe regex is not the best way either.

Regarding your questions:
split() is slower then charAt() because former is kind of a regex search in string, charAt is just similar to index access to array.

My opinion is that this "mambo-jumbo" with searching spaces and revering the rest of the string recursively is not worth any theoretical gains it possibly has.
Code is difficult to understand - it took me a minute to get the idea what you are doing here.

Why not just to split for all spaces and reverse iterate over tokens? This solution does not preserve spaces BTW, so maybe not good.
So question you should ask on interview - if spaces needs to be preserved on not.

I didn't read your link BTW - this maybe exactly what is proposed there - because the point is to comment on your code and not to compare with somebody else.


Decorators with and without arguments Disclaimer: This is my first post here, so I'm not completely sure if this is on-topic.

I recently added a decorator that wraps a context manager in pyfakefs (I'm a contributor), which has some optional arguments. In order to make the usage more convenient, I allowed both the usage with and without parentheses (mostly arguments are not needed, so the call without parentheses is the default). The code works but is not nice, and also probably not good if performance matters. I will show the full code here, and the question is just - can this be written nicer, and without the need to call another decorator function in the default case.

This is the complete code including comments:

def _patchfs(f):
    """Internally used to be able to use patchfs without parentheses."""

    @functools.wraps(f)
    def decorated(*args, **kwargs):
        with Patcher() as p:
            kwargs['fs'] = p.fs
            return f(*args, **kwargs)

    return decorated

def patchfs(additional_skip_names=None,
            modules_to_reload=None,
            modules_to_patch=None,
            allow_root_user=True):
    """Convenience decorator to use patcher with additional parameters in a
    test function.

    Usage::

        @patchfs
        test_my_function(fs):
            fs.create_file('foo')

        @patchfs(allow_root_user=False)
        test_with_patcher_args(fs):
            os.makedirs('foo/bar')
    """

    def wrap_patchfs(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            with Patcher(
                    additional_skip_names=additional_skip_names,
                    modules_to_reload=modules_to_reload,
                    modules_to_patch=modules_to_patch,
                    allow_root_user=allow_root_user) as p:
                kwargs['fs'] = p.fs
                return f(*args, **kwargs)

        return wrapped

    # workaround to be able to use the decorator without using calling syntax
    # (the default usage without parameters)
    # if using the decorator without parentheses, the first argument here
    # will be the wrapped function, so we pass it to the decorator function
    # that doesn't use arguments
    if inspect.isfunction(additional_skip_names):
        return _patchfs(additional_skip_names)

    return wrap_patchfs

Some more usage context:
The decorator can be used in unittest methods to execute the test in a fake filesystem. The actual work is done by the patcher, which is instantiated by the decorator. The fake filesystem is represented by the argument fs,which is taken from the patcher instance, and can be used for some convenience functions like file creation or copying of files from the real file system.
In most cases, this will work out of the box (the decorator without parentheses can be used), but in some cases additional configuration is needed, which can be done by adding some optional arguments to the decorator, which are passed to the patcher.

Your _patchfs and wrap_patchfs functions are virtually identical.  You don’t need the _patchfs version, just the internal one.  One function instead of two is easier to maintain:

def patchfs(_func=None, *,
            additional_skip_names=None,
            modules_to_reload=None,
            modules_to_patch=None,
            allow_root_user=True):
    """Your docstring here ..."""

    def wrap_patchfs(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            with Patcher(
                    additional_skip_names=additional_skip_names,
                    modules_to_reload=modules_to_reload,
                    modules_to_patch=modules_to_patch,
                    allow_root_user=allow_root_user) as p:
                kwargs['fs'] = p.fs
                return f(*args, **kwargs)

        return wrapped

    if _func:
        if not callable(_func):
            raise TypeError("Decorator argument not a function.\n"
                            "Did you mean `@patchfs(additional_skip_names=...)`?")
        return wrap_patchfs(_func)

    return wrap_patchfs

The if not callable: ... ensures you don’t accidentally try to use @patchfs(names_to_skip).  Using * forces the remaining arguments to keyword only arguments; you cannot just list the four arguments, which makes the decorator a little less error-prone.

Your docstring's Usage:: examples lack the required def keywords for defining functions.


Four Tic-Tac-Toe boards using kTurtle I am trying to learn kTurtle (slightly different from Logo) so that I can help my daughter learn to write code.  I have decided that I would write a program that would play Tic-Tac-Toe with a user.  So far, all I have is the Game board, and I make it more than just a single board to add to the intensity of my learning.  Hopefully I can get this figured out before my daughter graduates high school.

I am using kTurtle on Ubuntu which is similar to Logo but open source (free).

What I really want to know is if I am following good programming standards as this is a little different than what I am used to coding.

#Game board 1
$CanvasX = 300
$CanvasY = 300
#$x = ask "how big do you want the canvas to be?"
canvassize $CanvasX, $CanvasY

$x=$CanvasX/2
$y=$CanvasY/2

learn gameboard $a, $b, $x, $y {
    $TwoThirdsX = ($x/3)*2
    $OneThirdX = $x/3
    go $a, $b
    dir 180
    penup
    forward $OneThirdX
    turnleft 90
    pendown
    forward $x
    penup
    turnright 90
    forward $OneThirdX
    turnright 90
    pendown
    forward $x
    penup
    turnleft 90
    forward $OneThirdX
    turnleft 90
    forward $OneThirdX
    turnleft 90
    pendown
    forward $x
    penup
    turnright 90
    forward $OneThirdX
    pendown
    turnright 90
    forward $x
}
penwidth 1
gameboard 0, 0, $x, $y
$a=$x
$b=0
gameboard $a,$b,$x,$y
$a=$x
$b=$y
gameboard $a,$b,$x,$y
$a=0
$b=$y
gameboard $a,$b,$x,$y
penwidth 5
go $x, 0
forward 2*$x
go 0, $y
turnleft 90
forward 2*$y

Here is the finished product:

I've just installed KTurtle for Windows, and ran your code. I never thought a turtle could be so frantic! KTurtle is ..entertaining to see in action! I've played with LogoWriter back in high school, an eternity ago; this is very similar (although I was somehow expecting a 16-color, 320x240 resolution.. the shock it was!).

  Save often.

  KTurtle works on Windows, but it sometimes crashes when you click to run your script. Save often; save every time you want to run it, and it's workable. Also whatever you do, don't undock the code pane, it seems impossible to dock it back into the IDE afterwards (and restarting the IDE won't help). If you have access to KTurtle on Ubuntu, by all means don't bother with Windows (assuming it's more stable on Ubuntu).

So I ran it again, at a slower speed.. first thing I'm noticing is that you're missing a clear at the beginning of the script (/program?), so that successive executions start off an empty canvas.

Your algorithm is drawing the 4 boards clockwise, starting top-left. Each board is made of 2 horizontal and 2 vertical lines, which means if you skip drawing the larger/bolder lines in the center, the canvas looks like this:

Your algorithm takes good care of not drawing the same line twice and gets the job done, but there's no separation of concerns whatsoever - as was mentioned in @Sjlver's answer, you need abstractions; teaching a kid how to get things done is nice, teaching the kid how to think in terms of abstractions is even nicer. I would go by @Sjlver's recommendation and create a command responsible for drawing a single square (learn square), and use a repeat loop to keep the code DRY:

learn square $x, $y, $size {
    go $x, $y
    repeat 4 {
        edge $size, 90
    }
}

learn edge $size $angle {
    forward $size
    turnright $angle
}

Notice the square command is only responsible for drawing 4 edges at the specified coordinates - the edge command is responsible for drawing a single line and turning the turtle in the specified direction. It is not responsible for knowing whether or not the pen is up or down.

I like that you're using penup and pendown instead of the shorthand pu and pd - you've used the easier-to-read ones and that's good.

So, now you have a command that can draw a square; now you need one that draws 9 of them to draw a board:

learn board $x, $y {
    for $w = 0 to 2 {
        for $h = 0 to 2 {
            square $x + $w * $boxSize, $y + $h * $boxSize, $boxSize
        }
    }
}

And now you can have code like this:

$boardSize = 150
$boxSize = $boardSize/3

# number of boards to draw in each direction:
$boards = 2

clear
pendown
penwidth 1

for $x = 0 to $boards-1 {
    for $y = 0 to $boards-1 {
        board $x * $boardSize, $y * $boardSize
    }
}

It's slower than your code, and it's not as efficient (pretty much every line get drawn more than once), but thinking in abstractions, in terms of functions that do only one thing, is more important than getting a script to do what you need it to do.

This is the result:

Now you want have a black border around each board, right? The code to do that is pretty much already written!

penwidth 5
for $x = 0 to $boards - 1 {
    for $y = 0 to $boards - 1 {
        square $x * $boardSize, $y * $boardSize, $boardSize
    }
}

Now this leaves the "script" part doing 3 things: declaring global-scope variables, drawing the boards, and drawing the outlines. Here's the final script, with the result:

learn square $x, $y, $size {
    go $x, $y
    repeat 4 {
        edge $size, 90
    }
}

learn edge $size, $angle {
    turnright $angle
    forward $size
}

learn board $x, $y {
    for $w = 0 to 2 {
        for $h = 0 to 2 {
            square $x+$w*$boxSize, $y+$h*$boxSize, $boxSize
        }
    }
}

learn drawBoards {
    for $x = 0 to $boards-1 {
        for $y = 0 to $boards-1 {
            board $x*$boardSize, $y*$boardSize
        }
    }
}

learn drawOutlines {
    for $x = 0 to $boards-1 {
        for $y = 0 to $boards-1 {
            square $x*$boardSize, $y*$boardSize, $boardSize
        }
    }
}

$boardSize = 150
$boxSize = $boardSize/3
$boards = 2

clear
pendown

penwidth 1
drawBoards

penwidth 5
drawOutlines

The "script" part is now only in charge of controlling the high-level stuff; the lower-level actual looping and drawing is abstracted away into commands with meaningful names, that start with a verb, and as a bonus, the turtle ends up right in the middle!


An online store, being converted from procedural to OOP I just start to learn OOP, and it's far more interesting than procedural style.

I have a complete working online store written in procedural style. After realizing that my code is becoming very huge and very complex, I'm searching  for methods to make my code more maintainable and more comfortable. One solution of course is to move to OOP style. But because I just started to understand how OOP work, I do not know which way to go.

con.php:

// Create a database connection
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection occurred.
if(mysqli_connect_errno()) {
    die();
}

qfunctions.php

function get_user_info($user_id) {
// this function make a query for the user info
    global $connection, $query_error;;
    $query  = "SELECT *
                FROM users
                WHERE users.user_id = {$user_id}";
    $user_result = mysqli_query($connection, $query);

    // Test if there was a qurey error
    if (!$user_result || mysqli_num_rows($user_result) == 0) {
        $query_error = $err_array["PROFILE_NOT_FOUND"];
    } else {
        return $user_result;
    }

}

I feel like this method is good but not the most efficient way possible, so I built a class for my database.

new_con.php

class MySQLDatabase {

private $connection;

function __construct() {
    $this->open_connection();
}

public function open_connection() {
    $this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
    if(!$this->connection) {
        die("Database connection failed: " .mysqli_connect_errno());
    } else {
        $db_select = mysqli_select_db($this->connection, DB_NAME);
        if(!$db_select) {
        die("Database selection failed: " .mysqli_error($this->connection));
    }
    }
}

public function close_connection() {
    if(isset($this->connection)) {
    mysqli_close($this->connection);
    unset($this->connection);
    }
}

public function query($sql) {

    $result = mysqli_query($this->connection, $sql);
    $this->confirm_query($result);
    return $result;
}

public function fetch_assoc($result_set) {
    return mysqli_fetch_assoc($result_set);
}

private function confirm_query($result) {
    if(!$result) {
        die("Database query failed: " . mysqli_error($this->connection));
    }
}

public function free_result($result) {
    if($result) {
        return mysqli_free_result($result);
    }
}

}

I think this class is start to make the code more readable, but I now face a new problem: all my query functions are in procedural style and I don't know which way to go.

Option 1: change all the function to OOP style

new_qfunction.php

function get_user_info() {
global $DB;
$sql = "SELECT  * FROM USERS";
$result = $DB->query($sql);
return $DB->fetch_assoc($result);
}

Option 2: change all the functions to class

Class User {
function get_user_info($user_id) {
    $DB = new MySQLDatabase();
    $sql = "SELECT  * FROM USERS";
    $result = $DB->query($sql);
    return $DB->fetch_assoc($result);
}
}

I don't feel like doing Option 1 for all the query function will make a big difference. For Option 2, I think it's better but far complex, especially when I just start coding in OOP.

Can you tell me what is the best approach to move an entire working procedural site to an OOP site, slowly and safety, and without making the code more complex than its now?

Can you recommend an approach to take? And if I go with Option 1, will it be worthwhile?

At first I'm not mysqli guy and maybe somewhere I have mistake but the important part here Is the idea.

My advice to you is to throw exception instead of die or exit because you can catch them a lot easier. In your case you can put instantiation of MySQLDatabase in try/catch and if exception is occurred to show static page or whatever you wish.

class MySQLDatabase {

    private $connection;

    function __construct() {
        $this->open_connection();
    }

    public function open_connection() {
        $this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
        if(!$this->connection) {
            throw new \Exception("Database connection failed: " .mysqli_connect_errno());
        }
    }
    /*
     * This function (mysqli_select_db) should only be used to change the default
     * database for the connection. You can select the default database with 4th
     * parameter in mysqli_connect().
     */
    public function select_db($db_name){
        mysqli_select_db($this->connection, $db_name);
        if(!$this->connection){
            throw new \Exception(" meaningfull message");
        }
        return $this;
    }

    public function close_connection() {
        mysqli_close($this->connection);
        unset($this->connection);
    }

    public function query($sql) {
        $result = mysqli_query($this->connection, $sql);
        return $this->confirm_query($result);
    }

    public function fetch_assoc($result_set) {
        return mysqli_fetch_assoc($result_set);
    }

    private function confirm_query($result) {
        if(!$result) {
            throw new \Exception("Database query failed: " . mysqli_error($this->connection));
        }
        return $result;
    }

    public function free_result($result) {
        if($result) {
            return mysqli_free_result($result);
        }
    }
}

I will make separate class for every table or group of futures(e.g. some kind of statistics) in separate class and all SQL queries are there. Important part of this is to not make validation in this class. You must consider that every parameter of method Is validated and correct.

class UserDomain
{
    protected $conn;

    public function __construct(MySQLDatabase $conn){
      $this->conn = $conn;
    }

    public function getUser($id){
        $sql = "SELECT * FROM users WHERE u.id = ?";
        $stmt = $this->conn->prepare($sql);
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $tmp = array();
        while($res = $stmt->fetch()){
            $tmp[] = $res;
        }

        return $tmp;
    }

    public function setName($name, $user_id){}
    public function loginBy($user_id, $password){}
    public function changePassword($new_paswwrod, $user_id){}
    public function deleteUser($user_id){}
}

Here we have our class User. It can be tested very easy because your sql queries are now separated

// This class represents single user
class User {
    protected $id;

    protected $db;

    public function __construct($id, UserDomain $conn){
        $this->id = $id;
        $this->conn = $conn;
    }

    function getUserId(){
        return $this->id;
    }

    function changePassword($old_password, $new_password){

        if($this->conn->loginBy($this->id, $password)){
            // here you must validate new password against your business logic and if its true or pass try/catch you will update
            $this->changePassword($new_password, $this->id);
        }
    }

    function getUserInfo(){
        return $this->conn->getUserInfo($this->id);
    }
}

Finally I recommend you to watch this speak from Adam Culp he also have and book I think you will like it. And will give you nice ideas about refactoring legacy code and not write it


Refactor .each where each is redirected into a hash What would be the best way to refactor this :

@busy.each do |b|
  title =  b.title
  @events << {
    :id => b.id,
    :title => title,
    :start => b.busy_start_time(b.start_date,b.start_time),
    :end => b.busy_end_time(b.end_date,b.end_time),
    :allDay => false,
    :recurring => false,
    :color => 'black',
  }

@events is initialized as an empty array:

@events = []

And this busy statement is the SECOND of two pushes into @events.

I think that I can use map here something like :

@events = @events + @busy.map do |b|
  stuff
end

Because I don't want to overwrite @events, I want to add stuff into it.

But what I'm really searching for is a way to store the entire 'each' into a lambda and say something like :

@events += @busy(&:create_busy_hash)

And move all the hash creation into the Busy class as create_busy_hash

I'm still grasping lambdas and procs

I think this is where you are trying to get to:

class Busy
  def event_info
    {
      :id => id,
      :title => title,
      :start => busy_start_time(start_date, start_time),
      :end => busy_end_time(end_date, end_time),
      :allDay => false,
      :recurring => false,
      :color => 'black',
    }
  end
end

@events = @busy_items.map(&:event_info)

Some additional notes:

There is no need to initialize @events to an empty array, favor expressions over statements with side-effects (map, select, reduce and so on, instead of each).
I renamed the variable to busy_items to emphasize it's a collection.
Busy does not sound right for a class name. Classes are usually nouns, not adjectives. What's the nature of this class?


Writing an API for checked subtraction I have to write an API for checked subtraction where the input minuend can be < 0 but subtrahend can't be < 0. I think I've covered all the cases of underflow and overflow. With given conditions the range of subtrahend is [Long.MIN_VALUE, Long.MAX_VALUE] and of minuend is [0, Long.MAX_VALUE]; with these limits overflow is not possible and underflow can happen if subtrahend > minuend and in that case setting Long.MIN_VALUE as the minimum possible difference seems legit.

public static long checkedSubtract(final long minuend, final long subtrahend) {
    Preconditions.checkArgument(subtrahend >= 0, "Subtrahend must be >= 0");

    long difference;
    try {
        difference = LongMath.checkedSubtract(minuend, subtrahend);
    } catch (ArithmeticException e) {
        // With the precondition of subtrahend >= 0, this operation can not
        // overflow and if it underflows, return minimum possible difference
        difference = Long.MIN_VALUE;
    }
    return difference;
}

I'd appreciate it if someone could affirm my logic and/or point out any mistake.

I guess your logic is fine. I just don't like what you do with the variable difference. You could return directly instead and save the variable and two lines.

In case the overflow s probable, you're wasting a lot of time because of the exception. You could do something like

long result = minuend - subtrahend;
return minuend >= 0 | (minuend ^ result) >= 0 ? result : Long.MIN_VALUE;

instead (condition adapted from LongMath.checkedSubtract). You could test it both against your original implementation (e.g. with a few random values) and against some known cases.

As suggested by user1071840, a simpler condition may be used:

return Long.MIN_VALUE + subtrahend > minuend ? minuend - subtrahend : Long.MIN_VALUE;

Actually, rolfl's condition is even simpler.


File parsing code in C++ I'm processing about 3.5gb/15minutes, and I was wondering if I could get this down to a better time...

Note that this is for a very specific CSV file, so I am not concerned about generality - only speed of implementation and optimization.

int main(int argc, char *argv[]) {
    std::string filename;
    std::cout << "Please type the file name: " << std::endl;
    std::cin >> filename;

    std::string ticker;
    std::cout << "Please enter the ticker: " << std::endl;
    std::cin >> ticker;

    std::ifstream instream(filename.c_str());
    std::string ask_filename = ticker + "_ASK.NIT";
    std::ofstream askstream(ask_filename.c_str());

    std::string bid_filename = ticker + "_BID.NIT";

    std::ofstream bidstream(bid_filename.c_str());

    std::string line;
    std::getline(instream,line);

    while(std::getline(instream,line))
    {
        std::stringstream lineStream(line);
        std::string cell;
        std::string new_line;
        std::vector<std::string> my_str_vec;
        while(std::getline(lineStream,cell,','))
        {
            my_str_vec.push_back(cell);
            //new_line.append(cell.append(";"));
        }
        // works on date
        std::string my_date = my_str_vec[0];
        std::string::iterator my_iter;
        std::string processed_date = "";
        for(my_iter = my_date.begin(); my_iter != my_date.end(); ++my_iter) {
            if(std::isalnum(*my_iter) || *my_iter == ' ')
                processed_date.append(1,(*my_iter));
        }

        my_str_vec[0] = processed_date;

        std::vector<std::string>::iterator my_vec_iter;
        for(my_vec_iter = my_str_vec.begin() + 1; my_vec_iter != my_str_vec.end(); ++my_vec_iter) {
            std::string my_semicol = ";";
            *my_vec_iter = my_semicol.append(*my_vec_iter);
        }

        askstream << my_str_vec[0] << my_str_vec[1] << my_str_vec[3] << std::endl;
        bidstream << my_str_vec[0] << my_str_vec[2] << my_str_vec[4] << std::endl;
    }

    askstream.close();
    bidstream.close();

    return 0;
}

First off streams and specifically the stream operators >> and << are designed for robustness not speed. They make the code harder to write incorrectly (and provide some local specific conversions) that make expensive in terms of using (consider changing to C fscanf() if speed is paramount).

So if speed is you objective streams is not the best choice.

Assuming we are staying with streams (Ask another question about how to write this in C for speed):

Dead Code

Second delete dead code (it confuses a review) and costs in creation.

    std::string new_line;

Small Inefficiencies

There is no need to create the cell object each time through the loop create it once outside the loop. (Personally I would leave it in the loop, but if you are going for speed then this is an obvious simple save).

When scanning the date you are making a copy of the value:

    std::string my_date = my_str_vec[0];

No need just make a reference (you  can even use a const reference for safety):

    std::string const&   my_date = my_str_vec[0];
          //    ^^^^^^

Use Reserve

Building the string character by character may not be the most efficient way of getting the date (as the string processed_date may be resized on each insert).

    for(my_iter = my_date.begin(); my_iter != my_date.end(); ++my_iter) {
        if(std::isalnum(*my_iter) || *my_iter == ' ')
            processed_date.append(1,(*my_iter));
    }

Use reserve so you know that it is not re-sized internally, then use a standard algorithm for optimal looping:

processed_date.reserve(my_date.size());  // Note: not resize()
std::remove_copy(my_date.begin(), my_date.end(),
                 std::back_inserter(processed_date),
                 [](char const& my_char) {return !(std::isalnum(*my_char) || *my_char == ' ');}
                );
// Note if you don't have C++0x then lamda is easily replaced by a functor.

Standard algorithms.

Your code will be optimal when you use the standard algorithms. Its worth learning what is available.

http://www.sgi.com/tech/stl/table_of_contents.html
See section 5

I showed you how to copy all but the characters you want. But there is one to remove all elements in-place. I'll let you experiment.


Call center escalation excercise, using Chain of Responsibility pattern This is a coding interview I found online, to be solved within 30 minutes:

  Design an OOP concept for an application where employee can dispatch their incoming phone call according to their seniority level if they are not able to solve.

I chose to use Chain of Responsibility pattern, I also used Null pattern.
Please review OOP principles and the specific design pattern implementation.

The unit test is just a code sample.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace DesignPatternsQuestions
{
    [TestClass]
    public class ChainOfResponsibilityTest
    {
        [TestMethod]
        public void PhoneCallDispatchCORTest()
        {
            PhoneCallHandler gilad = new PhoneCallHandler(new LowLevel("Gilad"));
            PhoneCallHandler bonno = new PhoneCallHandler(new LowLevel("Bonno"));
            PhoneCallHandler batel = new PhoneCallHandler(new MediumLevel("Batel"));
            PhoneCallHandler daniel = new PhoneCallHandler(new HighLevel("Daniel"));
            gilad.RegisterNext(batel);
            bonno.RegisterNext(batel);
            batel.RegisterNext(daniel);

            BankPhoneCall call1 = new BankPhoneCall(1500);
            bool res = gilad.GetPhoneCall(call1);
            Assert.IsTrue(res);
        }
    }

    public interface IPhoneCall
    {
        int Budget { get; set; }
    }

    public class BankPhoneCall :IPhoneCall
    {

        public BankPhoneCall(int budget)
        {
            Budget = budget;
        }

        public int Budget { get; set; }
    }

    public interface IPhoneCallHandler
    {
        bool GetPhoneCall(IPhoneCall phoneCall);
        //the same item is able to call next Item in the chain of command
        void RegisterNext(IPhoneCallHandler employee);
    }

    public class PhoneCallHandler : IPhoneCallHandler
    {
        private IPhoneCallHandler _nextCallHandler = EndOfChainHandler.Instance;
        private Employee _employee;

        public PhoneCallHandler(Employee employee)
        {
            _employee = employee;
        }
        public bool GetPhoneCall(IPhoneCall phoneCall)
        {
            bool res = _employee.Resolve(phoneCall);
            if (!res)
            {
                //handle _nextcallHandler == null with null pattern
                return _nextCallHandler.GetPhoneCall(phoneCall);
            }
            return res;
        }

        public void RegisterNext(IPhoneCallHandler nextCallHandler)
        {
            _nextCallHandler = nextCallHandler;
        }
    }

    /// <summary>
    /// null pattern
    /// </summary>
    public sealed class EndOfChainHandler : IPhoneCallHandler
    {
        private static readonly Lazy<EndOfChainHandler> lazy = new Lazy<EndOfChainHandler>(()=> new EndOfChainHandler());
        public static EndOfChainHandler Instance { get { return lazy.Value; } }
        public bool GetPhoneCall(IPhoneCall phoneCall)
        {
            return false;
        }

        public void RegisterNext(IPhoneCallHandler employee)
        {
            throw  new InvalidOperationException("can't register next to null");
        }
    }

    public abstract class Employee
    {
        protected int _maxBudget;

        public string Name { get;set; }
        public Employee(string name, int maxBudget)
        {
            _maxBudget = maxBudget;
            Name = name;
        }

        public bool Resolve(IPhoneCall phoneCall)
        {
            return phoneCall.Budget <= _maxBudget;
        }
    }
    public class LowLevel : Employee
    {
        public LowLevel(string name)
            : base(name, 1000)
        {
        }
    }

    public class MediumLevel : Employee
    {
        public MediumLevel(string name)
            : base(name, 5000)
        {
        }
    }

    public class HighLevel : Employee
    {
        public HighLevel(string name)
            : base(name, 10000)
        {
        }
    }
}

Review

Well done, there isn't much I would change in this implementation. I would grant you the humble badge for putting yourself as LowLevel employee :)

The lazy and null pattern are well implemented (except a small issue that could possibly introduce null -> see minor issues). The chain of responsibility looks to be by the book. You've even used a visitor pattern between the handler and the employee. Each specific employee yields different behavior handling a phone call.

Minor issues

IPhoneCall as interface seems overkill to me. This is just a POCO.
Check arguments against null in public entry points such as public PhoneCallHandler(Employee employee).
GetPhoneCall could be written more compact: return _employee.Resolve(phoneCall) || _nextCallHandler.GetPhoneCall(phoneCall);.
RegisterNext should not allow null, as this bypasses your EndOfChainHandler.Instance pattern to avoid null handling.


Simple function that simulates survey results based on sample size and probability What is this:

This is a simple function, part of a basic Monte Carlo simulation. It takes sample size and probability as parameters. It returns the simulation result (positive answers) plus the input parameters in a tuple.

What I'm asking:

I'm trying to avoid using temporary variables, I have two questions.

Do I really save memory by avoiding storing interim results?
How could I improve readability without adding variables?

def simulate_survey(sample_size, percent_subscribes):
    return (
        sample_size,
        percent_subscribes,
        round(
            (
                sum([
                    r.random() < percent_subscribes
                    for _ in range(sample_size)
                ]) / sample_size
            ),
            2
        )
    )

As I discovered recently, summing a lot of booleans, where the chance that the value is False is not negligible, can be surprisingly slow.

So I would change your survey result calculation to:

sum([1 for _ in range(sample_size) if r.random() < percent_subscribes])

This allows sum to use its faster integer implementation and you do not sum a bunch of zeros.
Alternatively, you could look at this problem as an application of the binomial distribution. You have some chance that a certain result is obtained and you want to know how often that chance was true for some population. For this you can use numpy.random.binomial:

import numpy as np

def simulate_survey(sample_size, percent_subscribes):
    subscribers = np.random.binomial(sample_size, percent_subscribes)
    return sample_size, percent_subscribes, round(subscribers / sample_size, 2)

Using numpy here may also speed up your process in other places. If you need to run this function many times, you probably want to use the third argument to generate multiple values at once.

IMO, the readability is also greatly increased by using one temporary variable here, instead of your many levels of parenthesis.
I am not a fan of your function returning its inputs. The values of those should already be available in the scope calling this function, so this seems unnecessary. One exception would be that you have other, similar, functions which actually return different/modified values there.
You should add a docstring describing what your function does.


Update / save / display values in a table I am relatively new to Angular and need to put together an application to update / save / display values. The code is working, but I wanted your input the make sure that I am doing this 'the angular way'.

JavaScript

var app = angular.module('store', []);

app.controller('TableController', ['$scope', '$log',function($scope, $log){
   $scope.family = familyMembers;

   $scope.SaveMember = function() {
       var saveMember = { name: $scope.name, age: $scope.age };
       if ($scope.editItem == -1) {
            $scope.family.push(saveMember);
            // insert in db here
       }
       else {
           $scope.family[$scope.editItem] = saveMember;
           $scope.editItem = -1;
           // update db here
       }
       Init();
   };

   $scope.DeleteMember = function(idx) {
       $scope.family.splice(idx,1);
       // delete from db here
   }

   $scope.EditMember = function(idx){
       $scope.name = $scope.family[idx].name;
       $scope.age = $scope.family[idx].age;
       $scope.editItem = idx;
       $scope.buttonText = 'Update';
   }

   function Init() {
        $scope.name = '';
        $scope.age = '';
        $scope.editItem = -1;
        $scope.buttonText = 'Add new';
   }

   Init();

}]);

var familyMembers = [
    { name: "Joe", age: 42}
    , { name: "Jane", age: 40}
    , { name: "Bob", age: 13}
];

HTML

        <link href="./css/bootstrap.min.css" rel="stylesheet" type="text/css" />

Family Members:

                    {{p.name}}
                    {{p.age}}
                    X

Add member

            name

            <input type="text" ng-model="name">

            age

            <input type="number" ng-model="age">

            <input type="button" value="{{buttonText}}" ng-click="SaveMember()" />

Yup, looks like The Angular Way™. A good rule of thumb for controllers is that 1) it exposes data, 2) it exposes functionality, 3) not tied to any specific template. There's a few things though.

var familyMembers = [
    { name: "Joe", age: 42}
    , { name: "Jane", age: 40}
    , { name: "Bob", age: 13}
];

Why is this outside the controller? Why not define it inside? If you want it defined separately from the controller, consider using a provider/service/factory to store it. Then pull that provider/service/factory into the controller as a dependency.

Init isn't really some initialization. It's resetting your form data. A better way to do this, instead of emptying the object values, is to create a function that returns a blank version of the object and replace the form data.

function createMember(){
  return { name: '', age: '' };
}

function resetForm(){
  $scope.formData = createMember();
}

// Assuming the form uses `$scope.formData` as the form object

As for saving, before you reset, you just copy the form data using angular.copy and pop it in the members array. This way, the object you put in the array isn't the same object referenced by the form data, which may still be subject to binding. Then you reset the form data.

function saveForm(){
  var newMember = angular.copy($scope.formData);
  members.push(newMember);
  resetForm();
}


Primality predicate in Haskell I wrote a primality test for UniHaskell however, it seems complicated in terms of conditionals.

Here it is, rewritten to not use Unicode and other functions in the code:

-- Primality predicate
isPrime  :: Int -> Bool
isPrime 2 = True
isPrime 3 = True
isPrime n
    | n `mod` 2 == 0 = False
    | n `mod` 3 == 0 = False
    | otherwise      = check 5 2
  where check i w
            | i * i <= n = if n `mod` i == 0
                           then False
                           else check (i + w) (6 - w)
            | otherwise = True

The algorithm is simple: return True if n is 2 or 3, False if n is a multiple of 2 or 3, and then perform trial division over numbers that are not multiples of 2 or 3.

All in all, that is some good looking, idiomatic Haskell. Well done!

You seem to be using the mod n x == 0 idiom quite often, so let's extract that to its own function.

divides :: Integral a => a -> a -> Bool
n `divides` m = m `mod` n == 0

You could also make your predicate polymorphic. No need to restrict yourself to Int, any Integral will do the trick.

isPrime :: Integral a => a -> Bool
isPrime 2 = True
-- and so on

I've often read that rem is faster than mod, but I've never checked... maybe it does give you some speed.

Through clever reordering of the guards, you can get rid of the if then else.

Instead of having a simple comment to explain the function, consider writing actual Haddock documentation.

Putting it together:

-- | @divides n m@ checks whether @n@ evenly
--   divides @m@, meaning that @m `mod` n == 0@.
divides :: Integral a => a -> a -> Bool
n `divides` m = m `rem` n == 0

-- | Checks whether a given number is prime.
isPrime :: Integral a => a -> Bool
isPrime 2 = True
isPrime 3 = True
isPrime n
    | 2 `divides` n = False
    | 3 `divides` n = False
    | otherwise     = check 5 2
  where check i w
      | i * i > n     = True
      | i `divides` n = False
      | otherwise     = check (i + w) (6 - w)

Maybe check 5 2 deserves a comment, as I couldn't see why these numbers are there on a first glance.


Project Euler #3 in Haskell Project Euler #3 asks:

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

I've written a general solution for any number:
module Main where

isDiv :: Integer -> Integer -> Bool
n `isDiv` k = n `mod` k == 0

fullyDiv :: Integer -> Integer -> Integer
fullyDiv n k
    | n `isDiv` k = fullyDiv (n `div` k) k
    | otherwise = n

intSqrt :: Integer -> Integer
intSqrt = floor . sqrt . fromIntegral

maxPrimeFact :: Integer -> Integer
maxPrimeFact n = go n (1, wheel)
    where
        wheel = 2 : [3,5..intSqrt n]
        go n (x, []) = if n == 1 then x else n
        go n (x, (y:ys))
            | n `isDiv` y =
                let o = fullyDiv n y
                in go o (y, takeWhile (<= intSqrt o) ys)
            | otherwise = go n (x, ys)

problem3 :: Integer -> Integer
problem3 = maxPrimeFact

main :: IO ()
main = do
    _ <- getLine
    contents <- getContents
    let cases = map read $ lines contents
    let results = map problem3 cases
    mapM_ print results

An explanation of this algorithm can be found at my answer.
I'd appreciate any comments on rewriting maxPrimeFact as it seems unwieldy to me.

You don't need to terminate the list of candidate factors.  Haskell, being a lazy language, deals with infinite lists just fine.

In Haskell, it is common to use pattern matching instead of if … then … else.

There is not much advantage to having your go helper take an Integer (Integer, Integer) rather than three Integers.

You are repeating the isDiv test in fullyDiv and go.  Instead of a fullyDiv function, you can just fold the retry logic into go itself.

The names x, y, and o are hard to follow.  I suggest maxPrime instead of x, and w instead of y (the mnemonic being the first character of wheel).

isDiv :: Integer -> Integer -> Bool
n `isDiv` k = n `mod` k == 0

maxPrimeFact :: Integer -> Integer
maxPrimeFact n = go n 1 (2 : [3, 5..])
  where
    go 1 maxPrime _ = maxPrime
    go n maxPrime wheel@(w:ws)
      | n `isDiv` w = go (n `div` w) w wheel
      | otherwise   = go n maxPrime ws

But you should be able to rewrite it further by taking advantage of divMod.

maxPrimeFact :: Integer -> Integer
maxPrimeFact n
  | n < 2     = error ("Invalid n=" ++ (show n))
  | otherwise = go n 1 wheel
  where
    wheel = 2 : [3, 5..]
    go 1 largestPrimeFactor _ = largestPrimeFactor
    go n largestPrimeFactor (w:ws)
      | n `isDiv` w = go (n `div` w) w (w:ws)
      | otherwise   = go n largestPrimeFactor ws


Implementing Decorator Pattern Context

I'm looking into design patterns.  My first try is using the Decorator Pattern.

Question:

Is there another (maybe standard) approach to applying modifications in a decorator other than explicitly overwriting in the constructor?
 -

Car Interface

<?php

interface CarInterface
{
    public function drive();
}

Care Base Class

<?php

class CarBaseClass implements CarInterface
{
    public $model = 'Base Model';
    public $top_speed = null;
    public $features = ['AC', 'Radio'];

    public function __construct($top_speed)
    {
        $this->top_speed = $top_speed;
    }

    public function drive(): void
    {
        echo $this->model . " speed: " . $this->top_speed;
    }

}

Tesla

<?php

class Tesla extends CarBaseClass
{
    public $model = 'Tesla';
}

Engine Feature Decorator

<?php

class V20Engine extends CarBaseClass
{
    public $SPEED_BOOST = 1.5;
    public $new_features = ['V20 Engine'];

    public function __construct(CarBaseClass $car)
    {
        $this->model = 'V20 ' . $car->model;
        $this->top_speed = $car->top_speed * $this->SPEED_BOOST;;
        $this->features = array_merge($car->features, $this->new_features);
    }
}

Turbo Decorator

<?php

class TurboEnabled extends CarBaseClass
{
    public $TURBO_BOOST = 1.75;
    public $new_features = ['Turbo Enabled', 'Snoop Dog GPS'];

    public function __construct(CarBaseClass $car)
    {
        $this->model = 'Turbo Enabled ' . $car->model;
        $this->top_speed = $car->top_speed;
        $this->features = array_merge($car->features, $this->new_features);
    }

    public function activateTurbo() {
        $this->top_speed = $this->top_speed * $this->TURBO_BOOST;

        return $this;
    }
}

index.php

<?php

require 'classes/Car/CarInterface.php';
require 'classes/Car/CarBaseClass.php';
require 'classes/Car/Tesla.php';
require 'classes/Car/Feature/TurboEnabled.php';
require 'classes/Car/Feature/V20Engine.php';

echo "
";

$tesla = new Tesla(100);
$tesla->drive();

echo "
";

$turbo_tesla = new TurboEnabled($tesla);
$turbo_tesla->activateTurbo()->drive();

echo "
";

$v20_tesla = new V20Engine($tesla);
$v20_tesla->drive();

echo "
";

$v20_turbo_tesla = new V20Engine($turbo_tesla);
$v20_turbo_tesla->drive();

echo "
";

$car = new V20Engine( new TurboEnabled( new CarBaseClass(100) ) );
print_r( $car->features );

Decorators usually add more functional behaviors so if you had a method drive and TurboClass has a new functionality driveFast, you could probably call the Cars driveFast and then the some other special logic which turboClass has to do eg. checkTyres after driving fast. Here since you want the object construction to do it, this is the right way.


Using a spinner like a HTML select to display string but return int value I'm still learning Android, I need to have a spinner and for it to display a list of string values. However, when I submit that data later on I need a corresponding integer value.
Similarly to how a HTML Select uses <option value="2">BlahBlah</option>.

From searching I've come up with a method which works, just wondering if anyone had any suggestions for improving the code?

I've got the two variables setup:

private String[]            arrMuppetNames  = {"Kermit","Gonzo","Fuzzy","Animal"};
HashMap<String, Integer>    hashMuppets     = new HashMap<String, Integer>();

hashMuppets is built up with a simple set of "Kermit":1,"Gonzo":2 etc.
Then to stop the code running on load I've added a "--please select--" to index 0.

//Add "please select" to spinner
arrNewArray[0]  = this.getString(R.string.muppet_select);
for(int i=0; i < arrMuppets.length; i++){
    arrNewArray[i+1]    = arrMuppets[i];
}

Obviously I add this array arrNewArray to the spinner using ArrayAdapter. Then use the OnItemSelectedListener.

private Spinner.OnItemSelectedListener spinnerListener = new Spinner.OnItemSelectedListener(){
    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
        Spinner spinner             = (Spinner) findViewById(R.id.muppet_spinner);

        //Arg 3 is selected index. Lets ensure we didn't select our "Please select"
        if(arg3 != 0){
            //Get Selected Item and convert to corresponding value using hashMap
            String  strSelectedMuppet   = spinner.getSelectedItem().toString();
            int     intCatID            = hashMuppets.get(strSelectedMuppet);
            //Show toast of value
            Toast.makeText(getApplicationContext(), String.valueOf(intCatID), Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        //Do nothing
    }
};

If anyone has any suggestions or pointers I'd very much appreciate it. I'm happy to post the full code if you'd like, but I'm hoping the above short example is pretty self explanatory.

Thanks

As long as you are hard-coding the values, I would go with an enum

public enum Muppets {
    Kermit, Gonzo, Fozzie, Animal, Swedish_Chef, Miss_Piggy,
    Statler, Waldorf, Beaker, Beauregard, Dr_Benson_Honeydew,
    Crazy_Harry, Rowlf, Dr_Teeth, Zoot, Janice, Floyd;
    // Sorry, I just thought your list of muppets was way too short

    public int getNumber() {
        return this.ordinal() + 1;
    }
    @Override
    public String toString() {
        return super.toString().replaceAll("_", " ");
    }
}

(To make things easier for you, you can also add your Please Select as a muppet and override the toString method to return a custom string if this == PLEASE_SELECT, this would also remove the need for adding one in getNumber, and would greatly simplify adding the items to the adapter)

Then I would use the ArrayAdapter as ArrayAdapter<Muppet>, so that you can get the selected item like this:

Muppet selectedMuppet = spinner.getSelectedItem();
int value = selectedMuppet.getNumber();

To get an array of all the muppet enums, use Muppets.values().

If you want the possibility to add muppets dynamically at run-time, I would make a List<String> and get the position of an item using list.indexOf(muppetName).


Running SQL and mapping the reader to objects I currently have a method in my repository that will run SQL and map the reader to objects:

protected IEnumerable<T> Query<T, TFactory>(string sql, List<IDbDataParameter> parameters = null) where TFactory : IFactory<T>
{
    List<T> list = new List<T>();

    var factory = Activator.CreateInstance<TFactory>();
    var connection = (Db == null) ? Connection : Db.Connection;

    using (var manager = new DbCommandManager(connection, sql))
    {
        if (parameters != null)
            foreach (var parameter in parameters)
                manager.AddParameter(parameter);

        using (var reader = manager.GetReader())
        {
            while(reader.Read())
                list.Add(factory.CreateTFromReader(reader));
        }
    }

    return list;
}

To use the following you simply do:

public IEnumerable<Code> GetCodeWType(string CodeType, string Code)
{
    var sql = @"Select CODE_TYPE, CODE, DESCRIPTION From Codes  Where (CODE_TYPE = :1) AND (CODE = :2)";

    var parameters = new List<IDbDataParameter>();
    parameters.Add(DbFactory.GetParameter(":1", CodeType, DbType.String));
    parameters.Add(DbFactory.GetParameter(":2", Code, DbType.String));

    return this.Query<Code, CodeFactory>(sql, parameters);
}

I would love to hear thoughts and feedback on how I can improve.

It looks ok for me so, just a couple of suggestions:

First: given it is a protected method and not a private, it can be called be derived classes which probably could not be in the same assembly (this is true only if the class is public) then, you shouldn´t use optional parameters, they force you to recompile all when you change them.

Instead, use an overloaded method as follow:

protected List<T> Query<T, TFactory>(string query) where TFactory : IFactory<T>
{
    return Query<T, TFactoty>(query, Enumerable.Empty<IDbDataParameter>());
}

protected List<T> Query<T, TFactory>(string query, IEnumerable<IDbDataParameter> parameters)
    where TFactory : IFactory<T>
{

It also help you to remove the checking for nulls.

Second, if you return an IEnumerable, the callers will have less features. The rule is you you should require the most generic and return the most specific implementation so, if you have a list you could return a List<>, IList<> or a Collection. Then, callers have more options.

My attempts is this one:

protected List<T> Query<T, TFactory>(string query) where TFactory : IFactory<T>
{
    return Query<T, TFactoty>(query, Enumerable.Empty<IDbDataParameter>());
}

protected List<T> Query<T, TFactory>(string query, IEnumerable<IDbDataParameter> parameters)
    where TFactory : IFactory<T>
{
    var collection = new List<T>();

    var factory = Activator.CreateInstance<TFactory>();
    var connection = (Db == null) ? Connection : Db.Connection; // this line looks rare for me

    using (var manager = new DbCommandManager(connection, sql))
    {
        foreach (var parameter in parameters)
            manager.AddParameter(parameter);

        using (var reader = manager.GetReader())
        {
            while (reader.Read())
                list.Add(factory.CreateTFromReader(reader));
        }
    }

    return list;
}

Update:

One more thing about optional parameters, when you call the Query method with one argument, you really are passing two: the query and a null in 'parameters'. You have never pass nulls (or at least you have to try) because if you pass nulls then, you need to check for null values.

One more thing about the protected modifier, privates methods can trust that their parameter won´t be null but protected methods cannot do it. This is because private members will be called by other methods in the same class but protected method can be called by other methods in other classes.


Computation of address from Object I am computing address string form the JS object. I am using EmberJS. I wanted to review my code and tell me how we can improve the computation of address, or is there any better way to it?

const {
  get,
  computed,
} = Ember;

// other properties.
completeAdress: computed({
    let address = '';
    if (get(this, 'title')) {
        address = `${address},${get(this, 'title').toString()}`;
    }
    if (get(this, 'number')) {
        address = `${address},${get(this, 'number').toString()}`;
    }
    if (get(this, 'street')) {
        address = `${address},${get(this, 'street').toString()}`;
    }
    if (get(this, 'city')) {
        address = `${address},${get(this, 'city').toString()}`;
    }
    if (get(this, 'region')) {
        address = `${address},${get(this, 'region').toString()}`;
    }
    if (get(this, 'state')) {
        address = `${address},${get(this, 'state').toString()}`;
    }
    if (get(this, 'country')) {
        address = `${address},${get(this, 'country').toString()}`;
    }
    if (get(this, 'zipcode')) {
        address = `${address},${get(this, 'zipcode').toString()}`;
    }
    if (get(this, 'phone')) {
        address = `${address},${get(this, 'phone').toString()}`;
    }
    if (address.length > 0) {
        address = address.substring(1, address.length);
    }
    return address;
}),
// other properties

Basically is there any way to avoid too many if conditions.

{
  title: 'MacD',
  street: '49'
  // rest of the properties are related to address only
};
// This is example address object

2 suggestions..

Condense all that duplicated code.
Don't concat your strings like that. Every time you do that that string has to be re-loaded into memory all over again. It's more efficient to put your string pieces into an array and then join them later.

completeAdress: computed({
    let address = [];
    const address_components = ['title', 'number', 'street', 'city', 'region', 'state', 'country', 'zipcode', 'phone'];
    for(var i=0; i<address_components.length; i++)
        if (get(this, address_components[i]))
            address.push(get(this, address_components[i]).toString());
    address = address.join(',');
    if (address.length)
        address = address.substring(1, address.length);
    return address;
}),

(For some reason the markdown parser didn't want to format this as code unless i also formatted it as a quote.)


class IText - Validates text from Ajax POST | Add consistent return type, defensive coding, functional focus I denotes independent, no dependencies.

<?php
/**
 *Input - One Dimensional Non-Empty Post Array
 *Ouput - Boolean on pass or fail
 */
class IText
{
    private $text_array = array();
    private $patterns = array(
       'domain' =>              '/:\/\/(www\.)?(.[^\/:]+)/',
       'prefix_url' =>          '/^(http:)|(https:)\/\//',
       'url' =>                 '/^.{1,2048}$/',
       'tweet' =>               '/^.{1,40}$/',
       'title' =>               '/^.{1,32}$/',
       'name' =>                '/^.{1,64}$/',
       'email' =>               '/^.{1,64}@.{1,255}$/',
       'pass' =>                '/^.{6,20}$/'
    );
    public function __construct()
    {
        if ( count( $_POST ) === 0 )
        {
            echo "Hack Attempt";
            return;
        }
        else
        {
            foreach( $_POST as $key => $value )
            {
                if( !is_scalar( $value ) )
                {
                    echo "Hack Attempt";
                    return;
                }
                $this->text_array[ $key ] = htmlentities( $value );
            }
        }
    }
    public function get( $key ) // basic getter
    {
        return $this->text_array[ $key ];
    }
    public function set( $key, $value ) // basic setter
    {
        $this->text_array[ $key ] = $value;
    }
    public function checkPattern( $pattern ) // checks for pattern and returns bool
    {
        return ( ( boolean )preg_match( $this->patterns[ $pattern ], $this->text_array[ $pattern ] ) );
    }
    public function checkEmpty() // checks for empty and returns bool
    {
        return ( !in_array( '', $this->text_array, TRUE ) );
    }
}

I've tried to cover as many things I could.  A few of my explanations are rather brief, so if you want me to explain or defend anything, let me know.  And hopefully it doesn't read too ramble-y :).

IText

IName typically denotes an interface.  It's not a naming scheme often used in PHP, but it's used often enough that you should avoid prefixing an I onto a class that isn't an interface.  This is confusing.  In fact, when I first saw the name, I was expecting an interface.

As a developer consuming the class, it really is not all that important if it's "independent" since most IDEs will show the constructor signature.  Interface vs abstract vs concrete tends to matter, but I do not feel that independent necessitates its own naming scheme.

mixed concerns

I'm not sure if I understand what your class is doing.  Based on the name, it looks like you're trying to model a string. BUt what it's actually doing is sort-of processing POST.

Instead of doing this, I would create validators that are separate from the model of a string (or the model of any data type really).  Also, why hold an array of values inside of the object?  Is the object meant to be some kind of repository or something?

Once you get a lot of validations, or once you get a few very complicated ones, this class will grow to be unmanagable.

Personally, I like the model of Zend_Validate.  It completely separates the concept of data and the validation of data.  In your class, storage, validation and manipulation have all been (needlessly) coupled.  (Obviously storage and validation go together when storing things long term, but in this context, I mean storing as in storing in PHP-land.)

A perfect example of your validation and storage coupling is your checkPattern method.  What if you want to validate something as a URL, but it's not stored in $_POST['url']?  What if you want to check $_POST['website']?  Or what if you have an arbitrary $url that you want to check?  Your code now does not facilitate that.  It is directly tied to the expectation that the validation and the data will be stored with the same keys.

htmlentities

Your values are not being used in the context of HTML, so they should not be treated as HTML.  Only treat HTML as HTML.  In other words, don't escape data until it actually needs to be escaped.  Your validations are going to be confused when they see a &#38; b instead of a & b (or any other substitutions htmlentities may make).

$_POST

A lot of the comments in the "mixed concerns" section, you're probably thinking "but it's only meant to manipulate post?"

Well, what if at some point in the future, you have an arbitrary array you want to handle?  There's no need to couple your code to $_POST.  Instead, pass the array in to the constructor.  (Well, in all honesty, I think your design is flawed, but if you do stick with it, pass the array in.)  What if at some point in the future you have a JSON based API and you want to validate that?  How would you do that with your current code?

technicalities

If nothing is posted (count($_POST) === 0), then text_array is going to be NULL.  This will mean that every array access will issue a notice.  You should initialize the member to an array either in the declaration or in the constructor.  I would do it in the declaration:

private $text_array = array();

Also, you're assuming $_POST is one dimensional.  If someone posts a form like:

<input type="text" name="test[]" value="array">

Then $_POST will look like:

array('test' => array('array'))

This means that you'll end up passing an array to htmlentities.  In other words, don't assume that POST values are strings.  (Though they are always either a string or an array.)

in addPrefix, you've used textArray instead of text_array

Constants

Instead of using names of the validations, use class constants instead.  This will mean that calling code doens't need to know the array keys, and that they can be changed if needed/wanted.  It will also tend towards cleaner looking and more maintainable code since typos will be errors instead of falling through the cracks.

For example:

const DOMAIN = "domain";

Then:

$text->checkPattern(IText::DOMAIN);

Be paranoid

Never assume anything in code.  In particular, don't assume that a variable will be the type that you expect or that an array key will exist.

Note that these both basically only apply to user data since if you create the data, you can know with certainty what it is.

Consider your checkPattern method:

public function checkPattern( $pattern )  // pattern checker returns bool
    {
        return ( preg_match( $this->patterns[ $pattern ], $this->text_array[ $pattern ] ) );
    }

What if an invalid pattern name is provided?  Then suddenly you have at least 3 notices (two that the array key does not exist, and one that preg_match received an empty pattern).

You should be safe guarding things like this:

public function checkPattern($pattern)
{
    if (!array_key_exists($pattern, $this->patterns)) {
        //Pattern doesn't exist
        throw new Exception("Invalid pattern provided: " . $pattern);
    }
    if (!array_key_exists($pattern, $this->text_array[$pattern])) {
        //data doesn't exist
        return false;
    } else if (!is_scalar($this->text_array[$pattern])) {
        //If this were checked on construction, this would not be necessary
        throw new Exception("The data stored for {$pattern} is not a scalar, but it's being treated as such");
    }
    return (bool) ( preg_match( $this->patterns[ $pattern ], $this->text_array[ $pattern ] ) );
}

Also, while I'm at it, your comment is a lie.  preg_match returns an int, not a bool.  A wrong comment is significantly worse than no comment.

Final suggestions

I would consider decoupling your data and validations.  What you could do is create a "Form" that encapsulates all of this.  Basically your form would have elements and each element would have validations.  The form would then be capable of taking in an arbitrary array and telling you if it's valid per the specification of the form.

If you want a few ideas on this, you could look at Zend_Form.  It has a lot of limitations, and the rendering side of it can be a bit hard to get along with, but overall, it's a fairly decent modeling of a form.  Zend_Form is likely not the best, just Zend Framework happens to be what I'm familiar with.

Edit: URL handling

Just noticed that you've used a regex to extract out the domain from a url.  Instead of doing that, you might want to use parse_url.


Trimming whitespace in Excel cells I often receive large Excel-sheets in which data has been inserted via copy and paste. Usually a lot of the cells contain whitespaces at the beginning and the end before / after the actual value.

I made a VBA-script for to get rid of these whitespaces.

' Removes whitespaces at the
' beginning and the end
' of all cell-values.

Public Sub trimCells()
    Dim lastRow As Long
    Dim lastColumn As Long
    Dim row As Long
    Dim column As Long

    On Error GoTo errorHandler

    ' Find() == VBA-equivalent to
    ' the find-menue in the Excel-GUI.
    ' What:="*" => Matches EVERY content.
    ' Start in the bottom-right corner &
    ' search from there through the rows
    ' upward.
    lastRow = Cells.Find(What:="*", _
                         SearchOrder:=xlByRows, _
                         SearchDirection:=xlPrevious).row
    ' Search in the last row with content for most
    ' right cell with a value.
    lastColumn = Cells(lastRow, Columns.Count).End(xlToLeft).column

    ' Go through the detected range &
    ' apply the trim-function on every cell.
    For row = 1 To lastRow
        For column = 1 To lastColumn
          Cells(row, column).Value = _
            Trim(Cells(row, column).Value)
        Next
    Next

    Exit Sub

errorHandler:
    MsgBox "Error has occurred.", _
      vbCritical, "Error!"

End Sub

I apply the trim-function on every cell-value. So I ask myself:

What is better?

Doing unnecessary executions of the trim-function or checking if it has to be applied? Checking would cost me an additional if-then.

UPDATE

The above algorithm contains an error.

Concerning a table with the following structure:

First | Second |

Alpha | Beta | Gamma |

One   |

The result would be:

lastRow: 3
lastColumn: 1

Reason: It searches in the last row for the most right column.
But what is needed is the most right column overall.

Now I determine lastRow and lastColumn this way:

lastRow = Range("A1").SpecialCells(xlCellTypeLastCell).row

lastColumn = Range("A1").SpecialCells(xlCellTypeLastCell).column

It's faster to just trim a value than it is to try and figure out if it needs trimming in the first place.

However, that's not where your performance bottleneck is.

My personal #1 rule of fast spreadsheet manipulations:

Thou shalt not directly manipulate data in worksheets

By this I mean, doing anything in a worksheet has huge computational overhead. In the VBA object heirarchy, worksheets are only 2 steps removed from the application object itself. There are layers upon layers of abstractions, events, handlers, objects (not to mention several Billion range objects) buried in a worksheet object, and any time you do something in it, it will trigger a cascade of operations to make sure that nothing in your worksheet gets messed up.

Your sub might run fine for a couple of hundred cells in a small worksheet, but a few thousand cells in a larger spreadsheet might suddenly become unbearably slow.

For this reason, you should interact with worksheets as infrequently as possible. If there is data in your worksheet that you need to analyse: access the worksheet once to read the data into an Array, then do all your computations on the Array, then access the worksheet once to read the data back.

Your sub then looks like this:

Public Sub TrimWorksheetCellValues(Optional ByRef targetSheet As Worksheet)

    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual

    On Error GoTo errorHandler

    If targetSheet Is Nothing Then Set targetSheet = ActiveSheet '/ If no sheet is provided, assume the active sheet

    Dim firstRow As Long, lastRow As Long
    firstRow = 1
    lastRow = targetSheet.Cells.Find(What:="*", _
                         SearchOrder:=xlByRows, _
                         SearchDirection:=xlPrevious).row

    Dim firstColumn As Long, lastColumn As Long
    firstColumn = 1
    lastColumn = targetSheet.Cells(lastRow, Columns.Count).End(xlToLeft).column

    Dim sheetRange As Range
    Set sheetRange = targetSheet.Range(Cells(firstRow, firstColumn), Cells(lastRow, lastColumn))

    Dim sheetArray As Variant
    sheetArray = Array()
    sheetArray = sheetRange

    Dim ix As Long, iy As Long
    Dim elementValue As Variant, trimmedValue As Variant

    For ix = firstRow To lastRow
        For iy = firstColumn To lastColumn
            elementValue = sheetArray(ix, iy)
            trimmedValue = Trim(elementValue)
            sheetArray(ix, iy) = trimmedValue
        Next iy
    Next ix

    sheetRange = sheetArray

    Application.ScreenUpdating = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic

    Exit Sub

errorHandler:
    MsgBox "Error has occurred.", _
      vbCritical, "Error!"

End Sub

A few other things I modified while I was there:

Function names should be written in PascalCase with the leading word capitalised

Things should be explicitly scoped. Your sub was implicitly targeting the active sheet everywhere but nowhere was that explicitly declared or confirmed as the desired functionality. The sub now explicitly targets a particular sheet or explicitly targets the active sheet if no target is provided.

The firstRow and firstColumn are now explicitly declared and assigned, rather than magically appearing halfway through your code.

Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

These are the standard application settings to turn off if you want your macros to run faster. You should make sure any error handling resets them to their previous values in case your procedure terminates unexpectedly.

Don't catch errors if you're not going to handle them properly. This:

errorHandler:
    MsgBox "Error has occurred.", _
      vbCritical, "Error!"

Is just an error message, but with the useful information (error#, warning etc.) taken out. Do something useful with it (like resetting the application settings) or remove it.