C# classes for system health metrics My company wants me to build a serverless component (AWS Lambda) that checks every minute for our system components health.

The data model (classes structure) I have devised so far is as pasted below.
The main problem I am trying to address is I wanted to have a collection of all our system metrics. At first I thought of having clsMetric<T> where T would determine the type of Value and Threshold properties. But I can't have a collection of a generic class (at least not a generic collection of generic classes).

So I ended up creating subclasses of clsMetric for each metric value type I have, and left in the parent class a string representation of those properties for accessing them while looping over my collection of clsMetric.

Is this the way to go ? Current C# capabilities offer something else I do not know? Any design pattern suitable to apply here I am not aware of ?

public abstract class clsMetric
{
    public string Name { get; }
    public abstract string ValueAsStr { get; }
    public abstract eLogicalOperator LogicalOperator { get; }
    public abstract string ThresholdAsStr { get; }
    public abstract bool Faulty();
    public clsMetric(string name)
    {
         Name = name ?? string.Empty;
    }

    public override string ToString()
    {
        return Name;
    }
}

public class IntegerMetric : clsMetric
{
    eLogicalOperator _logicalOperator;
    #region Properties
    public int Value { get; private set; }

    public override string ValueAsStr => Value.ToString();

    public override eLogicalOperator LogicalOperator => _logicalOperator;

    public int Threshold { get; private set; }
    public override string ThresholdAsStr => Threshold.ToString();

    #endregion

    #region Constructors
    public IntegerMetric(string name, int value, eLogicalOperator logicalOperator, int threshold) : base(name)
    {
        Value = value;
        _logicalOperator = logicalOperator;
        Threshold = threshold;
    }

    public override bool Faulty()
    {
        if (LogicalOperator == eLogicalOperator.Equal)
            return Value == Threshold;
        else if (LogicalOperator == eLogicalOperator.GreaterOrEqualThan)
            return Value >= Threshold;
        else if (LogicalOperator == eLogicalOperator.GreaterThan)
            return Value > Threshold;
        else if (LogicalOperator == eLogicalOperator.LowerOrEqualThan)
            return Value <= Threshold;
        else if (LogicalOperator == eLogicalOperator.LowerThan)
            return Value < Threshold;

        return false;
    }

    #endregion
}

public class StringMetric : clsMetric
{
    eLogicalOperator _logicalOperator;
    #region Properties
    public string Value { get; private set; }

    public override string ValueAsStr => Value.ToString();
    public override eLogicalOperator LogicalOperator => _logicalOperator;

    public string Threshold { get; private set; }

    public override string ThresholdAsStr => Threshold.ToString();
    #endregion

    #region Constructors
    public StringMetric(string name, string value, eLogicalOperator logicalOperator, string threshold) : base(name)
    {
        Value = value;
        _logicalOperator = logicalOperator;
        Threshold = threshold;
    }

    public override bool Faulty()
    {
        if (LogicalOperator == eLogicalOperator.Equal)
            return string.Equals(Value, Threshold);
        else if (LogicalOperator == eLogicalOperator.Contains)
            return ValueAsStr.Contains(ThresholdAsStr, StringComparison.InvariantCultureIgnoreCase);

        return false;
    }
    #endregion
}

A design pattern often used, is to have a non generic base type and a generic type derived from it or a type implementing a non generic as well as a generic interface. An example is

public abstract class Comparer<T> :
    System.Collections.Generic.IComparer<T>, System.Collections.IComparer

You can see the full implementation here public abstract class Comparer<T> : IComparer, IComparer<T>.

You can see that it does an explicit implementaion of IComparer members and an implicit implementation of IComparer<T>. This hides the IComparer members when not accessed through this very interface. Original code:

public abstract int Compare(T x, T y);

int IComparer.Compare(object x, object y) {
    if (x == null) return y == null ? 0 : -1;
    if (y == null) return 1;
    if (x is T && y is T) return Compare((T)x, (T)y);
    ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArgumentForComparison);
    return 0;
}

A possible approach for your metric class, would be to implement two interfaces IMetric and IMetric<T>. The collection would then have an element type of IMetric.

public interface IMetric
{
    string Name { get; }
    object Value { get; }
    eLogicalOperator LogicalOperator { get; }
    object Threshold { get; }
    bool Faulty();
}

public interface IMetric<out T> : IMetric
{
    new T Value { get; }
    new T Threshold { get; }
}

Implementation:

public class Metric<T> : IMetric<T>
{
    public Metric(string name, eLogicalOperator logicalOperator, T value, T threshold)
    {
        Name = name ?? String.Empty;
        LogicalOperator = logicalOperator;
        Value = value;
        Threshold = threshold;
    }

    public T Value  { get; }
    public T Threshold  { get; }

    object IMetric.Value => Value;
    object IMetric.Threshold => Threshold;

    public string Name  { get; }
    public eLogicalOperator LogicalOperator { get; }

    public bool Faulty()
    {
        //TODO: implement;
    }
}

I don't know, however, how you would implement the Faulty method in a generic way. Maybe you could inject the logic and use a factory method to create metric objects.

Probably a better approach is to create an abstract Metric<T> class having only the Faulty method abstract to be able to implement specialized variants.

public class DecimalMetric : IMetric<decimal>

Yet another, elegant possibility is to pass a delegate doing the comparison, instead of the operator enum.

public Metric(string name, T value, T threshold, Func<T,T,bool> isValid)

This allows you to provide a type specific comparison and saves you a complex processing for different operators. I prefer to ask the positive question "is valid". It feels better than specifying what is wrong. You can call it like this

new Metric<int>("int test", 5, 10, (v, threshold) => v < threshold)

Usage (still with you original constructor):

var list = new List<IMetric>();
list.Add(new Metric<int>("int", eLogicalOperator.LowerThan, 5, 10));
list.Add(new Metric<double>("double", eLogicalOperator.LowerThan, 2.45, 10.0));

object value = list[0].Value;

switch (list[0]) {
    case Metric<int> intMetric:
        int i = intMetric.Value;
        break;
    case Metric<double> doubleMetric:
        double d = doubleMetric.Value;
        break;
    default:
        break;
}

// or

switch (list[0].Value) { // of type object
    case int i:
        int myInt = i;
        break;
    case double d:
        double myDouble = d;
        break;
    default:
        break;
}


Returning consonants of a plane's starting and ending points I am just starting to program in C#, so I am a beginner.  I've been practicing some coding and I would like your opinion on something.

I have a flying direction for a plane, e.g. ''London - Berlin'' (direction). I want to create a method that will return the first and the last consonant of the plane's starting point (London), and the first and the last consonant of the plane's destination (Berlin).

I have written this, so I would like to know if it's ok, or if you have some suggestions:

public class Flight
{
    private string direction;

    public Flight(string direction)
    {
        this.direction = direction;
    }

    public string Consonants()
    {
        string starting = direction.Split('-')[0];
        string destination = direction.Split('-')[1];

        string startConsonants = starting.ToUpper().Replace("A", "").Replace("E", "").Replace("I", "").Replace("O", "").Replace("U", "");
        string destConsonants = destination.ToUpper().Replace("A", "").Replace("E", "").Replace("I", "").Replace("O", "").Replace("U", "");

        return string.Format("{0}{1}-{2}{3}", startConsonants[0].ToString(), startConsonants[startConsonants.Length-1].ToString(), destConsonants[0].ToString(), destConsonants[destConsonants.Length-1].ToString());
    }
}

Your code is working but repeating all those Replace seems to be unnecessary. Firstly, you repeat them five times for single word and then once again two times because of processing two words. Code becomes long and unclear. Always, when we repeat code, it is good time to think about improvements and reducing those repeats.

So first, I would start to think about reducing repeats in line:

string startConsonants = starting.ToUpper().Replace("A", "").Replace("E", "").Replace("I", "").Replace("O", "").Replace("U", "");

You can do, for example, use LINQ:

string vowels = "aeiou";
var consonants = starting.Where(c => !vowels.Contains(char.ToLowerInvariant(c))); // (1)

And then simply, instead of operating on arrays startConsonants[0].ToString() and startConsonants[startConsonants.Length-1].ToString(), you can write:

char first = consonants.First();
char last = consonants.Last();

This code is more clear than yours because it has clear intention: select only not vowels and then take first and last of them. No repeating code, no indices calculation etc.

Then, to not repeat line (1) two times, I would create a method for it:

public string GetConsonants(string input)
{
    string vowels = "aeiou";
    var consonats = input.Where(c => !vowels.Contains(char.ToLowerInvariant(c)));
    return new string(consonats.ToArray());
}

and then:

public string Consonants()
{
    string starting = direction.Split('-')[0];
    string destination = direction.Split('-')[1];

    string startConsonants = GetConsonants(starting);
    string destConsonants = GetConsonants(destination);

    return string.Format("{0}{1}-{2}{3}", startConsonants.First(), startConsonants.Last(), destConsonants.First(), destConsonants.Last());
}

Eventually, to go along with .NET/C# ideology, I would create an extension methods for Char and String to make everything clear:

public static class CharExtensions
{
    private static string Vowels = "aeiou";

    public static bool IsVowel(this Char chr)
    {
        return Vowels.Contains(char.ToLowerInvariant(chr));
    }

    public static bool IsConsonant(this Char chr)
    {
        return !IsVowel(chr);
    }
}

public static class StringExtensions
{
    public static string OnlyConsonants(this String str)
    {
        return new string(str.Where(c => c.IsConsonant()).ToArray());
    }
}

and then:

public string Consonants()
{
    string starting = direction.Split('-')[0];
    string destination = direction.Split('-')[1];

    string startConsonants = starting.OnlyConsonants();
    string destConsonants = destination.OnlyConsonants();

    return string.Format("{0}{1}-{2}{3}", startConsonants.First(), startConsonants.Last(), destConsonants.First(), destConsonants.Last());
}


How can I enhance my jigsaw puzzle solver function? I'm working on writing code which gets several pieces of an image, and reconstructs them to one whole picture.  The images are represented by matrices, and two pieces should be "glued" if the right column of one matrix is the same as the left column in the other one.

from images import *

def reconstruct_image(m):
    try:
        Matrix.load("./im1.bitmap")
    except:
        for i in range(m**2):  #first run only - turn .bmp to .bitmap
            image2bitmap("./puzzle/im"+str(i+1)+".bmp")
    pieces=[Matrix.load("./im"+str(i+1)+".bitmap") for i in range(m**2)]
    #find top left
    for candidate in pieces:
        if is_top(candidate,pieces) and is_left(candidate,pieces):
            base=[pieces.pop(pieces.index(candidate))]
            break
    #building vertical "strips"
    strips=[]
    rows,cols=base[0].dim() #all pieces of equal size
    while len(strips)<m:
        for i in range(len(pieces)):
            if base[len(base)-1][rows-1:rows,0:cols]==pieces[i][0:1,0:cols]: #base is up
                if len(strips)==0 and is_left(pieces[i], pieces): #leftmost strip
                    down=pieces.pop(i)
                    base.append(down)
                    break
                elif pieces[i][0:rows,0:1]==strips[len(strips)-1][len(base)][0:rows,cols-1:cols]: #pieces[i] fits
                    down=pieces.pop(i)
                    base.append(down)
                    break
        if len(base)==m: #base became a strip
            strips.append(base)
            for candidate in pieces: #find top piece that matches strip on the left
                if candidate[0:rows,0:1]==strips[len(strips)-1][0][0:rows,cols-1:cols] and is_top(candidate,pieces):
                    base=[pieces.pop(pieces.index(candidate))]
                    break
    return join([join(strip, "v") for strip in strips], "h")

def is_top(candidate, pieces):
    '''checks if there are no pieces above candidate'''
    rows,cols=candidate.dim() #all pieces of equal size
    for piece in pieces:
        if candidate[0:1,0:cols]==piece[rows-1:rows,0:cols]:
            return False
    return True

def is_left(candidate, pieces):
    '''checks if there are no pieces left of candidate'''
    rows,cols=candidate.dim() #all pieces of equal size
    for piece in pieces:
        if candidate[0:rows,0:1]==piece[0:rows,cols-1:cols]:
            return False
    return True

def join(mats, direction, sep=0):
    '''variation on joined from class - recieve mats as list/tuple'''
    '''deletes overlapping pixel row/col'''
    res=mats[0]
    rows,cols=res.dim()
    if direction=="v":
        for mat in mats[1:]:
            res=join_v(res, mat[1:rows,0:cols])
    else:
        for mat in mats[1:]:
            res=join_h(res, mat[0:rows,1:cols])
    return res

def join_h(mat1, mat2, sep=0):
    """ joins two matrices, side by side with given separation """
    n1,m1 = mat1.dim()
    n2,m2 = mat2.dim()
    m = m1+m2+sep
    n = max(n1,n2)
    new = Matrix(n, m, val=255)  # fill new matrix with white pixels

    new[:n1,:m1] = mat1
    new[:n2,m1+sep:m] = mat2

    return new

def join_v(mat1, mat2, sep=0):
    """ joins two matrices, one below the other with given separation """
    n1,m1 = mat1.dim()
    n2,m2 = mat2.dim()
    n = n1+n2+sep
    m = max(m1,m2)
    new = Matrix(n, m, val=255)  # fill new matrix with white pixels

    new[:n1,:m1] = mat1
    new[n1+sep:n,:m2] = mat2

    return new

First - some minor comments regarding your code:

you are saying that all pieces of equal size, then it doesn't make sense to do rows,cols=candidate.dim() in a loop
I never worked with Matrix class, but I assume that [0:rows,0:1] is the same as [:-1, :1], so you don't have to carry rows and cols everywhere
instead of "./im"+str(i+1)+".bitmap" - you can do "./im{0}.bitmap".format(i + 1). IMO it is more readable
add more spaces to the code to make it more readable, at least around all operators. For example: n = n1+n2+sep => n = n1 + n2 + sep
instead of checking is this line throws an exception Matrix.load("./im1.bitmap"), you can just check if file exists with os.path.isfile
please don't do from images import * from modules, because now I don't know what came from images. Please consider from images import Matrix or something else.

Second, I feel like it would be possible to solve this problem with object graph rather than with indexes and temporary lists. E.g wrap a bitmap piece into an object an have it reference it's neighbours (left, right, top, bottom), once you have a complete graph - just draw it.

This is my version of the code. Please don't consider it to be a solution(I may swapped cols/rows accidentally etc), this is just an overall idea. I didn't even run this code , but I believe it is possible to use something like this.

Also this piece of code assumes that puzzle is ideal - so there is always exactly one solution and all pieces should be used.

import os.path
import itertools

# helpers to construct file names
def bitmap_file_name(index):
    return "./im{0}.bitmap".format(i + 1)

def puzzle_file_name(index):
    return "./puzzle/im{0}.bmp".format(i + 1)

# helpers to cut a piece of bitmap
def left_stripe(bitmap):
    return bitmap[:1, 0:-1]

def right_stripe(bitmap):
    return bitmap[-1:, 0:-1]

def bottom_stripe(bitmap):
    return bitmap[:-1, -1:]

def top_stripe(bitmap):
    return bitmap[:-1, :1]

class Piece(object):
    """
    Wrapper around bitmap piece, has references to it's neighbours
    """
    def __init__(self, bitmap):
        self.left = None
        self.right = None
        self.top = None
        self.bottom = None
        self.bitmap = bitmap

def reconstruct_image(m):
   images_range = range(m**2)

   # check if we already converted bmps to bitmaps
   if not os.path.isfile(bitmap_file_name(0)):
        for i in images_range:
            image2bitmap(puzzle_file_name(i))

    bitmaps_gen = (Matrix.load(bitmap_name(i)) for i in images_range)
    # list of `Piece` elements, all neighbours are `Nones`
    pieces = [Piece(x) for x in bitmaps_gen]

    # try all pairs of these pieces (it will twice over each pair A, B and B, A)
    for piece1, piece2 in itertools.permutations(pieces, 2):
        # compare edges of elements, but only if these edges are not taken
        if not piece1.left and not piece2.right and left_stripe(piece1.bitmap) == right_stripe(piece2.bitmap):
            piece1.left = piece2
            piece2.right = piece1
        elif not piece1.top and not piece2.bottom and top_stripe(piece1.bitmap) == bottom_stripe(piece2.bitmap):
            piece1.top = piece2
            piece2.bottom = piece1

    # assuming that our puzzle is always solvable
    # so now we have full graph, and there is one element that doesn't have top and left neighbours
    top_left = next(p for p in pieces if not p.left and not p.top)

    piece_width, piece_height = top_left.dim()

    # init result matrix
    result_matrix = Matrix(piece_width * m, piece_height * m)

    first_line_elem = top_left
    current_elem = first_line_elem
    # let's fill new matrix line by line, we could choose BFS or something else. but line by line seem to be more logical
    for row in xrange(m):
        for column in xrange(m):
            left_x = column * piece_width
            left_y = row * piece_height
            result_matrix[left_x : left_y, left_x + piece_width : left_y + piece_height] = current_elem.bitmap

            # choose next piece
            if current_elem.right:
                current_elem = current_elem.right
            elif first_line_elem.bottom:
                current_elem = first_line_elem.bottom
                first_line_elem = current_elem

    return result_matrix


Checks user level and limit the data before saving it to mongoDB I have a function that checks user level and limits the data before saving it to mongoDB database (pre 'save' middleware for mongoose).
It have been getting complexity warnings and tried to rewrite it, and came up with the second version. I think now it's really not human readable! Anyone has any suggestions?

Before:

providerSchema.pre('save', function(next) {

    if(this.level === 4){
        if(this.description.length >= 80 || this.certifications.length > 5){
            next(new Error('your current plan does not have this feature'));
        } else {
            next()
        }
    } else if(this.level === 3){
        if(this.description.length >= 50 || this.certifications.length > 3){
            next(new Error('your current plan does not have this feature'));
        } else {
            next()
        }
    } else if(this.level === 2){
        if(this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0){
            next(new Error('your current plan does not have this feature'));
        } else {
            next()
        }
    } else if(this.level === 1){
        if(this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart){
            next(new Error('your current plan does not have this feature'));
        } else {
            next()
        }
    } else {
        if(this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart){
            next(new Error('your current plan does not have this feature'));
        } else {
            next()
        }
});

After:

providerSchema.pre('save', function(next) {

    if(((this.level === 4) && (this.description.length >= 80 || this.certifications.length > 5)) ||
       ((this.level === 3) && (this.description.length >= 50 || this.certifications.length > 3)) ||
       ((this.level === 2) && (this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0)) ||
       ((this.level === 1 || this.level === 0) && (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart))){
         next(new Error('your current plan does not have this feature'));
    } else {
         next()
    }
});
```

According to www.lizard.ws the original's function cyclomatic complexity is 29 and for the second version is 22. Both numbers are usually considered high, and teams aim for much lower values (debatable what the good range is though and will see within this answer why).

In order to reduce it, one way is to encapsulate the if statements, among with removing the code duplication and separate the responsibilities.

The next calls seem duplicate, so let's reduce them first.

providerSchema.pre('save', function (next) {

     var valid = true;
    if (this.level === 4) {
        if (this.description.length >= 80 || this.certifications.length > 5) {
            valid = false;
        }
    } else if (this.level === 3) {
        if (this.description.length >= 50 || this.certifications.length > 3) {
            valid = false;
        }
    } else if (this.level === 2) {
        if (this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0) {
            valid = false;
        }
    } else if (this.level === 1) {
        if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {
            valid = false;
        }
    } else {
        if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {
            valid = false;
        }
    }

    if (valid) {
        next();
    } else {
        next(new Error('your current plan does not have this feature'));
    }
});

With this first refactoring we didn't gain much in terms of lowering CC, in fact it increased to 30, because of the added if statement. However this can let us to split the validation responsibility from enabling the actual feature (as @Margon mentioned).

providerSchema.pre('save', function (next) {
    if (isValidFeatureRequest()) {
        next();
    } else {
        next(new Error('your current plan does not have this feature'));
    }

    function isValidFeatureRequest() {
        if (this.level === 4) {
            if (this.description.length >= 80 || this.certifications.length > 5) {
                return false;
            }
        } else if (this.level === 3) {
            if (this.description.length >= 50 || this.certifications.length > 3) {
                return false;
            }
        } else if (this.level === 2) {
            if (this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0) {
                return false;
            }
        } else if (this.level === 1) {
            if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {
                return false;
            }
        } else {
            if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {
                return false;
            }
        }
        return true;
    }
});

The isValidFeatureRequest function is at 29 and providerSchema is at 2. We still need to work on.

Checking again the code duplication, I noticed the last two blocks have the the same checks for other levels than 2, 3 or 4, so let's merge them.

providerSchema.pre('save', function (next) {
    if (isValidFeatureRequest()) {
        next();
    } else {
        next(new Error('your current plan does not have this feature'));
    }

    function isValidFeatureRequest() {
        if (this.level === 4) {
            if (this.description.length >= 80 || this.certifications.length > 5) {
                return false;
            }
        } else if (this.level === 3) {
            if (this.description.length >= 50 || this.certifications.length > 3) {
                return false;
            }
        } else if (this.level === 2) {
            if (this.description.length >= 30 || this.certifications.length > 0 || this.teaser || this.social.length > 0) {
                return false;
            }
        } else {
            if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {
                return false;
            }
        }
        return true;
    }
});

We gained the following figures

function                               | CC
-------------------------------------------
providerSchema                         | 2
isValidFeatureRequest                  | 20

The CC for isValidFeatureRequest is now at 20, which is an improvement.
The check for description and certifications also seems to vary, so I can encapsulate it into a function.

providerSchema.pre('save', function (next) {
    if (isValidFeatureRequest()) {
        next();
    } else {
        next(new Error('your current plan does not have this feature'));
    }

    function isValidFeatureRequest() {
        if (this.level === 4) {
            if (descriptionOrCertificationsOffLimits(80, 5)) {
                return false;
            }
        } else if (this.level === 3) {
            if (descriptionOrCertificationsOffLimits(40, 3)) {
                return false;
            }
        } else if (this.level === 2) {
            if (descriptionOrCertificationsOffLimits(30, 0) || this.teaser || this.social.length > 0) {
                return false;
            }
        } else {
            if (this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart) {
                return false;
            }
        }
        return true;
    }

    function descriptionOrCertificationsOffLimits(descriptionLimit, certificationsLimit) {
        return this.description.length >= descriptionLimit || this.certifications.length > certificationsLimit;
    }
});

function                               | CC
-------------------------------------------
providerSchema                         | 2
isValidFeatureRequest                  | 17
descriptionOrCertificationsOffLimits   | 2

CC is now at 17, slightly better.

There is lot to check in the last branch, so let's extract it into his own function.

providerSchema.pre('save', function (next) {
    if (isValidFeatureRequest()) {
        next();
    } else {
        next(new Error('your current plan does not have this feature'));
    }

    function isValidFeatureRequest() {
        if (this.level === 4) {
            if (descriptionOrCertificationsOffLimits(80, 5)) {
                return false;
            }
        } else if (this.level === 3) {
            if (descriptionOrCertificationsOffLimits(40, 3)) {
                return false;
            }
        } else if (this.level === 2) {
            if (descriptionOrCertificationsOffLimits(30, 0) || this.teaser || this.social.length > 0) {
                return false;
            }
        } else if (hasAny()) {
            return false;
        }
        return true;
    }

    function descriptionOrCertificationsOffLimits(descriptionLimit, certificationsLimit) {
        return this.description.length >= descriptionLimit || this.certifications.length > certificationsLimit;
    }

    function hasAny() {
        return this.description || this.certifications.length > 0 || this.teaser || this.social.length > 0 || this.locationLat || this.locationLong || this.workingHourEnd || this.workingHourStart;
    }
});

Which results into

function                               | CC
-------------------------------------------
providerSchema                         | 2
isValidFeatureRequest                  | 10
descriptionOrCertificationsOffLimits   | 2
hasAny                                 | 8

We have now 4 functions with manageable complexities.
The hasAny function seems to have a large CC, compared to what it does. What we can do here is to improve its readability, by displaying one condition per line. This is also the moment when I think we can't do anything about this function, and is the time not to look at an arbitrary CC limit in order to squize the code just to pass the analyzer.

 function hasAny() {
        return this.description ||
            this.certifications.length > 0 ||
            this.teaser ||
            this.social.length > 0 ||
            this.locationLat ||
            this.locationLong ||
            this.workingHourEnd ||
            this.workingHourStart;
    }

Let's extract more, to check if it has a teaser or social data

providerSchema.pre('save', function (next) {
    if (isValidFeatureRequest()) {
        next();
    } else {
        next(new Error('your current plan does not have this feature'));
    }

    function isValidFeatureRequest() {
        if (this.level === 4) {
            if (descriptionOrCertificationsOffLimits(80, 5)) {
                return false;
            }
        } else if (this.level === 3) {
            if (descriptionOrCertificationsOffLimits(40, 3)) {
                return false;
            }
        } else if (this.level === 2) {
            if (descriptionOrCertificationsOffLimits(30, 0) || hasTeaserOrSocial()) {
                return false;
            }
        } else if (hasAny()) {
            return false;
        }
        return true;
    }

    function descriptionOrCertificationsOffLimits(descriptionLimit, certificationsLimit) {
        return this.description.length >= descriptionLimit || this.certifications.length > certificationsLimit;
    }

    function hasTeaserOrSocial() {
        return this.teaser || this.social.length > 0;
    }

    function hasAny() {
        return this.description ||
            this.certifications.length > 0 ||
            this.teaser ||
            this.social.length > 0 ||
            this.locationLat ||
            this.locationLong ||
            this.workingHourEnd ||
            this.workingHourStart;
    }
});

Which results into

function                               | CC
-------------------------------------------
providerSchema                         | 2
isValidFeatureRequest                  | 9
descriptionOrCertificationsOffLimits   | 2
hasTeaserOrSocial                      | 2
hasAny                                 | 8

The if followed by an inner if can be combined into and and operation so we can have this

 function isValidFeatureRequest() {
        if (this.level === 4 && descriptionOrCertificationsOffLimits(80, 5)) {
            return false;
        } else if (this.level === 3 && descriptionOrCertificationsOffLimits(40, 3)) {
            return false;
        } else if (this.level === 2 && descriptionOrCertificationsOffLimits(30, 0) || hasTeaserOrSocial()) {
            return false;
        } else if ((this.level === 1 || this.level === 0) && hasAny()) {
            return false;
        }
        return true;
    }

The CC doesn't change, but it enables me to extract validation for every level, so I gain smaller functions, with smaller complexity.
Edit to fix a bug here - This step introduced a bug, as @Roland Illig mentioned in the comments (the story of my life when I refactor even a simple if).
After fixing it the CC actually increased with 2, to 11, as I introduced two new checks and I also had to add a new function. end of edit

function isValidFeatureRequest() {
    if (isLevel4AndNotValid()) {
        return false;
    } else if (isLevel3AndNotValid()) {
        return false;
    } else if (isLevel2AndNotValid()) {
        return false;
    } else if (isBellowLevel2AndNotValid()) {
        return false;
    }
    return true;
}

function isLevel4AndNotValid() {
    return this.level === 4 && descriptionOrCertificationsOffLimits(80, 5);
}

function isLevel3AndNotValid() {
    return this.level === 3 && descriptionOrCertificationsOffLimits(40, 3);
}

function isLevel2AndNotValid() {
    return this.level === 2 && (descriptionOrCertificationsOffLimits(30, 0) || hasTeaserOrSocial());
}

function isBellowLevel2AndNotValid() {
    return (this.level === 1 || this.level === 0) && hasAny();
}

Which are

function                               | CC
-------------------------------------------
providerSchema                         | 2
isValidFeatureRequest                  | 5
isLevel4AndNotValid                    | 2
isLevel3AndNotValid                    | 2
isLevel2AndNotValid                    | 3
isBellowLevel2AndNotValid              | 3
descriptionOrCertificationsOffLimits   | 2
hasTeaserOrSocial                      | 2
hasAny                                 | 8

The isValidFeatureRequest still looks odd, I can remove the else statements and I can convert the last call into a return statement, which decrease the complexity with one point.

function isValidFeatureRequest() {
    if (isLevel4AndNotValid()) {
        return false;
    }

    if (isLevel3AndNotValid()) {
        return false;
    }

    if (isLevel2AndNotValid()) {
        return false;
    }

    if (isBellowLevel2AndNotValid()) {
        return false;
    }

    return true;
}

My final attempt is this:

providerSchema.pre('save', function (next) {
    if (isValidFeatureRequest()) {
        next();
    } else {
        next(new Error('your current plan does not have this feature'));
    }

    function isValidFeatureRequest() {
        if (isLevel4AndNotValid()) {
            return false;
        }

        if (isLevel3AndNotValid()) {
            return false;
        }

        if (isLevel2AndNotValid()) {
            return false;
        }

        if (isBellowLevel2AndNotValid()) {
            return false;
        }

        return true;
    }

    function isLevel4AndNotValid() {
        return this.level === 4 && descriptionOrCertificationsOffLimits(80, 5);
    }

    function isLevel3AndNotValid() {
        return this.level === 3 && descriptionOrCertificationsOffLimits(40, 3);
    }

    function isLevel2AndNotValid() {
        this.level === 2 && (descriptionOrCertificationsOffLimits(30, 0) || hasTeaserOrSocial());
    }

    function isBellowLevel2AndNotValid() {
        return (this.level === 1 || this.level === 0) && hasAny();
    }

    function descriptionOrCertificationsOffLimits(descriptionLimit, certificationsLimit) {
        return this.description.length >= descriptionLimit || this.certifications.length > certificationsLimit;
    }

    function hasTeaserOrSocial() {
        return this.teaser || this.social.length > 0;
    }

    function hasAny() {
        return this.description ||
            this.certifications.length > 0 ||
            this.teaser ||
            this.social.length > 0 ||
            this.locationLat ||
            this.locationLong ||
            this.workingHourEnd ||
            this.workingHourStart;
    }
});

With the following resuts:

function                               | CC
-------------------------------------------
providerSchema                         | 2
isValidFeatureRequest                  | 5
isLevel4AndNotValid                    | 2
isLevel3AndNotValid                    | 2
isLevel2AndNotValid                    | 3
isBellowLvel2AndNotValid               | 3
descriptionOrCertificationsOffLimits   | 2
hasTeaserOrSocial                      | 2
hasAny                                 | 8


Splitting C string without modifying input I wrote this after using strtok_r and needing something similar that can copy the input string and handle multiple characters in the delimiter. Its functionally similar to Python's str.split(), as it keeps empty spaces without trimming.

tokens.h

#ifndef TOKENS_H
#define TOKENS_H

#include <string.h>

struct Tokens {
    char **array;
    size_t count;
};

extern struct Tokens *string_split(const char *input,
                                   const char *delim,
                                   const int count);

extern void tokens_free(struct Tokens *tokens);

#endif

tokens.c

#include "tokens.h"

#include <stdbool.h>
#include <stdlib.h>

static bool tokens_add(struct Tokens *tokens, const char *token){
    tokens->array = realloc(tokens->array,
                            ++tokens->count * sizeof(char *));

    if (!tokens->array){
        tokens->count--;

        return false;
    }

    char *dupstr = strdup(token);

    if (!dupstr){
        tokens->count--;

        return false;
    }

    tokens->array[tokens->count - 1] = dupstr;

    return true;
}

struct Tokens *string_split(const char *input,
                            const char *delim,
                            const int count){

    struct Tokens *tokens = malloc(sizeof(struct Tokens));

    if (!tokens){
        return NULL;
    }

    tokens->count = 0;
    tokens->array = NULL;

    const size_t inputlen = strlen(input);
    const size_t delimlen = strlen(delim);

    if (count == 0 || delimlen == 0){
        tokens_add(tokens, input);

        return tokens;
    }

    int delimcount = 0;
    size_t inputpos = 0;
    const char *start = NULL;

    while ((start = strstr(&input[inputpos], delim))){
        const int delimpos = (start - &input[inputpos]);
        char token[delimpos + 1];

        memcpy(token, &input[inputpos], delimpos);
        token[delimpos] = '\0';

        if (!tokens_add(tokens, token)){
            return NULL;
        }

        inputpos += (delimpos + delimlen);

        if (delimcount++ == count){
            break;
        }
    }

    if (inputpos <= inputlen){
        const int charcount = (inputlen - inputpos);
        char token[charcount + 1];

        memcpy(token, &input[inputpos], charcount);
        token[charcount] = '\0';

        if (!tokens_add(tokens, token)){
            return NULL;
        }
    }

    return tokens;
}

void tokens_free(struct Tokens *tokens){
    if (!tokens){
        return;
    }

    for (size_t index = 0; index < tokens->count; index++){
        free(tokens->array[index]);
    }

    free(tokens);
}

test.c

#include <stdio.h>

#include "tokens.h"

int main(void){
    // <0 = split indefinitely
    struct Tokens *tokens = string_split("Hello;world;!;", ";", -1);

    if (tokens){
        for (size_t index = 0; index < tokens->count; index++){
            printf("%s\n", tokens->array[index]);
        }

        tokens_free(tokens);
    }
}

token_add()

do not change the struct members before you know that your call will succeed, otherwise you'll end up with inconsistent state (e.g. you're overwriting tokens->array if realloc fails). That means keep the increment of count and the assignment of array until the end of the function.
Note that strdup is not a C standard function.

split_string()

you're creating a temporary copy in the local variables token. If you'd pass the pointer and the length to token_add and you could safe the program a string copy.
there is no need to have delimpos in string_split being const. Same goes for the parameter count and charcount. As a rule of thumb, dont use const for integer types, booleans and floating points.
Note: your comment in test.c states that values less than 0 mean unlimited matching, but your code doesn't contribute to that statement. If you have enough matches you'll eventually increment delimcount to match -1.
Separate the increment of delimcount from the comparison with count. Some will ask himself if this is correct and right now, I couldn't tell ;-)
Why don't you use tokens->count?
If a call to tokens_add failes, you're returning NULL from split_string without freeing the Tokens struct allocated before, leaking its memory.

misc

Provide more test cases. One test case for handling unlimited matching, one for restricted matching, one for empty delimiters. Best is to write down what your API supports and then add a test for every special case.

For instance, if I test the following:

    struct Tokens *tokens = string_split("Hello;world;!;", ";", 2);

    assert(tokens->count == 2);
    assert(strcmp("Hello", tokens->array[0]) == 0);
    assert(strcmp("world!", tokens->array[1]) == 0);

I receive: test: test.c:22: test_2: Assertion 'tokens->count == 2' failed.

you don't need the include in tokens.h, it's sufficient if you add it to tokens.c


Non-repeatability (plagiarism and time travel) I heard/read that writers of texts can be recognized by counting their used words and compare these to previous works. As a code kata  I experimented with this a bit and found some disturbing facts.

'Romeo and Juliet' was written by one of the Bronte sisters.
Shakespeare plagiarized it from the future.
My program is not repeatable.

I think the last is most disturbing, see the numbers of corresponding words between brackets in my results below.

Used code is also below and used .txt files were downloaded from https://www.gutenberg.org/ and conveniently renamed, temporary available in a zip at http://kuiken.dyndns.org/spul/books.zip.

Questions:

Why is my code not repeatable
Coding style comments

Results:

jk@ASUS-flaptop:~/PythonFun/Boeken$ python books.py

I read WutheringHeights.txt by Bronte
I read PrideAndPrejudice.txt by Austen
I read TheMerchantOfVenice.txt by Shakespeare

I think SensAndSensibility.txt is written by Austen (405)
I think RomeoAndJuliet.txt is written by Bronte (278)
I think JaneEyre.txt is written by Bronte (376)
I think Hamlet.txt is written by Shakespeare (324)

jk@ASUS-flaptop:~/PythonFun/Boeken$ python books.py

I read WutheringHeights.txt by Bronte
I read PrideAndPrejudice.txt by Austen
I read TheMerchantOfVenice.txt by Shakespeare

I think SensAndSensibility.txt is written by Austen (404)
I think RomeoAndJuliet.txt is written by Bronte (279)
I think JaneEyre.txt is written by Bronte (376)
I think Hamlet.txt is written by Shakespeare (319)

Code:

from collections import Counter
from string import ascii_letters, whitespace

def read_book(filename):
    with open(filename) as f:
        return f.read()

def make_words(text):
    '''removes weird characters and split into words'''
    remain = ascii_letters + whitespace
    filtered = ""
    for ch in text:
        if ch in remain:
            filtered += ch
    return filtered.lower().split()

def most_used(words, n=500):
    '''returns a `set` of the `n` most used words'''
    counting = Counter(words)
    counted = counting.most_common(n)
    return set([item[0] for item in counted])

def read_and_analyse(filename):
    '''reads a book and returns most used words'''
    book = read_book(filename)
    words = make_words(book)
    favorites = most_used(words)
    return favorites

class WriterKnower():

    def __init__(self):
        self.analysed_books = []

    def read_and_remeber_words(self, filename, writer):
        favorite_words = read_and_analyse(filename)
        self.analysed_books.append({ 'favorite_words' : favorite_words,
                                     'writer' : writer})
        print("I read %s by %s" % (filename, writer))

    def read_and_recognize(self, filename):
        favorit_words = read_and_analyse(filename)
        writer = 'unknown'
        max_identical_words = 0
        for book in self.analysed_books:
            common = len(favorit_words.intersection(book['favorite_words']))
            if (common > max_identical_words):
                max_identical_words = common
                writer = book['writer']
        print("I think %s is written by %s (%d)" %
              (filename, writer, max_identical_words))

if __name__ == "__main__":

    nerd = WriterKnower();

    print()
    nerd.read_and_remeber_words('WutheringHeights.txt', 'Bronte')
    nerd.read_and_remeber_words('PrideAndPrejudice.txt', 'Austen')
    nerd.read_and_remeber_words('TheMerchantOfVenice.txt', 'Shakespeare')
    print()
    nerd.read_and_recognize('SensAndSensibility.txt')
    nerd.read_and_recognize('RomeoAndJuliet.txt')
    nerd.read_and_recognize('JaneEyre.txt')
    # to be a bit reinsured....
    nerd.read_and_recognize('Hamlet.txt')
    print()

More classes

Making the author guesser a class was a good start, but I think authors also should be a class.  Making them a class now will allow you to work more with the concept of an author in the future (see "More work to do").

Cleaning up

You don't really need the book reading method, and you can simplify how you teach your guesser about authors and then test them later.  I've tried to leave the general spirit of your code intact:

from collections import Counter
from string import ascii_letters, whitespace

def filter_words(text):
    '''removes weird characters and split into words'''
    remain = ascii_letters + whitespace
    filtered = [ch.lower() for ch in text if ch in remain]
    return "".join(filtered).split()

def most_used(words, n=500):
    '''returns a set of the "n" most used words'''
    most_used_words = Counter(words).most_common(n)
    return set([word for word, frequency in most_used_words])

def read_and_analyse(filename):
    '''reads a book and returns most used words'''
    with open(filename) as book:
        words = filter_words(book)
        favorites = most_used(words)
        return favorites

class Author(object):
    def __init__(self, name, favorite_words):
        self.name = name
        self.favorite_words = favorite_words

class WriterGuesser(object):
    def __init__(self):
        self.analyzed_authors = []

    def learn_about_authors(self, book, name):
        favorite_words = read_and_analyse(book)
        author = Author(name, favorite_words)
        self.analyzed_authors.append(author)
        print "I read {} by {}".format(book, name)

    def recognize_author(self, book):
        favorite_words = read_and_analyse(book)
        max_identical_words = 0
        guess = None
        for author in self.analyzed_authors:
            common = len(favorite_words.intersection(author.favorite_words))
            if common > max_identical_words:
                max_identical_words = common
                guess = author.name
        print"I think {} is written by {} ({} words in common)".format(book, guess, max_identical_words)

def main():
    nerd = WriterGuesser()

    learning_criteria = [
        ('WutheringHeights.txt', 'Bronte'),
        ('PrideAndPrejudice.txt', 'Austen'),
        ('TheMerchantOfVenice.txt', 'Shakespeare')
    ]

    for book, author in learning_criteria:
        nerd.learn_about_authors(book, author)

    books_to_recognize = [
        'SensAndSensibility.txt',
        'RomeoAndJuliet.txt',
        'JaneEyre.txt',
    ]

    for book in books_to_recognize:
        nerd.recognize_author(book)

if __name__ == "__main__":
    main()

More work to do

You can only learn about one book from an author.  Surely, you'd like a system that allows you to create an author and then use several books to develop their favorite words.  This is where a class is helpful - you can create the author class, get their favorite words, and then update them as you learn more books.
You should expand this so that you can use many books by the same author to learn favorite words.  Perhaps return the frequency of a word along with the word itself (which Counter already does), and remove less popular words as more popular ones come in.
You should also use the frequency of the word to determine how confident you are that the authors are the same.  Say an author's favorite words are ["cat", "purple", "clock"], but they use "clock" 600 times and use the rest only 10 times.  Your code will pick a book with "cat" and "purple" over a book with 500 instances of "clock", because 2 matching words > 1 matching word.  But we know "clock" is a more important word!
Everybody's favorite words are going to be "the", "it", "a", "and", etc.  Consider making a list of boring words and not using them for your filtering.


Inserting multiple elements at known locations in a vector Goal
In the vector x, I would like to insert the elements of the vector values at indices stored in vector positions. Note that the vector positions is not sorted.
For example, from the following input
std::vector<char> x = {'H','e','l','l','W','o','l','d'};
std::vector<char> values = {'r','o'};
std::vector<size_t> positions = {6,4};

I expect the following output
std::vector<char> x = {'H','e','l','l','o','W','o','r','l','d'};

My implementation
The idea is first to sort positions and reorder values accordingly. Then, I resize the vector x so that it can welcome the new elements. Finally, I iterate through the vector x from its last index to the lowest position of insertion by asking at each step what element should go there and move this element (whether it comes from a lower index in x of from values).
#include <iostream>
#include <vector>
#include <numeric>

//// Print a vector
template <typename T>
void print(std::vector<T>& x)
{
    for (auto& e : x) std::cout << e << " ";
    std::cout << "\n";
}

//// Return the indices to inform on how to sort the inputted vector
template <typename T>
std::vector<uint32_t> sort_indices(const std::vector<T> &v)
{

  // initialize original index locations
  std::vector<uint32_t> idx(v.size());
  std::iota(idx.begin(), idx.end(), 0);

  // sort indexes based on comparing values in v
  std::sort(idx.begin(), idx.end(),
       [&v](uint32_t i1, uint32_t i2) {return v[i1] < v[i2];});

  return idx;
}

//// reorder vector based on indices
template <typename T>
void reorder(std::vector<T>& v, std::vector<uint32_t>& order)
{
    auto v2 = v;
    for (uint32_t i = 0 ; i < v.size() ; i++)
    {
        v[i] = v2[order[i]];
    }
}

//// Insert multiple elements at specified positions into vector
template<typename T>
void insertAtPositions(std::vector<T>& x, std::vector<T>& values, std::vector<size_t>& positions)
{
  // assert values and positions are the same size
  assert(values.size() == positions.size());

  // Special case - values is empty
  if (values.size() == 0) return;

  // sort the values and the positions where those values should be inserted
  auto indices = sort_indices(positions);
  reorder(positions, indices);
  reorder(values, indices);

  // Special case - x is empty
  if (x.size() == 0)
  {
      x.swap(values);
      return;
  }

  // Allocate memory to x
  x.resize(x.size() + values.size());

  // Move things to make room for insertions and insert
  int pos_index = positions.size()-1;
  for (size_t i = x.size()-1 ; pos_index >= 0 ; --i)
  {
    if (i == positions[pos_index] + pos_index)
    {
      // A new value should go at index i
      x[i] = std::move(values[pos_index]);
      --pos_index;
    } else
    {
      // The value from index 'i-pos_index-1' must go to index 'i'
      x[i] = std::move(x[i-pos_index-1]);
    }
  }
}

int main()
{
  std::vector<char> x = {'H','e','l','l','W','o','l','d'};
  std::vector<char> values = {'r','o'};
  std::vector<size_t> positions = {6,4};

  print(x);
  insertAtPositions(x,values,positions);
  print(x);

}

It prints, as expected
H e l l W o l d
H e l l o W o r l d

Are there faster (or better in some other respect) implementations?
Note that

in practice, x's size typically ranges from 0 to 10^7 and positions (and values)'s size typically ranges from 0 to 50.
I have good reasons for using a vector and not a deque despite this insertion.

We need to include <algorithm> for std::sort and <cassert> for assert.

void print(std::vector<T> &x): Since we don't modify the vector, this should take a const& (and use a const& internally in the range-based for loop).

void reorder(std::vector<T> &v, std::vector<uint32_t> &order): Again, order can be a const&.

We should use std::size_t for indices into a vector, not uint32_t or size_t.

If we need a signed type for dealing with index differences, we should use std::ptrdiff_t, not int. It might be easier to count forwards, and then calculate the indices we need inside the loop though.

There's no point in std::moveing a char.

Rather than inserting elements in-place, we can create a new vector and copy the elements over, selecting from the appropriate source at each index. This doesn't require any more memory than calling x.resize().
e.g.:
{
    std::vector<char> x = {'H', 'e', 'l', 'l', 'W', 'o', 'l', 'd'};
    std::vector<char> values = {'r', 'o'};
    std::vector<size_t> positions = {6, 4};

    auto indices = sort_indices(positions);
    reorder(positions, indices);
    reorder(values, indices);

    auto size = x.size() + values.size();

    auto y = std::vector<char>();
    y.reserve(size);

    auto v = std::size_t{ 0 }; // index into x
    auto p = std::size_t{ 0 }; // index into positions / values

    for (auto i = std::size_t{ 0 }; i != size; ) // index into y
    {
        if (v == positions[p])
        {
            y.push_back(values[p]);
            ++p;
            ++i;
        }
        else
        {
            y.push_back(x[v]);
            ++v;
            ++i;
        }
    }

    print(y);
}

Since we expect the x vector to be much larger than the values to be inserted, we could copy larger ranges from x in the else branch above, something like:
            auto beg = v;
            auto end = (p == positions.size() ? x.size() : positions[p]);

            y.insert(y.end(), x.begin() + beg, x.begin() + end);
            v = end;
            i += (beg - end);

(Warning: code not properly tested).


Get module entry by name from external program via WinAPI I'm asking myself if there's any better/shorter way of getting a module entry by its name from an external process.

This is the code I have so far:

MODULEENTRY32 GetModule(const char* ModuleName) {

    HANDLE Module = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
    MODULEENTRY32 Entry;
    Entry.dwSize = sizeof(Entry);

    WCHAR *ModuleNameChar;
    int Chars = MultiByteToWideChar(CP_ACP, 0, ModuleName, -1, NULL, 0);
    ModuleNameChar = new WCHAR[Chars];
    MultiByteToWideChar(CP_ACP, 0, ModuleName, -1, (LPWSTR)ModuleNameChar, Chars);

    while (Module32Next(Module, &Entry)) {
        if (!wcscmp((wchar_t*)Entry.szModule, ModuleNameChar)) {
            CloseHandle(Module);
            return Entry;
        }
    }

    /*
        Return the module base 0x0 if we don't find any module
    */
    CloseHandle(Module);
    Entry.modBaseAddr = 0x0;
    return Entry;
}

It should work but it's quite complicated. Is there any useful function or method I can make use of to simplify this whole thing?

Unfortunately, I'm not sure of any way of being more concise.

There are a few changes you could make, but they're mostly optional.

Check the return value of CreateToolhelp32Snapshot(). The documentation says the following:

  Includes all modules of the process specified in th32ProcessID in the
  snapshot. To enumerate the modules, see Module32First. If the function
  fails with ERROR_BAD_LENGTH, retry the function until it succeeds.

I use CreateToolhelp32Snapshot() in an application that runs 24/7 and I know for a fact that I get the ERROR_BAD_LENGTH error here and there. In my case, I cannot afford false negatives, so I have to put this function in a loop. If you are okay with having false-negatives occasionally, then I wouldn't worry too much about it.
I don't know if you're showing us the full code for this function, but you have a memory leak here:

ModuleNameChar = new WCHAR[Chars];

I don't see where you are deleting this buffer. I personally would use an std::vector<WCHAR> as a buffer, give it the correct size, and pass the address of the first element to MultiByteToWideChar().
If you use HANDLEs a lot, consider wrapping them in an RAII container. That way, you don't have to worry about closing them manually. This will also make your code exception-safe if you ever add any functions that can throw (you actually already have one that can throw, the new call).
I noticed you're not calling ::Module32First(). You probably don't need it, but I always have it anyway.
This is a personal preference, but I think your upper-case variable names look absolutely horrendous. Please use snake-case or camel-case for variable names.

There's really nothing helpful to say unfortunately, the Windows API can be quite cumbersome.


Condensing code that generates Pascal's triangle I recently started learning Java for a class and my teacher gave us an assignment in which we had to write up code which would print out the Pascal's triangle to an amount of rows decided by the user, and use recursion to do so. I believe that I'm done with the assignment, but wanted to know, for myself, as to how I could improve and condense this messy code (the array complicates things but I wanted to use it for a different program that expands polynomials (\$(x+b)^n)\$).

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

public class PascalTriangleYar
{
private static int[][] xArr;
private static int g =2;

public void printArray(int[][] xArray)
{

  for(int r=0; r<xArray.length; r++){
  System.out.println("");
     for(int c=0; c<xArray[r].length; c++)
        if(xArray[r][c]==0)
           System.out.print("\t");
        else
           System.out.print(xArray[r][c]+"\t");}

}

public int[][] getTri()
{
return xArr;}

public void pTriangle(int r)
{
  int n=r;
  xArr = new int[r][2*r-1];
  xArr[0][r-1]=(1);
  p2T(r, 1);
  printArray(xArr);
}

private void p2T(int r, int n)
{
  int z=0;

  int p=r-g;

    xArr[n][p]=(1);

  for(int fd=0; fd<xArr[0].length-1; fd++){
  if(fd==0)
     xArr[n][fd]= xArr[n-1][0]+xArr[n-1][1];
  else
     xArr[n][fd]= xArr[n-1][fd-1] + xArr[n-1][fd+1];

     xArr[r-1][2*r-2]=1;

  }

  g++;
  if(n<r-1)
  {
     p2T(r,n+1);
  }
 // else
 // {return;}

}

public static void main(String [] args)
{
  PascalTriangleYar tri = new PascalTriangleYar();
  Scanner inputReader = new Scanner(System.in);
  System.out.println("Enter a number (x). A pascal's triangle of x rows will be printed.");
  int x = inputReader.nextInt();
  tri.pTriangle(x);
}
}

Bugs

The variables xArr and g shouldn't be static.
The consequence of them being static is that you cannot use this class twice,
because the static state is not reset per instance.
For example this will cause an ArrayIndexOutOfBoundsException:

new PascalTriangleYar().pTriangle(3);
new PascalTriangleYar().pTriangle(4);

You can fix that by making g non-static.
But you should also make xArr non-static too,
because quite simply, it doesn't need to be static,
and there's no reason whatsoever to make it static.

Condensing the code

Condense code doesn't sound great.
It makes me imagine code with no vertical spaces and no spacing around operators.
That's condense. And that's no good.
Maybe you're looking for a different term.
Maybe want to DRY this up, reducing duplication,
and increasing reusability and modularity.

There's one thing useful to do for "condensing",
is removing unnecessary elements:

The getTri method is unused
The n variable in pTriangle is unused
The z variable in p2T is unused

Another thing for condensing is removing some excessive vertical space.
That is, one blank line between methods is enough,
and there shouldn't be blank lines before the closing braces } of code blocks.

Code duplication

Look very suspiciously at code like this:

xArr[n][p] = 1;

for (int fd = 0; fd < xArr[0].length - 1; fd++) {
    if (fd == 0)
        xArr[n][fd] = xArr[n - 1][0] + xArr[n - 1][1];
    else
        xArr[n][fd] = xArr[n - 1][fd - 1] + xArr[n - 1][fd + 1];

    xArr[r - 1][2 * r - 2] = 1;
}

Notice the duplication in the if-else branches.
Something is fishy there.
What's so special about the fd == 0 case?
On closer look, the case of fd == 0 is already taken care of,
by the xArr[n][p] = 1; statement earlier.
You can change the initialization step of the for loop to int fd = 1,
and the if-else can go away:

for (int fd = 1; fd < xArr[0].length - 1; fd++) {
    xArr[n][fd] = xArr[n - 1][fd - 1] + xArr[n - 1][fd + 1];
    xArr[r - 1][2 * r - 2] = 1;
}

Coding style

As @Hosch already covered many coding style issues I shouldn't repeat that,
but they are actually so important that I want to reemphasize:
please do everything that he suggested,
it will make a huge difference in the readability of your code.
Note that you don't actually have to manually make those corrections by yourself,
any decent IDE (Eclipse, Netbeans, IntelliJ) has shortcuts to do at least most of it for you at the touch of a few keystrokes.

In addition, prefer to use for-each loops instead of counting loops whenever possible. For example printArray can be rewritten as:

public void printArray(int[][] xArray) {
    for (int[] row : xArray) {
        System.out.println();
        for (int item : row) {
            if (item != 0) {
                System.out.print(item);
            }
            System.out.print("\t");
        }
    }
}

Notice some other improvements there:

Flipped the item == 0 condition to avoid duplicating System.out.print("\t")
No need for the "" in System.out.println("")

Thread safety, robustness

The code as it is, is very fragile.
This is because of the member fields g and xArr.
These fields give instance of your class a state,
and if the pTriangle method gets called by multiple threads at the same time,
they can break each other.

It's ok to have state and have thread-unsafe code when necessary.
But in this program it's not necessary.
You can completely eliminate the g and xArr member fields,
and pass them around as parameters to the methods that need them.
In fact, you don't need g at all, because its value is always n + 1,
so you can always derive it from n.

With these tips, the code can be rewritten as:

public void pTriangle(int r) {
    int[][] xArr = new int[r][2 * r - 1];
    xArr[0][r - 1] = 1;
    p2T(xArr, r, 1);
    printArray(xArr);
}

private void p2T(int[][] xArr, int r, int n) {
    int p = r - n - 1;

    xArr[n][p] = 1;

    for (int fd = 1; fd < xArr[0].length - 1; fd++) {
        xArr[n][fd] = xArr[n - 1][fd - 1] + xArr[n - 1][fd + 1];
        xArr[r - 1][2 * r - 2] = 1;
    }

    if (n < r - 1) {
        p2T(xArr, r, n + 1);
    }
}


Creating a generic notification service I'm trying to create a generic notification service that works with

Mail (smtp )
Sms (Third part vendor)
Push events (For future)

  Purpose : Create a notification service and it should be pluggable

A Common interface for all notification service

public interface INotificationService
{
    bool Notify();
}

Mail Service

public class MailService : INotificationService
{
    readonly string address;
    readonly string subject;
    readonly string message;

    public MailService(string adrss, string subject, string mesg)
    {
        this.address = adrss;
        this.subject = subject;
        this.message = mesg;
    }

    public bool Notify()
    {
        //pseudo code
        Console.WriteLine("Email service invoked " + address + subject + message);
        return true;

    }
}

Sms Service

public class SmsService : INotificationService
{
    readonly string phoneNumber;
    readonly string message;
    readonly ISmsSender sender;
    public SmsService(string phone, string msg, ISmsSender send)
    {
        this.phoneNumber = phone;
        this.message = msg;
        this.sender = send;
    }

    public bool Notify()
    {
        Console.WriteLine("Sms service invoked" + phoneNumber, message);
        return sender.SendSms(message);

    }
}

ISms Sender interface Mocking third party sms service

public interface ISmsSender
{
    bool SendSms(string msg);
}

public class SmsSender : ISmsSender
{
    public bool SendSms(string msg)
    {
        return true;
    }
}

Consuming program

 INotificationService smsNotification = new
                                       SmsService("12346789", "content" ,new SmsSender());
smsNotification.Notify();

INotificationService mailNotification =
                                   new MailService("mail@gmail.com", "subject", "content");
mailNotification.Notify();

Please find the source code and have added couple of unit test here

Questions

Is it a good design or Any better design
Based on the code coverage still 42% are not covered.
Passing all necessary arguments in the constructor have any impact on maintainability

In general I'd say it's a good design. You use dependency injection and provide all required parameters via the constructor. You also use an abstraction (interface) for the service but... it's not very useful.

Why do you need an INotificationService? To be able to send notifications without knowing how they are going to be sent. You receive a notification-service and want to call the Notify method to send a notification. But do you want to repeatedly send the same notification? I don't think so. Thus the Notify method should probably require a message that you want to send.

I can imagine that such a service would have this API. You don't return bool but nothing if it worked and throw an exception if it didn't. If you don't throw exceptions then the user cannot know what went wrong if a service wasn't able to send a notification.

public interface INotificationService
{
    void Notify(string subject, string message);
}

Not all services may support a subject but a subject and a message are the two properties that actually every notification has.

Now the mail-service needs only the address (don't abbreviate names like adress):

public class MailService : INotificationService
{
    readonly string _address;

    public MailService(string address)
    {
        _address = address;
    }

    public void Notify(string subject, string message)
    {
        // send notification
    }
}

The sms-service requires only the phone number and the sms-sender:

public class SmsService : INotificationService
{
    readonly string _phoneNumber;
    readonly ISmsSender sender;
    public SmsService(string phone, ISmsSender sender)
    {
        _PhoneNumber = phone;
        _sender = sender;
    }

    public void Notify(string subject, string message)
    {
        // send notification
    }
}

var smsNotification = new SmsService("12346789", "content" ,new SmsSender());

You shouldn't mix the vocabulary. If you create a SmsService then the instance is a smsService and not a smsNotification although in this case it is technically a notification because it can only send a single message over and over again. If this is the desired behavior then you shouldn't call it an INotificationService but an INotification. The names need to be clear otherwise the usage of your API is very confusing.

Ok, with the new design both services can still send messages but you can send a new message each time instead creating a new instance just to send a new message - so they are now real notification-services and not just notifications.

var smsService = new SmsService("12346789", new SmsSender());
smsService.Notify("Test1", "This is a message");
smsService.Notify("Test2", "This is another message");


Static Methods for Dealing with Conversions from and to UTC I asked this question over at stackoverflow but was told it may be better suited here.

So I absolutely want to store DateTimeOffset objects in UTC format. To achieve the correct conversions, I've created my own methods to deal with the conversions.

/// String representation of the specified time zone.
        private const String LOCAL_TIME_ZONE_STRING_REPRESENTATION = "GMT Standard Time";
        /// TimeZoneInfo representation of the specified time zone.
        private static TimeZoneInfo LOCAL_TIME_ZONE = TimeZoneInfo.FindSystemTimeZoneById(LOCAL_TIME_ZONE_STRING_REPRESENTATION);

        /// With a given DateTime, passed DateTime is assumed it has been parsed and shares the same time zone as TimeZoneInfo LOCAL_TIME_ZONE.
        /// <param name="dateAndTime">DateTime in TimeZoneInfo LOCAL_TIME_ZONE.</param>
        /// <returns>UTC DateTime.</returns>
        public static DateTime ConvertToUtcDateTime(DateTime dateAndTime)
        {
            return TimeZoneInfo.ConvertTime(dateAndTime, LOCAL_TIME_ZONE).ToUniversalTime();
        }
        /// With a given DateTime, the DateTime is assumed to be a UTC time. It will then return a DateTime converted to TimeZoneInfo LOCAL_TIME_ZONE.
        /// <param name="dateAndTime">DateTime that is in UTC.</param>
        /// <returns>Converted to TimeZoneInfo LOCAL_TIME_ZONE DateTime.</returns>
        public static DateTime ConvertToLocalDateTime(DateTime dateAndTime)
        {
            return TimeZoneInfo.ConvertTimeFromUtc(dateAndTime, LOCAL_TIME_ZONE);
        }

Using the String constant LOCAL_TIME_ZONE_STRING_REPRESENTATION, any user who wishes to compile the code can specify which time zone they want the code to run in, rather than it try to use Window's local time zone.

Then the two above methods can be used to make a conversion between between the two:

private static void Main()
        {
            //Parse a date and time. It is to be assumed this parsed date and time is in the same time zone
            // as LOCAL_TIME_ZONE.
            DateTimeOffset dateTime = ConvertToUtcDateTime(new DateTime(2019,6,1,15,30,0));

            //Assuming we have retrieved a date and time that is in UTC time, we can now convert it
            // to the same time zone as LOCAL_TIME_ZONE.
            DateTime convertedFromUTC = ConvertToLocalDateTime(dateTime.DateTime);
}

The system would be able to parse DateTime's that have no time zone associated with them regardless where they would've came from, and convert them into UTC time assuming that DateTime came from the same TimeZone as LOCAL_TIME_ZONE. The only time where we would need to convert retrieved UTC DateTimes back into the same time zone as LOCAL_TIME_ZONE would be when we are visually displaying it to a user. All TimeSpan calculations etc, would use the UTC DateTimeOffset.

This seems to work as intended, and I can change LOCAL_TIME_ZONE_STRING_REPRESENTATION to any time zone I want, and using the methods I created, the system uses that time zone instead of Window's local time zone.

This would be particularly useful for me as the server hosting an application may be in a different time zone and have a different culture, but its intended users could be for a totally different time zone.

Am I making too much work for myself, or would this be a reasonable way to implement what I need?

Using the String constant LOCAL_TIME_ZONE_STRING_REPRESENTATION, any user who wishes to compile the code can specify which time zone they want the code to run in, rather than it try to use Window's local time zone.

I think this is not the right way to provide flexibility. Lets say you sell your application to three different customers that want three different LOCAL_TIME_ZONE, then you'll have to compile the application three times. Do yourself the favor and place this as a setting in a configuration file or database. And what if the application is to be used world wide by a global customer? Do you plan to use the same time zone in all their offices?

    public static DateTime ConvertToUtcDateTime(DateTime dateAndTime)
    {
        return TimeZoneInfo.ConvertTime(dateAndTime, LOCAL_TIME_ZONE).ToUniversalTime();
    }

I don't think this is working correctly:

A DateTime object can either represent a local time which is always regarded as  local according to the system settings or a UTC time if created with kind = DateTimeKind.Utc - seen from the DateTime api.

Let say LOCAL_TIME_ZONE_STRING_REPRESENTATION = "GMT Standard Time"; and the system time zone = "Romance Standard Time" (+01.00).

Because TimeZoneInfo.ConvertTime(dateAndTime, LOCAL_TIME_ZONE) converts from local time (Romance Standard Time), it converts

DateTime inputDate = new DateTime(2019, 3, 1, 15, 30, 0);

to

01-03-2019 14:30:00

and the call to ToUniversalTime() converts it further to:

01-03-2019 13:30:00

because this too anticipate the DateTime object to be in local time, which is "Romance Standard Time" and not "GMT Standard Time".

But if you - as you write in the explanation to the method - expect the input date time object to be in LOCAL_TIME_ZONE, no change should occur, because GMT = UTC.

To do it correctly I'll suggest this approach if the input DateTime object is still expected to be in LOCAL_TIME_ZONE:

public static DateTime ConvertToUtcDateTime(DateTime dateAndTime)
{
  return TimeZoneInfo.ConvertTimeToUtc(dateAndTime, LOCAL_TIME_ZONE);
}

That said, if I were you, I would reconsider the whole setup thoroughly before using it in a larger scale. Dates, Times and globalization in general is rather complicated, so do yourself the favor to read and test a lot before taking a concept into use that is not just relying on the system. A place to start reading could be here.


Finding consecutive primes matching p, p + 4, p + 6, p + 10, p + 12, p + 16 Someone asked about this question on the main StackOverflow. The full question is:

  Given a value N, find p such that all of [p, p + 4, p + 6, p + 10, p + 12, p + 16] are prime.

  The sum of [p, p + 4, p + 6, p + 10, p + 12, p + 16] should be at least N.

My thinking is:

Sieve all primes under N
Ignore primes below (N-48)/6
Create consecutive slices of length 6 for the remaining primes.
Check if the slice matches the pattern.

Here's my solution. I'd appreciate some feedback.

from itertools import dropwhile, islice
def get_solutions(n):
    grid = [None for _ in range(n+1)]
    i = 2
    while i < n+1:
        if grid[i] is None:
            grid[i] = True
            for p in range(2*i, n+1, i):
                grid[p] = False
        else:
            i += 1
    sieve = (index for index, b in enumerate(grid) if b)
    min_value = (n - 48) / 6
    reduced_sieve = dropwhile(lambda v: v < min_value, sieve)
    reference_slice = list(islice(reduced_sieve, 6))
    while True:
        try:
            ref = reference_slice[0]
            differences = [v - ref for v in reference_slice[1:]]
            if differences == [4, 6, 10, 12, 16]:
                yield reference_slice
            reference_slice = reference_slice[1:] + [next(reduced_sieve)]
        except StopIteration:
            break

n = 2000000

print(next(get_solutions(n)))

# or for all solutions
for solution in get_solutions(n):
    print(solution)

Overall, good first question!
The first obvious improvement is to factor out the code that generates the primes

def prime_sieve(n):
    grid = [None for _ in range(n+1)]
    i = 2
    while i < n+1:
        if grid[i] is None:
            grid[i] = True
            for p in range(i*i, n+1, i):
                grid[p] = False
        else:
            i += 1
    return (index for index, b in enumerate(grid) if b)

Note that for p in range(i*i, n+1, i): starts later than the for p in range(2*i, n+1, i): which you used. This is safe because anything less than the current prime squared will have already been crossed out. This difference alone makes the code about 2x faster for n = 4000000.

By separating the sieve, it makes things like profiling much easier, and you can see that most of the time this method takes is still in the sieve. Using some tricks from Find primes using Sieve of Eratosthenes with Python, we can focus our efforts on speeding this part up.

def prime_sieve(n):
    is_prime = [False] * 2 + [True] * (n - 1)
    for i in range(int(n**0.5 + 1.5)): # stop at ``sqrt(limit)``
        if is_prime[i]:
            is_prime[i*i::i] = [False] * ((n - i*i)//i + 1)
    return (i for i, prime in enumerate(is_prime) if prime)

This prime sieve works pretty similarly, but is shorter, and about 4x faster. If that isn't enough, numpy and https://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n/3035188#3035188 can come to the rescue with this beauty which is another 12x faster.

import numpy
def prime_sieve(n):
    """ Input n>=6, Returns a array of primes, 2 <= p < n """
    sieve = numpy.ones(n//3 + (n%6==2), dtype=numpy.bool)
    for i in range(1,int(n**0.5)//3+1):
        if sieve[i]:
            k=3*i+1|1
            sieve[       k*k//3     ::2*k] = False
            sieve[k*(k-2*(i&1)+4)//3::2*k] = False
    return numpy.r_[2,3,((3*numpy.nonzero(sieve)[0][1:]+1)|1)]

At this point, further speedup would need to come from fancy number theory, but I'll leave that for someone else.


Finding an increasing sequence from a given array in a time-efficient manner in Python Problem Statement:

  Given a sequence of integers as an array, we have to determine whether
  it is possible to obtain a strictly increasing sequence by removing no
  more than one element from the array.

  Example

  For sequence = [1, 3, 2, 1], the output should be
  almostIncreasingSequence(sequence) = false;

  Since there is no one element in this array that can be removed in
  order to get a strictly increasing sequence.

  For sequence = [1, 3, 2], the output should be
  almostIncreasingSequence(sequence) = true.

  You can remove 3 from the array to get the strictly increasing
  sequence [1, 2]. Alternately, you can remove 2 to get the strictly
  increasing sequence [1, 3].

I have formulated a solution for this which is as follows:

def almostIncreasingSequence(sequence):
    j=0
    k=0
    i=1
    m=1
    jflag=0
    kflag=0

    dupsequence = list(sequence)

    while i < len(sequence):
        difference = sequence[i]-sequence[i-1]
        if (difference) <= 0:
            j = j+1
            del sequence[i]
            i = 0
            if j > 1:
               jflag = 1
               break

        i = i + 1

    while m < len(dupsequence):
        if (dupsequence[m]-dupsequence[m-1]) <= 0:
            k = k+1
            del dupsequence[m-1]
            m = 0
            if k > 1:
                kflag = 1
                break

        m = m + 1

    if kflag == 0 or jflag == 0:
        return True

    if jflag ==1 and kflag==1:
        return False

It is working and when I try to run the above code on the stress tests provided in this link, especially the test: 26 is taking 167 milliseconds.

I tried to profile using this piece of code:

def timex():
    return time()*1000

def main():
    starttime = timex()
    almostIncreasingSequence(sequence)
    endtime = timex()
    print 'timetaken to execute is %d milliseconds' %(endtime-starttime)

if __name__ == '__main__':
    main()

  timetaken to execute is 167 milliseconds

I'm asking for a more performance and resource efficient implementation. I'm also an amateur in Python.

I have done this challange before and I quite liked it, now let's dive in teh codez...

Review of your code:

First of all those 2 while loops look kind of silly, and that is what is giving you your TLE's, if you wanted to improve the timing on your code, I would start there.

This should be possible with a 1 loop, now when for instance you look at the last test... one of the last elements needs to be changed. You change it, and it works... but then you loop through the entire array again i = 0 means we start checking from beginning which is not needed. And after that you check the array yet again but this time delete another part and loop through it again! After your second loop finishes you check the outcome and that is a little too late.

I would use 1 loop, to check where the array is not strictly
increasing, afterwards remove at 2 different possitions (with list
comprehension) and check if those are strictly increasing.
Or don't start at position 0 if you found a not increasing bit

Some other PEP8 improvements

Missing whitespace around operator i=0 should be i = 0
if var == False: could be rewritten as if not var:
if var == True and var2 == True: could be rewritten as if var and var2:

A better way of handling this, I explain below

Alternative:

Let's break down the problem statement:

  Given a sequence of integers as an array, we have to determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.

Which means our algorithm should be doing 2 things:

Checking if a list is increasing sequence
Removing item in list and check again

Ok first make a function to check if a list is in a sequence and if not return the first element where it is not strictly increasing

def check_increasing(seq):
    # This will check if it is increasing:
    # If it is return -1 else return the element at which is it not increasing
    for i in range(len(seq)-1):
        if seq[i] >= seq[i+1]:
            return i
    return -1

Well this is part 1 of the problem statement, Part 2 becomes simple if we re-use this function.

def almostIncreasingSequence(sequence):
    check = check_increasing(sequence)
    # List is increasing
    if check == -1:
        return True

We need to remove at most one element from the list, so if it is already strictly increasing we can return true, since no element has to be removed

If it is not we will continou, what are the possibilites from here?

If we delete earlier element, it becomes sctrictly increasing
If we delete later element, it becomes strictly increasing
If both are untrue,  we now that more than 1 element must be changed to form a strictly increasing sequence

Which in code translates to:

# Check if removing an item will make a strictly increasing list
if check_increasing(sequence[check-1:check] + sequence[check+1:]) == -1 or
   check_increasing(sequence[check:check+1] + sequence[check+2:]) == -1:
    return True
# If not return False, since more than 1 element needs to be removed
return False

Making our final code like this

def check_increasing(seq):
    # This will check if it is increasing:
    # If it is return -1 else return the element at which is it not increasing
    for i in range(len(seq)-1):
        if seq[i] >= seq[i+1]:
            return i
    return -1

def almostIncreasingSequence(sequence):
    check = check_increasing(sequence)
    # List is increasing
    if check == -1:
        return True
    # Check if removing an item will make a strictly increasing list
    if check_increasing(sequence[check-1:check] + sequence[check+1:]) == -1 or check_increasing(sequence[check:check+1] + sequence[check+2:]) == -1:
        return True
    # If not return False, since more than 1 element needs to be removed
    return False

Edit

Sorry but that test keeps breaking my IDLE,
But here proof... no TLE on CodeFights:


Square root approximations, implemented two ways Which version is more efficient in calculating the square root ?

There are 2 versions I have written to calculate square root programatically. Note reqs strictly state not using library functions ?

This is puzzling, the first method takes one extra iteration over the 2nd one but returns the more accurate answer of 3.00.

Why does it take an extra iteration ?

So, which one is more efficient ?
Do you find any bugs in this code ?
When will it overflow ?
Do both approaches seem logical, one is trying to calculate the difference between square of approximation and actual number, whereas other trying to bisect the interval. Would you pick one over the other ?

public void squareRoot()
{
    double n = 9;
    double epsilon = 0.001;
    double guess = n*n;
    double low = 0;
    double high = n;
    int cnt=0;
    while(Math.abs(guess*guess-n)>epsilon)
    {
         guess = (low + high)/2;
        if(guess*guess>n)
            high = guess;
        else
            low = guess;
        cnt+=1;
        System.out.println("Low:"+low+"high:"+high+"guess:"+guess+"cnt:"+cnt);
    }

    if(guess*guess-n<epsilon)
    {
        System.out.println("The square root is:"+guess);
    }
}

public void anotherSquareRoot()
{
    double n = 9;
    double epsilon = 0.001;
    double guess = n*n;
    double low = 0;
    double high = n;
    int cnt=0;
    while(high-low>epsilon)
    {
         guess = (low + high)/2;
        if(guess*guess>n)
            high = guess;
        else
            low = guess;
        cnt+=1;
        System.out.println("Low:"+low+"high:"+high+"guess:"+guess+"cnt:"+cnt);
    }

    if(guess*guess-n<epsilon)
    {
        System.out.println("The square root is:"+guess);
    }
}

In version 1, you are testing the difference of the square is within 0.001.

The square root of 9.001 is 3.000167

In version 2, you are testing the difference of the square root part. When you square it, the error becomes bigger.

The square of 3.001 is 9.006001

One error:

You need to get rid of the

if(guess*guess-n<epsilon)

at the end of version 2, it will not print for positive differences > 0.001 e.g. for 3.001 9.006001 is 0.00601 bigger.


Search in a big dictionary Python I have a big Python dictionary with more then 150,000 keys every key has list value. This dictionary contains infinitive words as key and all grammatical forms of these words as values:

 {"конфузити": ["конфузить", "конфужу", "конфузиш", "конфузить", "конфузим", "конфузимо", "конфузите", "конфузять", "конфузитиму", "конфузитимеш", "конфузитиме", "конфузитимем", "конфузитимемо", "конфузитимете", "конфузитимуть", "конфузив", "конфузила", "конфузило", "конфузили"]}

I formed list of words from particular text there are  more then 2m words in it, every word has it's grammatical form. So what I am trying to do is searching  these words in my dictionary values and returning dictionary keys, which as I have already told, are base or dictionary forms of words. This process is called lemmatization. Have tried different approaches but they are all too slow.

In this part I perform text tokenization.

lst =[]
with open("/home/yan/PycharmProjects/vk/my_patrioty/men_patrioty.txt", 'r', encoding="utf-8") as f:
    for sent in f:
        sent = sent.lower()
        sent = re.sub("[A-z0-9\'\"`\|\/\+\#\,\)\(\?\!\B\-\:\=\;\.\«\»\—\@]", '', sent)
        sent = re.findall('\w+', sent)
        for word in sent:
            lst.append(word)

In this part I am trying to perform binary search but is very slow.

with open("/home/yan/data.txt") as f:
    d = json.load(f)
    for w in lst:   #list of my words
        for key, value in d.items():
            lb = 0
            ub = len(value)
            mid_index = (lb + ub) // 2
            item_at_mid = value[mid_index]
            if item_at_mid == w:
                    print(key)
            if item_at_mid < w:
                    lb = mid_index + 1
            else:
                ub = mid_index

This is liner search it is a bit faster. But still not enough fast for my amount of data.

with open("/home/yan/data.txt") as f:
    d = json.load(f)  #dictionary to search in
    for w in lst:
        for key, value in d.items():
              if w in value:
                  print(key)

Below you can find links to my dictionary and sample of data to test it. If somebody does not know it is Ukrainian language that is presented in data set.

Dictionary data:

https://drive.google.com/file/d/0ByIY5scTeLYqbXp6OExKa0xXbDg/view?usp=sharing

Sample of text:

https://drive.google.com/file/d/0ByIY5scTeLYqMHhHbUJ5aXRWdWs/view?usp=sharing

I'd suggest turning the problem around. A dictionary is really good for looking up the key, but not for finding a key for a specific value.

First, you need to convert your dictionary to a dictionary in reverse:

with open("/home/yan/data.txt") as f:
    kv_dict = json.load(f)

vk_dict = {}
for k, vs in kv_dict.items():
    for v in vs:
        vk_dict.setdefault(v, []).append(k)

with open("/home/yan/data_rev.txt", "w") as f:
    json.dump(vk_dict, f)

Then, in your code, you can just write

with open("/home/yan/data_rev.txt") as f:
    d = json.load(f)

for w in list:
    for k in d.get(w, [])
        print(k)

The advantage: building data_rev.txt only needs to be done when data.txt changes, which is hopefully not that often.


N-Queens Problem in Java I have a version of the N-Queens problem in Java. I have function that returns the column placement for each row. And another function that takes that and translates it to a board with '.' representing blanks and 'Q' representing the queens. I was hoping to get an opinion on this.

public class Solution {
    public List<List<String>> solveNQueens(int n) {
        List<Deque<Integer>> result = this.nQueens(n);
        //String[] board = new String[n];
        //Arrays.fill(board, defaultRow);
        List<List<String>> resultAsStr = new ArrayList<List<String>>();
        for (Deque<Integer> variation: result){
            String[] board = new String[n];
            Integer[] temp = variation.toArray(new Integer[0]);
            for (int row=0;row<variation.size();++row){
                char[] currRow = new char[n];
                Arrays.fill(currRow, '.');
                Integer col = temp[row];
                currRow[col] = 'Q';
                board[row] = new String(currRow);
            }
            resultAsStr.add(new ArrayList<String>(Arrays.asList(board)));
        }

        return resultAsStr;

    }

    private List<Deque<Integer>> nQueens(int n){
        List<Deque<Integer>> result = new ArrayList<Deque<Integer>>();
        Deque<Integer> colPlacement = new ArrayDeque<Integer>();
        this.nQueens(n, 0, colPlacement, result);
        return result;
    }

    private void nQueens(int n, int row, Deque<Integer> colPlacement, List<Deque<Integer>> result){
        if (n==row){
            result.add(new ArrayDeque<Integer>(colPlacement));
        } else {

            for (int col=0;col<n;++col){
                colPlacement.add(col);
                if (this.isValid(colPlacement)){
                    this.nQueens(n, row+1, colPlacement, result);
                }
                colPlacement.pollLast();
            }
        }
    }

    private boolean isValid(Deque<Integer> colPlacement){
        int row_id = colPlacement.size() -1;
        Integer[] colArray = colPlacement.toArray(new Integer[0]);
        for (int i=0;i<row_id;++i){
            int diff = Math.abs(colArray[i] - colArray[row_id]);
            if (diff == 0 || diff == row_id -i){
                return false;
            }
        }
        return true;
    }

}

Like @feersum mentioned in a comment, it's not clear what exactly you return.
I had to go through the entire implementation before I found out. You either need to explain it in a comment, or choose a more intuitive representation. Another thing that might help is the name of your methods (and class).

If for example you had the following method signature:

public class NQueensSolver {
    public static List<char[][]> findAllSolutions(int n){

You expect a list of all the possible boards. Where each board is represented by a grid of char.

Your method SolveNQueens could mean find all solutions, or just find 1. If it's just 1, it might mean you get a list of rows, containing a list of strings, each representing a single cell. The fact that we can interpret the return type like this makes it really confusing what is actually returned.

Your initial idea of using String[] might have worked slightly better even. Since then you could guess that a String is an entire row, and the [] combines the rows into an entire board. Then the List is more easily interpreted as a list of all solutions.

I prefer to decouple finding a solution with how to show it to the user. Since NQueens is a rather small problem, we can just stick with 1 class and have it provide both a method to solve the NQueens and another one to print it. No need to write a specific class to show the solution. (Except if you want to show it graphically for example).

The class will look something like this:

public class NQueensSolver {
    public static SOLUTIONS findAllSolutions(int n) {...}
    public static void printSolutions(SOLUTIONS solutions) {...}
}

The methods are static because we don't keep any state inside the class. All state for a solution is either inside the method or passed in via parameters.

Now let's look at what return type fits for the SOLUTIONS.
I'd say there are 2 ways to look at the problem. Depending on how you look at it you'll use a different representation.

1) You want to find for each cell of the board whether or not it contains a queen.
2) For each row, you want to find in what column the queen is placed.

For case (1) you probably want to represent it by a boolean[][]. Since [][] means a 2D array of cells. And for each cell you say it contains a queen (true) or not (false). Alternatively you could also use a char and represent it with a . or Q like you did.

For case (2) you need a list of numbers. So either List<Integer> or int[]. This means the solution {1,3,0,2} could be printed as:

. Q . .
. . . Q
Q . . .
. . Q .

Since the way you actually solved it was by using the (2) representation, let's go with that.

Because we're putting all solutions in a List I peronally prefer to use List<int[]> over List<List<Integer>>. But both can work.

So now our method becomes:

/**
* Returns a list with all solutions. Each solution is represented by an array of rows.
* Where the number says for that row, in which column the queen is placed.
*/
public static List<int[]> findAllSolutions(int n){...}

Notice how I also put a comment above explaining how the solutions are represented.

Let's look at your main solving method:

private void nQueens(int n, int row, Deque<Integer> colPlacement,
                    List<Deque<Integer>> result){

This in itself works fine, but we're going to have to transform our result to List<int[]. So instead let's try to collect our result in the wanted type from the start.

Same for the colPlacement. This is our partial solution, but we can start by reserving exactly n numbers from the start and change those during the search.

This means our new method signature becomes:

private static void solve(int n, int currentRow, int[] currentSolution,
                          List<int[]> result){ ...}

We also don't really need a separate method to call this.

public static List<int[]> findAllSolutions(int n) {
    List<int[]> resultCollector = new ArrayList<int[]>();
    solve(n, 0, new int[n], resultCollector);
    return resultCollector;
}

A minor things to note here: new int[n] initialises the array to all 0. Otherwise we would have had use the Arrays.fill() like you already did for the .s.

Before we go to the solve(...) implementation, let's first look at the isValid(...) method.

Since we no longer work with Deque the signature is going to change to take an int[] partialSolution instead. But we can't do partialSolution.lenght (instead of deque.size()) anymore to find out what row we want to check. So let's also pass int currentRow as a parameter.

private static boolean isValid(int[] partialSolution, int currentRow){
    for (int i = 0 ; i < currentRow ; i++){
        int diff = Math.abs(partialSolution[i] - partialSolution[currentRow]);
        if (diff == 0 || diff == currentRow-i){
            return false;
        }
    }
    return true;
}

Note that i changed the ++i inside the for to i++. This is what people usually write.

Now let's look at what needs to change in the solve method.

private static void solve(int n, int currentRow, int[] currentSolution,
                          List<int[]> result){
    if(n == currentRow){
        result.add(Arrays.copyOf(currentSolution,n));
        return;
    }

    for(int col=0 ; col < n ; col++){
        currentSolution[currentRow] = col;
        if(isValid(currentSolution, currentRow)){
           solve(n, row+1, currentSolution, result);
        }
    }
}

We still need to make a copy when adding the solution to the result. Only now it's a copy of an array.
I added the return; inside the if, so we don't need the explicit else anymore which saves us a level of indentation.
Instead of adding the new column number to the Deque, we just set it in it's place in the solution array.
And don't forget to also pass the currentRow to the new isValid method call.

All that's left is to write the printSolutions() method so we can actually see the solutions. These are just some simple loops:

public static void printSolutions(List<int[]> solutions){
    for(int[] solution : solutions){
        for(int row = 0; row < solution.length; row++){
            for(int col = 0; col < solution.length; col++){
                if(solution[row]==col){
                    System.out.print("Q ");
                } else {
                    System.out.print(". ");
                }
            }
            System.out.println();
        }
        System.out.println();
        System.out.println();
    }
}

Running this simple main method shows that everthing works (given no copy-paste mistakes):

public static void main(String[] args) throws Exception {
    printSolutions(findAllSolutions(4));
}

. Q . .
. . . Q
Q . . .
. . Q .

. . Q .
Q . . .
. . . Q
. Q . .