Let's start with the good:

You documented your public API!
You used decently descriptive variable names
You somewhat have a test case
Your use of a dictionary is resourceful here. No need for some fancy Node class.
You separated out some of the functionality to make the algorithm easier to reason about (checking if words are 1 edit distance apart)

Here are some things I noticed that perhaps the interviewer did as well:

Your formatting is inconsistent. PEP8 your code (4 space indents, space around operators).
You mix snake_case and camelCase. Python typically prefers snake_case.
You didn't document your internal function (not the end of the world, but it is a nice touch)
You didn't indicate that your internal function was private by prefixing it with a _ (my policy is always if it doesn't have a leading _ it must be documented)
if count == 1: return True else: return False would concern me as an interviewer as it demonstrates that you may not understand boolean expressions. return count == 1 would work. But this additionally would pose another concern for me. Namely, one_letter_difference could be a short circuited function, but you did not implement it this way. I also would name it differently, one_letter_difference doesn't say what it does. Also, this function does not care about current or next words, so don't call them that. We also typically try to avoid indexing in Python. You should use zip here. And not to pile on, but this function is also probably not correct. You should have test cases for it. I believe that dog to doge should be an edit distance of 1 as well. With that in mind:

def _is_one_edit_apart(word_a, word_b):
    if abs(len(word_a) - len(word_b)) > 1:
        # It is impossible for words differing by 2 or more letters in length to
        # be just one edit apart
        return False

    if len(word_a) != len(word_b):
        shorter_word, longer_word = \
            (word_a, word_b) if len(word_a) < len(word_b) else (word_b, word_a)

        if longer_word.startswith(shorter_word) or longer_word.endswith(shorter_word):
            # The shorter word is a prefix or a suffix of the longer and
            # they differ by 1 character in length, so they are 1 edit apart
            return True

    num_edits = 0

    # We know that word_a and word_b are the same length, so zip won't truncate
    for a, b in zip(word_a, word_b):
        if a != b:
            num_edits += 1
            if num_edits > 1:
                return False

    return num_edits == 1

Note that you could also get clever here and make the edits a bit more succinct: num_edits = sum(1 for a, b in zip(word_a, word_b) if a != b). This is up to you. This certainly reads better. The approach above likely performs better because it short circuits (stops when it finds more than 1 edit).

Your graph construction is weird. range(-1, len(words)) seems like it could lead to trouble if you aren't careful. Generally, prefer for word in words. It seems like you add the edges to your graph for the current_word twice as a result of this.
Prefer for word in words to for word in range(len(words)). This may indicate to an interviewer that you don't understand Python iterators or common patterns. This could also be a comprehension (and probably should be a tuple since edges can't change): graph[word] = tuple(other_word for other_word in words if _is_one_edit_apart(word, other_word))
You should probably pull your BFS out into a helper function. It is used in your algorithm. It is not part of your algorithm. This way you can test it separately.
BFS is also probably not the best approach here. Dijkstra's is more suitable because it can find the shortest path between two nodes (we can just assume the edges indicate edit distance and are all cost 1).
queue.append([neighbor, distance +1]) should be a tuple not a list. You aren't going to mutate it. This would likely concern an interviewer.
This is part of the question, but I don't like returning -1 for error. If you forget to handle this, this could lead to a problem (say you try to do math on the distance and assume it's always positive). You should be raising some sort of error. If I was asked to do something this silly, I would probably write my own function that raises and then provide an alternate API for this use case which wraps this function and converts the exception to a -1 out of principle.
unittest your code. Don't just throw a print statement and manually verify! And test all the pieces! This is why you separate out the one edit distance check and the BFS (well, Dijkstra's)

There's another larger problem in my mind, which isn't specified by the question, but it's the kind of question that I'd expect an engineer who encountered this problem to explore: what is the use case? Is this is one off (eg. are we using different word lists with every query)? If the word list is reused, this algorithm is inefficient, because it constructs a graph for each query. If the word list remains the same, then you should build the graph up once and then only do Dijkstra's for each query. I would implement this with a class the encapsulates the built graph and provide external API to query for edit distances. Then you could provide a function that uses this class for a one off query (where the words list is unique--never to be used again) to satisfy this interview question.

There is also an optimization you can make in constructing the graph. It is apparent from my revised _is_one_edit_apart. Namely, words can only be one edit apart if they are the same length or differ in length by only 1 character. So, when building the graph you can take this into account. Take all of the words group them by length. Then to build the part of the graph for length 1 words, you only have to consider length 1 or length 2 words. For length 2 words you have to consider length 1, 2, and 3 words. Etc. You original approach is always O(n^2). This is still worst case O(n^2) but will average much better than this given a decent distribution of word lengths.


The implementation is simple enough to require any comments. Just a few things:

Is LinkedList a requirement? Can't it be done by an ArrayList?
Use Math.min while making the subList.

An alternative for simpler solution
You can add the Guava library to your project and use the Lists.partition method, e.g.

List<Integer> items = ...
List<List<Integer>> subLists= Lists.partition(items, pageSize);


A hash-signature-type which tests on comparing against normal strings

private string _Data;

public String Data
{
    get { return _Data; }
    private set { _Data = value; }
}

You should make this immutable by either declaring _Data as readonly and remove the setter or by having only public readonly string Data;.
In addition you should be consitent with the style you are using. Here you use one time the alias string and one time the String object. Most C# developers use only the alias, but thats a decision for you to make. Once you have made a decision you should stick to your style.

public ProtectedString(String value)
{
    _Data = "";
    _Data = CreateHash(value);
}

the assignment of "" to _Data is only adding noise to the code. Remove it.

because it is a struct the default parameterless constructor needs to be called like so

public ProtectedString(String value)
    :this()
{
    _Data = CreateHash(value);
}

public override bool Equals(object obj)
{
    return base.Equals(obj);
}

This should be changed in way that it is really doing an Equal of the class rather then only calling the base.Equals() like so

public override bool Equals(object obj)
{
    var protectedString = obj as ProtectedString;

    if (protectedString == null) { return false; }

    return _Data.Equals(protectedString.Data);
}

It could be possible that this isn't 100% correct, because I can't test it.

private string CreateHash(String value)
{
    RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();

    byte[] salt = new byte[SALT_BYTE_SIZE];

    csprng.GetBytes(salt);

    byte[] hash = PBKDF2(value, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);

    return
        Convert.ToBase64String(salt) +
        Convert.ToBase64String(hash);
}

RNGCryptoServiceProvider implements through its base class the IDisposable interface hence you should use a using block to proper dispose it. I would extract the generation of the salt to a separate method.

private byte[] GetSalt()
{
    using (RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider())
    {
         byte[] salt = new byte[SALT_BYTE_SIZE];

         csprng.GetBytes(salt)

         return salt;
    }
}

private string CreateHash(String value)
{

    byte[] salt = GetSalt();

    byte[] hash = PBKDF2(value, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);

    return
        Convert.ToBase64String(salt) +
        Convert.ToBase64String(hash);
}

private bool ValidateHash(String value, String validHash)
{
    byte[] full = Convert.FromBase64String(validHash);

    byte[] salt = full.Take(SALT_BYTE_SIZE).ToArray();

    byte[] hash = full.Skip(SALT_BYTE_SIZE).ToArray();

    byte[] testHash = PBKDF2(value, salt, PBKDF2_ITERATIONS, hash.Length);

    return SlowEquals(hash, testHash);
}

here you should replace hash.Length with HASH_BYTE_SIZE as the last parameter of the call to PBKDF2().

private bool SlowEquals(byte[] a, byte[] b)
{
    uint diff = (uint)a.Length ^ (uint)b.Length;

    for (int i = 0; i < a.Length && i < b.Length; i++)
        diff |= (uint)(a[i] ^ b[i]);

    return (diff == 0);
}

You should always use braces {} although they might be optional. Using braces makes your code less error prone which should have top priority for security related stuff.

private byte[] PBKDF2(string value, byte[] salt, int iterations, int outputBytes)
{
    Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(value, salt);

    pbkdf2.IterationCount = iterations;

    return pbkdf2.GetBytes(outputBytes);
}

Rfc2898DeriveBytes is implementing IDispoable through its base class too, hence you should use a using block.

private byte[] PBKDF2(string value, byte[] salt, int iterations, int outputBytes)
{
    using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(value, salt))
    {
        pbkdf2.IterationCount = iterations;

        return pbkdf2.GetBytes(outputBytes);
    }
}


This is a nice, clean implementation of a Linked list... Generally a good job.

You have a bug in your reverse method, a NullPointerException when the list is empty. There is an easy fix, but you should be aware.

I also had a look at your reverse method. I cannot see a way to do it with fewer than 3 variables, while still keeping the logic readable. I am not particularly fond of your implementation... The distinct if/else condition makes the internal logic cumbersome. It makes things easier if you consider the process to be closer to a swap... we want to swap the direction of the pointer between nodes.

So, the logic is, for three nodes A->B->C, we want to make B point to A, but, we have to remember that C comes after B before we reverse the pointer. Then we have to make C point to B, becoming A<-B<-C

But, we have a couple of loose ends (pun is intended)... we have the start pointer which points at A, and A is pointing at B still, So, we need to remove the now-redundant A->B pointer, and also move start to point at C..... All so complicated, but it boils down to a simple loop:

    public void reverse() {
        if (start == null) {
            return;
        }
        Node current = start;
        Node after = start.next;
        while (after != null) {
            Node tmp = after.next; // preserve what will come later.
            after.next = current;  // reverse the pointer
            current = after;       // advance the cursor
            after = tmp;           // the node after is the one preserved earlier.
        }
        start.next = null;         // null-out next on what was the start element
        start = current;           // move the start to what was the end.
    }

This, to me, is much more readable than the conditional logic you had. It does use three pointers in addition to the start.

If you want to, you can probably find a way to do it with one less pointer, but that is by hacking the start pointer and using it as a tracker in the loop (probably instead of current, but the readability, and simplicity will suffer if you do that.

Note also that Java coding convention puts the { open brace at the end of the line containing the conditional block.

Finally, at the risk of adding a little complexity to your code, most general-purpose Linked Lists in 'real' applications have an O (1) mechanism for getting the List size. If you have a custom purpose for the list where the size is not important, you can skip that, but, you should otherwise consider adding a size field so you can avoid doing a full iteration to get the size.

Another Finally, The Java Iterator concept is a very common idiom. It is surprisingly complicated though to get your implementation to match the specification. I strongly recommend that you take it upon yourself to make your List iterable, and to make sure your Iterator implementation conforms to the specification (especially the conditions under which the iterator throws exceptions).

I also extended your main method to do a few more tests than you have:

    public static void main(String args[]) {
        ReverseLL ll=new ReverseLL();
        ll.reverse();
        ll.display();
        System.out.println();

        ll.insert(1);
        ll.reverse();
        ll.display();
        System.out.println();

        ll.insert(2);

        ll.reverse();
        ll.display();
        System.out.println();

        ll.reverse();
        ll.display();
        System.out.println();

        ll.insert(3);
        ll.insert(4);
        ll.insert(5);
        ll.insert(6);
        ll.insert(7);
        ll.insert(8);
        ll.display();
        System.out.println();

        ll.reverse();
        ll.display();
        System.out.println();
    }


Use PascalCase for the method name
Move the calc for years and months lower to be minutely "more efficient"
Use inline return to reduces nesting
Use ternary operator (?:) for simple logic to reduce if/else clutter
Use the format override of ToString(string format) to reduce string concats
Use string.Format with a ternary to reduce duplication

The shorter version I came up with is 40 lines, but you can judge if it readable enough.

    public static string GetTimeSpan(DateTime postDate) {
        string stringy = string.Empty;
        TimeSpan diff = DateTime.Now.Subtract(postDate);
        double days = diff.Days;
        double hours = diff.Hours + days*24;
        double minutes = diff.Minutes + hours*60;
        if (minutes <= 1) {
            return "Just Now";
        }
        double years = Math.Floor(diff.TotalDays/365);
        if (years >= 1) {
            return string.Format("{0} year{1} ago", years, years >= 2 ? "s" : null);
        }
        double weeks = Math.Floor(diff.TotalDays/7);
        if (weeks >= 1) {
            double partOfWeek = days - weeks*7;
            if (partOfWeek > 0) {
                stringy = string.Format(", {0} day{1}", partOfWeek, partOfWeek > 1 ? "s" : null);
            }
            return string.Format("{0} week{1}{2} ago", weeks, weeks >= 2 ? "s" : null, stringy);
        }
        if (days >= 1) {
            double partOfDay = hours - days*24;
            if (partOfDay > 0) {
                stringy = string.Format(", {0} hour{1}", partOfDay, partOfDay > 1 ? "s" : null);
            }
            return string.Format("{0} day{1}{2} ago", days, days >= 2 ? "s" : null, stringy);
        }
        if (hours >= 1) {
            double partOfHour = minutes - hours*60;
            if (partOfHour > 0) {
                stringy = string.Format(", {0} minute{1}", partOfHour, partOfHour > 1 ? "s" : null);
            }
            return string.Format("{0} hour{1}{2} ago", hours, hours >= 2 ? "s" : null, stringy);
        }

        // Only condition left is minutes > 1
        return minutes.ToString("# minutes ago");
    }


Here is a proposal for a different approach that doesn't use a for loop and has some simplifications.

First, an example data frame:

dat <- data.frame(a1 = 9:11, a2 = 2:4, a3 = 3:5,
                  b1 = 4:6, b2 = 5:7, b3 = 1:3)
#   a1 a2 a3 b1 b2 b3
# 1  1  2  3  4  5  6
# 2  2  3  4  5  6  7
# 3  3  4  5  6  7  8

Now, we set the number of columns per group:

# number of columns per group (1-3, 4-6)
n <- 3

Based on this information, some necessary information can be calculated:

# number of groups
n_grp <- ncol(dat) / n
# 2

# column indices (one vector per group)
idx_grp <- split(seq(dat), rep(seq(n_grp), each = n))
# $`1`
# [1] 2 3 4
#
# $`2`
# [1] 5 6 7

In the next step, lapply is used to calculate the row means of each group. This is much more convenient with the rowMeans function.

# calculate the row means for all groups
res <- lapply(idx_grp, function(i) {
    # subset of the data frame
    tmp <- dat[i]
    # calculate row means
    rowMeans(tmp, na.rm = TRUE)
})
# $`1`
# [1] 4.666667 5.666667 6.666667
#
# $`2`
# [1] 3.333333 4.333333 5.333333

The command above returns a list. It can be transformed into a data frame:

# transform list into a data frame
dat2 <- as.data.frame(res)
#         X1       X2
# 1 4.666667 3.333333
# 2 5.666667 4.333333
# 3 6.666667 5.333333

In order to set the column names of the new data frame, we first have to extract the column names of the groups' first columns.

# extract names of first column of each group
names_frst <- names(dat)[sapply(idx_grp, "[", 1)]
# [1] "a1" "b1"

Now, these names are used for the new data frame:

# modify column names of new data frame
names(dat2) <- names_frst
#         a1       b1
# 1 4.666667 3.333333
# 2 5.666667 4.333333
# 3 6.666667 5.333333

Done.


To answer your questions up front:

  Should I bother checking to see if a variable is greater than zero before running the for loop?

No need. The first thing the loop does is the i <= x comparison. And since i starts at 1, there's no need for you to double-check by saying if(x > 0).

  Is there a better way to handle togging the classes? Setting all elements to "off" and then turning "on" the correct lamps seems a little heavy handed.

jQuery's toggleClass() works in a few different ways. One of them accepts a boolean as its 2nd argument, which forces the toggle state: If true, the class name is added (if missing), if false, the class name is removed (if present).

So for instance, you might do this:

lamps.each(function (index) {
  $(this).toggleClass("on", index < count);
});

Where lamps is a set of elements you want to manipulate, and count is the number of lamps that should light up.

I've also flipped the on/off states, so on is the class name you add, while the lamps by default are off. This isn't really important, but considering you call the elements "lamps" (albeit indirectly; they're in divs classed as lamp-rows), it seems ever-so-slightly more natural to me that they default to their off state.

Anyway, the point is that you loop through each "lamp", turning it on or off as needed, instead of turning them all off first.

  Should the tick() function be broken up?

You've got some repetition with the loops and all that, so it'd probably be a good idea to extract the repeated parts. For instance, you could package the each-loop above in a function:

 function updateLamps(lamps, count) { ... }

Then simply pass it a set of elements, and the "lit lamp count".

For this, it might also be worth taking a look at the HTML. Right now, you have IDs for each individual lamp. But that's a tad too specific for my liking, since they're all essentially the same kind of thing. No great need to give them unique IDs.

I'd suggesting IDing the rows instead, and use a selector like #single-hours > .lamp (for instance) to find the lamps, where #single-hours is the ID of the row. This will also allow you to find them once and simply loop through them on each tick, rather than re-finding them each time.

Incidentally, you use a class name selector to find the blinking circle, although that, if anything, should have an ID as it's a unique element.

Another alternative is to build the elements in code, and inject them into the page. The advantage would be that you don't have tight coupling between the markup and the JS (if either changes, the other might well break). The disadvantage is that you now have markup in you JS (while the CSS is still somewhere else). While I'd suggest you try it out, I won't necessarily recommend one approach over the other, when it's just a single page/single feature thing. (If it's instead intended as a widget meant to be added to any kind of page, it's a different story).

Other things:

Instead of Math.floor(clockMinutes - (fiveMinutes * 5)) you can simply use the modulo operator to get the remainder of a division: clockMinutes % 5. Same for singleHours of course.
The line used to update the #display element is exceedingly long and repetitive. Consider making a formatTime function (or similar) to handle the heavy-lifting.
You have classes like rectangle-*, yellow and red which describe appearance much to specifically. What if you decide the hours should be purple triangles? The classes they have now are suddenly misleading. Always aim for class names the describe what something is, not how it looks.
Speaking of semantics, you could consider using ol list elements for the lamps, since they are essentially ordered lists of elements.
The whole $(document).ready(...) thing can be shortened to simply $(startClock);
Lastly, you could consider skipping some steps (loops) entirely. For instance, only if singleMinutes == 0 is there a need to update "five minute" lamps; only if fiveMinutes is zero, do you need to update the "single hour" lamps, etc.. In other words, you only need to update the more "coarse" steps, if the finer-grained ones roll over.

Here's a snippet that incorporates some of the comments above.

function startClock() {
    'use strict';
    var delay = 1000,
        display = $("#display"),
        secondsLamp = $("#seconds-lamp"),
        fiveHourLamps   = $("#five-hour-lamps > div"),
        oneHourLamps    = $("#one-hour-lamps > div"),
        fiveMinuteLamps = $("#five-minute-lamps > div"),
        oneMinuteLamps  = $("#one-minute-lamps > div");

    function toggleLamps(lamps, count) {
      lamps.each(function (index) {
        $(this).toggleClass('off', index >= count);
      });
    }

    function tick() {
        var clockDate = new Date(),
            clockHours = clockDate.getHours(),
            clockMinutes = clockDate.getMinutes(),
            clockSeconds = clockDate.getSeconds(),
            fiveHours = Math.floor(clockHours / 5),
            fiveMinutes = Math.floor(clockMinutes / 5),
            singleHours = clockHours % 5,
            singleMinutes = clockMinutes % 5;

        secondsLamp.toggleClass("off");
        display.text(clockHours + ":" + ((clockMinutes < 10) ? "0" + clockMinutes : clockMinutes) + ":" + ((clockSeconds < 10) ? "0" + clockSeconds : clockSeconds));

        toggleLamps(fiveHourLamps, fiveHours);
        toggleLamps(oneHourLamps, singleHours);
        toggleLamps(fiveMinuteLamps, fiveMinutes);
        toggleLamps(oneMinuteLamps, singleMinutes);

        setTimeout(tick, delay);
    }

    tick();
}

$(startClock);
body {
    background: rgba(0,0,0,0.35);
}

.clock {
    width: 16rem;
    margin: 3em auto 0 auto;
    font-family: sans-serif;
}
.circle {
    width: 5rem;
    height: 5rem;
    border-radius: 50%;
    border: 1rem solid rgba(204, 204, 204, 1);
    margin: 0 auto 0 auto;
}
.lamp-row {
    border-radius: 1rem;
    background: rgba(204, 204, 204, 1);
    display: flex;
    padding: 0.5rem;
    margin: 0.5rem 0 0 0;
}
.rectangle-large, .rectangle-small {
    border-radius: 0.5rem;
    height: 2.5rem;
    box-sizing:border-box;
    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
    margin: 0.1rem;
    display: inline-block;
}
.rectangle-large {
    width: 4rem;
}
.rectangle-small {
    width: 1.45rem;
}
.red {
    background: rgba(255, 0, 0, 1);
}
.red.off {
    background: rgba(255, 0, 0, 0.5);
}
.yellow {
    background: rgba(255, 255, 0, 1);
}
.yellow.off {
    background: rgba(255, 255, 0, 0.4);
}
#display {
    margin-top: 1rem;
    text-align: center;
}


Update UNIX-like system user profile picture with its GitHub account's one

try:
    ...
except Exception:
    raise
else:
    ...

You're not doing anything with the captured exception, so this accomplish nothing more than the code in .... You can drop the try, the code in the else will never execute if there is an exception in the previous two functions anyway.
Depending on the size of the downloaded images, you may also consider streaming the http response to a file directly instead of using the memory as a buffer.


let

If you use let, you ask Kotlin to create an invisible function with a parameter.

1.let { println(5) }
    //changes to:
    fun func(it : Int) {
        println(5)
    }
    func(1)

Do you see the it? That's the name of the parameter.
Therefor, you can use it inside let.

1.let { println(it) }
//changes to
fun func(it : Int) {
    println(it)
}
func(1)

Now, the function returns something too, namely the result of the last statement.
In this case, it's just Unit, or void in Java (emptyNess):

fun func(it : Int) : Unit {
    return println(it)
}
func(1)

If we take another example, it will be clearer:

val a = 5.let { 3 + it }
//changes to
fun func(it: Int) : Int {
     return 3 + it
}
val a = func(5)

?.let

?. is very simple:

val b = a?.foo()
//changes to:
val b = if (a == null) a else a.foo()

?.let is exactly the same:

val b = a?.let { it+3 }
//changes to
fun func(it: Int){
   it + 3
}
val b = if (a == null) null else func(a)

inline

Kotlin is smart. it actually uses an inline function for let.
An inline function is a function that actually doesn't exist.
Instead, the code is copy pasted into the real code.
The parameters are just variables with random names.

so

val b = a?.let { it + 3 }
//is actually changed to
val b = if (a == null) null else {
    val ac432cd = a
    ac432cd + 3
}

simplyfication

roomGrid[gridX][gridY - 1]?.let { room?.setNeighbor(Room.SOUTH, it) }

step 1

// I would check room first:
if (room != null) {
   roomGrid[gridX][gridY - 1]?.let { room.setNeighbor(room.SOUTH, it) }
}

step 2

// flip the rooms (and directions)
if (room != null) {
   roomGrid[gridX][gridY - 1]?.let{ it.setNeighbor(room.SOUTH, room) }
}

step 3

//remove let
if (room != null) {
   roomGrid[gridX][gridY - 1]?.setNeighbor(room.SOUTH, room)
}

full code until now

 // neighbor relations
for (gridY in 0 until roomCountY) {
    for (gridX in 0 until roomCountX) {
        val room = roomGrid[gridX][gridY]
        if (room != null) {
            if (gridY > 0)
                roomGrid[gridX][gridY - 1]?.setNeighbor(Room.NORTH, room)
            if (gridY < roomCountY - 1)
                roomGrid[gridX][gridY + 1]?.setNeighbor(Room.SOUTH, room)
            if (gridX > 0)
                roomGrid[gridX - 1][gridY]?.setNeighbor(Room.EAST, room)
            if (gridX < roomCountX - 1)
                roomGrid[gridX + 1][gridY]?.setNeighbor(Room.WEST, room)
        }
    }
}

step 4

At the moment, we test in the beginning if room isn't null.
If it is, it skips the if-statement and continues with the next iteration.
We can tell to go to the next iteration immediately using the keyword continue.

// neighbor relations
for (gridY in 0 until roomCountY) {
    for (gridX in 0 until roomCountX) {
        val room = roomGrid[gridX][gridY]
        if (room == null) continue
        if (gridY > 0)
            roomGrid[gridX][gridY - 1]?.setNeighbor(Room.NORTH, room)
        ...
    }
}

step 5

last, kotlin has another language feature: ?:

val a = foo() ?: bar()
//will be rewritten to
val tmp = foo()
val a = if (tmp != null) tmp else bar()

Just as return continue skips immediately to the next variable.
This means that we can rewrite the code we wrote in step 4.

// neighbor relations
for (gridY in 0 until roomCountY) {
    for (gridX in 0 until roomCountX) {
        val room = roomGrid[gridX][gridY] ?: continue
        if (gridY > 0)
            roomGrid[gridX][gridY - 1]?.setNeighbor(Room.NORTH, room)
        ...
    }
}

full code

 // neighbor relations
for (gridY in 0 until roomCountY) {
    for (gridX in 0 until roomCountX) {
        val room = roomGrid[gridX][gridY] ?: continue
        if (gridY > 0)
            roomGrid[gridX][gridY - 1]?.setNeighbor(Room.NORTH, room)
        if (gridY < roomCountY - 1)
            roomGrid[gridX][gridY + 1]?.setNeighbor(Room.SOUTH, room)
        if (gridX > 0)
            roomGrid[gridX - 1][gridY]?.setNeighbor(Room.EAST, room)
        if (gridX < roomCountX - 1)
            roomGrid[gridX + 1][gridY]?.setNeighbor(Room.WEST, room)
    }
}


In R this is usually solved using the na.locf (Last Observation Carried Forward) function from the zoo package.

See also here:

Fill in NA based on the last non-NA value for each group in R
Using dplyr window-functions to make trailing values

# test data
x <- read.table(text="id;date
1;23-04
1;23-04
1;NA
1;NA
2;24-04
2;NA
2;NA
2;NA
3;23-04
3;NA
3;NA
3;NA
4;NA
4;NA
4;NA
4;NA", header=TRUE, sep=";")

library("dplyr")
library("zoo")

x %>% group_by(id) %>% transmute(date=na.locf(date, na.rm=FALSE))
Source: local data frame [16 x 2]
Groups: id

   id  date
1   1 23-04
2   1 23-04
3   1 23-04
4   1 23-04
5   2 24-04
6   2 24-04
7   2 24-04
8   2 24-04
9   3 23-04
10  3 23-04
11  3 23-04
12  3 23-04
13  4    NA
14  4    NA
15  4    NA
16  4    NA

Another option are rolling self-joins supported by the data.table package (see here).


That is very idiomatic Haskell code. The only thing I'd mention is that the empty list is a prefix of everything, so your first case should be

isPrefixOf' [] _ = True

With that change, you can remove

  | null xs && x == y = True

since it will be correctly handled by

  | x == y = isPrefixOf' xs ys

As for implementing isSuffixOf in terms of inPrefixOf, you're in good company; that's how Data.List does it.


Looks pretty good to me. You don't need the explicit return as the last statement of your lookup method. Also, in newer versions of Ruby (2.3+ I believe), you don't need the explicit nil check--instead, you can use the Safe Navigation Operator (&.).

  def lookup(lookup_value)
    return self if value.eql? lookup_value
    self.next&.lookup(lookup_value)
  end


Modify singly linked list such that all even numbers appear before odd numbers

There are two different things in your code: an implementation of a single-linked list, and an algorithm to make even numbers appear before odd numbers in a list.

Optimally, those two concerns should be separated. It is easier to do one thing well, so your list should focus on providing data management services (inserting, deleting, data access, memory safety, etc.) and your algorithm should use those services to accomplish its task of reordering elements. If you do so, your list's interface will be more concise and your algorithm more general.

The algorithm you're writing is actually a partitioning algorithm, that is one that puts elements satisfying a predicate before elements that don't. It's used in sorting algorithms for example. You can find the following implementation in the reference:

template<class ForwardIt, class UnaryPredicate>
ForwardIt partition(ForwardIt first, ForwardIt last, UnaryPredicate p)
{
    first = std::find_if_not(first, last, p);
    if (first == last) return first;

    for(ForwardIt i = std::next(first); i != last; ++i){
        if(p(*i)){
            std::iter_swap(i, first);
            ++first;
        }
    }
    return first;
}

You can see from this example implementation that you only need a way to iterate over the elements in your list one after the other, and a way to extract the value at a current position, to make your list interface powerful enough.

The hard but correct way to provide this interface is to provide an iterator class, and two iterator instances, begin and end. Then your list is fully compatible with most STL algorithms (some of them require more powerful iterators than those a single-linked list can expose) and you don't even need to implement the partition algorithm.

The quick and dirty way is to implement the algorithm directly on top of your list's nodes, given that they provide the two necessary functionalities via data and next.

P.S: your exchangeEvenOdd function should return the partition point. It's a valuable information that you have to compute anyway. By the way, the name could be more evocative.


What are the downsides of my Mergesort implementation?

First things first: Why are you returning a new array instead of directly sorting the input array? If we create 2 temporary arrays (left and right part) and then merge them back into the input array we don't need to return a new one (and can optimise later on).

private static void mergesort(int[] input, final int left, final int right) {
    //quick note here, I flipped your if check so we can return earlier.
    //This makes it easier to follow the complete flow
    if (left >= right) {
        return;
    }
    //edge cases handled before this point. Can continue with actual algorithm after.
    final int m = (right - left) / 2 + left;
    mergesort(input, left, m);
    mergesort(input, m + 1, right);

    int[] leftPart = new int[m - left + 1];
    for(int i = 0; i < leftPart.length-1;i++){
        leftPart[i] = input[left + i];
    }
    int[] rightPart = new int[right - m];
    for(int i = 0; i<rightPart.length-1;i++){
        rightPart[i] = input[m + i];
    }

    int i = 0, j = 0;
    while (i < leftPart.length && j < rightPart.length) {
        if (leftPart[i] <= rightPart[j]) {
            input[i + j] = leftPart[i++];
        } else {
            input[i + j] = rightPart[j++];
        }
    }
    while (i < leftPart.length) {
        input[i + j] = leftPart[i++];
    }
    while (j < rightPart.length) {
        input[i + j] = rightPart[j++];
    }
}

Now that we sort the input array directly theres one major memory optimisation we can do. We no longer need to store the right half in a temporary array anymore. Instead we can directly copy from the input array since the "current" spot is always smaller or equal than the index of the right part we're handling.

private static void mergesort(int[] input, final int left, final int right) {
    if (left >= right) {
        return;
    }

    final int m = (right - left) / 2 + left;
    mergesort(input, left, m);
    mergesort(input, m + 1, right);

    int[] leftPart = new int[m - left+1];
    //note: arraycopy is usually more efficient than manually copying an array.
    System.arraycopy(input, left, leftPart, 0, leftPart.length);

    int current = left;
    int currentLeft = 0;
    int currentRight = m+1;

    while (currentLeft < leftPart.length && currentRight <= right) {
        if (leftPart[currentLeft] <= input[currentRight]) {
            input[current++] = leftPart[currentLeft++];
        } else {
            input[current++] = input[currentRight++];
        }
    }
    while (currentLeft < leftPart.length) {
        input[current++] = leftPart[currentLeft++];
    }
    //no need to handle remaining right part, as it's already in the input array
}

Some extra notes:

I renamed some variables to make it more clear what they mean. Even though i and j are common enough for a simple loop, it wasn't obvious enough anymore once the right index started from halfway the part of the array that needed to be sorted.

I made the method static. It doesn't depend on any state of the class it's in so could be put into a more general utility class instead.

System.arraycopy is more performant than manually copying all elements into another array.


I would favor the first category approach, as it takes benefit of a great Objective-C feature: extend existing classes with new methods.

On the other hand probably both ways will fail if it comes to more advanced characters, like surrogate pairs, base characters plus combining marks, Hangul jamo, and Indic consonant clusters.

So here is my Category implementation:

@interface NSString (Split)
-(NSArray *)arrayBySplittingWithMaximumSize:(NSUInteger)size;
@end

@implementation NSString (Split)

-(NSArray *)arrayBySplittingWithMaximumSize:(NSUInteger)size
{
    NSMutableArray *letterArray = [NSMutableArray array];
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                                options:(NSStringEnumerationByComposedCharacterSequences)
                             usingBlock:^(NSString *substring,
                                          NSRange substringRange,
                                          NSRange enclosingRange,
                                          BOOL *stop) {
                                 [letterArray addObject:substring];
                             }];

    NSMutableArray *array = [NSMutableArray array];
    [letterArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (idx%size == 0) {
            [array addObject: [NSMutableString stringWithCapacity:size]];
        }
        NSMutableString *string = [array objectAtIndex:[array count]-1];
        [string appendString:obj];

    }];

    return array;
}

use it like:

NSArray *arraysWith9Letters = [letters arraysBySplittingWithMaximumSize:9];

This approach could be easily extended to split by words, sentences, lines too

@interface NSString (Split)
-(NSArray *)arrayBySplittingWithMaximumSize:(NSUInteger)size
                                     options:(NSStringEnumerationOptions) option;
@end

@implementation NSString (Split)

-(NSArray *)arrayBySplittingWithMaximumSize:(NSUInteger)size
                                     options:(NSStringEnumerationOptions) option
{
    NSMutableArray *letterArray = [NSMutableArray array];
    [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                                options:(option)
                             usingBlock:^(NSString *substring,
                                          NSRange substringRange,
                                          NSRange enclosingRange,
                                          BOOL *stop) {
                                 [letterArray addObject:substring];
                             }];

    NSMutableArray *array = [NSMutableArray array];
    [letterArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (idx%size == 0) {
            [array addObject: [NSMutableString stringWithCapacity:size]];
        }
        NSMutableString *string = [array objectAtIndex:[array count]-1];
        [string appendString:obj];

    }];

    return array;
}

Now use it like

NSString *letters = @"ABCDEFकट्रತ್ಯÖäüℝijgrvਉਤਸੁਕsasas";
NSArray *arraysWith9Letters = [letters arraysBySplittingWithMaximumSize:9 options:NSStringEnumerationByComposedCharacterSequences] ;
NSLog(@"%@", arraysWith9Letters);

NSString *lorem = @"Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam";
NSArray *loremArray = [lorem arraysBySplittingWithMaximumSize:9 options:NSStringEnumerationByWords];
NSLog(@"%@", loremArray);


First thing is that you should limit the degree of parallelism, to ex: 4 threads

Parallel.ForEach(
    listOfWebpages,
    new ParallelOptions { MaxDegreeOfParallelism = 4 },
    webpage => { Download(webpage); }
);

Without this, you are going to DDoS your service or resource you are using.

You seem to be using Project Orleans and AFAIK a grain should be a single threaded container. You should be able to do just:

private void ParallelDealUserList(IEnumerable<string> list)
{
    foreach(var item in list)
        GrainClient
            .GrainFactory
            .GetGrain<IUser>(item.id.ToGuid())
            .DoProcessInterestAsync(true);
}

I am not all that familiar with Project Orleans. Most likely this can be used, but I would use microservices (aka SOA2) instead.


Initialization of Extended class without too much overhead?

Those lines are managing the properties of A, so they belong in A.  I've added a protected copy constructor and used constructor chaining to solve your issue:

public class A
{
  public int [] prop1 ;
  public string prop2 ;
  public string prop3 ;

  public A() {}

  protected A(A a)  //copy constructor
  {
    this.prop1 = a.prop1 ;  //review: should this reference be copied, or a new copy made?
    this.prop2 = a.prop2 ;
    this.prop3 = a.prop3 ;
  }
}

public class B : A
{
  public Dictionary <int, int> prop4 ;

  public B (int [] keys, A a) : base(a)  //constructor chaining
  {
    prop4 = new Dictionary <int, int> () ;
    if (keys.Length == a.prop1.Length )
    {
      for (int i = 0 ; i < keys.Length ; i++ )
      {
        prop4.Add (keys[i], a.prop1[i]) ;
      }
    }
    else
    {
      throw new Exception ("something wrong") ;
    }
  }
}


Dynamic module import in Python with exception handling

I mean I'm not a fan of it since it's basically just a list of
statements to execute, but then again, the solution via globals and
importlib
doesn't look that much better:

import importlib
import nltk

req_modules = {'nltk.punkt': 'punkt',
               'nltk.corpus.stopwords': 'stopwords',
               'nltk.pos_tag': 'averaged_perceptron_tagger',
               'nltk.ne_chunk': 'maxent_ne_chunker'}

def try_load(module, name):
    print("Trying to load: '%s'" % module)
    globals()[name] = importlib.import_module(module)
    print("Success.")

for module, name in req_modules.items():
    try:
        try_load(module, name)
    except (LookupError, ImportError):
        # if data not found (not already installed), download it
        print("Tried to load: '%s'. Resource '%s' was not available \
               and is being downloaded.\n" % (module, name))
        nltk.download(name)
        try_load(module, name)

N.b. I'd say use a list of module/name pairs instead to enforce the
order to make diagnostics a bit easier (or load dependencies for one of
the later modules first).

Now that I read it again, this seems alright if it's in a module and reusable, otherwise doesn't look like it's less safe than other options that involve nltk.download and it provides informative output while it gets things, so that's nice.


You can get rid of the lifetimes completely, just replace every instance of:

&'a N

with just:

N

See Playground

But why? Well, in your current code N is inferred to be i32. However, with my suggested changes N will be inferred to be &'a i32. If you allow Rust to infer the reference it will also infer the correct lifetime for you.

But does this, as you ask, leak implementation details of DebugFollower? Not from a Rust perspective. In Rust, ownership details are very much part of the interface and not just an implementation detail. The key issue is that the Follower trait has to specify how long the references will be valid so that DebugFollower knows how long it is allowed to store those references.


Preforming some async operations with Rx.js

The code looks really easy to read to me, so I think you did well, really!

Consider using const instead of let.
You use #debug() in some places and console#log() in other places. If you can use another parallel instance of #debug() to remove the #log(), you will have some more control over logging.

Maybe you could extract the side-effects calls in #do() to not be part of the main stream, and create a separate stream that you can activate and deactivate. This will be overkill for your code, but in a bigger app, it would probably be nice.

Well done anyhow!


I like your version one better - in that you can break it up into even smaller pieces. Split out the printing of repeated characters:

void print_repeat(char c, int n) {
    while (n--) {
        printf("%c", c);
    }
}

So that printing a row just calls that twice:

void print_row(int row_num, int size) {
    print_repeat(' ', size - (row_num + 1));
    print_repeat('*', row_num + 1);
    printf("\n");
}

And printing the whole pyramid just calls that in a loop:

void print_pyramid(int size) {
    int i;
    for (i=0; i<size; ++i) {
        print_row(i, size);
    }
}


A few thoughts:

You shouldn't have the student ID's as a varchar(900) in the classes table. This is a classic many to many relationship. You should create a bridge entity that will have a record for each class-student relationship. This will allow you to get all the student's in a class without needing to parse a varchar.
Instead of a varchar with all of the meeting date, you would do something similar to what I mentioned in regards to the students. In a separate table create a separate record for each meeting date.
What I mentioned in 1 and 2 will now help make the attendance table a bit more compact. The date and class_id can be removed and replaced using the unique id from the bridge entity that has all the classes meeting date.
In the classes table, the BOOL completed can be a calculated field by checking if the the last meeting date has already passed or not (ie. the current date > last meeting date).


String find and replace method optimization

Your code looks fairly effective, but it could be a bunch more efficient if you rearrange the code a bit, do some pre-processing, and reduce your run-time checks. Let's go through that in order....

I recommend a 'set up' stage to your code. Consider an ideal situation at runtime, the code would look something like:

public static String toUserFriendlyErrorMessage(String parcelType, String message) {

    for (Rule rule : getRules(parcelType)) {
        message = rule.process(message);
    }
    return message;
}

That would be a neat solution, where you have a bunch of rules that you know apply to the messages of a particular type, and that you can then just apply whichever ones are appropriate. That would be the most efficient at use-time too.

How would you implement that? Using some pre-processing, of course, and a new Rule class.

This preprocessing is key, and the features you should look for here are:

the rules are sorted at pre-process time.
some rules are in multiple sets of operations.
Pattern instances are compiled just once, not at use-time.

Your rules are convenient in the sense that the parcelType values seems to have an 'extension' type system:

LEDES1998B is rules LEDES1998Bheaders
LEDES98BI is the same as LEDES1998B plus the rules in LEDES98BIheaders
LEDES98BI V2 is the same as LEDES98BI (and thus LEDES1998B) but also includes LEDES98BI_V2headers

How would I recommend preprocessing things?

private static final class Rule {
    private final Pattern key;
    private final String replacement;

    Rule(String search, String rep) {
        key = Pattern.compile(search);
        replacement = Matcher.quoteReplacement(rep);
    }

    String process(String msg) {
        return key.matcher(msg).replaceAll(replacement);
    }
}

So, that rule class is simple enough... how to add them together?

private static final Map<String, Rule[]> RULE_MAP = buildMap();

private static final Map<String, Rule[]> buildMap() {
    Map<String, Rule[]> result = new HashMap<>();
    List<Rule> rules = new ArrayList<>();

    addRules(rules, LEDES1998Bheaders);
    result.put("LEDES1998B", rules.toArray(new Rule[rules.size()]));

    addRules(rules, LEDES98BIheaders);
    result.put("LEDES98BI", rules.toArray(new Rule[rules.size()]));

    addRules(rules, LEDES98BI_V2headers);
    result.put("LEDES98BI V2", rules.toArray(new Rule[rules.size()]));

    return result;
}

private static final void addRules(List<Rule> target, Map<String,String> sources) {
    for (Map.Entry<String,String> me : sources.entrySet()) {
        target.add(new Rule(me.getKey(), me.getValue()));
    }
}

Now, your last part is the getRules method:

private static final Rule[] getRules(String parcelType) {
    Rule[] rules = RULE_MAP.get(parcelType);
    if (rules == null) {
        throw new IllegalStateException("No rules set for type " + parcelType);
    }
    return rules;
}

Now your code should go smoothly.


Exception handlers that don't either handle exceptions or rethrow them, generally shouldn't exist.

An exception signals that a breakage has occurred -- one serious enough that the thrower thinks that the app should die.  Because you've asked to catch the exception, it's now your job to deal with the problem -- and that means more than just logging it or printing a message or whatever.  That means cleaning up at least your part of the mess, making things right again, deciding what to return, etc.

If the code can't safely recover, then rethrow, or throw your own exception -- or, if there's nothing it can clean up, don't catch at all.

(If you were using a real database, i would have suggested creating the table in a transaction to make cleanup more feasible.  Unfortunately, MySQL is severely gimped transactionwise; CREATE TABLE causes an implicit commit, so rolling back isn't really an option.)

Aside from that, since you don't do any cleanup, there's not much point to the nesting.  You could have one block that has all the actions, and the first error will abort the process.  (If you want different errors for each step, then you could have a "current step" variable you update as you step through the process.  As an added bonus, i find it makes the code a bit more self-documenting.

In other words, i might suggest something like

# because i hate repeating this ugliness
$db = $con[$_POST['user-selected-connection']];

try {
    $state = 'creating table';
    $create = $db->query("CREATE TABLE...");
    KD::notice('success','table successfully created');

    $state = 'populating table';
    $insert = $db->query("INSERT...");
    KD::notice('success','table was populated successfully');
}
catch(PDOException $e) {
    KD::notice('error',"While $state: " . $e->getMessage());
    throw $e;
}


Checking against a string like this is error prone. What happens if you accidently misspell "correct" one of the times? You're better off using a number constant as an enum to signify success/failure (After rereading your post, I realized I may have misinterpreted your intent).
I'd just extract that repeated bit into a function:

function answerIsCorrect(answer, correctAnswer) {
    return answer.toLowerCase() === correctAnswer;
}

Then, since you're also repeating the use of this code, you might as well use a loop to prevent duplication:

function checkAnswers(correctAnswers) {

    //You could also just use a standard for-loop for this
    correctAnswers.forEach(function(correctAnswer, i) {
        //Note unless you check prevent i from being appended when i == 1,
        // your first answer ID will be "answer1" instead of "answer"
        var answer = document.getElementById("answer" + (i + 1)).value;

        if (answerIsCorrect(answer, correctAnswer)) {
            alert("Well done!");

        } else {
            alert("Too bad!");
        }
    });
}

correctAnswers could also be a list of numbers, representing each answer's position in the list of answers. This would mean you would only need to check the index of the answer, instead of the value of the answer, which would make manipulations like toLowerCase unneccessary.
Your indentation is a little off at the top, but that could be a pasting error.


You're bleeding memory for every line in the file.  This is probably ok for the challenge, however it's a good idea to get into the habit of cleaning up after yourself.

The call to malloc in str_mul needs to have a corresponding free call somewhere to release the memory.  Looking at your program in it's current state, the easiest way to do that is probably in the is_rotated method like so:

bool is_rotated(char *original, char *test_case) {
    int original_length = strlen(original);
    char *rotation_superset = str_mul(original, 2);
    bool is_substring = strstr(rotation_superset, test_case) != NULL;
    free(rotation_superset);
    return original_length == strlen(test_case) && is_substring;
}

I'd be tempted to actually move the malloc into the same method and pass the buffer into the str_mul method so that the allocation and release are at the same level.  This would also allow you to simply declare a local on the stack in is_rotated, rather than needing to use malloc:

void str_mul(char* str, char *string_multiplied, int times) {
    string_multiplied[0] = '\0';
    for (int i = 1; i <= times; i++) {
        strcat(string_multiplied, str);
    }
}

bool is_rotated(char *original, char *test_case) {
    int original_length = strlen(original);
    char rotation_superset[LINE_LENGTH*2];
    str_mul(original, rotation_superset, 2);
    bool is_substring = strstr(rotation_superset, test_case) != NULL;
    return original_length == strlen(test_case) && is_substring;
}

malloc Vs calloc

malloc isn't guaranteed to return zero initialized memory.  Since you're using strcat to append to the buffer, you should really ensure that the memory is a null terminated array.  You can either do that by initially null terminating it (as in my example above), or by using calloc instead.


Forming a dictionary where all values are only conditionally set

The easiest thing to do, seeing how similar most of these are, would be to have a lambda for the ternary if.

gettext = lambda var: var.text if var else "N/A"
'titleOfClass' : gettext(it.titleofclass)

If you do one for .string as well, then you only have a few (3?) cases where your if cannot be shortened to a lambda call.  You could pass in another lambda to pull the value you want to store out of var, but for just three cases the added indirection doesn't seem useful.


Different character outputs using loops and strings

better to declare first or does it not matter?

No. These days most people believe variables should be declared as late as possible, right by where they are used.

  This code just seems so ugly.

It is. A little whitespace in there would help a lot. Which is easier to read:

// This:
if(i==half && even){System.out.println(carat+"\n");}

// Or this:
if (i == half && even) {
  System.out.println(carat+"\n");
}

  that it is abusing integer rounding.

There's no abuse, and it's not rounding. Truncation on integer arithmetic is a specified part of the language. Feel free to use it. In this case, it does exactly what you want.

If I were writing this, I'd do:

printCarats(int numLines) {
  for (int line = 0; line < numLines; line++) {
    // Mirror vertically across center line.
    int halfLine = line;
    if (line > numLines / 2) halfLine = numLines - line - 1;

    int numCarats = 1 + halfLine * 2;
    for (int i = 0; i < numCarats; i++) {
      System.out.print(">");
    }
    System.out.println();
  }
}


There are some places where you can dictionaries instead of if/elif/else statements, I will analyze one here:

if(act=='+'):
    total=num1+num2
elif(act=='-'):
    total=num1-num2
elif(act=='*'):
    total=num1*num2
elif(act=='/'):
    total=num1/num2
else:
    print("input not recognized")

Is often re-written as a dictionary. So, you could create a dictionary called OPS and write:

import operator

OPS = {
    '+' : operator.add,
    '-' : operator.sub,
    ...
}
ERROR = lambda arg1, arg2: print("input not recognized")

You can then you can do:

def calculate(num1, num2, act):
    return OPS.get(act, ERROR)(num1, num2)

This tries getting the particular key which is a function. It then calls it. If the operator is not found, it defaults to the ERROR.


Dynamic IP Notification Using Google App Engine

Lint

PEP 8 recommends two blank lines around class definitions.  Indentation should be consistently 4 spaces — an important convention in Python, where indentation matters a lot.

log = Log() is pointless.

Database

A more Pythonic way to write this…

logs = Log.all()
is_new = True
for log in logs:
        if ip == log: is_new = False

… would be is_new = ip not in Log.all().

But your code wouldn't even work, since an IP address would never be equal to a db.Model object!

It also doesn't scale well, since it doesn't take advantage of the datastore's capabilities.  You should be using a query like this:

Logs.all().filter('ip_address =', ip).run(limit=1)


You could DRY the specs in the following way:

perform the authentication of the user in a before block
when testing a controller the subject could be the request itself
use context blocks for better structure
use functions for making the assertions when it comes to flash messages

So, keeping these in mind, you could write your specs like this:

require 'rails_helper'

describe EventsController, type: :controller do
  let(:link) { create(:link) }
  let(:event) { create(:event) }
  let(:admin) { create(:user_admin) }
  let(:moderator) { create(:user_moderator) }
  let(:user) { create(:user) }

  AUTHORIZATION_ERROR = /^You are not authorized to perform this action/

  describe 'GET #new' do
    subject { get :new, link: link.id  }

    before(:each) do
      sign_in(authorized_resource) if authorized_resource.present?
    end

    context 'for user with admin role' do
      let(:authorized_resource) { admin }
      it 'does not display an alert' do
        subject
        expect(flash[:alert]).to_not match(AUTHORIZATION_ERROR)
      end
    end

    context 'for user with moderator role' do
      let(:authorized_resource) { moderator }
      it 'does not display an alert' do
        subject
        expect(flash[:alert]).to_not match(AUTHORIZATION_ERROR)
      end
    end

    context 'for user with no role' do
      let(:authorized_resource) { user }
      it 'displays an alert' do
        subject
        expect(flash[:alert]).to match(AUTHORIZATION_ERROR)
      end
    end

    context 'for guest user' do
      it 'displays an alert' do
        subject
        expect(flash[:alert]).to match(AUTHORIZATION_ERROR)
      end
    end
  end
end

It might make sense to check for response codes as well (e.g. 401 Unauthorized, 403 Forbidden, etc) since a flash message on its own does say much about what's going on with the controller.


Maybe getting a character from a list of strings

I haven't used PureScript, but in Haskell the most straightforward way to do this would be to leverage the Monad instance for Maybe and write your function using do-notation. From toying around with http://try.purescript.org/ I think this should work.

getAt :: [String] -> Number -> Number -> String
getAt strings x y = fromMaybe " " $ do line <- strings !! y
                                       char <- charAt x line
                                       return $ fromChar char

Note the use of fromMaybe, after you've done your computation in the Maybe monad, you get back out by specifying a "default" to use in the case that any value of Nothing cropped up, causing the whole do-block to return Nothing.


I gather that request2 is an instance variable?  It's risky at best to set it with an autoreleased value and then expect it to be valid later in your displayView method.

But it probably works because you execute receive in a background task, and background tasks have no default autorelease pool.  If it weren't for that request2 would likely go "poof" before it got to displayView.

So all of the autoreleased data items in receive -- post2, dataToSend2, request2, several temporary strings, and at least one temporary URL -- are leaking.


To speed up the sorting you first have to find what is consuming time. In your case the slower part of your code is:

for(i = 0; i < rlen; i++){
    rows[i].innerHTML = ""+arr[i].join("	")+"	";
}

The reason is that the DOM elaboration is time consuming for the browser.

Here's an updated version that minimizes the access to the DOM:

function sort_table(tbody, col, asc){
    var rows = tbody.rows, rlen = rows.length, arr = new Array(), i, j, cells, clen;
    // fill the array with values from the table
    for(i = 0; i < rlen; i++){
    cells = rows[i].cells;
    clen = cells.length;
    arr[i] = new Array();
        for(j = 0; j < clen; j++){
        arr[i][j] = cells[j].innerHTML;
        }
    }
    // sort the array by the specified column number (col) and order (asc)
    arr.sort(function(a, b){
        return (a[col] == b[col]) ? 0 : ((a[col] > b[col]) ? asc : -1*asc);
    });
    for(i = 0; i < rlen; i++){
        arr[i] = ""+arr[i].join("	")+"	";
    }
    tbody.innerHTML = "
"+arr.join("

")+"
";
}

Proof: http://jsperf.com/table-sorting-stack-overflow


Enhancing search using Fuzzy Logic in NodeJS

Question

  "Will this causes to performance issue to my application or is there a Better Approach than this I should follow."

Well that will depend on a lot of factors.

1million clients.
fuzzy.js and its performance.
A single medium level server.

State of development

First a quick look at the link you provided to fuzzy and at the bottom of the page you find the ToDo list which contains 2 points of interest

  Async batch updates so the UI doesn't block for huge sets. Or maybe Web Workers?
  Performance performance performance!

Following through to the gitHub repository and we find that the last activity was 3 years ago. This suggests (not implies) that development has ended. That a key issue recognized by the developers (performance) will not be worked on in the near future.

Performance

To try and determine the performance per search entry I went to their demo and timed the search over several differently size lists of names, and search strings.

The performance test shows a slightly below linear complexity (in the range of 628 - 1,250,000 names), however its too close to call and the safe bet is its linear. It searched 1.25million names in ~1 +/- 0.2seconds

Tests method

The test was performed in the console running the following snippet many times

t = performance.now();
res = fuzzy.filter(searchStr, data);
totalTime += performance.now() - t;
count ++;

A complex regular expression, on the same data required 1/10th the time.

t = performance.now();
res = data.filter(name => regExpSearch.test(name));
totalTime += performance.now() - t;
count ++;

Conclusion

What Node.js does well is IO, and what is does not do well is processing.

Assuming one medium level server.

1 second for a search is a very long time.
Fuzzy.js performance is unlikely to change.
A response time over a second puts your site in the bottom 20% of services, and is unacceptable.
I estimate that at 30 thousand users performance will become a serious problem (see below)

If you are serving 1million active users, (using the 20/80 rule) with 20% of users visiting your site one day a year 20% of them once a month and 20% of them once a week (~600,000 searches a year) with users geographically clustered resulting in significant peak times.

It is highly likely that you will regularly have 30+ concurrent queries and a few times a year you can expect 300, in which case your server will be blocked for over 5 minutes.

(NOTE) these are very rough estimates based on one search per user per visit.

The answers

  "Will this causes to performance issue to my application or..."

Yes for a very heavy trafficked site this will present a serious performance issue.

No for a very small traffic loads nobody will notice.

  "...is there a Better Approach than this I should follow."

Yes of course there is, use a regExp, and there are many more. But I can not hand out advice on speculation. The information given above is already dubious as it is based on a single request rather than the site/service as a whole.

Refection

Well gee... any nerd knows this...

1+ million regular users is cash in the bank.

A service must start somewhere and that is with a few users, with growth being gradual and predictable (once moving). If you are monetizing the service then growth is great and not a problem (if managed well).

Start with the basics and work your way up. Replacing infrastructure (the search methods, upgrading the server/s) is part of the business. Performance is the least of your initial problems.

If you plan for viral growth then you are in the realm of highly speculative investment capital. Outsource a solution to people that have the experience or you will miss a lucrative opportunity.

If you plan to provide a free service for 1+ million users, good on you :), but you will need to have a fairly deep pocket.


Overriding properties at runtime but not for serialization

As far as the actual code goes, the implementation is clean and I don't really have any comments :)

As for the idea, I don't think it's quite right. Settings should be that - just settings. As soon as you start adding behaviour to them, they're not settings any more and you should look at what you're missing. Taking your example:

public interface IFilePathService
{
    string GetPath(string file);
}

public class LocalFilePathService : IFilePathService
{
    private readonly string resolvedDirectory;

    public LocalFilePathService(
        string baseDirectory,
        string workingDirectory)
    {
        // validation ignored.
        resolvedDirectory = Path.Combine(baseDirectory, workingDirectory);
    }

    public string GetPath(string file)
    {
        // validation ignored.
        return Path.Combine(resolvedDirectory, file);
    }
}

Now you create your service with 2 parts, one is your setting (working directory) and the other is the path to your base directory:

new LocalFilePathService(@"C:\temp", Settings.WorkingDirectory);

You just inject this service into all the places you need to get files in the working directory. You don't have any magic that you need to worry about. If you change the setting and save it, then you expect (and want) it to be saved.


Here are some problems I see with your code:

The code removes the Dictionary's constant-time lookup.
The code reparses the pattern and recompiles each regex every time you're
in the loop.
The code uses regex's even for simple lookups.
The code will die if you try to assign more than one handler to an event.
This might just be an artifact of you copying/pasting, but the indenting on your method is a little unusual.
The code does not favor composition over inheritance.
Your parameter name does not follow the convention of being camelCase.
Your regex pattern doesn't require the beginning and ends, so e.g. as?f matches the same things as *as?f*.

I would use the built-in Dictionary lookup functionality for simple (no-wildcard) lookups and store compiled regex's for the ones with wildcards. Also, you can look at the reference source in your link to get an idea of how to solve the problem of multiple handlers for an event.

This should be a good starting point, with code to add a listener and get handlers. It only uses regex's when needed, keeping them precompiled in a second Dictionary. If the "*" case is pretty common, you could further improve this by handling that as a special case: you don't really need to compile and store a Regex for it, you just always run it. This would probably be a third field, maybe private Delegate universalHandlers;

public class EventDictionary
{
    private readonly Dictionary<string, Delegate> eventTable = new Dictionary<string, Delegate>();
    private readonly Dictionary<string, Regex> regexTable = new Dictionary<string, Regex>();

    private bool HasWildcards(string pattern)
    {
        return pattern.Contains("*") || pattern.Contains("?");
    }

    public void AddListener(string eventType, Delegate eventDelegate)
    {
        Delegate currentDelegate;
        if (eventTable.TryGetValue(eventType, out currentDelegate))
        {
            var d = eventTable[eventType];
            if (d != null && d.GetType() != eventDelegate.GetType())
                throw new ArgumentException(string.Format("Attempting to add listener with inconsistent signature for event type {0}. Current listeners have type {1} and listener being added has type {2}", eventType, d.GetType().Name, eventType.GetType().Name));
            eventTable[eventType] = Delegate.Combine(currentDelegate, eventDelegate);
        }
        else
        {
            eventTable.Add(eventType, eventDelegate);
        }

        if (HasWildcards(eventType) && !regexTable.ContainsKey(eventType))
            regexTable.Add(eventType, new Regex("^" + Regex.Escape(eventType).Replace(@"\*", ".*").Replace(@"\?", ".") + "$"));
    }

    // TODO implement remove method

    public Delegate GetHandlers(string eventType)
    {
        Delegate handler;
        eventTable.TryGetValue(eventType, out handler);
        foreach (var pair in regexTable)
            if (pair.Value.IsMatch(eventType))
                handler = Delegate.Combine(handler, eventTable[pair.Key]);
        UnityEngine.Debug.Log(handler.GetInvocationList().Length);
        return handler;
    }
}


Property Parameters

The setter adds the new parameters to the list - I would expect, that the list will be cleared before.
The setter and getter throw a null reference exception if the connection was not opened before

Method OpenConnection

If an expected exception occurs, an exception is thrown; otherwise the method returns false. That is IMHO unusually... I would prefer to return a result like (enum OpenConnectionResult { ServerNotAvailable, AuthorizationFailed, UnknownError, Succeess }).
The error text of the exception can not be localized (that problem is also solved by the solution above)
If throwing a new exception, it makes sense to pass the underlying exception as inner exception to the new one (new Exception("Cannot connect to server. Contact administrator !", ex);)

Method CloseConnection

The methods returns always true or throws an exception.
The method is private and will not be called within the class.

if (ex.InnerException == null)
    throw new Exception(ex.Message);
throw new Exception(ex.InnerException.Message);

Don't do that... You hide valuable information that may be useful for error analysis! Just throw the exception here... You can handle that kind of stuff from outside if required.
What if the inner exception has another inner exception? If you want to get the most underlying exception use something like while(ex.InnerException != null) { ex = ex.InnerException; }

Method ExecuteStoredProcedure

The method throws a null reference exception if OpenConnection was not called.

Method _refreshCommand

Methods start with a capital letter in c# (even private ones)
Remember to dispose the command object!

General Design

Your class has some surprises for the user. The parameters can be set from outside, but after running a procedure, a new command is initialized and the modified parameter list is reset - very confusing! Even the error handling is not very usual.

I suppose, that you set the parameters before you are running ExecuteStoredProcedure!? If so, why not passing the command parameters to that method? There is no need for the class to know the command parameters.

IMHO that would simplify the usage of the class:

public class DBHelper
{
    private readonly MySqlConnection _connection;
    private readonly string _server;
    private readonly string _database;
    private readonly string _uid;
    private readonly string _password;

    public DBHelper(string server, string database, string uid, string password)
    {
        _server = server;
        _database = database;
        _uid = uid;
        _password = password;

        _connection = new MySqlConnection();
        _connection.ConnectionString = String.Format("server={0};database={1};uid={2};password={3}", _server, _database, _uid, _password);
    }

    public OpenConnectionResult OpenConnection()
    {
        try
        {
            _connection.Open();
        }
        catch (MySqlException ex)
        {
            switch (ex.Number)
            {
                case 0: return OpenConnectionResult.ServerNotAvailable;
                case 1045: return OpenConnectionResult.AuthorizationFailed;
                default: return OpenConnectionResult.UnknownError;
            }
        }
        catch (Exception ex)
        {
            return OpenConnectionResult.UnknownError;
        }
        return OpenConnectionResult.Succeess;
    }

    public void CloseConnection()
    {
        _connection.Close();
    }

    public int ExecuteStoredProcedure(string name, params MySqlParameter[] commandParamters)
    {
        using (var cmd = new new MySqlCommand())
        {
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Connection = _connection;
            cmd.CommandText = name;
            cmd.Parameters.AddRange(commandParamters);
            int count = cmd.ExecuteNonQuery();
        }
        return count;
    }
}


Returns Google Sheet cells from a named range

I didn't run unit tests for this on different search inputs, but it should give an idea of how you can bundle index information into the results for consumption with array class methods. Because you are working in a fairly robust environment (Google Sheets), you can be confident that the search array you are working with has a guaranteed nesting level (which limits a lot of possible issues).

The general idea is to replace the raw value with an annotated object, after which you can remove the row & column structure and work only with the value. (It's possible you could just use the reduce | forEach and push Array methods to go from the values array to the flattened array of annotated values.)

function annotateAndCase_(input2DArr, lower) {
  // Map the 0-base row and column indices onto the value.
  return input2DArr.map(function (row, rowIndex) {
    return row.map(function (val, colIndex) {
      var v = (lower && typeof val.toLowerCase === 'function') ? val.toLowerCase() : val;
      return {r: rowIndex, c: colIndex, v: v};
    });
  });
}

function getCellsWithValueInRange(SearchRange, search_string, case_sensitive) {
  // Pass exactly `false` to disable case sensitivity. Other falsy (0, "", null, undefined) -> `true`
  case_sensitive = case_sensitive !== false;
  if (case_sensitive) {
    search_string = search_string.toLowerCase();
  }
  const startRow = SearchRange.getRow(),
        startCol = SearchRange.getColumn();

  const indexedValues = annotateAndCase_(SearchRange.getValues(), !case_sensitive);

  // 2D array with max nesting level = 1 -> https://stackoverflow.com/a/10865042
  const flattened = Array.prototype.concat.apply([], indexedValues);

  const results = flattened.filter(function (cell) {
    return cell.v === search_string;
  }).map(function (match) {
    // Return a string R1C1 notation of each matched value.
    return ["R", match.r + startRow, "C", match.c + startCol].join("");
  });

  // Use a RangeList to optimize obtaining a large number of possibly-disjoint ranges.
  return results.length ? SearchRange.getSheet().getRangeList(results).getRanges() : [];
}

As mentioned in comments by @Dimu, you should reconsider why you need the individual cell references (perhaps just the collection as a RangeList is sufficient, e.g. for treating them in the same manner).

It's a similarly good idea to separate the functionality of annotating from this specific function that searches for values, since that allows reusing code, e.g. annotated a range object, use various filter predicates, various transformative maps, various final consumers, and so on. Probably you should further separate the casing from the annotation step - only certain filter predicates for the annotated array would care.


Avoiding Duplicates in a Ruby on Rails Factory Girl Factory with Fake

The simplest thing to do is probably to use FactoryGirl's sequence:

FactoryGirl.define do
  factory :company do
    sequence(:name) { |n| "#{Faker::Company.name} #{n}" }
  end
end

sequence basically gives you an auto-incrementing integer, so you can avoid uniqueness issues. Sure, it'll generate some slightly odd company names, but for testing that shouldn't matter much.

In general though, I don't feel too great a need for something like Faker. Something like this should work just as well:

FactoryGirl.define do
  factory :company do
    sequence(:name) { |n| "Acme Inc. #{n}" }
  end
end

If it's only your specs looking at the data, it doesn't really matter if the company name's "Acme", "foobar 42", or "ACC8B1B7-7EC0-4F05-AB2A-B487C134F6BF".

Besides, your current solution is:

non-deterministic, so it may never exit the while loop if it just happens to keep picking the same couple names again and again,
but even if we ignore that, the act of adding more tests that use company records, will mean more name collisions and longer time spent in the loop. I don't know how Faker works, but (unlikely but technically possible) you might even end up exhausting every name Faker can come up with, and end up looping forever.


I think the function looks good. It does what it's supposed to do when the input is correct. However, if the input number x is larger or equal to 1<<bitwidth, the behavior is undefined. To rectify this, I suggest:

uint64_t CircShift(uint64_t x, uint8_t n, uint8_t bitwidth)
{
    return ((x<<n)&((1<<bitwidth)-1)) |
           ((x&((1<<bitwidth)-1))>>(bitwidth-n));
}

Just add another mask to the right-shifted part. Also note that for shifts that are bigger than 64 bits, both your original function and my new function behave strangely. To rectify this, you can use the fact that a circular shift by bitlength steps simply give you the original number:

uint64_t CircShift(uint64_t x, uint8_t n, uint8_t bitwidth)
{
    return ((x<<(n%bitwidth))&((1<<bitwidth)-1))
        | ((x&((1<<bitwidth)-1))>>(bitwidth-(n%bitwidth)));
}


Filtering user input to not contain a specific character

Your code looks correct and safe to me.  However, I would simplify it as:

public static String filterInput(String userInput) {
    return userInput.replace("\u00b6" /* Pilcrow sign */, "");
}

Two public functions seems like overkill, when all you need is a static function.  (If you intend for the filter to be configurable by overriding checkCharacter() in a subclass, then I would suggest changing to a more flexible design where the naughty characters are specified as a parameter.)


Is using defvar for a non-global variable ok?

Defvar always creates a globally special variable (unless it already exists, of course).  It does not matter where you call it.

It is usually used as a toplevel form or directly inside of an eval-when.  The only reason to put it anywhere else that I can think of is the use of closures.

In all other cases, I would strongly suspect that the code does not mean what the author thinks it does.

Here, the globally special variable line is created on the first call of read-http-content.  This may lead to surprising effects if you use the name line in other places.  Don't do that.


Timeout Error in Fraudulent Activity Notification HackerRank

If this wasn't a programming challenge with restricted modules, I would suggest using pandas. It has a rolling windowed median implemented, so it is quite straight forward (just have to be careful not to have an off-by-one error with the shift):

import pandas as pd

def activityNotifications(expenditure, d):
    df = pd.DataFrame(expenditure)
    return (df.shift(-1) > 2 * df.rolling(d).median())[0].sum()

For the example input you gave, this runs in about 210 ms ± 3.71 ms on my machine. This is very hard to beat, both in runtime and readability.

Unfortunately, Hackerrank does not have pandas available (or even numpy for that matter). So, we need another implementation of a windowed running median. There are multiple ways to implement it, but here is one. You keep track of two collections, one is the window you are looking at and one is a sorted version of it. The former tells you which value drops out when you add a new one, and the latter allows you to easily get the median without having to sort the window each time, if you insert elements at the right place. For this you can use the bisect modules insort (which is \$\mathcal{O}(n)\$, instead of \$\mathcal{O}(n\log n)\$ for sorting each time).

I used the RunningMedian function from here, and modified it a bit to directly count instead of collecting the medians. It is not the most beautiful code to look at, I might clean it up a bit later.

from itertools import islice
from collections import deque
from bisect import insort, bisect_left

def activityNotifications(seq, M):
    """
     Purpose: Find the median for the points in a sliding window (odd number in size)
              as it is moved from left to right by one point at a time.
      Inputs:
            seq -- list containing items for which a running median (in a sliding window)
                   is to be calculated
              M -- number of items in window (window size) -- must be an integer > 1
      Otputs:
         medians -- list of medians with size N - M + 1
       Note:
         1. The median of a finite list of numbers is the "center" value when this list
            is sorted in ascending order.
         2. If M is an even number the two elements in the window that
            are close to the center are averaged to give the median (this
            is not by definition)
    """
    seq = iter(seq)
    s = []
    m = M // 2

    # Set up list s (to be sorted) and load deque with first window of seq
    s = [item for item in islice(seq, M)]
    d = deque(s)

    # Simple lambda function to handle even/odd window sizes
    median = lambda : s[m] if bool(M&1) else (s[m-1]+s[m])*0.5

    # Sort it in increasing order and extract the median ("center" of the sorted window)
    s.sort()

    # Now slide the window by one point to the right for each new position (each pass through
    # the loop). Stop when the item in the right end of the deque contains the last item in seq
    count = 0
    for item in seq:
        count += item > 2 * median()
        old = d.popleft()          # pop oldest from left
        d.append(item)             # push newest in from right
        del s[bisect_left(s, old)] # locate insertion point and then remove old
        insort(s, item)            # insert newest such that new sort is not required
    return count

This code takes about 871 ms ± 14.5 ms on my machine for the given testcase. It passes all testcases on Hackerrank as well. It is slower than the pandas one, but that is to be expected. Both functions give the same result.

Some additional comments about your code itself:

if nextNum >= 2*median: count += 1 could just be return nextNum >= 2*median. Summing bools is perfectly fine, since they are just ints underneath.
if d%2 != 0: can be if d % 2, because non-zero integers are truthy.
In actual code please follow Python's official style-guide, PEP8. It recommends naming your function activity_notifications.
You should add a docstring to explain what your function does.


Shouldn't you replace the whole code with session = String.Empty; ?

Let's assumme that this is just a placeholder for actual code. If you handle your different cases in order and if hours is an int, then you can make the logic a bit easier to follow :

if (hours == 23 || (hours >= 0 && hours <= 6))
{
    session = A;
}
else if (hours == 7)
{
    session = B;
}
else if (hours >= 8 && hours <= 11)
{
    session = C;
}
else if (hours >= 12 && hours <= 15)
{
    session = D;
}
else if (hours >= 16 && hours <= 20)
{
    session = E;
}
else if (hours == 22)
{
    session = F;
}
else
{
    session = G;
}

becomes

if (hours < 0 || hours > 23)
{
    session = G;
}
else if (hours <=6)
{
    session = A;
}
else if (hours <= 7)
{
    session = B;
}
else if (hours <= 11)
{
    session = C;
}
else if (hours <= 15)
{
    session = D;
}
else if (hours <= 20)
{
    session = E;
}
else if (hours <= 22)
{
    session = F;
}
else
{
    session = A;
}


I see a couple issues, though nothing too major.

Improper form for 'if not in'

While this works, it's not the proper form for this:

if not "_" in dashes:

The better form for this is:

if "_" not in dashes:

Tracking if a value is not equal to something

This works:

if not len(guess) == 1 or not guess.isalpha():

But, we can remove one 'not' though,  and use an inequality operator instead:

if len(guess) != 1 or not guess.isalpha():

Generation of dashes

You can shorten the creation of 'dashes' to this when you create it, and then get rid of the for loop that generated it previously:

dashes = ['_'] * len(word)

No tracking of guesses already made

Your code does not track guesses already made.  Therefore, people can 'waste' guesses.

Let's do two things:  first let's move around some things.  Secondly, let's add some code to capture this case and not increment the number of guesses made when this happens.

First, let's change where we increment the 'current guess' value, and define a different 'start' value:

for word in words:
    current_word += 1
    current_guess = 1
    dashes = []
    ....
    while current_guess < maximum_guesses:
        os.system("clear")
        ....
        guess = guess.lower()
        if not len(guess) == 1 or not guess.isalpha():
            current_guess += 1
            ....

Basically, we moved the current_guess incrementer to lower in the code.  And initialize the guess counter to 1 to begin with.

Now let's do some "already guessed" code:

for word in words:
    ....
    guesses = set()
    for letter in word:
        ...
    guess = guess.lower()
    if guess not in guesses:
        guesses.add(guess)
        current_guess += 1
        if not len(guess) == 1 or not guess.isalpha():
            current_guess -= 1
        for index, letter in enumerate(word):
            if letter == guess:
                dashes[index] = letter
        if "_" not in dashes:
            solved_words += 1
            break

This allows 'repeated' guesses of the same letter to not take effect.  That way, if someone enters 'o' as a guess twice, accidentally or intentionally, on the word 'foobar', they aren't penalized for something already guessed.  You can choose to not do this, but it helps protect against "What the heck, I shouldn't be penalized for something I already guessed!" complaints.

I don't change much of your program.  This is the total program with my above suggestions, plus some whitespace for readability.  I don't have any suggestions for improving the output, though, because it seems to be okay as it is, at least to me.

import os

words = ["foobar", "gnarf", "fnord"]

current_word = 0
maximum_words = len(words)
maximum_guesses = 10
solved_words = 0

for word in words:
    current_word += 1
    current_guess = 1
    dashes = ['_'] * len(word)
    guesses = set()

    while current_guess < maximum_guesses:
        os.system("clear")

        print("Word {}/{}".format(current_word, maximum_words))
        print("Solved {}/{}".format(solved_words, maximum_words))
        print("Guess {}/{}".format(current_guess, maximum_guesses))
        print("\n{}\n".format(" ".join(dashes)))

        guess = input("Guess: ")
        guess = guess.lower()

        if guess not in guesses:
            guesses.add(guess)
            current_guess += 1

            if len(guess) != 1 or not guess.isalpha():
                current_guess -= 1

            for index, letter in enumerate(word):
                if letter == guess:
                    dashes[index] = letter

            if "_" not in dashes:
                solved_words += 1
                break


Note that there are 2n-1 different such names for a string of lengh n, as there can or can not be a _ between any two characters. For your long-long name that makes 134,217,728 variants!

Regardless of what algorithm you use, this will take a very long time. One way to work around this, depending on your actual use case, might be to use a generator function. This way, you do not need to calculate all the variants, if maybe you need just a few of them (maybe just enough to find one that does not yet exist?). For example, like this:

def filename_generator(name):
    if len(name) > 1:
        first, rest = name[0], name[1:]
        for rest2 in filename_generator(rest):
            yield first + rest2
            yield first + "_" + rest2
    else:
        yield name

Output:

>>> list(filename_generator("name"))
['name', 'n_ame', 'na_me', 'n_a_me', 'nam_e', 'n_am_e', 'na_m_e', 'n_a_m_e']

Or, building upon the idea by @jacdeh, using binary numbers to determine where to put a _.

def filename_generator(name):
    d = {"0": "", "1": "_"}
    for n in range(2**(len(name)-1)):
        binary = "{:0{}b}".format(n, len(name))
        yield''.join(d[s] + c for c, s in zip(name, binary))

Or similar, using bit shifting:

def filename_generator(name):
    for n in range(2**(len(name)-1)):
        yield ''.join(c + ("_" if n & 1<<i == 1<<i else "") for i, c in enumerate(name))

However, either both those implementation are pretty lousy, or it does not help much in the end: They are both about 10 times slower than the recursive function, according to timeit.

Here's some timing information, using IPython's %timeit magic method:

In [8]: %timeit filename_generator("longname")         # your original function
1000 loops, best of 3: 610 µs per loop
In [9]: %timeit list(filename_generator1("longname"))  # my recursive generator
10000 loops, best of 3: 22.5 µs per loop
In [10]: %timeit list(filename_generator2("longname")) # my binary generator
1000 loops, best of 3: 322 µs per loop
In [11]: %timeit partition_string("longname")          # Eric's binary function
1000 loops, best of 3: 200 µs per loop

Another possibility, as posted in comments, would be to use itertools.product to generate the "mask", similar to the binary number solution, but with less involved math.

from itertools import product, chain
def filename_generator4(name):
    for mask in product(("_", ""), repeat=len(name) - 1):
        yield ''.join(chain(*zip(name, mask + ("",))))

However, performance is about the same as for the binary solutions. I guess the bottleneck is the number of string concatenations: In the recursive solution, you "reuse" the partial solutions, while each of the latter solutions construct each solution "from scratch", so there are fewer total string concatenation in the recursive case. Not sure, though, so feel free to comment.


Two approaches to count occurrences of one char in a String in Java

As I stated in the comments, both of your approaches have a time complexity of O(n), but your first approach has a O(1) space complexity whilst your second one requires O(n) space in the worst case, because replaceAll creates a copy with all the matches removed.

From complexity point of view, your first approach is basically ideal. In order to replace all occurrences of a char, you at least have to iterate every char in your input once, which corresponds to O(n) time complexity. Also, space complexity is, as stated, O(1) which is, obviously, the best case.

[Note: Java makes no guarantees about the time and space complexity of methods. Thus, replaceAll could, in theory, also have a much worse time and space complexity if not implemented well. I assumed that it runs in O(n) (which is the best case) when matching on a single char only. This fact, of course, makes the second approach even worse.]


Alternative for two sequentially executed loops with identical ranges

You could also define something like

private void MyLoop<T>(Action<T> action, IEnumerable<T> dataList)
{
    foreach (var data in dataList)
    {
        action(data);
    }
}

and use it

MyLoop(Process, dataList);

or using Action

Action<Action<int>> myLoop= action =>
{
    foreach (var data in dataList)
    {
        action(data);
    }
};

and use it like this

myLoop(Process);


(This is in addition to what @200_success already said about exit codes and error handling.)

Your main questions

  I'm pretty sure, here is lot of stuff, which I missed or did incorrectly (or not the "Python way").

The convention is to use CamelCase for class names. So MysqlUserDb would be better for your class. See PEP8 for more details.

Don't mix string concatenation and formatting expressions like this:

print 'Error: %s ' % error + '\nStop.\n'

Stick to formatting expressions without concatenation:

print 'Error: %s\nStop.\n' % error

You do this a lot. Apply this technique everywhere.

Similarly, you're not using formatting expressions enough. For example in SQL queries like this one:

self.cursor.execute('show databases like ' + '\'' + db + '\'')

With all those quotations and escaping, it's easy to overlook a mistake. It becomes simpler if you use formatting expression, and if you change the outermost quotes to double quotes:

self.cursor.execute("show databases like '%s'" % db)

Your code appears to be for Python 2.x. To be a bit more ready for a possible future migration to Python 3.x, I recommend to start writing your print ... statements as print(...), for example:

print('Connection OK, proceeding.')

  Also, I'm not sure - which way better:

  create methods for each action (add database, add user) and just call this methods from script (currently done)
  create one method, which will get needed action ('create database lalala') as argument and call this method several times in script

Your current approach is good: use a separate method for each separate action.

Unused fields

In __init__ you are setting these fields:

self.root = 'root'
self.host = 'localhost'
self.rootpw = 'p@ss'

But then you're not using them anywhere else within the class. So it seems these should not be fields, but perhaps global constants declared at the top of the class. I would also name them a bit differently:

DBROOTUSER = 'root'
DBROOTPASS = 'p@ss'
DBHOST = 'localhost'

Security

Are you sure you want to store the db's root account password in this script? Make sure the file has restricted permissions (do a chmod 0600 on it).

Needless to say, but better make sure the method parameters are cleaned before reaching your class to avoid SQL injection attacks. Or implement validation inside your methods.

Naming

Instead of these parameter names:

def createdb(self, db):
    # ...

def grants(self, user, userpass, db):
    # ...

I recommend this:

def createdb(self, dbname):
    # ...

def grants(self, dbuser, dbpass, dbname):
    # ...

This may be a matter of taste though.


Basic function to output repeating dates from iCal format

Something to keep in mind about anonymous functions (also known as lambda functions), is that they should only be used for tasks that are only going to be performed once. These functions are not compiled at runtime and so must be explicitly compiled each time they are run. Another thing to keep in mind, just because you can do something, doesn't mean you should. Sure this works, but its confusing and hard to read. Why use lambda functions at all? It looks like what you actually want is a class.

Judging by some of this code I'd hazard to say that you are coming from Java? I say this mostly because of the way you are throwing around lambda functions in a single "main" function. Reminds me of a lot of Java code I've seen. That and your calling an array a map. Just know that PHP is NOT Java. You don't need just one function/class, to house all your other functions. Just pretend they are in a class by default and you'll do fine. Or implement them to a PHP class, they are more or less the same. If you are not from Java, then you might want to look at class tutorials, but first forget you ever heard of lambda functions. You'll probably never need them.

Another thing, that main function, _bornhom_custom_calendar_event_dates(), is entirely too long for a function. Functions should do one thing, and do it well. Classes should also do just one thing, but on a larger scale by using many functions to do smaller things. For example: A class could get a valid date set and have many functions (or methods in a class context) that cared for getting single dates, checking if they were valid, and compiling them together. Abstracting these lambda functions will help immensely with this and the DRY principle.

For quoting DRY principle, I immediately spot code that violates it.

$start_timestamp = strtotime($datetime['value']);
$start_day = date('Y-m-d', $start_timestamp);

Instead of checking if $datetime['value2'] is set repeatedly, do it once to save processing time. And change that name. "value2" is entirely too vague. What differentiates it from value? What even is "value"? Try to be short, but descriptive. Describing what these "values" are supposed to contain will get you started.

$end_day = NULL;
$end_timestamp = NULL;

$value2 = isset( $datetime[ 'value2' ] ) ? strtotime( $datetime[ 'value2' ] ) : FALSE;
if( $value2 ) {
    $end_day = date( 'Y-m-d', $value2 );
    $end_timestamp = $value2;
}

Of course, if you could change your code so that $end_timestamp could have a default value of FALSE instead of NULL, you could just set $end_timestamp above and then check to see if $end_day needed to be set and completely bypass the need of a $value2 variable.

What is function t() as seen in your $single_day_output lambda function? Where does it come from? Just like above, please choose better names.

What is "rrule" and why does it have a child named "rrule"? Maybe the first should be called a "rule set"? I don't know, but the names should be unique.

Break up your long lines. There's no reason to have them so long.

$single_newday = $single_day_output($new_timestamp);
$time = $single_day_output($new_timestamp + ($end_timestamp - $start_timestamp))
$output .= $single_newday . ' ' . t('until') . '
' . $time . '
';

Right now I can't follow your code well enough to help you with any of your specific questions, but if you clean it up a bit I'll take another look. Hope this helps!


You are abusing the heads & tails lists into making simple counters.

heads = []
tails = []

for flips in range(int(guess)):
    random_number = random.randint(1, 2)
    if random_number == 1:
        heads.append("Heads")
    elif random_number == 2:
        tails.append("Tails")

len(tails)
len(heads)

This could be replaced with simply:

heads = 0
tails = 0

for flips in range(int(guess)):
    random_number = random.randint(1, 2)
    if random_number == 1:
        heads += 1
    else:
        tails += 1