I don't know anything about climbing. But I'll try this by way of analogy.

I imagine that climbing routes might be something like ski runs. You can have a resort with multiple mountains. Each mountain can have multiple runs. The runs don't necessarily start at the same place, nor end at the same place. The runs can have different levels of challenge.

So you have:

A Resort has m Mountains
A Mountain has

s starting points (where lifts take you)
e ending points (where runs take end, and you can go home)
p points

A Point has r runs leaving it
A Run has a difficulty rating (green circle, blue square, black diamond)

How to approach this in a game? Well, you have some of it already. The pump_level and energy_level are fine.

I would say that the top few items (resort, mountain, starting point) are a series of text prompts. What you really have is a graph. When the player starts, it is at a central node on the graph. This is the "big decision" that will decide the rest of the decisions: "What resort do you want to visit?"

From there, you can change resorts (which is slow and time consuming and expensive, but might be necessary for game play, or might be a "level up" feature- you can only change resorts as you get better). Or you can head for different starting points by taking different ski lifts. Or you could head for a different mountain by taking a van over, then a ski lift. Etc.

Finally, you get to a starting point, pick from a small set of runs. You reach a point at the end if your run, pick from a different small set of runs, reach a different point at the end of that run, etc. Eventually, you reach an ending point - the bottom of the hill. You can call it a day, or go back up for more runs!

I would reverse this for climbing. There are some places to start, maybe some "trails" that take you to the bottoms of a few routes. When you climb up, you reach a point that you can change routes. Then eventually you reach the top, or some other ending point, etc.

Update:

So you have a climber traversing this graph of starting/middle/ending points by various routes. So the nodes (points) have various weighted edges (weights = difficulty, cost, etc.) and they all have names.

Your climber will need some kind of "current node" or "current location" indicator. Your graph of routes should have a common "node" class, with various "routes" connecting the nodes.

class PathNode:
    def __init__(self, ...):
        self.routes = []

class Route:
    def __init__(self, name: string, grade: float, start: PathNode, end: PathNode):
        ...

Whatever your "bottom of the mountain" type is (I called it "Resort" in the ski example) would have a set of standard starting nodes.

class Resort:
    def __init__(self, ...):
        self.start_nodes = []

Your climber would have a current node:

class Climber:
    def __init__(self, ...):
        self.location = None

You might consider making a Resort inherit from PathNode and use a bunch of zero-cost routes to connect to the starting points. That would make everything a graph traversal.

If you put a "message" into each route, describing the struggle, then the Resort -> Start messages could play into that:

  You get in a van with a couple of hipsters, and head for the bottom of El Diablo. I wonder if those guys have what it takes to make the climb?"

You might consider adding in some "trap" nodes, that can only be reached by random chance. Thus, if your energy is low and you try to climb a difficult route, maybe you fall off and have to wait for a rescue chopper...


C string library inspired by Python string functions

Well efficiency can be improved by using the built-in string functions.
They have been optimized at the assembly level for most implementations.

Assuming you were writing len() in C rather than using some optimal assemble instructions. The canonical form looks more like this (though I am sure it can be done better). Though there is strlen() which does the same thing.

int len(char* string)
{
    char *end = string;
    for(;*end;++end)  /* Notice nothing here */;
    return end-string;
}

Looking at this:

char* lstrip(char* string){

    /* This makes it non optimal for strings we already know are good.
     * If I already know my string is fine I would want a function that
     * did not do this test.
     *
     * Of course you can then have a second function that does the test
     * then calls the non checked version (and if it is short the compiler
     * will inline
     */
    if(!string)
        /* Not returning a value from a function expecting a value is an error
         * Check the warning messages generated by the compiler
         */
        return;

    /*
     * ' ' is not white space it is just a space character
     *    What you are looking for is isspace(c)
     */
    while(*string == ' '){
        string++;
    }

    return string;
}

I would have written like this:

char* lstripNT(char* string){ return string?lstrip(string):NULL;}
char* lstrip(char* string){
    for(;isspace(string);++string) /*Nothing here*/;
    return string;

    // NOTE: there is an issue with this technique in that you
    //       are not returning the original string.
    //       If the string was dynamically allocated
    //       you now have issues with freeing it. Which means you
    //       specifically need to keep a copy of the original pointer
    //       for the purpose of freeing it when you are finished.
    //       This is NOT a good idea.
}

Because of the problem with dynamic allocation I would probably write like this:

char* lstrip(char* string)
{
    size_t  move = 0;
    char*   start= string;
    for(;isspace(start);++start,++move)
    {}
    if (move)
    {
        // Move all the characters down.
        // So we basically squish the white space.
        for(;*start;++start)
        {
            *(start-move) = *start;
        }
    }
    return string;
}

Right trim. Is not really optimal because you scan to the end (using len). Then you then scan backwards until you find a non space character. You can do this in a single traverse. Also you are not being consistent. lstrip() checks for NULL while this does not.

char* rstripNT(char* string){ return string?rstrip(string):NULL;}
char* rstrip(char* string){

      char* loop    = string;
      char* last    = NULL;
      int   isSpace = false;
      while(*loop)
      {
          isSpace = TRUE;
          last    = loop;
          for(;*loop && isspace(*loop);++loop)
          {}
          if (*loop)
          {
              isSpace = FALSE;
              for(;*loop && !isspace(*loop);++loop)
              {}
          }
      }
      if (isSpace)
      {
          *last = '\0';
      }
      return string;
}

The strip.

char* strip(char* string){

    /* Trim off both leading and trailing whitespace */
    char* lstring = lstrip(string);
    char* finalString = rstrip(lstring);

    return finalString;

}

This is conceptually what you want to do.
But I don't think that will be optimal way to do it. I would write this as a single pass.


Getting messages asynchronously using MailKit

It's hard to say how to write the ideal method for your use-case because you don't specify some of the details that would be necessary to know, such as:

How often will your code be making this query?

Is the connection always to the same IMAP server, username and password?

(if it'll be called fairly frequently with the same server/username/password combo, you could try to re-use the same ImapClient connection)

That said, I'll start with trying to at least clean up the code a bit.

public async Task<IList<IEmail>> EmailQueryAsync(string query, Action<IEmail> callBack)
{
    return Task.Factory.StartNew (() => {
        var result = new List<IEmail>();

        using (var client = new ImapClient ()) {
            client.Connect ("imap.gmail.com", 993, true);

            client.AuthenticationMechanisms.Remove ("XOAUTH2");

            client.Authenticate (this.userName, this.password);

            var folder = client.Inbox;

            folder.Open (FolderAccess.ReadOnly);

            var uids = client.Inbox.Search (SearchQuery.FromContains (query));

            foreach (var uid in uids) {
                var message = folder.GetMessage (uid);

                var email = new Email (date: message.Date, id: message.MessageId, messageBody: message.TextBody, references: message.References);

                callBack (email);

                result.Add (email);
            }

            return result;
        }
    }
}

I changed your code to put the entire block of logic into a single task which will all run on the same thread rather than your previous block which would effectively just run synchronously anyway since it didn't actually parallelize anything (it can't, really, since you can't search a folder until you've opened the folder - which you can't do until you've authenticated - which you can't do until you've connected, etc).

As far replacing your GetMessageAsync() logic goes, since the ImapClient can only process a single command at a time anyway, it doesn't make sense to spawn potentially thousands of command tasks asynchronously so that they can all just hurry up and wait for the previously queued tasks. Better to just write a synchronous loop in this scenario.

Update 2017-12-14: This will no longer be the case in MailKit 2.0. 2.0 will no longer wrap the synchronous calls using Task.Run() which means that they will no longer spawn threads.


Checking if each char in a string is a decimal digit

In the cctype header, you have the std::isdigit(int) function. You can use this instead of your conditions that check if the character is between '0' and '9'.
You index into a std::string with an int inside the for loop. Use std::string::size_type as that is the proper type that can index into a std::string (int might be too small).
Mark the function as noexcept.
Consider passing the std::string parameter by reference if you're planning on using large number strings (~20 character numbers). This prevents unnecessary copying from dynamically allocated strings.
Check vs. the size instead of indexing into the string and checking if the current character is '\0'.
Qualify standard types with std::. Don't use using namespace std;.
There is no need to negate that first condition.
Bug: isNum("-") and isNum("+") return true. An additional check is required if the first character is '+' or '-'.
Naming is important. Your function is called isNum(), but I believe that isInt() better describes it; the function does not detect floating point numbers. Please also consider this comment by Toby Speight in regards to naming.

After changes are applied:

#include <string>
#include <cctype>

bool isinteger(std::string const& n) noexcept
{
    if (std::isdigit(n[0]) || (n.size() > 1 && (n[0] == '-' || n[0] == '+')))
    {
        for (std::string::size_type i{ 1 }; i < n.size(); ++i)
            if (!std::isdigit(n[i]))
                return false;

        return true;
    }
    return false;
}

Note 1: I've renamed the function to isinteger() to keep consistency with other similar functions such as isdigit(). I've also reordered the initial condition to take advantage of boolean short circuiting.

Note 2: As Rakete1111 points out, if your compiler hasn't caught up to C++11 yet, accessing the first character of an empty string is undefined behaviour.

The condition should be modified like so:

// check that the string is not empty, only if we're working with < C++11
if ((!n.empty() && std::isdigit(n[0])) || (n.size() > 1 && (n[0] == '-' || n[0] == '+')))
{
    // ...
}

However, if your compiler is C++11 (or later) compliant, you can safely leave it; accessing the first character of empty strings returns '\0' in that case.

See here for more information: http://en.cppreference.com/w/cpp/string/basic_string/operator_at


How would you improve this object model design to get around Covariance Issues with ObjectModel.Collection?

I think the model here is broken. If you have a RoadVehicle that's actually Truck, the interface lets you to add a normal Wheel to it, which is wrong.

One way to make it work is to make the collection immutable (e.g. IEnumerable<T>). This can be a reasonable solution if you're okay with setting the wheels only in the constructor.


Refactoring from if-else-if to Dictionary

Second option is definitely a preferred way over first one. Also you may consider a switch statement.

UPDATE. Since Region is a class then the only good way to avoid long if...else is the mapping like in your second variant

First option that you proposed (Map = new Dictionary<Region, Func<double?>>) requires the construction of Dictionary each time the method is executed. It is a waste of resources and time, and for this case even the if..else..if..else statements don't look that ugly :).

Second option (static Dictionary with fixed mappings) is a traditional way to branch the logic for your case. Moreover in certain cases C# compiler will compile the switch statement into static Dictionary to run lookups.


Decrypt multiple 10Mb files with defined password

I can't help too much as I don't have running code, but I can at least get rid of all List and Array conversions, that will make it run faster and reduce lot of memory garbage. I also removed all the optionals as immutability is our best friend :)

Is it ran once per stream and then it is closed or more than once per stream? There is no information about how stream is being handled and if it is closed properly. That can be issue.

fun InputStream.cipherDecryptWithSessionPwd(password: String): String {
    val payloadArray: ByteArray = this.readBytes()
    val salt = payloadArray.sliceArray(0 until 32)
    val spec = Rfc2898DeriveBytes(password, salt, 50000)
    val realData = payloadArray.sliceArray(32 until payloadArray.size)

    val keyBytes = spec.getBytes(256 / 8)
    val ivBytes = spec.getBytes(128 / 8)

    val cipher = Cipher.getInstance("AES/CFB/PKCS7Padding")
    val secretKey: SecretKeySpec? = SecretKeySpec(keyBytes, "AES")
    val ivSpec: IvParameterSpec? = IvParameterSpec(ivBytes)
    cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec)
    val byteArrayInputStream = ByteArrayInputStream(realData)
    val decipherStream = CipherInputStream(byteArrayInputStream, cipher)

    val d = BufferedReader(InputStreamReader(decipherStream, Charsets.UTF_8), 0xFFFF)
    return d.readLine()
}

Edit:

I was thinking what you could cache and only possible variable is I guess cipher:

val cipher = Cipher.getInstance("AES/CFB/PKCS7Padding")

It probably won't speed up performance as I expect it to be cached factory method, but you can try putting variable outside of function anyway :)


Function to generate all valid parentheses of n*2

isCombinationValid

          for(int i=0 ; i < comb.length() ; i++)
          {
              char current = comb.charAt(i);

Since you never use i for anything other than generating current, you could just

          for (char current : comb.toCharArray())
          {

This way you wouldn't have to manage i at all.

        if(st.isEmpty())
        {
            return true;
        }
        else
        {
            return false;
        }

This is more complicated than need be.

        return st.isEmpty();

This has the same result in seven fewer lines.

            if(current == '(')
            {
                st.push('(');
            }
            else
            {
                if(!st.isEmpty() && st.peek() == '(')
                {
                    st.pop();
                }
                else
                {
                    st.push(')');
                }
            }

Instead, you can say

            if (current == '(')
            {
                st.push('(');
            }
            else if (st.isEmpty())
            {
                return false;
            }
            else
            {
                st.pop();
            }

You know that anything in the stack must be a '(', so you don't need to peek to check.  And if you ever find an extra ')', you can quit immediately.  You already know that it's not well-formed.  So if the first character is a ')', you don't even have to go through the rest of the string.

I prefer not to use an else with an if !.  I just find the logic easier to follow this way.  And I switched to the more common else if rather than

getAllPossibleCombinations

        if (presentCombinations.isEmpty())
        {
            temp.add("(");
            temp.add(")");
        }
        else //From second call, add ( and ) for current values in stack
        {

You are doing this with each recursive call, but that's not necessary.  Rather than do this in getAllPossibleCombinations, replace

        ArrayList<String> allCombinations = getAllPossibleCombinations(2*a,new ArrayList<String>());
        ArrayList<String> prunedCombinations = new ArrayList<String>();

        for(String comb : allCombinations)

with

        List<String> initialCombinations = new ArrayList<>();
        initialCombinations.add("(");

        List<String> prunedCombinations = new ArrayList<>();
        for (String comb : getAllPossibleCombinations(2*a, initialCombinations)))

You don't need the ")" one at all, because no valid version can start with a closing parenthesis.

I also changed your use of ArrayList<String> as the variable type to just use List<String>.  Unless you use some functionality specific to ArrayList, it is generally better to use the interface (List) rather than the implementation (ArrayList) as the type.  This makes it easier to change the implementation in the future.

I also changed the right hand side to use the newer <> notation.  It's possible that your Java doesn't support that.  If so, just leave it as <String>.

One might argue that this makes getAllPossibleCombinations less reusable, as you have to pass a specific opening parameter.  This is true, but it was also true of your original.  To get around this, you can specify a version that does not require a List to be passed:

    public List<String> getAllPossibleCombinations(int maximumPairCount) {
        List<String> initialCombinations = new ArrayList<>();
        initialCombinations.add("(");

        return getAllPossibleCombinations(maximumPairCount - 1, initialCombinations);
    }

Now you could declare the two parameter version private, as all consumers should call this version instead.  And you can get rid of your isEmpty check, as it will never be called that way.  This won't shorten your code, but it will make it run faster, as you save checking isEmpty for nearly every call.

Optimization

The code that you link checks for validity as it builds the string.  If you do that, you don't have to save invalid combinations like "))))".  Since there are \$2^{2*n}\$ combinations but only a smaller number of these are valid, this should make your program take longer to run out of memory.

Note that if you do this, you don't return false if the stack has extra '(' in it.  It's valid for a partial expression to have unmatched '('.  What's invalid is unmatched ')'.


I think this is a good case for refactoring the ajax call out into its own method.  I have given some suggested changes in the code below.  My comments are inside /* ... */ comments.

/*
 * use more meaningful and specific name
var ajaxDetails;
*/
var carTreeXHR;

$('#carTree').on('changed.jstree', function (e, data) {
    /*
     * why initialize to i and j here?
     * use more meaningful name for selected ID's array
    var i, j, p = [];
    */
    var selectedIds = [];

    // create the id[] array
    /*
     * initialize i and j here.
     * simplify call to get node id from existing 'node' object
    for (i = 0, j = data.selected.length; i < j; i++) {
        node = data.instance.get_node(data.selected[i]);
        if (node.data.type != 'root') {
            p.push(parseInt(data.instance.get_node(data.selected[i]).id));
        }
    }
    */
    for (var i = 0, j = data.selected.length; i < j; i++) {
        var node = data.instance.get_node(data.selected[i]);
        if (node.data.type != 'root') {
            selectedIds.push(parseInt(node.id));
        }
    }
    /*
     * remove from this location and put inside  new function
    // cancel previous request
    if ((ajaxDetails && ajaxDetails.readyState != 4)) {
        ajaxDetails.abort()
    }
    */

    // get only selected cars info.
    /* call new function */
    updateCarTreeDetails(selectedIds);

   /*
   * remove to function
   ajaxDetails = $.ajax({
        type: 'POST',
        url: '@Url.Content("/GTracker/Cars/CarTreeDetails")',
        data: { "id": p },  //cars list
        traditional: true,
        success: function (data) {
            $('#footer-details').html(data);
        }
    });
    */
});

/* New function. Include in appropriate scope */
function updateCarTreeDetails(selectedIds) {
    // abort existing request if needed
    if ((carTreeXHR && carTreeXHR.readyState != 4)) {
        carTreeXHR.abort()
    }
    // execute new request
    // not shown - consider handling ajax failure case as well
    carTreeXHR = $.ajax({
        type: 'POST',
        url: '@Url.Content("/GTracker/Cars/CarTreeDetails")',
        data: { "id": selectedIds },  //cars list
        traditional: true,
        success: function (data) {
            $('#footer-details').html(data);
        }
    });
}

/* In your document.ready handler, you can call this function
 * just like you did inside the change handler */
updateCarTreeDetails([]);

One additional note - it seems odd to be executing a 'POST' method if a case where you are just reading data from the remote data source (i.e. you are not performing a create, update, or delete operation).  If you have control over this API, you might consider implementing as GET.


Print the first, last, and in-between integers of a range

As you ask for optimization:

You re-evaluate Math.abs() in each iteration of the loop, which is a constant value. Consider for(int n = 1, upperBound = Math.abs(b - a); n < upperBound; n++) instead.
The same goes for if (b > a) which is also constant. Maybe calculate an offset beforehand int offset = (b > a) ? 1 : -1; and then just add the offset in the loop.
... and if you already calculate such an offset, you may also use it to replace getInitial() with initial = a + offset;


Writing a set of JavaScript conditionals more efficiently

I like @janos solution, but if that is not possible for you, you might extract the code into a function. I know, it's just one line of code, but I think it would still be beneficial:

// marks className element as complete if isEdit is true
function addComplete(isEdit, className) {
    if (isEdit) {
        $(className).addClass("complete");
    }
}

addComplete(stepOneEdited, stepOne);
addComplete(stepTwoEdited, stepTwo);
addComplete(stepThreeEdited, stepThree);
addComplete(stepFourEdited, stepFour);
addComplete(stepFiveEdited, stepFive);
// stepSix depends on stepFiveEdited, not stepSixEdited
addComplete(stepFiveEdited, stepSix);

This way, each additional step only takes one line instead of three, I think that this makes it a lot more readable (and also adding a new case is a lot easier). The other benefit is that it is easier to adapt this code if the specification changes. For example if the class name changes, or if instead of adding a class, the program should react differently, you only need to change it in one place.


Shorter way of writing my displayError() function?

I don't use Javascript, but i could write it in this way:

function displayError(display, string, xhr)
{
    var args = arguments;
    var $error = $("div#error");
    var visible = $error.is(":visible");

    if (!display)
    {
        $error.slideUp();
    }
    else
    {

        if (visible)
        {
            switch (args.length)
            {
                case 1:
                case 2:
                    $error.fadeOut(function ()
                    {
                        $(this).html('(!) ' + string).fadeIn();
                    });
                    break;
                case 3:
                    $error.fadeOut(function ()
                    {
                        $(this).html('(' + xhr.status + ") " + string).fadeIn();
                    });
                    break;
            }
        }
        else
        {
            $error.html('(' + xhr.status + ") " + string).slideDown();
        }
    }
}

But why you use args.length == 1/2/3 if you don't do anything with it?
You could just write:

function displayError(display, string, xhr) {
    var $error = $("div#error");
    var visible = $error.is(":visible");
    var status = typeof xhr === "object" ? xhr.status : "!";

    if (display) {
        if (visible) {
            $error.fadeOut(function () {
                $(this).html('(' + status + ') ' + string).fadeIn();
            });

        } else {
            $error.html('(' + status + ") " + string).slideDown();
        }
    } else {
        $error.slideUp();
    }
}

I used var status = typeof xhr === "object" ? xhr.status : "!"; so you will get the status if xhr is an object, or ! if not.

I removed all typeof parts since i found it useless, you will always get a string so why you worry about it


It is generaly a bad idea to shadow a builtin (like list) by using a variable named after it.
You can use slices and array extension to simplify a bit your algorithm:

def unpack(n, lst):
    result = lst[:n]
    return result + [None] * (n - len(result))

You can use the itertools module to improve memory management and allow for any iterable:

import itertools

def unpack(n, iterable):
    infinite = itertools.chain(iterable, itertools.repeat(None))
    return itertools.islice(infinite, n)

Python 3 has an extended unpacking capability that is closer to your needs:

>>> x, y, *z = [1, 2]
>>> print(x, y, z)
1, 2, []


Faster way to perform function calculation in Python?

This continues from Jaime's post.

This can be trivially sped up to \$\mathcal{O}(1)\$ by caching sum(1/j for j in range(1, 10001)) = 9.787606036044348. Then one just does

def func_O1(mass, density):
    # 9.7876... = sum(1/j for j in range(1, 10001))
    return log(mass * density) * 9.787606036044348

This gives a speedup by a factor of 3000.

If the limit (10000) is varied, use an approximation for the harmonic series:

from math import log

def harmonic(n):
    gamma = 0.57721566490153286060651209008240243104215933593992
    return gamma + log(n) + 0.5/n - 1./(12*n**2) + 1./(120*n**4)

def func_fastest(mass, density):
    return log(mass * density) * harmonic(10000)

harmonic is inaccurate below \$n \approx 120\$ so it would make sense to cache exact values up to harmonic(120). Note that whilst this is an approximation, for \$n\$ greater than \$120\$ it's exact \$\pm 1\text{eps}\$ whereas the summation gets steadily worse.

This only speeds up the function by a factor of 500.


Formatting the opposite of some numbers, with decimal alignment

There are only really two things you need here.

float. Which allows you to convert the input to a floating point number. If you change to needing more precision or larger numbers, decimal would be a better choice - thanks @200_success. And,
str.format. Which uses the Format String Syntax. Which you can use pad the left with spaces, so the output has a width of eight. {: >8}. This however needs to be adjusted for your "there always are 3 numbers in the decimal" requirement, and so you can force this too with {: >8.3f}.

And so I'd use:

def opposite(x):
    return '{: >8.3f}'.format(-float(x))

If however you don't want to use float then you can use str.lstrip. With just one if-else:

def opposite(x):
    x = x.lstrip()
    if x.startswith('-'):
        x = x[1:]
    else:
        x = '-' + x
    return '{: >8}'.format(x)


I know this is technically outside the scope of the review here, but your first parameter's type is Method.  This enum desperately needs to be renamed.  When I see Method, I cannot help but think of a programming method... I think you're passing a pointer to a class's method here.  This type needs a better, more descriptive name.

Our sender parameter doesn't need to be a UIViewController.  Does it?  In fact, are we even using the sender parameter?  Can we just eliminate it?

The postParams needs to be an AnyObject parameter.  We can turn more than just dictionaries into valid JSON.  The NSJSONSerialization class offers a isValidJSONObject method for which to check whether or not we can serialize.  So, we can leave this parameter as is, and simply make this check:

if let param: AnyObject = postParams {
    if NSJSONSerialization.isValidJSONObject(param) {
        urlRequest.HTTPBody = NSJSONSerialization.dataWithJSONObject(param, options: nil, error: nil)
    } /* else {
        // call the error handler?
    } */
}

And finally, one comment on the parameters our method takes... taking two completion blocks isn't the suggested best practice.  By taking two completion blocks, you force the user into duplicating any code they want to happen whenever this callback occurs (if they want it to happen under both scenarios).   So, we should combine these arguments into a single completion block (much like AFmanager is doing in the code you're using) and more importantly, we should make this argument the last argument.

In Swift, when the last argument is a closure, we get a slightly nicer syntax.  Instead of something like:

someObject.someMethod(param1: foo, param2: bar, closureParam: { println("hello world") })

We get a slightly better syntax:

someObject.someMethod(param1: foo, param2: bar) {
    println("hello world")
}

Again, you made use of that when you used the AFmanager, so let's make our code follow suit.  Combine your success and error completion handlers into a single closure parameter which is called no matter success or failure, and move it to the last argument to give users a better syntax option (and so we don't have any dangling parameters after the space-consuming closure).


Write int, short int or any integer value in a file in binary form using fputc

Using malloc() and free() in readListPos() seems like overkill. You could use:

short s;
char *posChar = (char *)&s;

for (int i = 0; i < sizeof(s); i++)
{
    int c;
    if ((c = fgetc(comp->inputFile)) == EOF)
        …handle EOF…
    *posChar++ = c;
}
return s;

Note that this code handles EOF, unlike the original; you must always error check your inputs.

This code matches the code that writes the data.  It is, however, tied to a particular endian-ness; the written data is not portable between, say, an Intel machine and a SPARC or PowerPC machine.  If that doesn't matter to you, then you're more or less OK.

For non-portable reading and writing of binary data, the fread() and fwrite() functions are simpler.

Reading:

short s;
if (fread(&s, sizeof(s), 1, comp->inputFile) != 1)
    …process error/EOF…
return s;

Writing:

if (fwrite(&listPos, sizeof(listPos), 1, comp->outputFile) != 1)
    …process error…

If you're doing it portably, you define whether the number is written big endian or little endian and then write the bytes in that order on both big endian and little endian machines.  (If you can demonstrate it's a performance problem, you can optimize one of the two platform types, but it complicates the code for what is usually negligible benefit.  ('Premature optimization is the root of all evil.')


Some thoughts:

Writing testCode(h1.textContent = world) is a bit unconventional, and might not do what you expect: this is the same as writing the two lines
h1.textContent = world;
testCode(world);

because the assignment (the first line) evaluates to the value of the right hand side.

Instead of writing var code = codeEntered;, you can save yourself a line and just use the variable codeEntered instead of making a new variable.

The line  var run = code *= 1; also is a bit unexpected. This is equivalent to writing
code = code * 1;
var run = code;

But code is a string, and multiplying it by 1 evaluates to NaN (try it!), so after that line, code == run == NaN.

Code style: return(run); would typically be written return run; instead (it's not a function).

In summary, testCode actually always returns NaN, but the value then gets thrown away because it isn't used anywhere. In effect, your code actually just runs h1.textContent = world when you click the button, then runs testCode whose value isn't used (but is always NaN anyway).

I hope this gives you some useful feedback.


Sampling words from randomly chosen text files

Since your code performs multiple things at once, you should split it into functions for readability. A first naive rewrite can yield:

from collections import Counter
import random

def filter_text(text):
    return (text
            .replace('\n', ' ')
            .replace('\xa0', '')
            .replace('  ', '')
            #Removing these automated notifications
            .replace('Wichtiger Hinweis:Diese Website wird in älteren Versionen von Netscape ohne graphische Elemente dargestellt. Die Funktionalität der Website ist aber trotzdem gewährleistet. Wenn Sie diese Website regelmässig benutzen, empfehlen wir Ihnen, auf Ihrem Computer einen aktuellen Browser zu installieren.Zurück zur Einstiegsseite Drucken Grössere Schrift', '')
            .replace('Vorwärts ähnliche Leitentscheide suchenähnliche Urteile ab 2000 suchen Drucken nach oben', '')
            .replace('Bundesgericht Tribunal fédéral Tribunale federale Tribunal federal', '')
            .replace('Navigation Neue Suche Zurück zum Suchresultat Rang: Zurück 180', '')
            .replace('Navigation Neue Suche Zurück zum Suchresultat Rang:1 ähnliche Leitentscheide suchenähnliche Urteile ab 2000 suchen Drucken nach oben', '')
            .replace('  ', ' '))

def create_string_from_files(files, root='txt_sr_de/txt_sr_de', sample=50):
    #creating random list
    random_list = []
    for item in range(sample):
       list_item = random.choice(files)
       random_list.append(list_item)

    #creating long string
    long_str = ''
    for de in random_list:

        input_file = open(os.path.join(root, de), 'r')
        text = input_file.read()

        long_str = long_str + filter_text(text)
    return long_str

def extract_most_common_sequence(text, minimum_occurences=3, times=3):
    for n in range(1,int(len(text)/times+1)):
        substrings=[text[i:i+n] for i in range(len(text)-n+1)]
        freqs=Counter(substrings)
        if freqs.most_common(1)[0][1] < minimum_occurences:
            n-=1
            return seq
        else:
            seq=freqs.most_common(1)[0][0]

def main(files, repeat=100):
    str_seq_list = []

    for str_seq in range(repeat):
        long_str = create_string_from_files(files)
        str_seq_list.append(extract_most_common_sequence(long_str))

    return str_seq_list

if __name__ == '__main__':
    import pickle
    de_list_soz = pickle.load(open('de_list_soz.p', 'rb'))
    str_seq_list = main(de_list_soz)
    pickle.dump(str_seq_list, open('SOZIALRECHT_DE.p', 'wb'))

Now we can start cleaning things up.

In create_string_from_files, you are basically reinventing random.sample:

>>> import random
>>> random.sample('abcdefghi', 4)
['h', 'e', 'c', 'f']

You also happen to open files but never close them: use the with statement to automatically handle that.

Lastly, concatenating long sentences manually is not memory efficient. Let's ask str.join to do it for us for now. But in order to do it nicely, we need to split the function further:

def read_and_filter_file(filename):
    with open(filename) as input_file:
        text = input_file.read()
    return filter_text(text)

def create_string_from_files(files, root='txt_sr_de/txt_sr_de', samples=50):
    return ''.join(
        read_and_filter_file(os.path.join(root, de))
        for de in random.sample(files, samples)
    )

The same kind of improvements can be made to the main function by replacing the "create empty list + for loop + append" template by a more efficient list-comprehension:

def main(files, repeat=100):
    return [
        extract_most_common_sequence(create_string_from_files(files))
        for _ in range(repeat)
    ]

The extract_most_common_sequence function can also be optimized by using some itertool recipe. I’m thinking about a variation of the pairwise recipe since your list-comprehension, with n being 2 is pretty much it. i.e. using:

>>> long_str = 'This is a test'
>>> n = 2
>>> [long_str[i:i+n] for i in range(len(long_str)-n+1)]
['Th', 'hi', 'is', 's ', ' i', 'is', 's ', ' a', 'a ', ' t', 'te', 'es', 'st']
>>> n = 4
>>> [long_str[i:i+n] for i in range(len(long_str)-n+1)]
['This', 'his ', 'is i', 's is', ' is ', 'is a', 's a ', ' a t', 'a te', ' tes', 'test']

So using something like:

def tuplewise(iterable, length):
    tees = itertools.tee(iterable, length)
    for i, t in enumerate(tees):
        for _ in xrange(i):
            next(t, None)
    return itertools.izip(*tees)

For Python 2 or:

def tuplewise(iterable, length):
    tees = itertools.tee(iterable, length)
    for i, t in enumerate(tees):
        for _ in range(i):
            next(t, None)
    return zip(*tees)

for Python 3, you can simplify the writting and save a bit on memory usage like so:

def extract_most_common_sequence(text, minimum_occurences=3, times=3):
    sequence = ''
    for n in range(1, int(len(text)/times+1)):
        freqs = Counter(tuplewise(text, n))
        (most_frequent, higher_frequency), = freqs.most_common(1)
        if higher_frequency < minimum_occurences:
            break
        sequence = ''.join(most_frequent)
    return sequence

Now I defined sequence = '' as a security measure in the unlikely event that the text is quite short an no letter appear more than twice. It's just to make the function return something in each and every cases.

Now that the code is more readable, let's tackle that memory issue of yours.

The thing to note is that aggregating the content of 50 files in one single string in memory is likely to blow things up. So instead, let's use some disk storage. We'll use the tempfile module for that. The idea is to store the filtered bits of text into a single file and read that file (over and over again) to get the desired most common sequence. We thus need to adapt our tuplewise a bit to either read one character at a time and yield words of the requested size or, better as I/O is concerned, repeatedly read a block of data of a fixed size and grab caracters out of it one by one to produce words of the desired size:

import os
import random
import itertools
import tempfile
from collections import Counter

def filter_text(text):
    return (text
            .replace('\n', ' ')
            .replace('\xa0', '')
            .replace('  ', '')
            #Removing these automated notifications
            .replace('Wichtiger Hinweis:Diese Website wird in älteren Versionen von Netscape ohne graphische Elemente dargestellt. Die Funktionalität der Website ist aber trotzdem gewährleistet. Wenn Sie diese Website regelmässig benutzen, empfehlen wir Ihnen, auf Ihrem Computer einen aktuellen Browser zu installieren.Zurück zur Einstiegsseite Drucken Grössere Schrift', '')
            .replace('Vorwärts ähnliche Leitentscheide suchenähnliche Urteile ab 2000 suchen Drucken nach oben', '')
            .replace('Bundesgericht Tribunal fédéral Tribunale federale Tribunal federal', '')
            .replace('Navigation Neue Suche Zurück zum Suchresultat Rang: Zurück 180', '')
            .replace('Navigation Neue Suche Zurück zum Suchresultat Rang:1 ähnliche Leitentscheide suchenähnliche Urteile ab 2000 suchen Drucken nach oben', '')
            .replace('  ', ' '))

def read_and_filter_file(filename):
    with open(filename) as input_file:
        text = input_file.read()
    return filter_text(text)

def create_string_from_files(output, files, root='txt_sr_de/txt_sr_de', samples=50):
    for filename in random.sample(files, samples):
        output.write(read_and_filter_file(os.path.join(root, filename)))

def read_chunks(file_object, chunk_size, block_size=4096):
    word = file_object.read(chunk_size)
    yield word
    while True:
        data = file_object.read(block_size)
        if not data:
            return
        for character in data:
            # Drop first character and append the next one
            word = word[1:] + character
            yield word

def extract_most_common_sequence(input_file, minimum_occurences=3, times=3):
    input_file.seek(0, os.SEEK_END)
    file_size = input_file.tell()
    sequence = ''

    for n in range(1, int(file_size/times+1)):
        input_file.seek(0)  # Be sure to read the whole file each time
        freqs = Counter(read_chunks(input_file, n))
        (most_frequent, higher_frequency), = freqs.most_common(1)
        if higher_frequency < minimum_occurences:
            break
        sequence = most_frequent
    return sequence

def main(files):
    with tempfile.NamedTemporaryFile(mode='w+') as storage:
        create_string_from_files(storage, files)
        return extract_most_common_sequence(storage)

if __name__ == '__main__':
    import pickle
    de_list_soz = pickle.load(open('de_list_soz.p', 'rb'))
    str_seq_list = [main(de_list_soz) for _ in range(100)]
    pickle.dump(str_seq_list, open('SOZIALRECHT_DE.p', 'wb'))

I changed main into returning a single element rather than a whole list as it feels cleaner with this implementation. The whole repetition thing is done in the test code now.


Each blood factor can be present or not present.  The blood types can be bit-encoded using one bit for the A factor, one bit for the B factor, and one bit for the Rh factor.

enum { A=1, B=2, Rh=4 };

You would parse the blood type "AB+" as A + B + Rh == 7, and "O-" as 0 because it does not contain any A factor, B factor, or Rh factor.

Survival requires the donor's blood not contain any factors missing in the recipient's blood type.  Compliment the recipient's blood type to get the bad factors, and use a bit-wise and operation to test that all of the factors are not present in the donor's blood.

bool donor_matches = (donor & ~recipient) == 0;

If you want to leave you enum's as encoding the 4 blood types, and the Rh factor separately, you can get to a similar coding.

Note that:

enum { O, A, B, AB } abo;

will define O=0, A=1, B=2, AB=3, so you have a similar bit assignment as above.  The Rh factor on the other hand would be better to reverse the order:

enum { M, P } rh;

so that M=0, P=1.  Now you could express the match condition:

bool donor_match = (donor_abo & ~recipient_abo) == 0 && (donor_rh & ~recipient_rh) == 0;

Finally, if you want to leave the rh enum as you have originally defined it:

enum { P, M } rh;

then note that donor_rh >= recipient_rh would express that the rh factors match, or the donor has a less-restrictive (numerically higher) rh factor.


Binary search: first/last/random occurrence

You want to have the ability to choose between finding the first, last and a random occurrence of an element in a list. Since you have three options, you cannot use true/false, and numbers aren't very intuitive (and they usually end up magic numbers). The remaining options are strings, functions or some other data structure. Since you don't like strings, and other data structures wouldn't make much sense (why use a complex object when a simple one will suffice?), then let's stick to functions.

But wait, you don't want any code duplication. That's perfectly ok. We note that all 3 of these options involve variations of calling the basic binary search.

Let's create a basic binary search that outputs a few extras:

def _binary_search(array, element, low, high):
    """Binary search that returns (index, low, high) of the final search step"""
    while low <= high:
        mid = (low + high) // 2
        current_element = array[mid]
        if current_element == element:
            return (mid, low, high)
        elif current_element < element:
            low = mid + 1
        elif current_element > element:
            high = mid - 1

    return (-1, 0, 0)

Then, let's create the new functions:

def lower_bound(array, element):
    """Returns the index of the first occurrence of element in array"""
    index = -1
    first_index, low, high = _binary_search(array, element, 0, len(array)-1)
    index = first_index
    while first_index != -1:
        index = first_index
        first_index, low, high = _binary_search(array, element, low, first_index-1)
    return index

def upper_bound(array, element):
     """Returns the index of the last occurence of element in array"""
     index = -1
     first_index, low, high = _binary_search(array, element, 0, len(array)-1)
     index = first_index
     while first_index != -1:
         index = first_index
         first_index, low, high = _binary_search(array, element, first_index+1, high)
     return index

def binary_search(array, element):
    """Basic binary search"""
    lower_bound = 0
    upper_bound = len(array) - 1
    return _binary_search(array, element, lower_bound, upper_bound)[0]

This has the advantage of being readable, not susceptible to spelling errors ("First" vs "first" vs "fist") and not having much in the way of duplicated code.

As a fun fact: this entire problem can be easily solved by making wrappers around bisect_left and bisect_right from the bisect module like this very convenient SortedCollection Python recipe has done here.

Update:

Renamed functions to comply with standards as per comments
Changed algorithms to not create new arrays and instead do an in-place binary search
Changed algorithms to produce the correct results
Added reference to an easy to use Python recipe that implements this, and other features.


Ability to forget the memoized supplier value

Class names should be nouns. I'd rename DoubleCheck to DoubleCheckedResource or something similar.
ForgettableMemoizingSupplier should not allow null suppliers. You should check that and throw a NullPointerException.
The name of the invalid method in the DoubleCheck class is ambiguous. Does it invalidate something or does it check that something is valid or not? It seems that the latter is true, so I'd call this isInvalid (or isValid to eliminate the negation).
The T t field could be in the DoubleCheck anonymous subclass because this is the only class which uses it.
Is DoubleCheck a ReentrantReadWriteLock? Currently it is. I think your clients should not be able to call getOwner(), writeLock() or isFair() on a DoubleCheck instance. I'd use composition instead of inheritance here:

public abstract class DoubleCheck<T> {

    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    private final ReadLock readLock = lock.readLock();

    private final WriteLock writeLock = lock.writeLock();

    ...

}

Check Effective Java, Second Edition, Item 16: Favor composition over inheritance.
The get method with the lock() call in the finally block smells a little bit. Are you sure that the object will always be in a consistent state? What happens when retrieve(), create() or invalid() throws an exception? Will  all locks be released properly?

If I'm right the following is the same but use the usual lock(); try { use() } finally { unlock(); } construction:

public T get() {
    readLock.lock();
    try {
        final T value = retrieve();
        if (!isInvalid(value)) {
            return value;
        }
    } finally {
        readLock.unlock();
    }

    writeLock.lock();
    try {
        T value = retrieve();
        while (isInvalid(value)) { // this spins until no more invalidations
                                   // are made
            value = retrieve();
            if (isInvalid(value)) {
                value = create();
            }
        }
        return value;
    } finally {
        writeLock.unlock();
    }
}

(Please note that in the original code between the readLock.unlock() and writeLock.lock() calls another threads could get the read lock, therefore more than one thread could acquire the write lock at the same time.)
If you can ignore the forget calls which are parallel with get calls it could be more simple:

public T get() {
    readLock.lock();
    try {
        final T value = retrieve();
        if (!isInvalid(value)) {
            return value;
        }
    } finally {
        readLock.unlock();
    }

    writeLock.lock();
    try {
        T value = retrieve();
        if (!isInvalid(value)) {
            return value;
        }
        return create();
    } finally {
        writeLock.unlock();
    }
}

(Here if (isValid(value)) would be more natural than the current if (!isInvalid(value) ....)
I'd consider using an AtomicReference and a simple ReentrantLock too:

public final class ForgettableMemoizingSupplier<T>
        implements ForgettableSupplier<T> {

    private final Supplier<T> delegate;

    private final AtomicReference<T> resourceRef = new AtomicReference<T>();

    private final ReentrantLock lock = new ReentrantLock();

    public ForgettableMemoizingSupplier(final Supplier<T> delegate) {
        this.delegate = checkNotNull(delegate, "delegate cannot be null");
    }

    @Override
    public void forget() {
        resourceRef.set(null);
    }

    @Override
    public T get() {
        final T resource = resourceRef.get();
        if (resource != null) {
            return resource;
        }
        return getAndSetResource();
    }

    private T getAndSetResource() {
        lock.lock();
        try {
            final T resource = resourceRef.get();
            if (resource != null) {
                return resource;
            }
            final T newResource = delegate.get();
            resourceRef.set(newResource);
            return newResource;
        } finally {
            lock.unlock();
        }
    }
}

(Untested code.)


This is an interesting problem. I think your solution will be possible and much, much faster if you use memoization. This is the process where you remember your previous calculations and reuse them in your current calculations.

So, for example, suppose you process your array row-by-row.... if your input 2D array is:

1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1

And we were now processing the second row, and fourth column, our current result would look like (our current position is marked with a ?):

1 2 3 4 5 6 7
2 4 6 ? 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0

Now, at that position, we know that the value will be 8 because we are human, and can see that. The best algorithm on the computer though, to get that 8, is that we can split the data we know in to 4 areas....

Consider the input data again (I have marked our spot with the parenthesis):

1 1 1 1 1 1 1
1 1 1(1)1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1

The 4 areas that we can think of as special are:

the value we are processing right now (the value 1)
the column above the us (contains the values [1])
the row we have processed so far (contains the values [1, 1, 1])
the rectangle above-left of where we are so far (contains the value [1, 1, 1] as well)

Now, what is the sum of the values in the rectangle? We know that, because we have our grid right now which looks like:

1 2(3)4 5 6 7
2 4 6 ? 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0

So, the rectangle from (0,0) to (0,2) has the sum 3 which has already been calculated (and which I have marked with parenthesis).

We have also calculated the sum of the data in the row to the left of us... look at the grid again:

1 2(3)4 5 6 7
2 4(6)? 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0

The sum of the values in the row to the left is the difference between the rectangle above left, and the rectangle plain-left, or 6 - 3 == 3.

Similarly, the sum of the values in the column above us, is the sum of the rectangle above us, less the rectangle above-left of us.

So, for any position in the solution matrix, the solution-sum of the values is:

the value at this point
plus the sum of all values above-left of us
plus the sum of all values above us
plus the sum of all values to the left.

Using a more convenient input format than the scanner, this can all be done in a single loop....

int[][] sumAboveLeft(int[] datasource) {
    if (datasource == null || datasource.length == 0 || datasource.length != datasource[0] * datasource[0] + 1) {
        throw new IllegalArgumentException();
    }
    // first value in the source data is the matriz size
    final int size = datasource[0];
    // because the first value is the size, we expect the loop limit to be unusual.
    final int limit = datasource.length - 1;

    int[][] result = new int[size][size];

    for (int i = 0; i < limit; i++) {
        // convert the linnear/flat address to a row/column
        int row = i / size;
        int col = i % size;

        // rectangle-sum above us
        int abovesum = row > 0 ? result[row - 1][col] : 0;
        // rectangle-sum to left of us
        int leftsum = col > 0 ? result[row][col - 1] : 0;
        // rectangle-sum above-left of us.
        int aboveleftsum = (col > 0 && row > 0) ? result[row - 1][col - 1] : 0;
        // our value at this point (note the index+1 offset because the first value is the size)
        int val = datasource[i + 1];
        // the sum here is
        // the value here
        // plus above-left-rectangle-sum
        // plus above-column-sum
        // plus left-row-sum
        result[row][col] = val
                         + aboveleftsum
                         + (leftsum - aboveleftsum)
                         + (abovesum - aboveleftsum);
    }
    return result;

}

I have put a lot of comments in there for you...

I have also tested it with:

public static void main(String[] args) {
    System.out.println(Arrays.deepToString(sumAboveLeft(new int[]{
         7,
         1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1,
         1, 1, 1, 1, 1, 1, 1,
    })));
}

So, the process can be done in O(n), where n is the number of members in the matrix.


Holding a reference of the active Android Activity

First, I would recommend that you take a look at the null object pattern to avoid the != null check here:
if (rateMyApp != null)
    rateMyApp.appLaunched(activity);

By using a "null object", simply rateMyApp.appLaunched(activity); would be enough. Your null object is an instance of a special class that just doesn't do anything in the appLaunched method.

The first thing I'd like to ask is if it acceptable to require the creation of a new class extending Application just to hold the main component of my library.

No. Absolutely not. I don't really see why you are using the Application to do that. You could write a regular Java class for holding the main component of your library. Or rather, you could let the user of your library determine how to hold the main component of your library.
Instead of using the onCreate method of the Application, you could let the user initialize the RateMyApp object in the onCreate of a regular Activity.

I'd also like to get a feedback about the fact that my library needs to create instances of DialogFragment and to start new activities. Both these tasks require an active Activity and this is a source of a bit of trickery.

Technically, those tasks don't need an active Activity. They need a Context. However, "acquiring" an activity should not be that much of a problem. See below.

I don't really like how I get the class extending Application to get a reference of the current Activity.

Me neither. Why does it need a reference of the current activity?

Would you do it in an alternative (and possible cleaner) way?

Let the user whenever he likes create a RateMyApp object, and call the .appLaunched method on it (as you've done in the sample). There is no need for your RateMyApp to know which is the current showing activity, it only needs to know about an activity (or rather, Context) when it should do something - i.e. possibly show a dialog or read/write the preferences to keep track on how many times/days the application has been used. When the user of your library wants your library to possibly show the dialog, let it call a method on your library and pass along the current Activity as a parameter. That's it. No need to make things more complicated than necessary.
Summary
By extending Application as you've done in your question, you have only added a middle hand that doesn't add any value at all. All the things that are done there can, and in this case really should, be done in the MainActivity instead.


Running a script recursively in subdirectories

Check yourself before you wreck yourself...

shellcheck.net is an awesome website that checks your Bash syntax.
Among other things, it will tell you to:

Double-quote your path variables
Use $(...) instead of the legacy `...` for sub-shells

Avoid cd inside scripts

cd inside scripts is troublesome.
In case something goes wrong,
you might find yourself in unexpected places, and wreak havoc.

But if you must, like in your example,
there's a better way than saving the previous directory in PREV_DIR and then cd "$PREV_DIR" to go back, using a (...) sub-shell environment:

(
cd "$f" || break
RESULT=$(eval "$RUN_SCRIPT")
local RESULT_CODE=$?
if [ $RESULT_CODE -eq 0 ]; then
    echo "$f"
    echo "$RESULT"
    echo
else
    recurseCheck "$f"
fi
)

Notice that there is only one cd in, no cd out.
This is because the cwd changes only affect the environment inside the (...).

Also notice the cd "$f" || break: if the cd command fails for some reason,
you probably don't want to execute the rest of the block.
You might go as far as exit at that point (shellcheck recommends it too) and investigate the troublesome directory.

Minor things

You had a pointless ; in done;, and instead of echo "" you can write simply echo.

Input validation

What if you run this script without arguments?
eval "" exits with success, so it will simply print all directories.
If that's ok, then everything's fine.
If not, then you might want to add some input validation, for example:

if [ ! "$RUN_SCRIPT" ]; then
    echo usage: $0 'some script'
    exit 1
fi

Suggested implementation

Putting it together (coming to you in a Pull Request very soon):

#!/bin/bash

RUN_SCRIPT=$1

recurseCheck() {
    local f
    for f in $1/* ; do
        if [ -d "$f" ]; then
            (
            cd "$f" || break
            RESULT=$(eval "$RUN_SCRIPT")
            local RESULT_CODE=$?
            if [ $RESULT_CODE -eq 0 ]; then
                echo "$f"
                echo "$RESULT"
                echo
            else
                recurseCheck "$f"
            fi
            )
        fi
    done
}

START_DIR=$(pwd)
recurseCheck "$START_DIR"


I want to get weekdays for common time sets from the following hashmap

The thing you need to do is commonly called "grouping", i.e. you iterate over a given dataset, take one property (the time in your case) and collect the entries with the same property in a useful structure.

Fortunately, java (8+) already can do this for you by streaming through the map entries and grouping them all automagically:

    Map<String, List<Map.Entry<String, String>>> grouped = days.entrySet().stream()
        .collect(Collectors.groupingBy(Map.Entry::getValue));

OK, the data-structure looks a little wierd here, because your list consists of map-entries, but this was the main work. If you print this result, you already get (format added manually):

{
     9-4=[TUE=9-4],
     9-5=[MON=9-5, WED=9-5, THU=9-5, FRI=9-5],
     Closed=[SAT=Closed, SUN=Closed]
}

... which is exactly what you need from a data perspective. Using a further iteration over this map which uses the time as a key and the old map's entries as values to format the respective output should be quite trivial.

BTW: to keep the order of the days, you should use a LinkedHashMap instead of a HashMap.


Interactive dictionary with inexact lookups (step 1)

The biggest thing that jumps out at me is that your project isn't in the form of a class, it's a function. This is, while not quite discouraged, certainly non-advantageous. Classes make things more portable. If I were building this, I'd structure it something like this:

class fuzzydict:
  """Fuzztdict: A dictionary with inexact lookups
       #Function definitions, etc go here.
  """
  def __init__(self):
    #Create the data file, initialize all your other variables.
  def __str__(self):
    #This one isn't necessary, but it would allow you to customize what would happen when you call print on a fuzzydict.
  def find_word(self,word):
    #Find a word in the dictionary, or report that it (probably) doesn't exist.
  def add_word(self,word,definition):
    #Add a word to the dictionary.

Then, you'd instantiate it with newDict = fuzzydict() and you'd be good to go. You can use stuff like newDict.find_word('apple'), which is a much more intuitive interface than your while loop.

A few other things about your code:

You're checking various versions of your data in the JSON. Do you intend to eventually be able to input data yourself? Then I'd suggest formatting your entries into all UPPER or all lower case, then including how they were originally inputted as an attribute for that entry. This'll eliminate the multiple checks.
Error handling. The difference between a good program and a truly epic program is how gracefully it can recover from something it didn't expect.
As stated in other answers, document. Document, document, document. Even when it's just a particularly interesting way of doing something, make your code as descriptive as possible. Future you will thank you, as well as anybody else who tries to decipher the finished project. Remember docstrings, they're a gift from whatever deities the creators of Python worship.


I suspect you’re stuck using one-pop-at-a-time if you want to get multiple elements at once.

I found this quote from one of the collections developers on Stack Overflow about using pop() for many elements in a deque:

  There is no multi-pop method for deques.

The OP on that question had a very similar construction to you (they were saving the data to a list rather than a str), and he said:

  Yes, it is correct. Yes, it is reasonably efficient though it can be further sped-up with boundmethods and itertools. No, it isn't stupid :-)

I don’t know enough about boundmethods or itertools to know what he was suggesting.

That doesn’t seem particularly helpful, so here are a few other comments on your general coding style:

You shouldn’t have a space immediately before the opening parens that starts a list of arguments to a function. (PEP 8: Pet Peeves)
It’s also recommended that you don’t have a space around the equals sign for keyword arguments or default values. (PEP 8: Other Recommendations)
In the interest of using descriptive variable names, I see no reason not to extend the length of the variable name _buf to _buffer. Characters are cheap.
Lines should be limited to 79 characters (PEP 8: Maximum Line Length), which includes docstrings: specifically, the docstring for peek().
If you have a single double-quote within a triple-quoted string, you don’t need to escape it. You only need to escape quotes within a triple-quoted string if you have three of them at once.
The docstring for RingBuffer() is almost useless. It tells me nothing that I couldn’t have learnt from the name of the class.

And a few comments on your get() method in particular:

In the for loop, your index variable is named i, but you never use the value of this variable. It’s common practice to give unused index variables the name _, to make it explicit that the value of this variable is unimportant. That is,

for _ in xrange(size):
    data += self._buf.popleft()

It used to be the case that it was better to construct a list of strings and then call join() on the list than be continually appending to strings, but I think that’s fixed in newer versions of Python.

Regardless, I happen to have a personal preference for that construction. It makes the method slightly shorter:

def alt_get(self, size):
    """Retrieves data from the beginning of the buffer."""
    data = ''.join(self._buf.popleft() for _ in xrange(size))
    return data

But I think that’s entirely personal preference: I did an short performance test, and I couldn’t see any difference between this and your get() method.
Suppose I have an empty ring buffer, and I try to get() an element from it:

r = RingBuffer()
r.get()

The user sees the IndexError that arises from trying to pop an empty deque:

Traceback (most recent call last):
  File "buffer.py", line 29, in <module>
    r.get(1)
  File "buffer.py", line 17, in get
    data += self._buf.popleft ()
IndexError: pop from an empty deque

Unless you knew that RingBuffer() was using a deque under the hood, this error message would be confusing. I’d recommend having a custom error message to explain that somebody’s trying to get more items than you have to give.

It’s also worth noting that if you use a try … except block here, the buffer will be emptied before you notice, and the contents could be lost. You need a check before you access anything from the buffer. Something like this:

def get(self, size):
    """Retrieves data from the beginning of the buffer"""
    if size > len(self._buf):
        raise IndexError("Too many items: trying to access %d items "
                         "from a buffer of length %d" % (size, len(self)))
    data = [self._buf.popleft() for _ in xrange(size)]
    return data

Your peak() method doesn't suffer from this problem.


Early return, unless return value is nil

Naming temporary variable is troublesome because [...] sometimes it costs time to read and understand a large block of code meanwhile it doesn't give any meaning.

Well, then give it some meaning. The name value doesn't describe much of anything. Instead, you could do something like

def some_method
  new_click = TopicLinkClick.create_from(new_params)
  return new_click unless new_click.nil?
  # do something else
end

You can shorten it a bit, but I wouldn't recommend it, as it's not quite as clear in my opinion

def some_method
  return new_click if new_click = TopicLinkClick.create_from(new_params)
  # do something else
end

Your other options are of course to not return early, but use a good old conditional instead

def some_method
  new_click = TopicLinkClick.create_from(new_params)
  unless new_click
    # do something else
  end
end

Alternatively, if you've got your code factored really nicely into methods, you can do

def some_method
  TopicLinkClick.create_from(new_params) || some_other_method(...)
end

Or, if you need a bit more logic, you can use a begin..end block, but again it's not as nice in my opinion.

def some_method
  TopicLinkClick.create_from(new_params) || begin
    # do something else
  end
end

Overall, though, your current approach is fine. Just use more descriptive names.

If you have a method that's simply a shortcut for calling either method A or method B, then I'd recommend using the method_a || method_b trick. Otherwise, like @schism, I'd recommend against doing too much on one line (as in code blocks 2 and 5)


Python program to transform an Excel document, with some parsing

Using pandas you can do it in much simpler way.
Steps:
1. Load the data in pandas dataframe from your excel sheet - https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html
2. Filter out the columns which you want to keep (you can specify the column names to be loaded while importing in step 1 also)
3. Transform the columns based on your requirement
4. Delete the rows which are null, in your case as it is H7 using pandas function dropna() - https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.dropna.html
5. Export the data to an excel sheet - https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html

For your reference, refer this blog- https://towardsdatascience.com/replacing-excel-with-python-30aa060d35e


Beautifulsoup scrape posts that has the word python in it with no python tag

The most important change: Check the tags before even getting the question's page. If it's tagged with python, then you know the question doesn't fit your criteria, regardless of what's in the body. Considering how popular the python tag is, this should save a good amount of time and processing.
I introduced a requests.Session object, which could improved performance. I also tweaked the variable names, and replaced the CSS selectors with the find()/find_all() methods. It's mostly a matter of personal preference, though.
Keep in mind that this code contains no error handling.
import requests
from bs4 import BeautifulSoup

tag_keywords = ['python']
content_keywords = ['python'.casefold()]

res = []

with requests.Session() as sess:
    for page_num in range(1):
        new_questions_page_req = sess.get(f'https://stackoverflow.com/questions?tab=newest&page={page_num}')
        soup = BeautifulSoup(new_questions_page_req.content, 'lxml')
        questions_container = soup.find('div', attrs={'id': 'questions', 'class': 'flush-left'})
        questions_list = questions_container.find_all('div', attrs={'class': 'question-summary'}, recursive=False)

        for curr_question_cont in questions_list:
            question_id = curr_question_cont['id'][17:]
            summary_elem = curr_question_cont.find('div', attrs={'class': 'summary'})
            tags_container = summary_elem.find('div', attrs={'class': 'tags'})
            tag_names = [elem.get_text() for elem in tags_container.find_all('a', recursive=False)]

            if not any(curr_tag in tag_keywords for curr_tag in tag_names):
                question_rel_url = summary_elem.find('h3').find('a', attrs={'class': 'question-hyperlink'})['href']
                question_page_req = sess.get(f'https://stackoverflow.com/q/{question_id}')
                question_page_soup = BeautifulSoup(question_page_req.content, 'lxml')
                question_body = question_page_soup.find('div', attrs={'class': 's-prose'})
                question_body_text = question_body.get_text().casefold()

                if any(curr_keyword in question_body_text for curr_keyword in content_keywords):
                    res.append(question_id)

print(res)


C++ memset / memcpy / strcpy implementation performance

These are Runtime library functions, not STL (template library) functions.

The run-time library is arguably part of the language (so you can use the built-in library functions and still be "using C++").

It's possible that your compiler is able to generate these as intrinsic functions.

Things you can try to make your functions faster:

Use a compiler with a better optimizer
Copy 4 or 8 bytes at a time
If the buffers aren't aligned on a 4- or 8-byte boundary, copy 1 byte at a time until you come to a boundary alignment, and then copy 4 or 8 bytes at a time


Retrieve words from dictionary when they meet letter requirements

How about removing the dictionary preparation each time at a cost of increasing your dictionary width?
You could have an alphabetized lookup column (the rows aren't alphabetized -- each letter of each word is sorted alphabetically) and a word column:
lookup  |  word
-----------------
aelpp   |  apple
aelmps  |  sample
aip     |  api
aip     |  pia
икотҷ   |  тоҷик

Using your lowercase, alphabetized $needle, when you want to find "whole" matches, you merely search the lookup column with the = operator.
SELECT `word` FROM `dictionary` WHERE `lookup` = 'икотҷ'

When you want to match the $needle characters at a minimum, you call:
SELECT `word` FROM `dictionary` WHERE `lookup` REGEXP '.*и.*к.*о.*т.*ҷ.*'

Leveraging something like this technique: Custom REGEXP Function to be used in a SQLITE SELECT Statement with this intended usage: ~.*и.*к.*о.*т.*ҷ.*~u
This, of course, is just a theoretical suggestion -- I haven't tried to do anything like this before.
And definitely remember to sanitize and escape the $needle to be offered to the query for security reasons.
Mostly I am suggesting that you sacrifice memory for speed.  Only the $needle should be modified with character sorting and strtolower actions.  These processes are expected to be "already done" on words prior to being stored in the dictionary.
Here is another post of mine with the same basic logic: How to best compare these two strings for values even though they are in random order?

If altering the dictionary table structure is unattractive, this is how I would recommend searching for exact character matches in any order:
Code:
function getWordsContainingTheExactSpecifedLetters_inanyorder_nomore_noless(array $dictionary, string $letters, string $encoding = 'UTF-8'){
    $lettersLength = mb_strlen($letters, $encoding);  // call just once and cache
    $lettersSplit = preg_split('//u', mb_strtolower($letters, $encoding), null, PREG_SPLIT_NO_EMPTY);
    sort($lettersSplit);

    $result = [];
    foreach ($dictionary as $word) {
      if(mb_strlen($word, $encoding) == $lettersLength) {
        $wordSplit = preg_split('//u', mb_strtolower($word, $encoding), null, PREG_SPLIT_NO_EMPTY);
        sort($wordSplit);
        if ($wordSplit === $lettersSplit) {
          $result[] = $word;
        }
      }
    }
    return $result;
}

Of course, you will need to change the qualifying condition if you wish to retain larger words that merely contain the letters.


Changing your function to something like this would work. I don't think you need to model your function after the mathematical equation.

function factorial(num) {
  if (num < 0) {
    return num * factorial(num + 1);
  } else if (num == 0) {
    return 1;
  } else {
    return num * factorial(num - 1);
  }
}

Another solution that uses tail call optimization could be

function factorial(num) {
  function recur(n, acc) {
    if (n < 0) {
      return recur(n + 1, n * acc);
    } else if (n == 0) {
      return acc;
    } else {
      return recur(n - 1, n * acc);
    }
  }
  return recur(num, 1);
}


First off, naming, one of the hardest things in Software Development. I would propose a different name than AnalyzeWord, because it is a word-that-has-been-analyzed object and not an analyzer-of-words object. Maybe something like PhoneticWord, EspeakWord or simply Word might better describe this object.

Next, you call super(), even though you don't have any base-class (except object, implicitly, since you are using Python 3.x). So you don't need it at all.

Regarding the better storing of the IPA vowels, I would first make it a global constant (it does not change between instances of the class. If you want to you could also make it a class constant, same difference. Next, I would make it a set, for which membership testing is \$\mathcal{O}(1)\$ instead of \$\mathcal{O}(n)\$ as it is for a list.

In your check_rhyme function, I would add a if not isinstance(word, AnalyzeWord) check around the casting of the other word. This way you could pass in an already analyzed word. I would also make the function return the match percentage and let the caller do the printing, if they want to. In addition, returning a float here, instead of an int gives the caller even more power. If he really wants an int, let them do the casting (or, if you use this feature, together with the printing, often enough, write another function that does just that).

For the printing itself, I would use str.format.

You should add a if __name__ == '__main__': guard to your testing code so it will not be executed when you do e.g. import ip_word_analyzeer in another script.

from difflib import SequenceMatcher
from subprocess import check_output

class Word:
    """
    Uses espeak's output to get a word's phonetics & syllables.
    """
    ipa_vowels = {'ɐ', 'i', 'ɪ', 'e', 'ɛ', 'æ', 'a', 'ə',
              'ɑ', 'ɒ', 'ɔ', 'ʌ', 'ɚ', 'o', 'ʊ', 'u', 'eɪ', 'aɪ'}

    cmd = ['espeak', '-q', '-v', 'en-us', '--ipa']

    def __init__(self, arg):
        self.arg = arg
        self.word = arg

        self.phon = list(check_output(
            Word.cmd + [self.arg]).decode('UTF-8').strip())
        for i, x in enumerate(self.phon):
            if x == 'ɪ' and self.phon[i - 1] in Word.ipa_vowels:
                self.phon[i - 1:i + 1] = [''.join(self.phon[i - 1:i + 1])]
        self.syll = len([l for l in self.phon if l in Word.ipa_vowels])

    def check_rhyme(self, word):
        if not isinstance(word, Word):
            word = Word(word)
        sm = SequenceMatcher(None, self.phon, word.phon)
        return sm.ratio() * 100

def compare_words(word1, word2):
    if not isinstance(word1, Word):
        word1 = Word(word1)

    perc = word1.check_rhyme(word2)
    if perc > 50:
        print("Good rhyme - {}%".format(perc))
    else:
        print("Not a good rhyme - {}%".format(perc))

if __name__ == '__main__':
    test1 = Word('steed')
    compare_words(test1, 'speed')

Maybe with some more thought (and an example containing a 'ɪ' vowel) that loop could be improved as well.

If you want to go slightly further, you could make this Word class inherit from str, giving it a __str__, __add__, __len__ and so on function. Or you could implement sensible things for that, maybe like so (here I actually made a new class inheriting from Word, so I don't have to re-implement the constructor and such.:

class FancyWord(Word, str):

    def __repr__(self):
        return "".join(self.phon)

    def __str__(self):
        return self.word

    def __add__(self, other):
        return FancyWord(str(self) + str(other))

    def __len__(self):
        return self.syll

    def __iter__(self):
        return iter(self.phon)

With this you can now do these things:

>>> x = FancyWord("speed")
>>> print(x)
speed
>>> x
spˈiːd
>>> repr(x)
spˈiːd
>>> len(x)
1
>>> for phoneme in x: print(phoneme)
s
p
ˈ
i
ː
d

>>> y = FancyWord("steed")
>>> x + y
spˈiːdstiːd

>>> " ".join([x, y])
'speed steed'

The last one works, because of multiple inheritance magic, so basically the second base class str of FancyWord her. Word inheriting from str, as I suggested bove and then implementing these methods would also work.

This might help you with whatever you want to further do with this class.


Three quick comments:

There’s no documentation anywhere in your code. Ideally there should be a docstring, and some comments explaining why the code is behaving in a particular way. I wasn’t able to work out your approach to the problem because there are no comments, and I didn’t want to sit down and reverse engineer it.

Note that variable names are also a form of documentation, and some of yours could be better – x is a poor name, and so is count. What’s it counting?
Your tests aren’t very useful, because I have to work out if they're correct by hand. If I start editing the code, and I introduce a bug, there’s a possibility I won’t notice the test changes. Your tests should warn me if there’s been a regression, not simply print out some results.
The most basic form of this is something like.

assert test(a) == 0
assert test(b) == 3
assert test(c) == 8

Now I can read your tests and find out what the results should be, and I can be warned if I introduce a bug.

The better way to do tests is with the unittest module. If you haven’t used that before, I recommend Ned Batchelder’s talk Getting started with testing, which is a good introduction to Python testing in general.
I don’t know why you have the try…except block. You should really only use try…except if you expect an exception to be raised, so that you can wrap it accordingly. Unexpected exceptions tell you something about your program – there’s a problem – and you shouldn’t be ignoring that information.

And you should try to avoid broad except: statements. Better to catch only the specific exceptions you think might be raised (in this case, there aren’t any), and let anything else bubble to the top.


Synchronization of new data with previous data

Coding Conventions

First of all: You should follow common naming conventions for Java.  It makes it harder to read your code if you don't -- or to put it differently: It is easier to help if the code does follow common conventions.  Maybe have a look at Google's Java Style or at least:

write methods in lowerCamelCase style and
classes in UpperCamelCase style.

Furthermore it would be good to provide a compilable minimal example.

Threadsafe List

From what I understood you want to have a list which is capable of being accessed and modified from multiple threads.  If so, you may have a look at this stackoverflow discussion.

Java Concurrency

Some general things:

You don't need to instantiate an object for your synchronized blocks.  If you do not specify an object, the current object is used.  That should be sufficient for your use cases.
Don't start a thread directly.  Rather use an ExecutorService instead.
Don't subclass Thread, but rather use a Runnable (also see here).
Very good book on the whole topic: Java Concurrency in Practice.


You validate the input string against a regular expression, but then you manually parse it again the hard way.  Instead, you should use parentheses within the regular expression to define capturing groups.

I also think that your regular expression is not quite correct.  Optional digits X preceding "d" should be \d* or (\d+)?.  An optional ±Z should be ([+-]\d+)?.

function dieRoll(dieSpec) {
    var match = /^(\d+)?d(\d+)([+-]\d+)?$/.exec(dieSpec);
    if (!match) {
        throw "Invalid dice notation: " + dieSpec;
    }

    var howMany = (typeof match[1] == 'undefined') ? 1 : parseInt(match[1]);
    var dieSize = parseInt(match[2]);
    var modifier = (typeof match[3] == 'undefined') ? 0 : parseInt(match[3]);

    …
}


When I use your complex expression, I don't get the leading zeros on the hour field that your code suggests that you want.  AFAICS, the expression that tries to add a leading zero is fiddling with the minutes field.  I'm not sure why you're doing the double MOD operations, either.

I think it is sufficient to use the vastly simpler CAST expression shown in the following SELECT statement.  Here, instead of using CURRENT YEAR TO SECOND (or minor variants thereupon), I've created a second table, reference_times, with a single column reftime of type DATETIME YEAR TO SECOND.  That allows me to test many different reference times reliably, in a way that using CURRENT simple does not.  I use an explicit CROSS JOIN between the reference times and the recv table to compare every row in each table with each of the rows in the other.

SELECT reft.reftime,
       recv.rcpt_dtim,
       (reft.reftime - recv.rcpt_dtim) AS delta_t_1,
       CAST(reft.reftime - recv.rcpt_dtim AS INTERVAL HOUR(4) TO MINUTE) AS delta_t_2,
       TRIM((((reft.reftime - recv.rcpt_dtim)::INTERVAL SECOND(9) TO SECOND)/3600)::VARCHAR(12) ||
           ':' ||
           CASE WHEN (MOD(MOD(((reft.reftime - recv.rcpt_dtim)::INTERVAL MINUTE(9) TO MINUTE)::VARCHAR(12)::INT,60),60))<10
           THEN "0"
           ELSE "" END ||
           (MOD(MOD(((reft.reftime - recv.rcpt_dtim)::INTERVAL MINUTE(9) TO MINUTE)::VARCHAR(12)::INT,60),60))::VARCHAR(12)) AS delta_t_3
  FROM reference_times AS reft JOIN recv ON 1 = 1
 ORDER BY reft.reftime, recv.rcpt_dtim;

Given the setup code:

CREATE TEMP TABLE reference_times
(
    reftime     DATETIME YEAR TO SECOND NOT NULL PRIMARY KEY
);
INSERT INTO reference_times VALUES('2019-05-01 03:01:03');
INSERT INTO reference_times VALUES('2019-05-01 05:32:27');
INSERT INTO reference_times VALUES('2019-05-01 10:22:44');
INSERT INTO reference_times VALUES('2019-05-01 12:49:00');
INSERT INTO reference_times VALUES('2019-05-01 14:59:59');
INSERT INTO reference_times VALUES('2019-05-01 23:59:58');

CREATE TEMP TABLE recv
(
    rcpt_dtim   DATETIME YEAR TO SECOND NOT NULL PRIMARY KEY
);
INSERT INTO recv VALUES('2019-05-01 01:10:11');
INSERT INTO recv VALUES('2019-05-01 02:00:00');
INSERT INTO recv VALUES('2019-04-30 22:19:45');
INSERT INTO recv VALUES('2019-04-30 18:37:21');
INSERT INTO recv VALUES('2019-04-30 03:31:00');
INSERT INTO recv VALUES('2019-04-30 01:19:45');
INSERT INTO recv VALUES('2019-04-30 00:00:00');
INSERT INTO recv VALUES('2019-04-29 20:10:58');
INSERT INTO recv VALUES('2019-04-10 22:09:00');
INSERT INTO recv VALUES('2019-04-01 22:09:00');

I get output such as:

reftime              rcpt_dtim               delta_t_1 delta_t_2  delta_t_3
2019-05-01 03:01:03  2019-04-01 22:09:00   29 04:52:03    700:52  700:52
2019-05-01 03:01:03  2019-04-10 22:09:00   20 04:52:03    484:52  484:52
2019-05-01 03:01:03  2019-04-29 20:10:58    1 06:50:05     30:50  30:50
2019-05-01 03:01:03  2019-04-30 00:00:00    1 03:01:03     27:01  27:01
2019-05-01 03:01:03  2019-04-30 01:19:45    1 01:41:18     25:41  25:41
2019-05-01 03:01:03  2019-04-30 03:31:00    0 23:30:03     23:30  23:30
2019-05-01 03:01:03  2019-04-30 18:37:21    0 08:23:42      8:23  8:23
2019-05-01 03:01:03  2019-04-30 22:19:45    0 04:41:18      4:41  4:41
2019-05-01 03:01:03  2019-05-01 01:10:11    0 01:50:52      1:50  1:50
2019-05-01 03:01:03  2019-05-01 02:00:00    0 01:01:03      1:01  1:01
2019-05-01 05:32:27  2019-04-01 22:09:00   29 07:23:27    703:23  703:23
2019-05-01 05:32:27  2019-04-10 22:09:00   20 07:23:27    487:23  487:23
2019-05-01 05:32:27  2019-04-29 20:10:58    1 09:21:29     33:21  33:21
2019-05-01 05:32:27  2019-04-30 00:00:00    1 05:32:27     29:32  29:32
2019-05-01 05:32:27  2019-04-30 01:19:45    1 04:12:42     28:12  28:12
2019-05-01 05:32:27  2019-04-30 03:31:00    1 02:01:27     26:01  26:01
2019-05-01 05:32:27  2019-04-30 18:37:21    0 10:55:06     10:55  10:55
2019-05-01 05:32:27  2019-04-30 22:19:45    0 07:12:42      7:12  7:12
2019-05-01 05:32:27  2019-05-01 01:10:11    0 04:22:16      4:22  4:22
2019-05-01 05:32:27  2019-05-01 02:00:00    0 03:32:27      3:32  3:32
2019-05-01 10:22:44  2019-04-01 22:09:00   29 12:13:44    708:13  708:13
2019-05-01 10:22:44  2019-04-10 22:09:00   20 12:13:44    492:13  492:13
2019-05-01 10:22:44  2019-04-29 20:10:58    1 14:11:46     38:11  38:11
2019-05-01 10:22:44  2019-04-30 00:00:00    1 10:22:44     34:22  34:22
2019-05-01 10:22:44  2019-04-30 01:19:45    1 09:02:59     33:02  33:02
2019-05-01 10:22:44  2019-04-30 03:31:00    1 06:51:44     30:51  30:51
2019-05-01 10:22:44  2019-04-30 18:37:21    0 15:45:23     15:45  15:45
2019-05-01 10:22:44  2019-04-30 22:19:45    0 12:02:59     12:02  12:02
2019-05-01 10:22:44  2019-05-01 01:10:11    0 09:12:33      9:12  9:12
2019-05-01 10:22:44  2019-05-01 02:00:00    0 08:22:44      8:22  8:22
2019-05-01 12:49:00  2019-04-01 22:09:00   29 14:40:00    710:40  710:40
2019-05-01 12:49:00  2019-04-10 22:09:00   20 14:40:00    494:40  494:40
2019-05-01 12:49:00  2019-04-29 20:10:58    1 16:38:02     40:38  40:38
2019-05-01 12:49:00  2019-04-30 00:00:00    1 12:49:00     36:49  36:49
2019-05-01 12:49:00  2019-04-30 01:19:45    1 11:29:15     35:29  35:29
2019-05-01 12:49:00  2019-04-30 03:31:00    1 09:18:00     33:18  33:18
2019-05-01 12:49:00  2019-04-30 18:37:21    0 18:11:39     18:11  18:11
2019-05-01 12:49:00  2019-04-30 22:19:45    0 14:29:15     14:29  14:29
2019-05-01 12:49:00  2019-05-01 01:10:11    0 11:38:49     11:38  11:38
2019-05-01 12:49:00  2019-05-01 02:00:00    0 10:49:00     10:49  10:49
2019-05-01 14:59:59  2019-04-01 22:09:00   29 16:50:59    712:50  712:50
2019-05-01 14:59:59  2019-04-10 22:09:00   20 16:50:59    496:50  496:50
2019-05-01 14:59:59  2019-04-29 20:10:58    1 18:49:01     42:49  42:49
2019-05-01 14:59:59  2019-04-30 00:00:00    1 14:59:59     38:59  38:59
2019-05-01 14:59:59  2019-04-30 01:19:45    1 13:40:14     37:40  37:40
2019-05-01 14:59:59  2019-04-30 03:31:00    1 11:28:59     35:28  35:28
2019-05-01 14:59:59  2019-04-30 18:37:21    0 20:22:38     20:22  20:22
2019-05-01 14:59:59  2019-04-30 22:19:45    0 16:40:14     16:40  16:40
2019-05-01 14:59:59  2019-05-01 01:10:11    0 13:49:48     13:49  13:49
2019-05-01 14:59:59  2019-05-01 02:00:00    0 12:59:59     12:59  12:59
2019-05-01 23:59:58  2019-04-01 22:09:00   30 01:50:58    721:50  721:50
2019-05-01 23:59:58  2019-04-10 22:09:00   21 01:50:58    505:50  505:50
2019-05-01 23:59:58  2019-04-29 20:10:58    2 03:49:00     51:49  51:49
2019-05-01 23:59:58  2019-04-30 00:00:00    1 23:59:58     47:59  47:59
2019-05-01 23:59:58  2019-04-30 01:19:45    1 22:40:13     46:40  46:40
2019-05-01 23:59:58  2019-04-30 03:31:00    1 20:28:58     44:28  44:28
2019-05-01 23:59:58  2019-04-30 18:37:21    1 05:22:37     29:22  29:22
2019-05-01 23:59:58  2019-04-30 22:19:45    1 01:40:13     25:40  25:40
2019-05-01 23:59:58  2019-05-01 01:10:11    0 22:49:47     22:49  22:49
2019-05-01 23:59:58  2019-05-01 02:00:00    0 21:59:58     21:59  21:59

Column names/types:

reftime      DATETIME YEAR TO SECOND
rcpt_dtim    DATETIME YEAR TO SECOND
delta_t_1    INTERVAL DAY(8) TO SECOND
delta_t_2    INTERVAL HOUR(4) TO MINUTE
delta_t_3    VARCHAR(26)

Observe that the delta_t_2 column produces the same output as the delta_t_3 column — apart from type (interval vs string); the left vs right adjustment is mostly an artefact of the way the program that generated the data futzes with the formatting.

Consequently, your elaborate expression can be simplified to:

CAST(CURRENT YEAR TO SECOND - recv.rcpt_dtim AS INTERVAL HOUR(4) TO MINUTE)

or:

(CURRENT YEAR TO SECOND - recv.rcpt_dtim)::INTERVAL HOUR(4) TO MINUTE

And if your time gaps are small enough, you can change the 4 to 2.


Your Ruby code is so dense as to be unreadable. What you want to do is separate each component into a separate method, and use descriptive names for the methods, which are a way of commenting your code. I can't figure out what the methods and tests do, but you want to replace second_test and such with clear multi-word underscored descriptions of that test, such as any_valid_points?.

Separately, you want to use the -= and zero? methods. Rather than using an if statement without an else, you want to use a guard clause. {} blocks should only be used when they fit on one (80 character!!) line. Finally, I really recommend the use of Rubocop, which will give you all these pointers, and also push you to reduce the Assignment Branch Condition complexity of the remaining methods.

def initialize
  @arr = []
end

def x_wing
  box_line_reduction
  remaining_points.each do |point|
    point.nums.each do |num|
      [:x, :y].each { |symbol| process(symbol, num) }
    end
  end
end

def process(symbol, num)
  @arr = first_method(symbol, num)
  next unless second_test?(symbol, num)
  last = second_method(symbol, num)
  third_method(last) if third_test?(last)
end

def first_method(symbol, num)
  @points.select do |p|
    p.nums.include?(num) &&
      p.send(flip(symbol)) == point.send(flip(symbol)) &&
      p.value == 0
  end
end

def second_test?(symbol, num)
  @arr.count == 2 &&
    @points.select do |p|
      p.value == num && p.send(flip(symbol)) == point.send(flip(symbol))
    end.zero?
end

def second_method(symbol, num)
  @points.select do |p|
    p.nums.include?(num) &&
      @arr.map { |a| a.send(symbol) }
        .include?(p.send(symbol)) &&
      (!arr.include?(p)) &&
      p.value == 0 && check_row(p.y, p, num, symbol)
  end
end

def third_test?(last)
  last.all? { |x| x.send(flip(symbol)) == last.first.send(flip(symbol)) } &&
    last.count == 2 &&
    @points.select do |p|
      p.value == num && p.send(flip(symbol)) == last.first.send(flip(symbol))
    end.zero?
end

def third_method(last)
  final = @arr + last
  places = final.map { |m| m.send(symbol) }.uniq
  remaining_points
    .select { |p| places.include?(p.send(symbol)) && (!final.include?(p)) }
    .each { |poi| poi.nums -= [num] }
end


Searching files in a directory for a string

Currently your method does two things. It searches the directory structure and anylizes the files at the same time. This should be separated so that you can maintain each feature separately without affecting the other. For example should you want to search the directories recursively you now only need to change the GetFileNames method without thinking about reading the files.

public static IEnumerable<string> FindLines(this IEnumerable<string> fileNames, Func<string, bool> predicate)
{
    return fileNames.Select(fileName =>
    {
        using (var sr = new StreamReader(fileName))
        {
            var line = string.Empty;
            while ((line = sr.ReadLine()) != null)
            {
                if (predicate(line))
                {
                    return line;
                }
            }
        }
        return null;
    })
    .Where(line => !string.IsNullOrEmpty(line));
}

public static IEnumerable<string> GetFileNames(this string path)
{
    return
        Directory.EnumerateDirectories(path)
        .SelectMany(Directory.EnumerateFiles);
}

If you want you can make it parallel later with:

var results =
    @"c:\foo".GetFileNames()
    .FindLines(line => line.IndexOf("bar", StringComparison.CurrentCultureIgnoreCase) >= 0)
    .AsParallel()
    .ToList();


Here is another recent Code Review question that has a lot of similarities to yours: Daily SQL job to delete records older than 24 hours.
I think I would recommend three things here:

Snapshot isolation
Not using TOP
Doing the work in another table

Snapshot isolation
Snapshot isolation is a really cool tool that effectively prevents most things from blocking readers. As a result, even if your delete is running long, report-writers can still hit your table and they'll see the most recent, valid data. Then once your delete finishes, they'll start seeing the data without your deleted rows. This lets you do whatever you need to do without having to worry as much about end-users. It doesn't make your code faster, but it will somewhat reduce the need for it to be.

Not using TOP
Because you're using TOP, you effectively force all of the data to be re-sorted every time. Additionally, TOP will usually introduce row goals. This isn't necessarily a bad thing, but it may choose less-ideal plans in the interest of getting a subset of rows as quickly as possible.
Because your Id column is an indexed IDENTITY column, and because we're deleting the oldest data (I'm assuming you don't generally update old data), you can do something like this:
DELETE FROM [Logs]
  WHERE Id BETWEEN @LowestCurrentIndex AND @HighestCurrentIndex
    AND CAST([Timestamp] AS date) < CAST(DATEADD( DAY, -7, GETUTCDATE()) AS date);

This assumes you can maintain @LowestCurrentIndex and @HighestCurrentIndex as the range of values to currently consider. This will get you nice index accesses as well.
A potential enhancement is to get a separate table that has all potentially affected rows, like so:
SELECT Id
  INTO #OldData
  FROM [Logs]
  WHERE CAST([Timestamp] AS date) < CAST(DATEADD( DAY, -7, GETUTCDATE()) AS date);

Then you can just join between the two (and if you have an index on #OldData.Id it'll be a great merge-join) with the same bounds logic.
DELETE [Logs]
  FROM [Logs]
    INNER JOIN #OldData OldData
      ON [Logs].Id = OldData.Id
  WHERE OldData.Id BETWEEN @LowestCurrentIndex AND @HighestCurrentIndex -- This could be on either table

Do the work in another table
If copying the data is less expensive than deleting it (very possible), then you may be able to more efficiently do the work with less user interruptions by doing all of your work in a separate table, and then switching the tables. Broadly speaking, the workflow would look like this:

Copy all of the valid data into another identically formatted table (same indices, constraints, etc)
Truncate the original table
Perform a partition switch

Alternatively, if partition switching isn't your jam, you can do a very similar thing manually:

Copy all of the valid data into another identically formatted table (same indices, constraints, etc)
Rename the original table to something else
Rename the table from #1 to the original table's name
Truncate the original (now renamed) table from #2

These will result in much less index maintenance, and many of the operations can be done via minimal logging if well structured.


I find the reverse iterators a bit confusing, but I might be a little slow. That said, I'm probably not the only one, so you wouldn't waste your time looking for a simpler way to express yourself.

I'd add that you forgot to handle the case where the input is already sorted, meaning that you could have been overwhelmed yourself ;-)

My suggestion, using std::adjacent_find to detect sign changes (note that I use a reverse iterator only once, to denote the vector's last element -in that case it feels intuitive to me):

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

void is_almost_sorted(std::vector<int>& vec) {
    // find swap candidates, swap and check if sorted
    auto first  = std::adjacent_find(vec.begin(), vec.end(), std::greater<int>()); // first sign change...
    if (first == vec.end()) {
        std::cout << "Already sorted";
        return;
    }
    auto bkp = vec;
    auto second = std::adjacent_find(first+1, vec.end(), std::greater<int>()); // and second
    if (second != vec.end()
        && (std::iter_swap(first, second+1), std::is_sorted(vec.begin(), vec.end()))) {
        std::cout << "swap " << *first << " and " << *++second;
        return;
    }
    // restore from original vec
    auto offset = std::distance(vec.begin(), first);
    vec = std::move(bkp);
    first = vec.begin()+offset;
    // find inverse change of signs, reverse and check if sorted
    second = std::adjacent_find(first+1, vec.end(), std::less<int>());
    std::reverse(first, second == vec.end() ? second : second + 1);
    if (std::is_sorted(vec.begin(), vec.end())) {
        std::cout << "reverse from " << *first
                  << " to " << (second == vec.end() ? *std::rbegin(vec) : *++second);
        return;
    }
    std::cout << "no solution";
}