Thanks for sharing your code.

It's a nice project you have there.

Naming

You should take some time to choose carefully your variable. l1 is not obvious, maybe input, input_string, sentence or text would be more appropriate?

Without the commentary above the function, it would have been hard to find what that was supposed to be.

Same for it_l1 and it_word. After reading your code a few time, I am not sure what they are. Find a descriptive name, it helps tremendously when reading code.

Documentation

You have comments, that's good. But it is way better to have a good docstring for the function, and fewer comments.

Your docstring should describe what the function try to accomplish, why it exists, the parameter (eventually their type) and what does the function return.

And more annoying, some of your comments seem to be outdated/wrong?

# determiners is the config file below parsed by configparser but it seems determiners is not a config file, but a list of string. (True it is the content of a file parsed by configparser, but it's not the same)
# the goal is to obtain a string shorter than 38 char you did change your code but did not change that comment I presume? I couldn't find where it was supposed to restrict the size to 38char

Indentation

Your code here:

while(it_word < len(key) and it_l1 + it_word + 1 < len(l1)
and l1[it_l1 + it_word + 1] == key[it_word].upper()):
    it_word += 1
if(it_word == len(key) and (it_l1 + it_word + 1 == len(l1)
or l1[it_l1 + it_word + 1] in ' -.')):

is very hard to read. Maybe it's because you pasted it into CodeReview, but be carefull when writing long and hard condition. The more difficult it is to read, the more difficult it is to debug/maintain/extend.

Putting it altogether

Note: it_l1 and it_word are still in the code because I don't know how to name them properly but you should probably change them.

def remove_determiners(determiners, text):
    """
    Removes determiners words from text

    :param determiners: the words to remove in `text`
    :param text: a text to remove determiner in
    :type determiners: List[str]
    :type text: str:
    :return: The value of `text` after removing all words present in determiners
    """
    for key in determiners:
        it_l1 = 0

        while(it_l1 < len(text)):

             # Finds possible beginning of words
             if(text[it_l1] in ' -' or it_l1 == 0):
                 if(it_l1 == 0):
                      it_l1 = -1

                 # Finds possible end of words
                 it_word = 0
                 while(it_word < len(key)
                       and it_l1 + it_word + 1 < len(l1)
                       and text[it_l1 + it_word + 1] == key[it_word].upper()):
                      it_word += 1
                 if(it_word == len(key)
                    and (it_l1 + it_word + 1 == len(text)
                         or text[it_l1 + it_word + 1] in ' -.')):
                      if(it_l1 == -1):
                          it_l1 = 0

                      # cuts the determiner out
                      text = l1[:it_l1] + l1[it_l1 + it_word + 1:]

             it_l1 += 1
             if(it_l1 == 0):
                 it_l1 = 1
    return(text)

Algorithm

You could also really simplify your code by using set.

Below is a code that works for the simple case, need to be improved to deal with punctuation. (if you have a text like "LE, LA, ET.", it will not remove the determiners. Or use a clean up step as shown below)

def remove_determiners(determiners, text):
    """
    Removes determiners words from text

    :param determiners: the words to remove in `text`
    :param text: a text to remove determiner in
    :type determiners: List[str]
    :type text: str:
    :return: The value of `text` after removing all words present in determiners
    """

    determiners_set = set(determiners)

    text_list = text.split(' ')

    resultat = []
    for element in text_list:
        if(element not in determiners_set):
            resultat.append(element)

    return ' '.join(resultat)

Or as a two-liner using list comprehension as @Josay pointed out in the comment:

def remove_determiners(determiners, text):
    determiners_set = set(determiners)
    return ' '.join(e for e in text.split(' ') if e not in determiners_set)

Usage:

determiners = ['AND',
               'THE',
               'ET',
               'LE',
               'LA',
               'LES',
               'DE']

text = 'LES PILES DE LA TELECOMMANDE'

remove_determiners(determiners, text)
# returns 'PILES TELECOMMANDE'

Sidenote

Why in you config file you have & = nope instead of &? Is there more values than nope?

EDIT

Code changed slightly since my answer, adding the 38 char constraint. Should be straightforward to modify my response to accomodate this change

EDIT2

Also to address @Josay point about noise in the text, a cleaning step is possible like this:

def clean_text(text)
    """Remove ponctuation from text and replace it by a empty char
       for -_,.?!:; and '" by a space
       :param text: The text to remove punctuation in
       :return: Text cleaned up
    """
    text = re.sub('[-_,.?!:;]', '', text)
    text = re.sub('[\'"]', ' ', text)
    return text

And usage

determiners = ['AND',
               'THE',
               'ET',
               'LE',
               'LA',
               'LES',
               'DE']

text = 'LES PILES DE-LA TELECOMMANDE'

remove_determiners(determiners, clean_text(text))


Your implementation is simple, which isn't bad, but it suffers from an accuracy issue. What if there is a single above-threshold sample at the middle of your window, preventing it from being detected as silent, and a similar subsequent window with one above-threshold sample in the middle? That constitutes one window's worth of silent samples that have not been detected. Instead, you should adopt a moving aggregate - absolute max, or maybe absolute median. Moving max requires that you maintain a queue and a sorted list. When you get a new sample, do a sorted insert of the absolute value of the sample to the list, a push to the queue, a pop to the queue, and drop the popped value from the list. The item at the end of the list will always be the max, and the item in the middle of the list will always be the median. As soon as the threshold is detected, silence has started and should not be considered to end until the threshold is exceeded.


How should I set a daily method as executed, from inside or from outside?

As your code stands now it looks to me as if the timer has some responsibilities it shouldent have.

My suggestion would be to either move all the timer information to your timer, including bigService.ExecutedToday and SetAsExecuted OR you move all that logic inside the service. I would go for the latter since that would be more in line with the "Tell dont ask" principle.

The code in the timer would look like this:

static void TimerElapsed(object sender, ElapsedEventArgs e)
{
    foreach (BIGService bigService in runningServices)
    {
           bigService.Execute();
    }
}

In your BigService method you contain the logging and wether or not that service can be run at the time it is requested.

One more thing: I would make an Enum to store the 0 value for executionResult, at a later date it might not be clear to you what 0 actually means


A custom Pandas dataframe to_string method

import pandas
np = pandas.np

What you are doing here is using the numpy that pandas imports, which can lead to confusion. There is an agreed standard to import pandas and numpy:

import pandas as pd
import numpy as np

And importing numpy yourself does not load the module twice, as imports are cached. Your import only costs a lookup in sys.modules because numpy already gets imported on the pandas import, but you add a lot of readability.

At the end you use random.choice() but you never imported random.

In get_lines_standard() you first convert the complete DataFrame to a string, then split it on the line breaks. In your example and then you slice the top 5 off it to display. The way your code works here, there is no way to only show the top 5 rows without rendering the complete DataFrame - which applies to all 3 methods.
Just to demonstrate the difference of slicing before and after (using random data generated at the end of your code but with 10k rows instead of 1k):

# both calls have the same output:

%timeit df.to_string(index=False).split('\n')[:5]
1 loops, best of 3: 1.51 s per loop

%timeit df[:5].to_string(index=False).split('\n')
100 loops, best of 3: 3.38 ms per loop

PS: I don't want to pep8ify you, but please don't line up your equal signs.

/edit:

Ok, let's focus on get_lines_fast_struct(). You are doing things manually for which there actually exist tools:

Creating a copy of a DataFrame with the same values as strings can be accomplished by str_df = self.astype(str)
The maximum lengths of cells per column of such a dataframe could be determined by self.spaces= [str_df[c].map(len).max() for c in str_df.columns]
For col_data you use a list comprehension that just call a method for each element, which is basically just map()
In _format_line() you fill up the strings with spaces on the left until they have length n+1 with n being the maximum col length by even mixing 2 styles of string formatting (old and new). string.rjust() does the same thing and might be faster.

All those things in mind the code might look like this:

def get_lines_fast_struct2(self, col_space=1):
    str_df = self.astype(str)
    self.space = [str_df[c].map(len).max() for c in str_df.columns]
    col_titles = map(_format_line2, [self.columns])
    col_data = map(_format_line2, str_df.to_records(index=False))
    return col_titles + col_data

def _format_line2(self, row_vals):
    return "".join(cell.rjust(width) for (cell, width) in zip(row_vals, self.space))

Let's compare this with the original in terms of speed and equality:

In [160]: %timeit df.get_lines_fast_struct()
100 loops, best of 3: 11.3 ms per loop

In [161]: %timeit df.get_lines_fast_struct2()
100 loops, best of 3: 9.78 ms per loop

In [162]: df.get_lines_fast_struct() == df.get_lines_fast_struct2()
Out[162]: True

Maybe there is even a better way with more pandas magic involved, but I am not that experienced with pandas yet.


Implement clojure-a-like comp() function in python3

Your approach has one serious drawbacks: it creates N-1 new bound function instances on every invocation of the returned function with an argument length of N if big-O performance guarantees are relevant to you. To avoid this you can either use a loop or the reduce operation, both of which only create a fixed number of function instances (that doesn't depend on the number of functions to chain).

Additionally I believe that both variants are easier to understand than the code in your question because it doesn't rely on recursion.

Loop

def comp_loop(*fns):
    def comped(*x):
        for fn in reversed(fns):
            x = fn(*x)
        return x

    if len(fns) == 0:
        return lambda *x: x
    if len(fns) == 1:
        return fns[0]
    return comped

Reduce

from functools import reduce

def comp_reduce(*fns):
    if len(fns) == 0:
        return lambda *x: x
    if len(fns) == 1:
        return fns[0]
    return lambda *x: reduce(lambda accum, fn: fn(*accum), reversed(fns), x)


Finding the number which satisfies specific conditions

Testing for self-descriptiveness is easy if you use the built-in collections.Counter to do the counting for you:

from collections import Counter

def self_descriptive(n):
    """Return True if n is self-descriptive, that is, if n is made up of
    digits d0 d1, ..., then d0 of them are 0, d1 are 1, and so on.

    >>> self_descriptive(1210)
    True
    >>> self_descriptive(310100)
    False

    """
    digits = [int(d) for d in str(n)]
    return Counter(digits) == +Counter(dict(enumerate(digits)))

And then the solution is a one-liner:

next(filter(self_descriptive, range(10**7, 8*10**7)))

But this takes so long that it's faster to solve the problem by hand:

   Consider how many zeroes there are. It's easy to rule out 8, 7, and 6, so could there be 5? This would require the number to be \$ 5abcd100 \$, with \$ a ≥ 1 \$ and \$ b = c = d = 0 \$, but this doesn't work: either \$ a = 1 \$ but there are two 1's, or \$ a > 1 \$ and there is only one 1.
 There can't be 3 (or fewer) zeroes, because that leaves 4 (or more) non-zeroes, adding up to at least 1 + 2 + 3 + 4 = 10 other digits, which is too many.
 So that leaves 4 zeroes. This requires the number to be \$ 4abc1000 \$ with \$ a ≥ 1 \$ and either \$ b = 0 \$ or \$ c = 0 \$ (but not both). If \$ b = 0 \$ then \$ c ≥ 1 \$ but this is not possible because that would require 3 of some digit, so it must be \$ c = 0 \$ and the (only) answer is \$ 42101000 \$.


Implement array element swap in a functional language

First and foremost: while mutation may be generally frowned upon in F#, in some cases (like this one) it's acceptable to make a tradeoff of immutability vs. performance or maintainability. In this case, it serves both of those goals.

Let's say you want to do this idiomatically, and you want to avoid directly mutating the array. It isn't that hard:

let swap el1 el2 arr =
    arr |> Array.mapi (fun i v ->
        match i with
        | _ when i = el1 -> arr.[el2]
        | _ when i = el2 -> arr.[el1]
        | _ -> v)

This uses the mapi function, which provides the current index and value (in that order, defined by the int -> 'T -> 'U signature) which we can then match with our el1 (first element to swap) and el2 (second element to swap). If we hit either of those simply return the other element.

But then, this isn't enough. What if we have several pairs to swap? We have to call swap a1 b1 arr then a swap a2 b2 arr, which could have a substantial performance penalty.

We could define a swapMany function which would take a list of tuples which are the first and second elements to swap and then handle them.

let swapMany els arr =
    arr |> Array.mapi (fun i v ->
        match els |> List.tryFind (fun el ->
            match el with
            | (el1, el2) when el1 = i || el2 = i -> true
            | _ -> false) with
        | Some (el1, el2) when el1 = i -> arr.[el2]
        | Some (el1, el2) when el2 = i -> arr.[el1]
        | _ -> v)

Now we handle all the swaps in one pass. If they're ordered, then the cost is even lower.

let values = [|1..10|]
let value =
    values
    |> swapMany [(4, 8); (2, 5)]

Result:

[|1; 2; 6; 4; 9; 3; 7; 8; 5; 10|]

But we're still not done, let's say we want to write our swapMany such that it doesn't create the entire result array, we want to stream it, sort of like an IEnumerable in C#.

In F# this isn't nearly as hard as it seems, all we have to do here is rewrite our swapMany as a sequence generator, which turns it into:

let swapMany els arr =
    seq {
        for i in 0..(Array.length arr - 1) ->
            match els |> List.tryFind (fun el ->
                match el with
                | (el1, el2) when el1 = i || el2 = i -> true
                | _ -> false) with
            | Some (el1, el2) when el1 = i -> arr.[el2]
            | Some (el1, el2) when el2 = i -> arr.[el1]
            | _ -> arr.[i]
    }

Now, you might say "why would I want to write a sequence generator for an array?" Consider you have a huge array:

let values = [|1..100000000|]

And you want to swapMany on it, but you're then going to enumerate the array for the first 10 values:

let value =
    values
    |> swapMany [(4, 8); (20, 50)]
printfn "%A" (value |> Seq.take 10 |> Seq.toArray)

You don't have to swap everything in the array now, you just have to swap the elements you need.

Second, the only issue I see with your code is the order of arguments. When writing functions it's nice to be able to use the pipe-right operator (|>) to push the left value as a parameter to the function on the right. In the case of your function, if I were to try to pipe an array to the right, it won't work. This is because the pipe-right (or pipe-forward) operator pipes the left side as the last argument to the right side.

let swap (array: 'a[]) (first: int) (second: int): 'a[] =
    let originalFirst = array.[first]
    array.[first] <- array.[second];
    array.[second] <- originalFirst;
    array

[|1..10|] |> swap 4 5

The above code is invalid, because the argument 4 is expected to be the 'a[] array, and the argument 5 is the first int, and the array [|1..10|] is expected to be the second int argument.

let swap (first: int) (second: int) (array: 'a[]): 'a[] =
    let originalFirst = array.[first]
    array.[first] <- array.[second];
    array.[second] <- originalFirst;
    array

[|1..10|] |> swap 4 5

F# also includes a double-forward-pipe and triple-forward-pipe operator, which do the same thing but pipe a tuple of either two or three values, respectively, to the right side as the last two or three arguments, respectively.

Consider an example:

let append str1 str2 str3 = str1 + "." + str2 + "." + str3
printfn "%s" ("ghi" |> append "abc" "def")
printfn "%s" (("def", "ghi") ||> append "abc")
printfn "%s" (("abc", "def", "ghi") |||> append)

All three of the printfn statements will print abc.def.ghi.

You can see more of this looking through the framework. You'll see that most functions in List and Seq take the list or sequence as the last parameter, so that you can pipe the result of one function to another.

Consider how much more painful the following code would have been to write had the framework designers chosen to not take this factor into account:

let values = [1..100]
let value =
    values
    |> List.map (fun v -> Math.Sin(float v))
    |> List.choose (fun v -> if v >= 0.0 then Some v else None)
    |> List.rev
    |> List.takeWhile (fun v -> v > 0.05)
    |> List.fold (fun v acc -> acc + v) 0.0
printfn "%f" value


Returning the size of the largest clique in a graph

First of all, start passing things by const reference more.  You're passing both nodes and edges by value, which will make a copy.
Instead of looping through the containers by index, you should use iterators.
Pushing tmp into previous_cliques will make a copy.

The following may be faster:

std::vector<VertexID> tmp(1);
for (...) {
    tmp[0] = nodes[i];
    previous_cliques.push_back(tmp);
}

(If you're worried about scope, just wrap it in braces.)

Checking for emptiness with size() may be less efficient than with empty(); unlikely in the case of a vector, though (I think size() must be O(1)).
You're not showing us isClique, so it's hard to comment on that.  Make sure you're passing be const reference there.  Also consider not copying previous_cliques until you know you want to push it into new_cliques and instead handling nodes[i] as a special case (may be faster, may be slower).
If you're using C++11, the emplace functions are your friend.


Implementation of inheritable pImpl idiom and MVC pattern

Stop doing this:

using namespace std;

Its a bad habit that you need to stop. Prefix your stuff with std:: and don't be lazy. The whole reason its std and not standard_lib is so that it would not be an issue using the prefix everywhere. Anyway there are issues that will crop up in real code see Why is “using namespace std;” considered bad practice?

Why.

class Ancestor{}; //every object using the "template" inherits this class

Just saying they do is not a good comment.
A good comment would explain why they need to. Also since there is no interface you are implementing I don't see a reason for this (maybe a comment would clarify).

In this class:

template <typename IMPL> class Obj : public Ancestor {

You are doing resource management. But you don't implement the rule of three (as such it is broken). Please make sure you correctly do resource management. What is The Rule of Three?

While we are here. You may also want to look at move semantics (its 2014 so you should be using at least C++11 or C++14). This will make your code more efficient in the 3% of places that RVO and NRVO don't apply. Also containers are now move aware that makes them more efficient.

Pointers in your class. Not good.

// well a template is used for the same reason as for Obj<>
template <typename MODEL> struct MVCController {
    MODEL *m_pModel;
};

A pointer does not semantically help with determining ownership. I assume a controller is always linked to a model (ie it is never null) so I think a reference would be a better way to represent the connection to the model. If you can potentially have a NULL model (I would not go this way) then maybe a std::shared_ptr as many controllers can potentially use the same model.

A lot of implementations combine the controller and model so that is fine.

// same reason for a template
template <typename MODEL, typename CONTROLLER> struct MVCImpl {
    MODEL *m_pModel;
    CONTROLLER *m_pController;
    // leave alone the View for simplicity

    //constructor
    MVCImpl(MODEL *m = new MODEL(), CONTROLLER *c = new CONTROLLER()) :
    m_pModel(m), m_pController(c) {m_pController->m_pModel = m;};
};

But you have an bad obsession about creating these things dynamically. Please use to learn how to use automatic objects. This makes resource management much easier.

Also you do need to figure out how the view(s) are connected to your MC object.


Word Separator and Pig Latin Program Final Edit

Your commenting is absolutely abusive. This one is particularly beautiful... in its own way:
//Close keyboard
keyboard.close();

None of these comments are useful, because:

They state the obvious. Let the code speak for itself!
They tell the reader what the code is doing, but not why it's doing it.
They are a distraction. Reader/maintainer reads the comment, and then the code, and then subconsciously validates whether the comment reflects what the code underneath is saying.

See this beautiful answer specifically about comments - two things to remember:

Comments are supposed to make plain what the code does not tell us already.

Good code seldom needs comments

The naming is also inconsistent:
StringBuilder str = new StringBuilder(sentence);

String str = tokens[i];

A better name for the former could be builder, and a meaningful name for the latter could be token.
Comments should not replace meaningful names:
// Get first letter from string
String str1 = str.substring(0, 1);

If str1 were firstLetter...


Checking unique words and their abbreviations

Variable names
I assume that your dictionary: List refers to an English dictionary and not a data-structure dictionary. This is confusing. Consider calling it something like words.
PEP8
isUnique should be is_unique if LeetCode lets you.
Formatting
'{}{}{}'.format is a quite slow method of concatenating three strings in this case. Try instead
''.join((
   key[0],
   str(len(key) - 2),
   key[-1],
))

This should also be factored out into a function since you use it twice.
Define slots
Read about how to do this here:
https://docs.python.org/3/reference/datamodel.html#object.__slots__


What is the best approach to use in R and why?

As you realize, your first approach works (it gives a result consistent with the criteria you specify), but it is not idiomatic R. Iterating over elements of a set/list/vector is idiomatic of python, and does have a place in R as well. However, what this approach misses is 2 aspects of R: inherent vectorization and the factor data type.

In R, all basic types are vectors and can hold multiple items (of the same type).  A single value is just a special case of a length 1 vector.  Since everything is a vector, all the standard functions are designed to operate on the whole vector at once.  They are implicitly vectorized over the elements of the vector rather than needing an explicit loop (iteration or for loop) to operate on each element.  So the first simplification is to eliminate the for loop over elements of faithful$waiting and just do the comparison on the whole vector.

> faithful$waiting < 79
  [1] FALSE  TRUE  TRUE  TRUE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE FALSE
 [13]  TRUE  TRUE FALSE  TRUE  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE
 [25]  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE
 [37]  TRUE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE  TRUE FALSE  TRUE  TRUE
 [49] FALSE  TRUE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE FALSE
 [61]  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE
 [73] FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE FALSE  TRUE  TRUE
 [85]  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE
 [97] FALSE  TRUE  TRUE FALSE  TRUE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE
[109] FALSE FALSE  TRUE  TRUE FALSE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE
[121]  TRUE  TRUE  TRUE  TRUE FALSE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE
[133]  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE
[145]  TRUE  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE
[157] FALSE FALSE  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE
[169]  TRUE FALSE  TRUE  TRUE  TRUE  TRUE FALSE FALSE  TRUE  TRUE FALSE  TRUE
[181]  TRUE  TRUE FALSE FALSE  TRUE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE
[193]  TRUE FALSE  TRUE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE FALSE  TRUE
[205]  TRUE  TRUE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE
[217]  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE
[229]  TRUE FALSE  TRUE  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE
[241]  TRUE  TRUE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE  TRUE  TRUE FALSE
[253]  TRUE  TRUE FALSE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE
[265]  TRUE  TRUE  TRUE FALSE  TRUE FALSE  TRUE  TRUE

This brings up another aspect.  faithful$waiting is of length 272, 79 is length 1.  Argument recycling causes the 79 to be repeated until it is of the same length as faithful$waiting.  Then the comparison is done element-wise, returning a logical variable.  If you want it as a numeric (as in your first example), this can be converted directly: FALSE becomes 0 and TRUE becomes 1

> as.numeric(faithful$waiting < 79)
  [1] 0 1 1 1 0 1 0 0 1 0 1 0 1 1 0 1 1 0 1 0 1 1 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1
 [38] 0 1 0 0 1 0 1 1 0 1 1 0 1 1 0 1 0 1 0 1 1 1 0 1 0 1 0 1 0 1 1 1 1 0 1 0 1
 [75] 1 1 1 1 1 0 1 0 1 1 1 0 1 0 1 0 1 0 1 1 1 1 0 1 1 0 1 0 1 0 0 1 0 1 0 0 1
[112] 1 0 0 1 0 1 0 1 0 1 1 1 1 0 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 0 1 0 1 1 1 0 1
[149] 0 1 1 1 1 0 1 1 0 0 1 0 1 0 1 1 1 1 1 0 1 0 1 1 1 1 0 0 1 1 0 1 1 1 0 0 1
[186] 1 0 1 0 1 0 1 1 0 1 0 0 1 1 1 1 0 0 1 1 1 1 0 1 0 1 0 1 1 1 1 1 0 1 1 1 0
[223] 1 1 1 0 1 1 1 0 1 1 0 1 0 1 1 1 0 1 1 1 0 1 0 0 1 0 1 1 1 0 1 1 0 0 1 0 1
[260] 0 1 0 1 0 1 1 1 0 1 0 1 1

The second aspect of R I mentioned was factors.  Factors are the implementation of a data type which can take on any of a predefined set of values.  In some languages, these are enumerated types.  Internally, they are stored as integer indexes into a vector of values (and this sometimes shows through).

You can create a factor from another vector by defining the levels it can take and, optionally, labels these levels should be displayed as.  Continuing the example

> factor(as.numeric(faithful$waiting < 79), levels=c(1,0), labels=c("<79", "79+"))
  [1] 79+ <79 <79 <79 79+ <79 79+ 79+ <79 79+ <79 79+ <79 <79 79+ <79 <79 79+
 [19] <79 79+ <79 <79 <79 <79 <79 79+ <79 <79 <79 79+ <79 <79 <79 79+ <79 <79
 [37] <79 79+ <79 79+ 79+ <79 79+ <79 <79 79+ <79 <79 79+ <79 <79 79+ <79 79+
 [55] <79 79+ <79 <79 <79 79+ <79 79+ <79 79+ <79 79+ <79 <79 <79 <79 79+ <79
 [73] 79+ <79 <79 <79 <79 <79 <79 79+ <79 79+ <79 <79 <79 79+ <79 79+ <79 79+
 [91] <79 79+ <79 <79 <79 <79 79+ <79 <79 79+ <79 79+ <79 79+ 79+ <79 79+ <79
[109] 79+ 79+ <79 <79 79+ 79+ <79 79+ <79 79+ <79 79+ <79 <79 <79 <79 79+ 79+
[127] <79 79+ <79 79+ <79 79+ <79 79+ <79 79+ <79 79+ <79 79+ 79+ <79 79+ <79
[145] <79 <79 79+ <79 79+ <79 <79 <79 <79 79+ <79 <79 79+ 79+ <79 79+ <79 79+
[163] <79 <79 <79 <79 <79 79+ <79 79+ <79 <79 <79 <79 79+ 79+ <79 <79 79+ <79
[181] <79 <79 79+ 79+ <79 <79 79+ <79 79+ <79 79+ <79 <79 79+ <79 79+ 79+ <79
[199] <79 <79 <79 79+ 79+ <79 <79 <79 <79 79+ <79 79+ <79 79+ <79 <79 <79 <79
[217] <79 79+ <79 <79 <79 79+ <79 <79 <79 79+ <79 <79 <79 79+ <79 <79 79+ <79
[235] 79+ <79 <79 <79 79+ <79 <79 <79 79+ <79 79+ 79+ <79 79+ <79 <79 <79 79+
[253] <79 <79 79+ 79+ <79 79+ <79 79+ <79 79+ <79 79+ <79 <79 <79 79+ <79 79+
[271] <79 <79
Levels: <79 79+

Note that in the output of the factor, the possible levels are listed as any given vector may or may not have an every possible value in it.  The set of allowed values can be larger than the ones that are present in any given vector.

For dividing into two groups based on a single cut point, this is fine, but this approach becomes unwieldy when making more than two groups.  cut is a built-in function which is designed to do just this: categorize a continuous variable based on a set of cut points.  There is always one fewer groups than cut points because the points define the edges of the groups (and anything outside the extremes is set to NA).  When including everything, I don't usually compute the extremes and use those, but use -Inf and Inf.  By default, the intervals are closed on the right which means that the upper value is included in the range but the lower value is not.  Since you wanted 79 in the upper group, you have to include right=FALSE.

> cut(faithful$waiting, breaks=c(-Inf,79,Inf), right=FALSE)
  [1] [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf)
  [8] [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79)
 [15] [79, Inf) [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79)
 [22] [-Inf,79) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79)
 [29] [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79)
 [36] [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [79, Inf) [-Inf,79)
 [43] [79, Inf) [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79) [79, Inf)
 [50] [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf)
 [57] [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79)
 [64] [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [-Inf,79)
 [71] [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [-Inf,79)
 [78] [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79)
 [85] [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79)
 [92] [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79)
 [99] [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [79, Inf)
[106] [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [79, Inf) [-Inf,79) [-Inf,79)
[113] [79, Inf) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79)
[120] [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf) [79, Inf)
[127] [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79)
[134] [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf)
[141] [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf)
[148] [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf)
[155] [-Inf,79) [-Inf,79) [79, Inf) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79)
[162] [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf)
[169] [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf)
[176] [79, Inf) [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79)
[183] [79, Inf) [79, Inf) [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf)
[190] [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf)
[197] [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf) [79, Inf)
[204] [-Inf,79) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf)
[211] [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [-Inf,79) [-Inf,79)
[218] [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79)
[225] [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79)
[232] [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79)
[239] [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf)
[246] [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79) [-Inf,79) [79, Inf)
[253] [-Inf,79) [-Inf,79) [79, Inf) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79)
[260] [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79)
[267] [-Inf,79) [79, Inf) [-Inf,79) [79, Inf) [-Inf,79) [-Inf,79)
Levels: [-Inf,79) [79, Inf)

This gives the idiomatic way of doing this as:

waiting_cat <- cut(faithful$waiting, breaks=c(-Inf,79,Inf), right=FALSE)

It implicitly loops over faithful$waiting and returns a factor which represents a categorical set of choices.


Determining if two strings are anagrams of each other

The code is technically broken: it only tells that the strings are composed of the same letters. It is not enough for the strings to be anagrams. Each letter must appear the same number of times in both strings.

Making your char_set array integer instead of boolean you can get the correct result still in linear time:

    int [] counters = new int[256];
    set_counters_to_zero();
    for (int i = 0; i < str1.len(); i++) {
        counters[str1.charAt(i)]++;
    }
    for (int i = 0; i < str2.len(); i++) {
        counters[str2.charAt(i)]--;
    }
    return all_counters_are_zero();


First of all i think making a view in your database which sums your needs will be better because generally sql engine sum operator's performance is way better than lopping values in programming languages.

Second if we go through your code:
You have done mapping for all objects one by one. Java stream mapping is similar to for loops in compile time. So here what you make is similar to creating for loop foreach object which is bad for performance.
To be performance wise you can create one for loop and generate your sum values in it.

Note: BigDecimal is the preferred way to store double money values in Java


Non brute force algorithm for Birthday Chocolate

You basically always need to use brute force here. There is no other way. However, you can do it a bit more efficiently.

You're redoing the whole summation in every step of the loop. You don't need to. You can compute the total with one subtraction and one addition in each step of the loop. Like this:

static int birthday(List<int> s, int d, int m) {
    int n = 0;
    int t = s.Take(m).Sum();
    for(int i = 1; i < s.Count - m; i++) {
        if (t == d) n++;
        t = t - s[i - 1] + s[i + m];
    }
    return n;
}

I hope this makes sense, I never write C#. I got here because of your 'javascript' tag. The code might not work correctly, it is untested, but I hope you understand the intention.

However, I do think there's a bug in your code. You loop over the whole list, all the way to the end, where you cannot take m squares anymore. The sum() there might result in unexpected matches.


Ruby on Rails - Creating many models associated with another one

You should be able to do this with accepts_nested_attributes_for.
  see https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accepts_nested_attributes_for

class Poll < ApplicationRecord
    validates :title, presence: true, allow_blank: false
    validates :options, presence: true

    has_many :options, dependent: :destroy
    accepts_nested_attributes_for :options
end

def poll_params
  params.require(:poll).permit(:title,
                               options: :title)
end

def create
    @poll = Poll.new(poll_params)

    if @poll.save
        render json: @poll, status: :created, location: @poll
    else
        render json: @poll.errors.full_messages, status: :unprocessable_entity
    end
end


Parsing and converting DMS Coordinates from String to Double

You have defined a value type (struct) and not a class, which is good. In

var latitude: Double = 0.0
var longitude: Double = 0.0

you can omit the type annotations because the compiler can infer the
type automatically:

var latitude = 0.0
var longitude = 0.0

But actually I would go the other way around and replace the initial
values by an init() method. The reason is that – since you defined
your own init method – there is no default memberwise initializer anymore.
Therefore I would start with

struct PLNWaypointCoordinate {
    var latitude: Double
    var longitude: Double

    init(latitude: Double, longitude: Double) {
        self.latitude = latitude
        self.longitude = longitude
    }

    // ...
}

which allows you to create a value not only from a string, but
also from a given latitude and longitude:

let c = PLNWaypointCoordinate(latitude: ..., longitude: ...)

Your init(coordinateString: String) method assumes that the given
string is in a valid format and can crash otherwise (by accesssing
out-of-bounds array elements or unwrapping nils). As
@Ashley already said in his answer, you should define a
failable initializer instead, which returns nil if the input is
invalid:

init?(coordinateString: String) { ... }

Alternatively, define a throwing initializer:

init(coordinateString: String) throws { ... }

which throws an error for invalid input.

Your helper methods convertCoordinate and convert are private,
which is good. They do not use any properties of the value, which means
that they can be made static.

The conversion helper function is very lenient, it will for example
accept X47 15 36.75 instead of N47° 15' 36.75"
as latitude. It does not check that the coordinate starts with
a valid direction, or that the proper separators are used.

I don't know what the final part +001906.00 stands for, but that
is ignored completely in your code.

There is also a flaw in your conversion, the fractional part
of the seconds is ignored, e.g. 36.75" is taken as 36 seconds.

I would suggest to use Scanner instead, which makes it relatively
easy to check for a valid input and simultaneously
parse the values into variables. To distinguish
 between latitude and longitude, two arguments for the positive
and the negative direction are passed to the helper method.

The complete code then looks like this:

struct PLNWaypointCoordinate {
    var latitude: Double
    var longitude: Double

    init(latitude: Double, longitude: Double) {
        self.latitude = latitude
        self.longitude = longitude
    }

    init?(coordinateString: String) {
        let components = coordinateString.components(separatedBy: ",")
        guard components.count >= 2,
            let latitude = PLNWaypointCoordinate.convertCoordinate(coordinate: components[0],
                                                                   positiveDirection: "N",
                                                                   negativeDirection: "S"),
            let longitude = PLNWaypointCoordinate.convertCoordinate(coordinate: components[1],
                                                                    positiveDirection: "E",
                                                                    negativeDirection: "W")
            else {
                return nil
        }
        self.init(latitude: latitude, longitude: longitude)
    }

    private static func convertCoordinate(coordinate: String,
                                          positiveDirection: String,
                                          negativeDirection: String) -> Double? {
        // Determine the sign from the first character:
        let sign: Double
        let scanner = Scanner(string: coordinate)
        if scanner.scanString(positiveDirection, into: nil) {
            sign = 1.0
        } else if scanner.scanString(negativeDirection, into: nil) {
            sign = -1.0
        } else {
            return nil
        }

        // Parse degrees, minutes, seconds:
        var degrees = 0
        var minutes = 0
        var seconds = 0.0
        guard scanner.scanInt(&degrees),         // Degrees (integer),
            scanner.scanString("°", into: nil),  // followed by °,
            scanner.scanInt(&minutes),           // minutes (integer)
            scanner.scanString("'", into: nil),  // followed by '
            scanner.scanDouble(&seconds),        // seconds (floating point),
            scanner.scanString("\"", into: nil), // followed by ",
            scanner.isAtEnd                      // and nothing else.
            else { return nil }

        return sign * (Double(degrees) + Double(minutes)/60.0 + seconds/3600.0)
    }
}


Boggle solver in Rust - Looking for speedup

The main thing that's going to get you a speed boost is returning early from the search if there's no word that starts with what you have so far.

One simple way to do this is to keep a HashSet of all the prefixes of words in the dictionary. Or, better yet, a HashMap where the value indicates whether the prefix is actually a word or not.

struct PrefixMap<'a>(HashMap<&'a str, bool>);

impl<'a> PrefixMap<'a> {
    fn new(words: impl IntoIterator<Item = &'a str>) -> Self {
        let mut map = HashMap::new();
        for word in words {
            // note that this gets every prefix except the whole word
            for (ending, _) in word.char_indices() {
                map.entry(&word[..ending]).or_insert(false);
            }
            map.insert(word, true);
        }
        Self(map)
    }

    fn is_word(&self, word: &str) -> bool {
        self.0.get(word).copied().unwrap_or(false)
    }

    fn is_prefix(&self, prefix: &str) -> bool {
        self.0.contains_key(prefix)
    }
}

Then, in the first part of boggle_solve_help, we can use is_word and is_prefix to determine whether to print the word or return early.

if !dict.is_prefix(&word) {
    return;
}

if word.len() > 3 && dict.is_word(&word) {
    println!("{}", word);
}

While this isn't the most efficient thing possible, that simple step makes the program run almost instantly on my computer (less than a second). If you still want to improve more, look up tries for a memory efficient and quick way to do the same thing. Since creating the index of words takes a little while, you might try to cache it between runs using serde or something similar.

Now for some more suggestions.

Derive PartialEq. Right now you implement PartialEq for Coordinate manually, but the same implementation can be done by adding PartialEq to the derive attribute.
Use descriptive variable names. The main offenders are the arguments to move_c and later on c in boggle_solve_help. I know sometimes this is annoying, but even just changing a and b to dy and dx (calculus shorthand for "change in y/x") makes everything clearer. It's probably worth spelling out height and width to make it clear that that's what you mean.
Don't forget to use cargo fmt. It's a simple step and will instantly make your code more standardized and easier to read for other Rust programmers.
Encapsulate the grid into its own type. Right now, you're using Vec<Vec<char>> directly, which is fine, but means that lots of annoying details are strewn about the functions that use it. The type can still be Vec<Vec<char>> under the surface, but having a method like grid.get(coordinate) rather than grid[coordinate.row as usize][coordinate.col as usize] makes things easier to read and make sense of. As a plus, this will also silence Clippy's complaint about using &Vec<_> instead of &[_].
Consider switching to an iterative algorithm. You won't run into stack overflow here since you have a hard cap on how deep the recursion can go. Still, if you want a slightly faster algorithm, a depth-first search can be memory efficient and avoid the repeated String allocations you currently have (with format!).
Bonus: don't show duplicate words. Right now, a word will be duplicated if can be spelled with a different path of letters on the board. For example, "trees" can be written three different ways near the bottom right corner of the board so it gets printed 3 times. It also shows up in a few other places. I might suggest keeping a HashSet of all the words you've found so far to eliminate duplicates.

Here's the code after applying the early return and the first three of my suggestions. I'll let you figure out the other two.

use std::collections::HashMap;
use std::fs;

const MAX_WORD_LEN: usize = 12;

#[derive(Clone, Debug, Copy, PartialEq)]
struct Coordinate {
    row: i64,
    col: i64,
}

impl Coordinate {
    // Returns a new coordinate if the move is valid. None otherwise.
    fn move_coord(&self, dy: i64, dx: i64, height: i64, width: i64) -> Option<Coordinate> {
        let height_range = 0..height;
        let width_range = 0..width;
        if height_range.contains(&(self.row + dy)) && width_range.contains(&(self.col + dx)) {
            Some(Coordinate {
                row: self.row + dy,
                col: self.col + dx,
            })
        } else {
            None
        }
    }
}

// Keys consist of all prefixes of words
// Values say whether the prefix is a word
// Since we keep references rather than `String`s,
// the lifetime of the map can't exceed the lifetime of wherever
// the `&str`s come from.
// If you decide to make this more persistent, using `String` rather than `&str`
// might be appropriate.
struct PrefixMap<'a>(HashMap<&'a str, bool>);

impl<'a> PrefixMap<'a> {
    // We can produce this from any iterator of `&str`s.
    fn new(words: impl IntoIterator<Item = &'a str>) -> Self {
        let mut map = HashMap::new();
        for word in words {
            // note that this gets every prefix except the whole word
            for (ending, _) in word.char_indices() {
                map.entry(&word[..ending]).or_insert(false);
            }
            map.insert(word, true);
        }
        Self(map)
    }

    fn is_word(&self, word: &str) -> bool {
        self.0.get(word).copied().unwrap_or(false)
    }

    fn is_prefix(&self, prefix: &str) -> bool {
        self.0.contains_key(prefix)
    }
}

fn boggle_solve(grid: &Vec<Vec<char>>, dict: &PrefixMap) {
    for (i, row) in grid.iter().enumerate() {
        for (j, ch) in row.iter().enumerate() {
            boggle_solve_help(
                grid,
                dict,
                ch.to_string(),
                Coordinate {
                    row: i as i64,
                    col: j as i64,
                },
                vec![Coordinate {
                    row: i as i64,
                    col: j as i64,
                }],
            )
        }
    }
}

fn boggle_solve_help(
    grid: &Vec<Vec<char>>,
    dict: &PrefixMap,
    word: String,
    coord: Coordinate,
    path: Vec<Coordinate>,
) {
    // Base case.
    // No more work if the string is long enough
    if word.len() > MAX_WORD_LEN {
        return;
    }

    if !dict.is_prefix(&word) {
        return;
    }

    if word.len() > 3 && dict.is_word(&word) {
        println!("{}", word);
    }

    // For every possible direction the path can take, if it is valid, take it.
    for dy in -1..=1 {
        for dx in -1..=1 {
            match coord.move_coord(dy, dx, grid.len() as i64, grid[0].len() as i64) {
                Some(new_coord) if !path.contains(&new_coord) => {
                    let mut new_path = path.clone();
                    new_path.push(new_coord);
                    let new_word = format!(
                        "{}{}",
                        &word, &grid[new_coord.row as usize][new_coord.col as usize]
                    );

                    boggle_solve_help(grid, dict, new_word, new_coord, new_path);
                }

                Some(_) => (),

                None => (),
            }
        }
    }
}

fn main() {
    let contents = fs::read_to_string("words_alpha.txt").unwrap();
    let dict = PrefixMap::new(contents.split_whitespace());

    let grid: Vec<Vec<char>> = vec![
        vec!['c', 's', 't', 'e', 't'],
        vec!['a', 'i', 'r', 'l', 's'],
        vec!['p', 'd', 'a', 'e', 's'],
        vec!['u', 'e', 'c', 's', 'e'],
        vec!['r', 'o', 't', 'r', 'i'],
    ];

    boggle_solve(&grid, &dict)
}

(playground - but note that words_alpha.txt doesn't exist, so you can't run it)


I would suggest following:

Do not compare strings by ==, use String.equals(). And in Your case is better String.isEmpty()

text != "" → !text.isEmpty()
Use constants for numbers and strings. It increases readability and futher refactoring.

private static final String WORD_SEPARATOR = " ";
There is no need to use indexed iterations

for(int j=0;j<arry.length;j++) → for (String s : arry)
Use IDE with spelling checker:

arry → array
Use meaning variable names.

String s → String word
No need to use cast:

int number = (int) sd[0]; → int number = sd[0];
Decrease level of visibility

public static String encryptThis → static String encryptThis
Use method extraction to decrease nesting level

private static StringBuilder encrypt(char[] wordChars, int number)
You add first char in any case so condition can be omitted.
You could use chain of method .append(...) calls for StringBuilder
It is nice to move conditions like k==1 to meaningful named method:

See isSecondChar(...)
It is nice to validate input params early and prevent any actions if it is not valid:

if(text!="") → if (text.equals("")) then return empty string;

I would strongly suggest you to read great Joshua Bloch 'Effective Java' book.

Have a look at the refactored code:

class NewEnpc {

    private static final String WORD_SEPARATOR = " ";

    static String encryptThis(String text) {
        if (text.isEmpty()) {
            return text;
        }
        StringBuilder result = new StringBuilder();
        String[] words = text.split(WORD_SEPARATOR);
        for (String word : words) {
            char[] wordChars = word.toCharArray();
            result.append((int) wordChars[0])
                    .append(encrypt(wordChars))
                    .append(" ");
        }
        return result.toString().trim();
    }

    private static StringBuilder encrypt(char[] wordChars) {
        StringBuilder encrypted = new StringBuilder();
        for (int index = 1; index < wordChars.length; index++) {
            if (isSecondChar(index)) {
                int len = wordChars.length - 1;
                encrypted.append(wordChars[len]);
            } else if (isLastChar(index, wordChars.length - 1)) {
                encrypted.append(wordChars[1]);
            } else {
                encrypted.append(wordChars[index]);
            }
        }
        return encrypted;
    }

    private static boolean isLastChar(int currentIndex, int prevCharIndex) {
        return currentIndex == prevCharIndex;
    }

    private static boolean isSecondChar(int currentIndex) {
        return isLastChar(currentIndex, 1);
    }
}

public class EncryPt {
    public static void main(String[] args) {
        System.out.println("Hello");
        System.out.println(NewEnpc.encryptThis("A wise old owl lived in an oak"));
    }
}


JSON formatting and processing hierarchies

Assuming you're using JavaScript to manipulate the object, you could also split it up into 2 different structures, one for maintaining the hierarchy and another for easy access:

var hierarchy = {
    transportation: {
        road: {
            colour: "rgb(0,0,0)"
        },
        railway: {
            colour: "rgb(100,100,100)"
        }
    }
};

var features = {
    road: hierarchy.transportation.road,
    railway: hierarchy.transportation.railway
};


In this case, you really just need an atomic variable, and you can do a compare_exchange_strong to set the value once:

#include <thread>
#include <iostream>

std::atomic_bool m_running;
bool wrote[4];

void func1(int num) {
    bool f{ false };
    if (m_running.compare_exchange_strong(f, true))
        wrote[num] = true;
}

int main(){
    std::vector<std::thread> t;

    for (int i = 0; i < 4; i++)
        t.emplace_back(func1, i);

    for (auto &t1 : t)
        t1.join();

    for (bool b : wrote)
        std::cout << std::boolalpha << b << "\n";
}

Given that thread 1 starts running first, and it's not doing very much, chances are that the first thread will do the write to the variable virtually every time. In case you're not familiar with it, atomic_bool is (obviously enough) an atomic Boolean type, and compare_exchange_strong does an atomic comparison and exchange. Specifically, it compares the current value to the first parameter, then if (and only if) they're equal, sets the value to the second parameter. The first parameter has to be passed by reference, because it also writes the new value to that variable. Finally, it returns true if and only if it actually wrote to the variable. In this case I've used that to record which thread actually wrote to the variable, so the final printout should show true once, and false three times.

Looking at the code as you've written it:

void func1(bool isSet)
{
  mut.lock();
  if (!isRunning())
  {
    setRunning(true);
  }
  mut.unlock();
}

You almost certainly want to use an std::lock_guard to automate unlocking the mutex. Right now, the code also ignores the isSet parameter, and always sets the value to true. I'd assume you really want to compare to isSet, and set it to that value if it's not already equal to it. Combining these, the code would come out something like:

void func1(bool isSet) {
     std::lock_guard g(mut);

     if (isRunning() != isSet)
        setRunning(isSet);
}

That's somewhat simpler, but I still think the atomic_bool with compare_exchange_strong is neater. The atomic variable can degenerate to pretty much what you've done with a mutex in the worst case, but in quite a few cases, it'll be substantially more efficient.


What you have is essentially:

if (a) {
   if (b) c();
   d();
}
else if (b) e();

Where:

a = user_ptr
b = batchOrTimestamp != "batch"
c = user_ptr->ping();
d = 2 lines, starting with `AttributeMap::GuardSPtr guard = user_ptr->m_attrMap.get_guard();`
e = 3 lines, starting with `user_ptr = User::MakeUser(user_id);`

One way to rewrite this is:

if (a && b) c();
if (a) d();
else if (b) e();

And another way is:

if (b) {
   if (a) c();
   else e();
}
if (a) d();

Which of these ways you prefer is up to you. The problem is that you have a total of three branches. One for a, one for b && !a and one for a && b.

I don't believe it's possible to simplify this in a better way (I would gladly be proven wrong).


The solution is slow because you aren't using data structures effectively.  In particular, the nested (0..size).each loops will cause it to take \$O(N^2)\$ time, which will be very problematic for large \$N\$.

You created new_array (which is actually a hash, not an array as the name suggests), but populate it the hard way.  The easy way is to loop once through all of the words; for each word you encounter, increment its count by 1.  There is no need to construct the intermediate array a.

# Read N, then count occurrences of the next N lines of text
word_counter = Hash.new { |count, word| count[word] = 0 }
n_lines = gets.to_i
n_lines.times { word_counter[gets] += 1 }

# Read k; limit it to the number of distinct words
k = gets.to_i
k = [k, word_counter.keys.length].min

# Sort words by descending frequency, breaking ties by alphebetical order
words_desc_freq = word_counter.sort do |a, b|
  cmp = a.last - b.last                    # .last is the count
  cmp != 0 ? -cmp : (a.first <=> b.first)  # .first is the word
end

# Output k most frequent words
(0...k).each do |i|
  puts words_desc_freq[i].first
end

The solution above has complexity \$O(N \log N)\$, dominated by the time it takes to sort.

Usually, when constraints are given for problems like this, it means that your program is not expected to handle input exceeding the stated limits gracefully.  It does not mean that your program needs to actively reject input that exceeds those limits.  In any case, your "validation" isn't quite right: in Ruby, 0 is treated as a true value.

Your code is formatted reasonably well.  I would just note that the line that performs the sort is long and should be broken up.  One-line blocks are typically written using braces, like (0..size).each { |j| count += 1 if a[i] == a[j] }


Python script to delete sections of text

Program flow

You have a lot of booleans being thrown around and you could clear out a lot. if nextFlag == True is the same as if nextFlag, and the latter looks neater so stick with it.

For the main flow, you have it in a bit of a mess. You should have only one flag, which denotes lines should be deleted or skipped. Your two flags are entirely confusing the process. Think about it this way, you need a flag to indicate that a part should be skipped. You don't need two values indicating the same thing. So how does that work?

Well obviously you start with looking for beginDelete. We need to first check if deleteFlag is True or False. If it's True we want it to remain as it is until stopDelete is found and skip. So if deleteFlag isn't True, then we set it to be the result of beginDelete in line. You can assign expressions to variables, even if it's a boolean expression. So on this basis we don't need another if check, we can just set deleteFlag to equal this result directly. Obviously this means the flag is now True if we've found beginDelete but False otherwise.

for line in lines:
    if not deleteFlag:
        deleteFlag = beginDelete in line

Now, we also need to find stopDelete to turn the flag False when it's found. This only needs to run if deleteFlag is True, so it should be an else condition:

for line in lines:
    if not deleteFlag:
        deleteFlag = beginDelete in line
    else:
        deleteFlag = stopDelete not in line
        continue

Now you can see that deleteFlag is being set based on whether or not stopDelete has been found yet. We're using not so that deleteFlag remains True until stopDelete is found. Once that happens, deleteFlag is once again False. However, since you don't want to write the line where you've just found stopDelete then you should use continue to skip to the next iteration of the line. continue is a keyword that tells a loop to immediately go to the next iteration, ignoring any remaining code in the loop's block.

Now, writing to the file is easy. You just want to write if not deleteFlag, ie. if the flag isn't True.

    if not deleteFlag:
        output.write(line)

Style Notes

Stick to 4 space indentation. It's the Python standard and far more readable for people. Speaking of standards, Python naming uses snake_case, so beginDelete should be begin_delete etc.

Your names could be better too. You're not really deleting anything. You're 'skipping' or 'ignoring'. You don't really need to include flag in the name, using ignore would be pretty clear. Also avoid using input as that shadows the builtin Python method of the same name. Instead input_file or in_file. With such a brief usage, you can also use f.

Speaking of files, you should use with when opening files. It's a context manager that makes file manipulation safer. When using open you can easily run into trouble if you don't close the file. Sometimes that can happen due to errors, or if you forget to. Which it looks like you actually did with output. Using with means that a file is always automatically closed, even in the case of errors or exceptions, so it's a more reliable method. This is how you'd use it for lines.

with open(path, "r") as f:
    f.readlines()

The indentation signals how long to leave the file open, and then it's closed once you move out of that block. You should do the same for output, also open defaults to opening in "r" mode so you don't need to specify the argument there.

Also in your final os.walk loop you assign start and dirs but don't seem to use them. If you don't need those values, consider using the names _ and __. That's a Python way of saying that variables are unused throwaways, so people reading your code know they don't matter.


Since you have main() below the other function, you don't need the prototype for that function.  It's only needed if main() is defined before a function that it calls.
There's no need to declare a variable and then assign to it:

int* intArray;
// ...
intArray = createIntArray(stringNumbers,&arrayLength);

Variables should just be initialized in the closest scope possible.  This will ease maintenance as you won't have to search for the declared variable elsewhere, such as if it's no longer in use.

int* intArray = createIntArray(stringNumbers,&arrayLength);

Instead of incrementing i in createIntArray(), why not just increment array_size?

Plus, i is more commonly used as a for loop counter, which isn't the case here.  If someone were to take a glance at that while loop without further context, they may think that it should be a for loop instead.  By making this change, you'll remove that possible misconception and better communicate your exact intentions.


Ruby selenium script waiting for an element to disappear

Some notes:

waitUntilDisappears. In Ruby, always: wait_until_disappears.
if element != nil -> if element.
if element != nil. I think find_element never returns nil, it raises exception if not found, so this is not needed.
rescue Exception => e. A rescue that covers a whole method can omit the begin.
rescue Exception => e. Rescuing from Exception is bad practice. Rescue from StandardError, which is the same as rescue => e.
puts "Error". It's bad practice to catch an exception (even worse ifit's all exceptions), just print to the screen and return as if nothing happened. Raise an exception or return a value that signals the error.
Is Element#visible? not enough?

I'd write:

def wait_until_disappears(type, name, timeout: 5)
  wait = Selenium::WebDriver::Wait.new(timeout: timeout)
  wait.until { !driver.find_element(type, name).visible? }
end


I would use an associative array (also known as  a "map" or "dictionary" in other languages).

$errorMessages = array('emailInvalid' => 'Invalid email',
    'passLength' => 'invalid password length',
    'passLowerCase' => 'missing lower case character in password'
    // and so on...
);

Then I would loop across this map:

foreach ($errorDetails as $key => $value) {
    if (strpos($errorDetails, $key) !== false) {
        $errorList .= '
' . $value . '
';
    }
}

strpos

Storing your error-message stubs in $errorDetails is inefficient. strpos loops through the string each time. I'd recommend to instead append your error messages to an array, which would open up the possibility of looking up the full error message from something like emailInvalid with a O(1) complexity.

How did I know it was a map that was needed?

Let's look at this code:

if(strpos($errorDetails, "emailInvalid") !== false){
    $errorList .= "
Some text
";
}
if(strpos($errorDetails, "passLength") !== false){
    $errorList .= "
Some (other) text
";
}

There are two things that differs here, these parts can be simplified to:

if (strpos($errorDetails, $xxxxxxx) !== false) {
    $errorList .= $yyyyyyy;
}

To clean up this code, we could extract a method and call that multiple times, such as:

addErrorList($errorDetails, 'emailInvalid', 'invalid e-mail');
addErrorList($errorDetails, 'passLength', 'invalid password length');
...

However, this is still not very nice. A map / associative array contains a key to value mapping, which is precisely what you have here. For each specific error detail key, there is an associated error message. So add those values to an associative array and then loop through it.


Generating business summary stats in SQL dynamically, based on an inputted date

It is possible to simplify this:

CASE when prha.creation_date between to_date(:myDate,'DD-MON-YY') and to_date(:myDate,'DD-MON-YY') + 7  then 'Week 1'
    when prha.creation_date between to_date(:myDate,'DD-MON-YY') + 7 and to_date(:myDate,'DD-MON-YY') + 14  then 'Week 2'
    when prha.creation_date between to_date(:myDate,'DD-MON-YY') + 14 and to_date(:myDate,'DD-MON-YY') + 21 then 'Week 3'
    when prha.creation_date between to_date(:myDate,'DD-MON-YY') + 21 and to_date(:myDate,'DD-MON-YY') + 28  then 'Week 4'
  else 'After Month 1' END as "Req_Created",     1  as "Req Lines",

In Oracle SQL, you can extract a date from the other date. Result is a number, which equals to day count between dates (fractional part is hours, minutes and seconds). So, prha.creation_date - to_date(:myDate,'DD-MON-YY') gives number of days, ceil((prha.creation_date - to_date(:myDate,'DD-MON-YY' - 1) / 7) gives number of week. Here is the code:

case when prha.creation_date - to_date(:myDate,'DD-MON-YY') > 28
       then 'After Month 1'
     else 'Week ' || ceil((prha.creation_date - to_date(:myDate,'DD-MON-YY') - 1) / 7)
     end as "Req_Created"

The following expression:

CASE when prha.authorization_status='APPROVED' then 1 else 0 END as "Approved Req"

could be replaced with decode function:

decode(prha.authorization_status, 'APPROVED', 1, 0) as "Approved Req"

decode is more brief, but has its own limitations. For more details, see documentation.


Are there any open vulnerabilities in this mailer script?

Your mailer is vulnerable to a header-splitting attack!  (Also known as a CRLF-injection attack.)

Basically, if one of the fields contains a CRLF, the attacker can insert any arbitrary header into the generated message.  For example, if the email parameter is

victim1@example.com%0d%0aCc:%20victim2@example.net

… then you will compose a message with headers

From: victim1@example.com
Cc: victim2@example.net
Reply-To: victim1@example.com
Cc: victim2@example.net

PHP's mail() function will "helpfully" add victim2@example.net as a spam recipient.  The spam will look like it came from victim1@example.com.

The simplest mitigation, I believe, is to pass all of the header fields through
mb_encode_mimeheader() first.

  General warning regarding string concatenation and interpolation

  Any time you compose a string that will be interpreted by another computer system, be it an e-mail message, HTML page, or SQL query, assume that you are vulnerable to some kind of injection attack.  Every single one of these "human-friendly" languages (as opposed to binary formats such as JPEG images) will have delimiters of special significance.  Header-splitting, HTML/JavaScript injection, and SQL injection attacks all have the same root cause: careless string concatenation or interpolation.

  Therefore, before concatenating or interpolating strings, stop and think: "What is the appropriate escaping mechanism that I should be using?"  Better yet, ask: "Is there a higher-level library that will let me accomplish the task without low-level string manipulation?"

  RFC time!

  I'm diving into a deeper technical discussion about why mb_encode_mimeheader() is my choice for escaping.  If you get confused by this technical discussion, you can safely ignore this explanation and just filter all the input through mb_encode_mimeheader().

  There are actually two relevant standards for e-mail headers.  Mail Transfer Agents (MTAs) care about RFC 2822.  Mail User Agents (MUAs) care about RFC 2047.

  MTAs are completely oblivious to MIME encoding.  As long as they see the headers they need (e.g. "From", "To", "Return-Path"), and the headers contain a safe subset of ASCII, they are happy.

  MUAs, on the other hand, are more sophisticated, in that they have to handle non-ASCII text for the benefit of non-English users.  For example, a "Subject" header could contain arbitrary text, such as "¡Hóla!".  Such a Subject line should be encoded using

mb_encode_mimeheader("¡Hóla!", "UTF-8", "Q");

  as

=?UTF-8?Q?=C2=A1H=C3=B3la!?=

  That is, by the way, the way to ensure that the $subject parameter is RFC 2047-compliant, as specified in the mail() documentation.

  What about headers that are relevant to both MTAs and MUAs, such as the "From" header?  One might want to generate a header that looks to the user like

From: "François Müller" <francois.mueller@example.com>

  Over the wire, such a header must be encoded, since it contains non-ASCII characters.  One acceptable encoding would be

From: "=?UTF-8?Q?Fran=C3=A7ois=20M=C3=BCller?=" <francois.mueller@example.com>

  Such an encoding satisfies both RFC 2822 (since the MTA sees an opaque ASCII string between the double-quotes) and RFC 2047 (since the MUA should know how to decode the MIME-encoded string for display).  To achieve such a result, you would need PHP code such as

$from_header = sprintf('From: "%s" <%s>',
                       mb_encode_mimeheader("François Müller", "UTF-8", "Q"),
                       "francois.mueller@example.com");

  If you write your code as

$email = '"François Müller" <francois.mueller@example.com>';
$from_header = mb_encode_mimeheader("From: $email", "UTF-8", "Q");

  … you'll get

From: =?UTF-8?Q?=22Fran=C3=A7ois=20M=C3=BCller=22=20=3Cfrancois=2Emueller?=
 =?UTF-8?Q?=40example=2Ecom=3E?=

  … which is wrong, since the MTA sees one opaque ASCII string that does not look like a valid e-mail address.  However, the main point is that such code, though simplistic, is not vulnerable to header injection.  As long as the $email variable contains simple ASCII text, it will work.  For example,

$email = '<francois.mueller@example.com>';
$from_header = mb_encode_mimeheader("From: $email", "UTF-8", "Q");

  … passes the text through unchanged, producing

From: <francois.mueller@example.com>

  PHP-bashing time!

  As is often the case with PHP, the mail() function is poorly designed, such that it is easy to fall into this trap.  Expecting programmers to know the RFCs and take the time to encode all of the headers properly is pure madness!  If mail() were designed such that it accepted an associative array of (header name → header value) pairs, then it could automatically apply mitigation against header-splitting attacks.


You are sorting your dictionary each time you use it, do it once and store it.

Also, you are sorting your scrambled word more than once, only do it once:

import numpy as nm
import pytesseract
import cv2
import ctypes
from PIL import ImageGrab

def imToString(dictionary):

    # Path of tesseract executable
    pytesseract.pytesseract.tesseract_cmd =r'C:\Program Files (x86)\Tesseract-OCR\tesseract'
    while(True):

        # ImageGrab-To capture the screen image in a loop.
        # Bbox used to capture a specific area.
        cap = ImageGrab.grab(bbox =(687, 224, 1104, 240))

        # Converted the image to monochrome for it to be easily
        # read by the OCR and obtained the output String.
        tesstr = pytesseract.image_to_string(
                cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY),
                lang ='eng')
        checkWord(tesstr, dictionary)

def checkWord(tesstr, dictionary):

    scrambled = tesstr
    sorted_scrambled = sorted(scrambled) # Only do this 1 time
    if sorted_scrambled in dictionary:
        print(dictionary[sorted_scrambled]

# ... Create your dictionary somewhere else and pass it in:
dictionary ={sorted('orange'): 'orange',sorted('marshmellow'):  'marshmellow'}

imToString(dictionary)


Perl one-liner for parsing host names from ssh config file

I would use something like

perl -lane '@h{@F[1..$#F]}=()if/^Host\b/;END{$,=" ";print keys %h}' -- file

or

perl -lane '@h{ @F[ 1 .. $#F ] } = () if /^Host\b/;
            END {
                $, = " ";
                print keys %h;
            }' -- file

-l removes newlines from input and adds them to prints
-n runs the code for each line of the input
-a splits each line on whitespace into the @F array
the hash %h is populated by all the non-whitepsace strings following Host
at the end, all the keys are printed separated by space


Your function doesn't have docstrings.  Docstrings are good because they give you an opportunity to tell users of your code how to use it.  I had to read the whole code to determine that the binary search you were referring to was for element extraction on a (presumably sorted) list.
You don't check for (or even document) that your function only works on sorted lists.  For example binarySearch('acb', 0, 2, 'b') gives -1 which might not be what users expect.  You could add an assert array == sorted(array) statement to guard against unsorted arrays being passed in, or at the very least mention the requirement for sortedness in the docstring.
You could easily supply default arguments for beginIndex and endIndex in the common use case that the search should start on the whole array.  The case of endIndex is a bit tricky since the default value depends on the length of the whole array.  But you could so something like:

def binarySearch(array, value, beginIndex=0, endIndex=None):
    """Docstring you need to add"""
    if endIndex is None:
        endIndex = len(array) - 1
    # rest of code

That way, users would not always have to supply arguments for beginIndex and endIndex if they didn't feel like it.  Notice how I had to re-order the parameter to achieve this effect, because arguments with default values must all be listed after arguments with no default (and you won't likely ever want a default value for value).

You could make the code forward-compatible with Python 3 by adding a from __future__ import division at the top and using // instead of /.
For consistency with most other regular Python functions, you might want to raise ValueError or something similar instead of return -1 when the search does not succeed.  I'm only slightly joking when I say that Pythonic users might interpret a -1 as meaning that the desired value was found at the end of the array!
You don't use PEP8 style recommendations.  binary_search() and begin_index would be preferred names relative to binarySearch() and beginIndex.


Count the frequency of words in a text file

Use a Context Manager

When dealing with something like a file, it's safer to write:

with open(filename) as file:
    ## code ##

That will automatically handle file closing correctly in case of exceptions and the like. I also find it clearer. Also, why r+?

Prefer Generators

file.read() reads the entire file into memory. Prefer to just go a line at a time by iterating through it.

wordcount.items() gives you a full list of all the items. But you don't need them all at once, you just need to iterate through them. For that there's iteritems().

Use the tools at your disposal

You have:

if word not in wordcount:
    wordcount[word] = 1
else:
    wordcount[word] += 1

That's a lot of code for a simple operation. What are you doing here? You're counting the incidence of word. But there's an app for that: collections.Counter:

wordcount = collections.Counter()
for line in file:
    for word in line.split():
        wordcount[word] += 1

Furthermore, we also have Counter.update, which lets us do:

for line in file:
    wordcount.update(line.split())

Full solution:

#!/usr/bin/python
import collections

wordcount = collections.Counter()
with open("C:/python27/python operators.txt") as file:
    for line in file:
        wordcount.update(line.split())

for k,v in wordcount.iteritems():
    print k, v


Your bruteforce method seems correct, there might be better ones available (using heuristics for instance), but let's stick with what you have.

First thing, you pass the matrix by value in each longestpathfrom and not by reference, probably a mistake given you do it for the rest. Given how many times you use this function and how big the matrix can be, it can make a huge difference.

Second thing, you can reduce the search space.
For instance, you know that if start is "a" and stop is "b", the longest path possible is "b-a". If, instead of starting by [0][0] then [0][1] ..., you start by the lowest value then the second lowest ..., you know you can stop searching once the maximum value of the matrix minus the current start value is lower than the length of the current maximum path.

Just a few words on coding style if I may.
Try to keep the style of the name of variables constant. Leetcode seems to use camelCase, so it's best if you stick to it (so longestPathFrom instead), or switch everything to C style (lowest_path_from).
Try not to use capital letters at the start/for variable names (your I).
Try to keep spacing consistent either you use variable=value or variable = value, but not both. I'd say the later is much better and readable.


A quick way to make your code more Go-styled is to have it automatically formatted.  Specifically, spaces are a bit off.  For example, in the isSameTree() signature, you have a space before a comma, a space before the closing parenthesis, and no space before the opening brace.  The parentheses around (bool) are unnecessary.  You're also writing semicolons inconsistently.

The isSameTree() implementation is a bit confusing ("A but not B and not C.  If you made it this far, check D and E and F?").  It would be clearer as one long affirmative expression.

func isSameTree(p *TreeNode, q *TreeNode) bool {
        return (p == nil && q == nil) ||
               (p != nil && q != nil &&
                p.val == q.val &&
                isSameTree(p.left, q.left) && isSameTree(p.right, q.right))
}


Const correctness

We don't modify the contents of str, so pass it as a const char*.  This allows us to give string literals as arguments without compiler warnings.

Check the arguments

What if str or substr is null?  What does it mean for length to be negative?  We should use size_t for indexing and lengths.

int overlap(const char *str, const char *substr, size_t length)
{
    if (!str || !substr)
        /* invalid arguments */
        return 0;

Add more tests

I'm not 100% sure from the description what the code is supposed to do.  That can be made clearer by providing more tests.  I recommend using a test framework to help identify the failures, but we can make our own for this:

int test(const char *a, const char *b, size_t len,
         int expected, const char *file, int line, const char *message)
{
    const int actual = overlap(a, b, len);
    if (actual == expected) return 0;

    fprintf(stderr, "%s:%d: %s should be %d, but got %d\n",
            file, line,
            message, expected, actual);
    return 1;
}

#define TEST(a, b, len, expected) \
    test(a, b, len, expected, __FILE__, __LINE__, "overlap(" #a ", " #b  ", " #len ")")

int main(void)
{
    return
        + TEST(NULL, NULL, 1, 0)
        + TEST("abc", "def", 0, 1)
        + TEST("abc", "abc", 4, 0)
        + TEST("abc", "abc", 3, 1)
        + TEST("abc", "bcd", 3, 0)
        + TEST("abc", "bcd", 2, 1)
        + TEST("bcd", "abc", 2, 1)
        + TEST("abcef01239", "abckef01798", 4, 1);
}

Algorithm

We're going more times over the data than we need to - although it looks like we're scaling as O(n²), it's actually O(n³), because of the if/else at the end of the loop that resets substr from time to time.

What we need to do is for each offset of str and substr, walk along the pair of them, counting character matches as we go (reset the count on a non-match).  If the count reaches length, then we've found a substring match.

As a worked example, let's test "ab1cdefg" against "bcde2":

ab1cdefg
bcde2
.....

In that first pass, nothing matched.  Now shift one of the strings by one character (i.e. index by n+1 instead of by n):

ab1cdefg
 bcde2
 1....

The longest run was 1, when we matched the b.  Next iteration:

ab1cdefg
  bcde2
  .123.

Here, we matched c, d and e successively, for a run length of 3.

In code, that looks something like:

#include <string.h>

/* internal method - returns true if a and b are equal for a run of
   length, without shifting */
static int overlap_run(const char *a, const char *b, size_t length)
{
    size_t count = 0;
    while (*a && *b) {
        /* add one to count, or reset it to 0 */
        if (*a == *b)
            ++count;
        else
            count = 0;

        if (count == length)
            /* match found */
            return 1;

        ++a, ++b;
    }
    return 0;
}

int overlap(const char *a, const char *b, size_t length)
{
    if (!a || !b)
        /* invalid arguments */
        return 0;

    if (!length)
        /* every pair of strings has a zero-length match */
        return 1;

    const size_t la = strlen(a);
    const size_t lb = strlen(b);

    if (length > la || length > lb)
        /* strings are too short to match */
        return 0;

    for (size_t offset = 0;  offset <= la - length;  ++offset)
        if (overlap_run(a+offset, b, length))
            return 1;

    for (size_t offset = 1;  offset <= lb - length;  ++offset)
        if (overlap_run(a, b+offset, length))
            return 1;

    /* no match */
    return 0;
}

You might be able to avoid pipeline stalls by replacing

    if (*a == *b)
        ++count;
    else
        count = 0;

With

    count += (*a == *b);
    count *= (*a == *b);

But you'll need to benchmark to find out on your hardware.


Importing database of 4 million rows into Pandas DataFrame

Your code

def import_db_table(chunk_size, offset):

It doesn't look like you need to pass offset to this function. All it does is give you the functionality to read from a given row to the bottom. I would omit it, or at least give it a default value of 0. It also looks like you need connection as one of the variables.

    dfs_ct = []
    j = 0
    start = dt.datetime.now()
    df = pd.DataFrame()

    while True:
        sql_ct = "SELECT * FROM my_table limit %d offset %d" % (chunk_size, offset)
        dfs_ct.append(psql.read_sql_query(sql_ct, connection))

        offset += chunk_size

        if len(dfs_ct[-1]) < chunk_size:
            break

As written, the while loop should stop here. You can also get better performance by making a generator instead of a list out of the query results. For example:

Code suggestions

    def generate_df_pieces(connection, chunk_size, offset = 0):
        while True:
            sql_ct = "SELECT * FROM my_table limit %d offset %d" % (chunk_size, offset)
            df_piece = psql.read_sql_query(sql_ct, connection)

            # don't yield an empty data frame
            if not df_piece.shape[0]:
                break
            yield df_piece

            # don't make an unnecessary database query
            if df_piece.shape[0] < chunk_size:
                break

            offset += chunk_size

Then you can call:

    df = pd.concat(generate_df_pieces(connection, chunk_size, offset=offset))

The function pd.concat can take a sequence. Making the sequence be a generator like this is more efficient than growing a list, as
you don't need to keep more than one df_piece in memory until you actually make them into the final, larger one.

Back to your code

        df = pd.concat(dfs_ct)

You're resetting the entire dataframe each time and rebuilding it anew from the whole list! If this were outside of the loop it would make sense.

        # Convert columns to datetime
        columns = ['col1', 'col2', 'col3','col4', 'col5', 'col6',
                   'col7', 'col8', 'col9', 'col10', 'col11', 'col12',
                   'col13', 'col14', 'col15']

        for column in columns:
            df[column] = pd.to_datetime(df[column], errors='coerce')

        # Remove the uninteresting columns
        columns_remove = ['col42', 'col43', 'col67','col52', 'col39', 'col48','col49', 'col50', 'col60', 'col61', 'col62', 'col63', 'col64','col75', 'col80']

        for c in df.columns:
            if c not in columns_remove:
                df = df.drop(c, axis=1)

This part could be done in the loop / generator function or outside. Dropping columns is a good thing to place inside as then the big dataframe you build won't ever need to be larger than you want. If you're able to put only the columns you want in the SQL query, that would be even better, as it would be less to send over the connection.

Another point to make about df.drop is that by default it makes a new dataframe. So use inplace = True so you don't copy your huge dataframe. And it also accepts a list of columns to be dropped:

Code suggestions

        df.drop(columns_remove, inplace = True, axis = 1)

gives the same result without looping and copying df over and over. You can also use:

        columns_remove_numbers = [ ... ] # list the column numbers
        columns_remove = df.columns[columns_remove_numbers]

So you don't have to type all those strings.

Back to your code

        j+=1
        print('{} seconds: completed {} rows'.format((dt.datetime.now() - start).seconds, j*chunk_size))

If you use the generator function version of this, you could put this inside that function to keep track of the performance.


Count unique characters in a String and group the counts

For the most part, there isn't much that I would change - well done!

First, minor things:

Remove the semi-colon in valid_nucleotide.
Next, you can change nucleotides.contains(_) (an anonymous function) to just nucleotides.contains (a method value).
The reuse of valid_nucleotide in count will result in any call with an invalid parameter getting an IllegalArgumentException("DNA is wrong"). I think this error would be confusing in this context.

The biggest single change I would make is to precompute the nucleotide counts. Currently, the code recomputes them each and every time either count or nucleotideCounts is called. Since code is immutable, it is only necessary to compute them once.

In a Java program, the "empty" nucleotides map could be made into a static member (rather than having a copy of it in every instance of the DNA class). The equivalent approach in Scala is to use a companion object (an object with the same class name as the class it is a companion to).

My version of your code looked like this:

object DNA {
  val nucleotides = Map('A' -> 0, 'T' -> 0, 'C' -> 0, 'G' -> 0)
}

class DNA(code: String) {

  code foreach validNucleotide

  val counts = countNucleotides()

  def nucleotideCounts(): Map[Char, Int] = counts

  def count(nucleotide: Char): Int = {
    validNucleotide(nucleotide)
    nucleotideCounts()(nucleotide)
  }

  private def countNucleotides(): Map[Char, Int] = {
    DNA.nucleotides ++ code.filter(DNA.nucleotides.contains).groupBy(identity).mapValues(_.length)
  }

  private def validNucleotide(char: Char) = {
    if (!DNA.nucleotides.contains(char)) {
      throw new IllegalArgumentException("Character not found in valid nucleotide set")
    }
  }
}


Checking whether a number starts with any of a list of string prefixes

It's better to pass containers as references to avoid copying like this:

bool prefix_vect(long double rand, const std::vector<std::string>& prefix)

Also, when iterating on sequence, references also can improve performance:

for(const auto& i : prefix) {

As for one-liner I'd used something like this:

bool prefix_vect2(long double rand, const std::vector<std::string>& prefix) {
    std::string str_rand = std::to_string(rand);
    return std::none_of(prefix.begin(), prefix.end(),
             [&str_rand](const std::string& s){ return boost::starts_with(str_rand, s); });
}


Oracle query to split 1 row into two where conditions are applicable

I'd solve the problem by providing a PL/SQL procedure that knows the "split"-logic.

In the example below I assume that non-splitted rows are not inserted into the table at all but all inserts should be done with the procedure. This is a rather common pattern when there's data manipulations but it is not clear from your problem statement if this is an acceptable solution in your case.

I used regular expressions as it's a very handy tool for pattern matching with superior expressiveness and clarity compared to substr(instr()) spaghetti.

I didn't used triggers as it's not possible to modify the table trigger is attached to.

The solution can be easily applied even if you need to read the input data (i.e. non-splitted) from the same table.

Example

create table cr1_t(
 id number
,orig_id number
,old varchar2(24)
,new varchar2(24)
);

create sequence cr1_s;

create or replace procedure cr1_insert(
  p_id in number
 ,p_old in varchar2
 ,p_new in varchar2
) is
  -- the p_*-variables are visible in the nested subprogram
  procedure insert_if(p_pattern in varchar2) is
    v_old constant varchar2(32767) := regexp_substr(p_old, p_pattern);
    v_new constant varchar2(32767) := regexp_substr(p_new, p_pattern);
  begin
    -- insert only if the values are different
    if v_old <> v_new
    then
      insert into cr1_t(id, orig_id, old, new) values (cr1_s.nextval, p_id, v_old, v_new);
    end if;
  end;
begin
  -- https://en.wikipedia.org/wiki/Tuple
  -- note the separator doesn't matter

  -- the pattern will match the first member of a "2-tuple"
  -- regexp explained:
  -- ^           anchor the pattern to the beginning of a string
  -- [[:upper:]] any uppercase character
  -- -           character '-'
  -- [[:upper:]] any uppercase character
  --
  insert_if(p_pattern => '^[[:upper:]]-[[:upper:]]');

  -- the pattern will match the second member of a "2-tuple"
  -- (T-[[:upper:]])$
  -- regexp is similar than above but now the search is anchored to the end of the string ($):
  insert_if(p_pattern => '[[:upper:]]-[[:upper:]]$');
end;
/

Test run

begin
  for i in (with data(id, old, new) as (
              select 10, 'L-D / T-E', 'L-E / T-E' from dual union all
              select 20, 'L-D / T-E', 'L-D / T-D' from dual union all
              select 30, 'L-D / T-E', 'L-E / T-D' from dual union all
              select 40, 'A-B | C-D', 'A-E | C-D' from dual union all
              select 50, 'L-D / T-E', 'L-D / T-E' from dual
            ) select * from data)
  loop
    cr1_insert(i.id, i.old, i.new);
  end loop;
end;
/

select * from cr1_t;

ID ORIG_ID OLD NEW
-- ------- --- ---
 1      10 L-D L-E
 2      20 T-E T-D
 3      30 L-D L-E
 4      30 T-E T-D
 5      40 A-B A-E