My 2 cents,

the first function seems fine, you could make it a little DRYer by just setting the compareMethod in your if statement and then have only 1 complicated line of logic. And if you are doing that, you might as well put the Cstr's there.

Public Function StringContains(haystack, needle, Optional ByVal caseSensitive As Boolean = False) As Boolean

   Dim compareMethod As Integer

    If caseSensitive Then
        compareMethod = vbBinaryCompare
    Else
        compareMethod = vbTextCompare
    End If
    'Have you thought about Null?
    StringContains = (InStr(1, CStr(haystack), CStr(needle), compareMethod) <> 0)

End Function

Notice as well that I love the idea of searching for needles in haystacks, I stole that from PHP.

For StringContainsAny, you are not using the code you wrote for StringContains, you repeat it. If you were to re-use the first function, you could do this:

Public Function StringContainsAny(haystack, ByVal caseSensitive As Boolean, ParamArray needles()) As Boolean

    Dim i As Integer

    For i = LBound(needles) To UBound(needles)
        If StringContains(CStr(haystack), CStr(needles(i)), caseSensitive) Then
          StringContainsAny = True
          Exit Function
        End If
    Next

    StringContainsAny = False 'Not really necessary, default is False..

End Function

For the last one I wanted to you consider passing values that you will convert as ByVal, since you are going to make a copy anyway of that variable.

Public Function StringMatchesAny(ByVal string_source, ParamArray potential_matches()) As Boolean

  string_source = CStr(string_source)

  ... 'That code taught me a new trick ;)

End Function


LINQ transforming hierachical data to flat list

You need to look through your code with an analytical eye and discover the pattern that you are implementing. I call it default if (null or) empty.

So I created an extension method to implement that pattern.

public static string DefaultIfEmpty(this string source, string defaultValue)
{
    return string.IsNullOrEmpty(source) ? defaultValue : source;
}

(Note of caution: you may want to choose a different name for it since this method already exists in LINQ; technically, this is an overload, which could create problems if a future version of C# adds this signature.)

This makes it possible to adapt the LINQ expression:

var currentHead = string.Empty;
var currentValue = string.Empty;
var result = lines.Select(
    line =>
    {
        currentHead = line.Head.DefaultIfEmpty(currentHead);
        currentValue = line.Value.DefaultIfEmpty(currentValue);
        return new { Head = currentHead, Value = currentValue };
    }).ToList();

Sweet, isn't it?


Changing cuts to sed for parsing dates from apache log (common log file)

Your suspicions are correct.  The amount of work that the operating system does for you to spawn a process is formidable — much more work than the string processing work itself.

For every line in the log file, you are spawning 13 processes:

cut
tr
cut
tr
xargs
date
bash — due to the use of $( ) substitution
cut
tr
cut
tr
xargs
date

Therefore, the problem can be simplified to that of extracting, reformatting, and comparing dates repeatedly using the fewest subprocesses possible.  I would even advise against any use of the date command within the loop.  The whole thing can be done with just string processing, using sed and awk.

# Log is in common log format
# host ident authuser date request status bytes
# 127.0.0.1 user-identifier frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326

first_date=$(date --date='1 fortnight ago' +%Y-%m-%d)
last_date=$(date --date='1 day ago' +%Y-%m-%d)

# Processing the log file in reverse chronological order,
# extract the date as YYYY-MM-DD, if it is between
# $first_date and $last_date, inclusive.
#
# Then, present the hit counts in chronological order.
tac /etc/httpd/logs/access_log | \
    sed -e 's!.*\[\(../.../....\):.*!\1!' | \
    gawk -F/ -v first_date="$first_date" -v last_date="$last_date" '
        BEGIN {
            M["Jan"] = "01"; M["Feb"] = "02"; M["Mar"] = "03"; M["Apr"] = "04";
            M["May"] = "05"; M["Jun"] = "06"; M["Jul"] = "07"; M["Aug"] = "08";
            M["Sep"] = "09"; M["Oct"] = "10"; M["Nov"] = "11"; M["Dec"] = "12";
        }
        {
            DATE=sprintf("%s-%s-%s", $3, M[$2], $1);
            if (DATE < first_date) { exit }
            if (DATE <= last_date) { print DATE }
        }
    ' | \
    uniq -c | \
    tac

Some additional remarks:

I am puzzled by the fact that $enddate was defined with a granularity of one second.  I would have expected that you would want to use midnight as the limit, not whatever time of day you happen to run the script at.
I am also puzzled by the use of head -n -1 and head -n 2 to discard some of the results.  Why not just set the first and last date correctly in the first place?
Since the output from the loop is already in reverse chronological order, sort merely reverses everything.  tac would accomplish the same thing more easily.

I would also suggest that you not bother processing the log file in reverse.  Reading a file line-by-line backwards is trickier, as reading is not done sequentially, byte by byte.  Furthermore, the need to reverse the results requires buffering all of the output, preventing the script from printing results incrementally a day at a time.  Reverse chronological processing only makes sense if the log file is enormous and covers a period much much longer than the fortnight of interest.  However, if your log file is really that large, you really ought to consider a log-rolling mechanism.  If each log file only spans one day, the entire problem becomes a trivial line count exercise!


How can a code that takes dict as input and validates it based on multiple conditions be further optimized?

Keyerror
Did you test this code with some invalid input?
The code will fail with a keyError if the items key does not exist, since your code just assumes it exists.
You could do a try-except with the json_to_test['items'] so that you can handle the keyError.
Unspecificness
if any(isinstance(i, list) for i in json_input)

You're testing that json_input contains at least one element that is a list, but that could be something elese than json_to_test['items'] which you clearly said has to be a list. Why aren't you testing that particular object?
Nested code
Your code is triple-nested which makes it hard to read and to maintain.
It is better if you check each error condition separately without nesting and return only if they all pass. That also makes it much easier to add or remove another validation check without re-indenting the whole code and figuring out where it goes.
Something like this:
if fail_condition_1:
    abort("error_message_1")

if fail_condition_2:
    abort("error_message_2")

if fail_condition_3:
    abort("error_message_3")

print('Data ready to be saved to DB')
return json_input
```


What should I do to reduce run time of my code?

set in the first solution, and while i in range(n) in the second one are very expensive.

That said, thou shalt not bruteforce.

The crazy guy moves right as long as he visits the odd-populated farms, leaving a trail of even-populated farms behind. As soon as he hits the even-populated farm, he switches direction, and since now on he faces only the even-populated farms, he goes all the way to the Star 1, and the track stops there.

So, find the leftmost even-populated farm. If there is none, the guy would visit all farms, stealing one ship per farm. If there is, its index is the number of farms visited; on the way there, one ship per farm will be stolen, and on the way back another ship per farm will be stolen (except if initially there was just one ship).

This should be enough to keep you going.

As a side note, break in

    if x[i] == 0:
        if i >= farm_visited: farm_visited = i+1
        break

is a bug. An empty farm should not stop him:

  he steals only one sheep (if there is any) from that farm and moves on


Basic myVector class raw vs smart pointer

In the following, I tried to collect the options you have for your custom vector class, and summarize their pros and cons. But before that I'd suggest to use generic programming when you write your vector class, i.e.

template<typename T>
class myVector
{
     size_t sz;
     T* array;

     //all the rest
};

Note two things here: Instead of the int *, I've wrote T*, where T is the type you specify in the program via myVector<int>, say. This you can hold elements of arbitrary type and you do not need to copy the whole class once you need a double type.

Further, I've used the type size_t for the size of the vector, which is the type often used in C++ to denote sizes of objects (in fact, it's just a large unsigned int type).

Choosing the right storage type:

First, and most naturally, you can use an STL container inside, preferably std::vector: this is one example of the RAII way to do it, which basically means that you usually don't have to care for the memory management by yourself. Although from the first it sounds a bit redundant to include a std::vector in your custom vector class, it actually can be rather useful, for instance when you want to add arithmetics to your vector.

template<typename T>
class myVector
{
     std::vector<T> array;
};

This has several advantages: visibly, you don't need a variable sz anymore, as the std::vector already manages the size. Next -- and this is an important thing -- as your array becomes correctly copied, moved, assigned and destructed, your class will perform these operations correctly as well.

In the following, let us consider the copy operation as an example: in the above approach, when one copies the class, the new class contains a copy of the original std::vector.
Using a raw pointer as in your OP. This is nowadays a discouraged way to do it, just because you have to manually care for the memory management. Once you invoke array = new int[sz], array is a pointer to some allocated memory on the heap, i.e. it's so to say something outside of the class, and the class itself must take care that this memory is correctly released for further usage when it is destructed. Thus you need to write a destructor, and therefore -- according to the rule of three(five) -- also copy constructors, assignment operators (, move constructors).

Consider again the copy process. The copied myVector just copies the raw pointer, such that now two pointers point to the same memory region. However, these two pointers don't know about each other. So, it becomes a hard task to prevent one of the classes to delete the memory when it goes out of scope, as then the other class will become a dangling pointer: it points to a destructed and thus invalid object. In order to avoid this, you'd need to count how many pointers point to a given object, and call the delete only if the last pointer goes out of scope (i.e. when nobody needs the object anymore).
Shared pointers exactly do this: they count how many pointers point to a given object which has been allocated on the heap.

template<typename T>
class myVector
{
     std::shared_ptr<T> array;
     // construct via array= std::make_shared( new T[sz], std::default_delete<T[]>() );
     // this is necessary so that "delete[]" is called, an not "delete".

     //or better
     std::shared_ptr<std::vector<T> > array;
};

By using them, you get almost the same behaviour as by using a raw pointer but have a lot of advantages. Most importantly, you again are on the RAII track, you don't need to care for all the default functions and let the compiler generate them. A disadvantage is that a shared_ptr is usually less performant than a raw pointer, but this is often taken into account in favor of a correct code.

Regarding the example, copying works fine: the newly copied class only contains the pointer to the object and not the object itself, which is an advantage when the arrays are large and do not need to be changed in the copy. In the copy process, the shared_ptr increases its so-called reference count, such that it knows when exactly to call delete.
Finally, there is another smart pointer, namely std::unique_ptr. It addresses the above problem in a completely different way: it simply doesn't allow copying, so that there is always one pointer which does the memory management. It's also said that the unique_ptr owns the object. Other, non-owning pointers are allowed, but these should never do any memory-related operations (--never call delete).

It is possible to use it here and it could also be reasonable, but be aware that your class won't possess automatically generated copy and assignment operators. This is probably not intended.

Summary: as written above, I'd use the std::vector<T> alternative, and depart from it only for a good reason. Only then, I'd use the shared_ptr alternative. I would never use the raw pointer array.


Hex colors can be in 3 digits or 6 digits. In the case where you want 3 digits, you can't do it because 6 is hardcoded. You may want to move it into a variable with a default value of 6.

Strings characters in JS are accessible via indices the same way as an array. So splitting the characters into an array is unnecessary, not to mention the additional memory consumed by creating an array.

Adding | 0 after a number truncates the decimal places from the number. Internally, it converts the internal representation of the number from a float into an integer, dropping the decimal information. So basically, it does the same thing as Math.floor, albeit in a more vague but shorter way.

You could also use reverse looping, and using the length as the condition. When length is zero, it's essentially falsy, thus stopping the loop.

function getRandomColor() {
  var length = 6;
  var chars = '0123456789ABCDEF';
  var hex = '#';
  while(length--) hex += chars[(Math.random() * 16) | 0];
  return hex;
}

document.write(getRandomColor());


Insert Selected item in listbox using Ado.net and stor proc

If you are using the Enterprise Library it is often better to set up a default connection in the configuration file:

<configuration>
  <configSections>
    <section name="dataConfiguration"
       type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings,
            Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0,
            Culture=neutral, PublicKeyToken=null"
        requirePermission="false"/>
  </configSections>

  <dataConfiguration defaultDatabase="SiteSqlServer" />

  <!-- Rest of your settings here, including your SiteSqlServer connection string -->
</configuration>

Now you don't need to look up the connection string - you can rely on the Enterprise library to get it for you:

public static void Insert(IEnumerble<int> skills, int resourceId)
{
    // No dependency on SQL anymore - the connection string is found
    // from the dataConfiguration section in your config file. If you change
    // to another (supported) provider, you don't need to change this code.
    Database db = DatabaseFactory.CreateDatabase();

    // Add in your schema to the stored proc name (I've assumed dbo).
    using (var cmd = db.GetStoredProcCommand("dbo.Insert_Skills_Resources"))
    {
        // This method populates the parameters collection of the DbCommand
        // by interrogating the database about the command.
        db.DiscoverParameters(cmd);

        // As the parameters are now known, we can just set the value of
        // them directly, no need specify direction or type etc.
        cmd.Parameters["ResourceID"].Value = resourceId;

        foreach (var skill in skills)
        {
            cmd.Parameters["SkillID"].Value = skill;
            db.ExecuteNonQuery(cmd);
                    // Don't need to clear the parameters now.
        }
        // <Pointless try catch removed.>
    }
}

EDIT:

Sorry, it's been a year or more since I used the Enterprise Library I can't remember whether you need the @ at the start of the parameter name or not - it might be cmd.Parameters["@SkillID"].

EDIT 2:

I remembered why I couldn't remember if you need the @ or not (if that makes sense). You do need the @ BUT, you should use the Database.BuildParameterName method to create the parameter in the format the current provider expects - for sql server this is an @ symbol before the parameter name.

This is how you should do it:

cmd.Parameters[db.BuildParameterName("ResourceID")].Value = resourceId;

With this final correction the code is actually ignorant of the provider!


Yes,

you could for starters derive the child position once with

var index =  $('div.nav ul li').index( this )

Then you could adapt to index 0 and 1 in 1 if statement
Finally, you could just derive the index and have the animate statement only once.

Something like this in the end might do:

$('div.nav ul li').on('click', function() {

    var index = $('div.nav ul li').index( this ), top;

    if( index < 2 ){
      top = '0';
    }
    if( index == 2 ){
      top = $('div.features').offset().top + 'px';
    }
    if( index == 3 ){
      top = $(document).height() + 'px';
    }
   if(top){
        $("html, body").animate({
            scrollTop: "0"
        }, 'slow');
   }
});


Finding all pairs of elements in an array that sum to a target value using multiple pointers (follow up)

using namespace std;
There are lot of good answers why you shouldn't use it. See here

Use std::pair<int, int>
Since your result struct is just acting as a container for two ints, consider using std::pair<int, int>

Don't hardcode values
Why do you want hardcode 16 as the array length? You can just pass it to the function as a parameter, or use std::array. Your code should be able to handle any number of elements.

while(p1 <= p2)
This is incorrect. This will allow the algorithm to run for single length arrays as well. For example, consider the array {7} and target value 14. Your code returns {7,7} as an answer. In fact, the rogue [10, 9] in your output is a direct result of this.

Comparison of signed and unsigned ints
If you turn on warnings -Wall -pedantic, you will see your compiler warn you about comparing signed and unsigned ints. For example, comparing k which is a signed int to res.size() - 1 which is an unsigned int.
In fact, you're quite lucky that the first time you encounter a valid pair, it's inserted into the result vector. res.size() - 1 wraps around to whatever the maximum value of vector<result>::size_type is (in my case, 18446744073709551615) which means k < res.size() - 1 is valid.
In fact, you don't even need this entire loop (see below).
Use curly braces consistently
Your use of curly braces is very inconsistent. As a general use, always use curly braces for your conditional statements. It looks cleaner and can help avoid subtle bugs.

Since you're using arr[p1] + arr[p2] quite a bit, better to use a variable to store the value.

if(res.size() == 0) is irrelevant because it's always gonna be false (ignoring that one case at the very beginning because it's poor code, not an edge case to be handled).

I'm still not quite sure what the flag variable is mean to do. All your inner loop is doing is looking at the second to last element in the res vector and comparing values. flag will never be true unless the second to last element in the res vector has elements matching arr[p1] and arr[p2].

You have needlessly complicated your algorithm (the inner loop inside of the else if block, for example).
In pseudocode, this algorithm can be written as:
while(p1 < p2)
      sum = array[p1] + array[p2]
      if sum == target
           insert into res vector
           p1++
           p2--
     else if sum < target
           p1++
    else
           p2--

You could use res.emplace_back(arr[p1], arr[p2]); instead of res.push_back(result(arr[p1], arr[p2]));. The former constructs the struct in-place, while the latter might invoke the move constructor.


Get a collection of child positions for a given parent position

If Position and Position() in your code is the same and you supposed to call GetChildPos instead of GetChildRows in the inner loop then your code can be significantly simplified:

var someVariable = GetChildPos(posId).ToList();

public IEnumerable<Position> GetChildPos(int posId)
{
    yield return serviceRepo.Position.GetById(posId);

    foreach (var pos in serviceRepo.Position().GetAll()
                                              .Where(x => x.ParentPosId == posId)
                                              .SelectMany(x => GetChildPos(x.Id)))
    {
        yield return pos;
    }
}

Also it can improve performance because in your original code you do this instructions

serviceRepo.Position().GetAll().Where(x => x.ParentPosId == posId)

two times that can cause slowing down if some method in this chain is not lazy and executes heavy code even for Any().


Generating row and column of a given nonogram-like table

Size of the grid

    raise Exception("You need exactly four line breaks and 25 characters!") #throw exception if conditions don't match

Using a generic Exception is bad practice. What should the calling code look like if it want to handle such failure? Something like

with open('da_file.txt') as picture:
    pic = picture.read()
try:
    descr = nono_descriptor(pic)
except Exception:
    print('Not the right size')
else:
    print(descr)

probably. Meaning that if anything goes wrong, it would be treated as if the input was not as expected.

You should at least use a more specific kind of exception (such as ValueError) or roll your own:

class BadGridSizeError(Exception):
    pass

def nono_descriptor(...):
    ...
    raise BadGridSizeException("...")

But why limit at 5×5 grids in the first place, why not let the user provide a grid with the size they like? It is easy to check that the grid is square and keep the size for further operations instead of hardcoding the value 5:

def nono_descriptor(given_string):
    list_of_lines = given_string.splitlines()
    grid_size = len(list_of_lines)

    assert all(len(row) == grid_size for row in list_of_lines), "Square grid expected"

    rows_split = [] #list that contains each line split
    columns_list = [] #list that contains columns
    rows_list = [] #list that contains rows

    for each_line in list_of_lines:
        rows_split.append(list(each_line)) #populate rows list with split up characters
        columns_list.append(each_line.count('*')) #populate columns list with the number of asterisks in each column

    for i in range(grid_size):
        temp_list = [row[i] for row in rows_split]
        rows_list.append(temp_list.count('*'))

    print (columns_list, rows_list)

Using an assert here is also more friendly to the user that can deactivate such checks (using the -O or -OO switch on the command line) when they know that their input is good.

You don't even need to restrict the grid to being square, you can have m×n grids if you check that each row is the length of the first one:

def nono_descriptor(given_string):
    list_of_lines = given_string.splitlines()

    assert list_of_lines, "At least one row expected"

    grid_size = len(list_of_lines[0])

    assert all(len(row) == grid_size for row in list_of_lines), "Rectangular grid expected"

    rows_split = [] #list that contains each line split
    columns_list = [] #list that contains columns
    rows_list = [] #list that contains rows

    for each_line in list_of_lines:
        rows_split.append(list(each_line)) #populate rows list with split up characters
        columns_list.append(each_line.count('*')) #populate columns list with the number of asterisks in each column

    for i in range(grid_size):
        temp_list = [row[i] for row in rows_split]
        rows_list.append(temp_list.count('*'))

    print (columns_list, rows_list)

Counting by rows and columns

You can easily get the count of '*' using a list-comprehension rather than using append():

columns = [row.count('*') for row in list_of_lines]

You can argue that it's better to build row_split in the meantime while iterating over list_of_lines… But you don't need that list. The only thing you use it for is to be able to index the ith column in each row. But you can do that exactly the same way using plain strings because list(my_str)[i] is exactly the same as my_str[i]. Meaning you can write:

columns = [row.count('*') for row in list_of_lines]

rows = []
for i in range(grid_size):
    tmp = [row[i] for row in list_of_lines]
    rows.append(tmp.count('*'))

However there are two improvements possible. The first one being using a list-comprehension:

rows = [[row[i] for row in list_for_lines].count('*') for i in range(grid_size)]

The second one being to use zip instead of trying to manually do its exact job:

rows = [colum.count('*') for column in zip(*list_of_lines)]

One more advantage using zip is that it will stop producing columns when the shortest row has been exhausted. Meaning you don't even need to check that the grid is rectangular anymore:

def nono_descriptor(given_string):
    lines = given_string.splitlines()

    columns = [row.count('*') for row in lines]
    rows = [column.count('*') for column in zip(*lines)]

    print(columns, rows)

print vs return

Printing a result within a function that perform some computations is bad practice. Your function can't be reused in a different context. What if I wanted to iterate over some files and use your function to append the various counts at the end of said file. Well I can't, because you print the result, so I can't do anything with it:

def nono_descriptor(given_string):
    lines = given_string.splitlines()

    columns = [row.count('*') for row in lines]
    rows = [column.count('*') for column in zip(*lines)]

    return columns, rows

Your use case should now be

print(nono_descriptor('0*0*0\n***00\n****0\n*0*0*\n****0'))

which might seem more work here, but it lets you reuse you function way more easily.


Stack implementation with singly linked list

You have a typo/mistake in if not self._head and not self._head, I think you wanted to write self._tail in one of them.
I do not see the interest of making Node() inner to LinkedList(). In opposite, doing so condemns you not to reuse the Node() code and slaughters your code scalability (in case you will need to add functionality to your code by implementing a queue, for example)
You can refactor this code into one function and call it when necessary:

if not self._head and not self._head:
    self._head = self._tail = node
    return

While it apparently does the job, the return statement of your code in (3) is not in the right place. You should remove it and use the if ... else statements instead because this makes sense and that is what the reader of your code may expect.
Here, we can use more common sense: if not self._head and not self._tail: honestly, if the head is None, it must be obvious the tail is in the same condition. I mean you can replace similar lines to simply: if not self._head
You said you want to code a stack: by definition, in a stack, we need only a pointer to its head. The head is the tail, and the tail is the head because that is where operations occur.
Do not code what you do not need: it is unnecessary to use add_last() and remove_last(). Why? Because you are coding a stack, and a stack follows the principle of LIFO, so do not care  about the other end at all. In a stack, we need to perform the push and pop operations; at best, we would like to know its size, everything else does not belong to the stack notion.
The points (6) and (7) are a gentle introduction to what I will tell you here: you misunderstood the stack implementation: we can implement a stack using an array or a simple linked list. You chose the later one but you misunderstood it because you lost yourself in  implementing a linked list and you ended up by missing the notion of the stack.

If you carefully read this section, for example, you will understand that stack implementation using linked lists does not require you to implement a linked list and its different operations but simply having a data structure which looks like a node that belongs to a linked list, and by designing the pop and push operations, your stack will look, by default, as a singly linked a list. So based on your code, let me share with you the right way to implement a stack based on linked lists:

class EmptyStack(Exception):
    def __init__(self):
        super().__init__('Stack is empty: invalid operation!')

class Node:

    def __init__(self):
        self.data = None
        self.next = None

class Stack:

    def __init__(self):
        self.head = None
        self.size = 0

    def get_size(self):
        return self.size

    def push(self, item):
        self.node = Node()
        self.node.data = item
        self.node.next = self.head
        self.head = self.node
        self.size += 1

    def pop(self):
        if self.head == None:
            raise EmptyStack
        self.head_item = self.head.data
        self.head = self.head.next
        self.size -= 1
        return self.head_item

if __name__ == '__main__':
    stack = Stack()
    for i in range(10):
        stack.push(i)
    print('size: {}'.format(stack.get_size()))
    print(stack.pop())
    print(stack.get_size())


Add spaces around variable with $ symbol bookends

Here's a version using Regular Expressions.

Option Explicit

Sub SpaceVarsAndEqns()

    Dim DocumentRange As Range, ParagraphRange As Range
    Dim i As Long, P As Paragraph
    Dim Pattern As String, Replace As String, RegEx As New RegExp
    Dim ParagraphText As String

    Pattern = "(?:\s?)\$[^$(]*\$(?:\s?)"
    Replace = " $& "

    With RegEx
        .Global = True
        .MultiLine = True
        .IgnoreCase = True
        .Pattern = Pattern
    End With

    Set DocumentRange = ActiveDocument.Range
    For i = 1 To DocumentRange.Paragraphs.Count
        Set P = DocumentRange.Paragraphs(i)
        ParagraphText = P.Range.Text
        If RegEx.Test(ParagraphText) Then
            P.Range.Text = RegEx.Replace(ParagraphText, Replace)
        End If

    Next

End Sub

Before:

\begin{bmatrix} $eval(($d$*$d.pmv$)/(|$d.et$|)*($d.et$*$xm$) + (($b$*-1)*$d.pmv$)/(|$d.et$|)*($d.et$*$ym$) + $dist5$,0.###)\\ $eval((((($a$*$d$)-$d.et$)/($b$))*$d.pmv$*-1)/(|$d.et$|)*($d.et$*$xm$) + ($a$*$d.pmv$)/(|$d.et$|)*($d.et$*$ym$)+ $dist6$,0.###) \end{bmatrix}

After:

\begin{bmatrix} $eval(( $d$ * $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $xm$ ) + (( $b$ *-1)* $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $ym$ ) +  $dist5$ ,0.###)\\ $eval((((( $a$ * $d$ )- $d.et$ )/( $b$ ))* $d.pmv$ *-1)/(| $d.et$ |)*( $d.et$ * $xm$ ) + ( $a$ * $d.pmv$ )/(| $d.et$ |)*( $d.et$ * $ym$ )+  $dist6$ ,0.###) \end{bmatrix}

This requires adding a reference to the Microsoft VBScript Regular Expressions 5.5 by going to Tools > References and checking that box:

You can read more on Regular Expressions in VBA in this Stack Overflow answer.


You can pass a function that gets the correct object from tagdb.
AKA Service Locator pattern

typedef HashTable* (*ITEM_GETTER)(tagdb*);

HashTable* getTag(tagdb *db)  { return db->reverse;}
HashTable* getFile(tagdb *db) { return db->forward;}

GHashTable *tagdb_get_item_files (tagdb *db, int itemId, ITEM_GETTER getter)
{
    return g_hash_table_lookup(getter(db), GINT_TO_POINTER(itemId));
}

void tagdb_remove_item (tagdb *db, int id, ITEM_GETTER getter)
{
    GHashTable *its_files = g_hash_table_lookup(getter(db), GINT_TO_POINTER(id));
    if (its_files == NULL)
    {
        return;
    }

    GHashTableIter it;
    gpointer key, value;
    g_hash_table_iter_init(&it, its_files);
    if (g_hash_table_iter_next(&it, &key, &value))
    {
        tagdb_remove_tag_from_file(db, id, key);
    }
    g_hash_table_remove(getter(db), GINT_TO_POINTER(id));
}

Edit for clarity:

The old functions can now be implanted like this:

GHashTable *tagdb_get_tag_files (tagdb *db, int tag_code)
{
    return tagdb_get_item_files(db, tag_code, getTag);
}

GHashTable *tagdb_get_file_tags (tagdb *db, int file_id)
{
    return return tagdb_get_item_files(db, file_id, getFile);
}

void tagdb_remove_tag (tagdb *db, int id)
{
    tagdb_remove_item(db, id, getTag);
}

void tagdb_remove_file(tagdb *db, int id)
{
    tagdb_remove_item(db, id, getFile);
}


Implementing an algorithm that walks the DOM without recursion

I know you are doing this as an exercise, and personally I like the recursive function. But just as an alternative, there is also the much forgotten TreeWalker API.

  Browser compatibility

  Supported by IE9+, FF2+, Chrome 1+, Safari 3+, Opera 9+

Javascript

var treeWalker = document.createTreeWalker(document.getElementById("list"), NodeFilter.SHOW_ALL, {
    acceptNode: function (node) {
        return NodeFilter.FILTER_ACCEPT;
    }
}, false);

do {
    console.log(treeWalker.currentNode);
} while (treeWalker.nextNode());

On jsfiddle


I think it would be instructive to compare my rank amateur code to the code that an experienced software developer would produce to accomplish the same result.

To me, the most obvious differences between experienced and novice programmers are:

consideration of edge cases
organization of data in a manner that lets the data drive the program's flow
broadness of their working definition of the word data

In that light, here are things I'd do differently from what you have done.

Make the most of the data you've got

You're silently truncating the user's input with int().  This is bad!  Mangling user data is necessary sometimes and to be avoided otherwise.  Especially here, where the change will affect the output in surprising and subtle ways.

You're displaying results with maximum "precision" but basing them on a value of pi that has only four significant figures.  This is misleading.  Define pi with more digits, and shorten the result so that it shows the actual precision.

Separate content from presentation

A common pattern arises when you create something that's useful to someone (yourself, usually), later it becomes useful to other people, and those people need the output in a different format.  Not only do you have to change the code, but it's been months since you looked at it! You won't remember how everything works.  Make it easy to affect how output is displayed.  Do this by keeping results in a structure that preserves the semantics of the data, and defer formatting to the very end.

Think about the task of using your code to make a web page: it's going to be hairy because your math functions have print statements in them.  It's better if those functions return numbers to be printed later by formatter function.

Separate program logic from UI elements

This is the same point as the previous one, just applied to input instead of output.  Use data structures that group input characteristics together, keeping display values independant from logic-affecting values.

As written, the button labels dictate the program flow (if var.get() == "Circle Circumference": etc.).  If you translate your program to another language, it won't work anymore.

Functions can be data

Each kind of user-selected computation has a formula to go with it.  It is natural to group those formulae alongside the other traits of the calculation.

Example

Here is one approach to your problem.  Observe how the actual code has almost nothing to do with what you're calculating, or how, or what the output will look like.  Instead, the data structure dictates how many variables to ask for, how to transform them into an answer, and how to format the answer for display.

From here, you could generalize this in all kinds of ways with few changes to the code.  For example, float(input(prompt)) is "hardcoded" in the logic.  This could be another lambda in the data, perhaps attached to each prompt, so that you can configure it to ask for integers or strings instead of just floats.

PI = 3.141592653589793
calculations = [
    dict(
        label="Circle Circumference",
        prompt=[
            "Enter the radius of the circle in the units of your choice: "
        ],
        result_format="\nThe volume of the sphere is: {0:.4f} units.",
        formula=lambda r: r*2*PI
    ),
    dict(
        label="Sphere Volume",
        prompt=[
            "Enter the radius of the sphere in the units of your choice: "
        ],
        result_format="\nThe volume of the sphere is: {0:.4f} units.",
        formula=lambda r: r**3 * 4/3 * PI
    ),
    dict(
        label="Cone Volume",
        prompt=[
            "Enter the radius of the cone in the units of your choice: ",
            "Enter the height of the cone in those same units: "
        ],
        result_format="\nThe volume of the cone is: {0:.4f} units.",
        formula=lambda r,h: r**2 * h * PI / 3
    ),
    # ... etc.
]

# selected_menu = var.get()
selected_menu="Cone Volume"  # hardcoded for demonstration purposes

action = next( filter(lambda x: x['label'] == selected_menu, calculations) )

inputs = list( map( lambda prompt: float(input(prompt)), action['prompt'] ))

answer = action['formula'](*inputs)

result_text = action['result_format'].format(answer)

print(result_text)


Gaining better performance when screen scraping is required

It's hard to tell exactly how it's being utilized since your code sample is an example.  However, a few notes.

Due to the design of your use case above most of the time any improvements are going to pale in comparison to pulling a web page live (especially multiple).  If you want real improvement, cache the information from the other websites.

Regarding the Code sample above, the only item I would recommend looking into is the parallel.foreach statement.  If you utilize it, make sure you've already pulled all the data from the database to loop through (not waiting on EF lazy loading).  Otherwise you will run into some EF threading issues.

I would also recommend creating static delegate methods for each website provider and when your application loads put the methods into a concurrent dictionary.  It will help to clean up you code to make it more readable.


Drawing a regression line with a timeseries

You don't need dfc, dfc.sort_index() and dfc.sort_values(time_col_str) both make a copy of the data. They don't perform an in-place sort.
del dfc isn't needed, Python will perform that action at the end of the function anyway. Also I don't think it's doing what you think it's doing. I may be wrong, but since variables in Python are like names, when you're using del, you're just removing one name tag to the object.

  Deletion of a name removes the binding of that name from the local or global namespace, depending on whether the name occurs in a global statement in the same code block.

In my personal opinion, Python doesn't lend itself well to functional programming. Yes you can do FP in it, but it tends to start looking very ugly very fast. Don't care about whether something is FP or not, just make it work.
I don't really know what your code is doing, but the if-else and the 'plotting' should probably be in two separate functions.


import socket # imports the socket module

The comment is completely pointless. But I cannot help it, my eyes naturally read it, my brain processes it, only to realize it says nothing new. Let your code speak for itself, avoid comments as much possible.

print '\nThis program is being run by', usr, 'on machine name', sname

Maybe it's somewhat more readable if you use standard Python formatting like this instead:

print '\nThis program is being run by %s on machine name %s' % (usr, sname)

runagain = 'y'

Instead of setting this to a string, and later using == 'y' to evaluate, it would be better to use proper booleans for this kind of thing. For example:

Similarly, instead of:

clradd = raw_input('\nWould you like to add any colors to the list? y or n\n')

while clradd == 'y':

You could write like this:

clradd = raw_input('\nWould you like to add any colors to the list? y or n\n') == 'y'

while clradd == 'y':

Try-catch block writing style:

try:
    removecolor = raw_input('\nWhat colors would you like to remove? ').title()
    templist.remove(removecolor)
except ValueError:
    print 'Looks like that color was not in the list, try again.'
    continue

It's better to keep the try block as small as possible. For example, the removecolor assignment should be moved out from it. Also, since you simply want to check if the given color is in the list of colors, it would be cleaner to write that exactly:

removecolor = raw_input('\nWhat colors would you like to remove? ').title()
if removecolor in templist:
    templist.remove(removecolor)
else:
    print 'Looks like that color was not in the list, try again.'
    continue

There are couple of other things too, globally:

Incorrectly indented code
Incorrectly using while instead of a simple if
Duplicated code blocks
sys.exit is a bit harsh way to exit, try to avoid if possible

Suggested implementation

Putting the above suggestions together:

import socket

usr = raw_input('What is your name?\n').title()
sname = socket.gethostname()
print '\nThis program is being run by %s on machine name %s' % (usr, sname)

mylist = ['Red', 'White', 'Blue', 'Yellow', 'Green', 'Orange']
templist = list(mylist)
runagain = True

while runagain:
    print '\nThe current colors are:', templist

    clradd = raw_input('\nWould you like to add any colors to the list? y or n\n') == 'y'

    if clradd:
        colors = raw_input('\nWhat colors would you like to add to the list? Please type one color. \n').title()
        templist.append(colors)

        print templist
        print '\nAscending and Descending'
        print '-' * 30
        print '\nAscending (high to low): ', sorted(templist, reverse=True)
        print '\nDescending (low to high): ', sorted(templist, reverse=False)

    clrdel = raw_input('\nWould you like to remove any colors from the list? y or n\n') == 'y'

    while clrdel:
        removecolor = raw_input('\nWhat colors would you like to remove? ').title()
        if removecolor in templist:
            templist.remove(removecolor)
        else:
            print 'Looks like that color was not in the list, try again.'
            continue

        print 'Updated list\n', templist
        break

    runagain = raw_input('\nWould you like to run this program again again? y or n\n') == 'y'


Refactoring with many duplicates using Bash

Use a function with a parameter for the variable part to eliminate duplication:

post_report() {
  local result=$1
  curl -X POST -H 'Content-type: application/json' \
      --data '{"text":"Tests '"$result"' for Platform: '"$PLATFORM"'\nEnvironment: '"$ENVIRONMENT"'"}' \
      https://hooks.slack.com/services/rr/qq/pp
}

if ! npm test
then
  echo >&2 "Testing failed"
  post_report failed
  exit 1
else
  echo "Tests passed"
  post_report passed
fi


Longest Substring without Repeating Characters Problem - Kotlin Recursion

Note, I don't think about performance, only about kotlin.
Iluminate branch
in your when, you check if the rightIndex >= string.length+1.
this means in the next branches the size is maximal string.length.
Substring is exclusive, so it allows str.length.
this means the second and third branches are identical.
Use Set
It would make more sense to me to use toSet instead of toList.distinct, because sets are meant to hold distinct versions.
personal Choices:
Single-expression function
A single-expression-function is a function with one expression .
In kotlin, you can write this in an easier way.
Instead of writing
fun lengthOfLongestSubstring(str: String): Int {
    return when {
        ...
    }
}

you can write
fun lengthOfLongestSubstring2(str: String): Int = when {
    ...
}

or even without return-type:
fun lengthOfLongestSubstring2(str: String) = when {
    ...
}

I personally like to write these like:
fun helper(
    str: String,
    leftIndex : Int,
    rightIndex : Int,
    max: Int
) = when {
    ...
}

function with receiver
If I'm right functional means:

The function knows about the type and the type doesn't know about the function
If a function receives the same input, it should return the same output

(or only the later)
The first way is often expressed by having a function that only takes parameters, but is not called on an object: b(a) instead of a.b()
Kotlin allows to let a function like b(a) look like a.b(), if you define it that way.   This is called a function with receiver.
Note, inside de function-body, you refer to the receiver using this.
isDistinct("hi")
private fun isDistinct(
    substring: String
): Boolean = substring.toSet().size == substring.length

can be rewritten to
"hi".isDistinct()
private fun String.isDistinct() : Boolean = this.toSet().size == this.length

And as you don't have to call this inside a scope:
"hi".isDistinct()
private fun String.isDistinct() : Boolean = toSet().size == length

Or just:
"hi".isDistinct()
private fun String.isDistinct() = toSet().size == length

Under the scenes it's still the same function.
Inside kotlin, you can't call it the old way anymore
New code
class Solution {
    fun lengthOfLongestSubstring(
        str: String
    ) = when {
        str.length == 1 -> 1
        str.isEmpty() -> 0
        else -> helper(str, 0, 1, 0)
    }

    private tailrec fun helper(
        str: String,
        leftIndex: Int,
        rightIndex: Int,
        max: Int
    ): Int = when {
        rightIndex >= str.length + 1 -> max
        str.substring(leftIndex, rightIndex).isDistinct() ->
            helper(str, leftIndex, rightIndex + 1, max(rightIndex - leftIndex, max))
        else -> helper(str, leftIndex + 1, leftIndex + max + 1, max)
    }

    private fun String.isDistinct() = toSet().size == length
}


It is a question of how much will the project expand beyond what is described here.  For instance, are you going to persist driver details and other data? if you are going to use a database, then you will probably want to use an Object-Relation-Mapping (ORM) framework, and they tend to expect Java Beans to work with. perhaps you will want to develop a web api that will send or receive such data in json format? json parsers/generators also prefer objects that follow Java Bean standard.

for very simple, small, one-man projects it is probably ok to skip the boilerplate code of getters/setters.  it is just that usually projects tend to grow and expand in time.

another point that can and should be addressed now is the calculator: it feels wrong to me to create instances just to do fine calculation. if we make the analogy to windows calculator, it is like openning a new window each time you want to do a new calculation.  the calculator is stateless: it takes arguments and produces a result. it does not carry any state between calculations.  So I would make the calculateFine() method static and have it accept the two arguments.

another issue is the calculation process itself.  all the attributes of a fine are closely related to each other and come in mutually exclusive sets: the result is a textual description of the enum, the amount and points are also linked to it.

I would make these values properties of the enum:

public enum FineType
{
    NONE("The user was not going above the speed limit, no actions will be taken.", 0, 0),
    WARNING("No fine issued, no points gained but a warning will be issued to the driver.", 0, 0),
    FIFTY("A fine of £50.00 will be issued to the driver. 0 points gained.", 50.00, 0),
    // and so on

    private String description;
    private int    fine;
    private int    points;

    FineType(String description, int fine, int points) {
        this.description = description;
        this.fine = fine;
        this.points = points;
    }

    public String getDescription() { return description; }
    public String getFime() { return fine; }
    public String getPoints() { return p[oints; }
}

now you can have the Fine take a type in the constructor and fill the properties by itself. this makes the calculator process clearer:

public static Fine calculateFine(int speedlimit, int carspeed) {

    int milesover = carspeed - speedlimit;

    if(milesover < 1) {
        return new Fine(FineType.NONE);
    }
    else if(milesover < 5) {
        return new Fine(FineType.WARNING);
    }
    ...


That seems a worthwhile objective.  The syntax looks a bit clunky when we have to write lambdas inline like that, but you'll probably develop a library of useful filters (like standard Ranges ones) that look much more natural.
I don't think we've got the use of forwarding references quite right - and you'll be pleased to hear that fixing that should simplify the code a bit.
What we should do is use typename Any&&.  Although that looks like an rvalue-reference, it's actually a forwarding reference because Any is a template parameter.
Any&& allows the template parameter to bind to either lvalue or rvalue, so we just need the one function:
template <typename Any>
auto operator| (Any&& obj, std::invocable<Any> auto&& func) {
    return func(std::forward<Any>(obj));
}

(Note also the auto&& for func, so it can be a mutable functor if we want).

Having written that, I'm not so convinced that I like operator|() to be modifying its argument.  I would prefer a | b to leave a alone, and have to write a |= b when I intend a to be modified in place.

Minor points:

There are headers included but not needed for the template:

#include <vector>
#include <iostream>
#include <deque>

inline is implicit for a template function.
We don't need to spell out the full return type for the "append 7" lambda in the example - -> auto& is easier.


Heavily nested anonymous classes for Swing UIs

Anonymous constructors are very confusing for many people. They don't correspond well to people's expectations, and are not common knowledge.

I would recommend against them on principle.

Having said that, I can see how you think this has helped reduce your code boilerplate, but, you need to be consistent about it then. Currently your class is defined as:

public class TestFrame extends JFrame {
    public TestFrame() {
        super("A Frame");
        add(new JPanel() {
            {

when really, that should be:

public class TestFrame extends JFrame {
    {
        setName("A Frame");
        add(new JPanel() {
            {

If you are going to be unconventional, then you at least need to be consistently unconventional.

timesClicked should probably be an AtomicInteger so you can deal with some concurrency in the clicked event - or, rather, so you can read it from a different thread later. Lambdas with side-effects should be avoided.

Having said all of that, you really should use a style that is more conventional just so others can read your code better. The indentation levels on their own are a distraction with the addition of the anonymous blocks.

Oh, there's one other item that needs to be said, with all the anonymous classes there, your stack traces for any exceptions are going to be much harder to read without the code in hand too. You lose all the benefits of named classes. This will hamper your debug time.


Read from csv file, transform to dictionnary

I have found a great piece of code to decode/encode on the fly:
https://stackoverflow.com/a/9177937/2659902

So, I wrote this class, based on that:

class CSVRecoder(object):
    def __init__(self, filename, decoder, encoder='utf-8', eol='\r\n',
                 dialect='excel', **fmtparams):
        """
            filename: to open the file object
            decoder, encoder, eol: to instanciate the recoder object
            dialect, **fmtparams: are passed to the csv.reader function
        """
        self.filename = filename
        self.decoder = decoder
        self.encoder = encoder
        self.eol = eol
        self.dialect = dialect
        self.fmtparams = fmtparams

    def __enter__(self):
        self.f = open(self.filename, 'rb')
        sr = Recoder(self.f, self.decoder, self.encoder, self.eol)
        return csv.reader(sr, self.dialect, **self.fmtparams)

    def __exit__(self, type, value, traceback):
        self.f.close()

def reader(*args, **kwargs):
    with CSVRecoder(*args, **kwargs) as csv_recoder:
        for row in csv_recoder:
            yield row

Now, I can do things like:

def get_data(fname, cols, encoding):
    def foo(row):
        data = {}
        get = data.get
        for i in xrange(len(cols)):
            key = cols[i]
            data[key] = get(key, '') + row[i].strip()
        yield data
    res = list(map(foo, csv_recoder.reader(fname, encoding)))

Perhaps I can optimise the dictionnary construction a bit more, but I doubt it would make a big difference (performance wise). Thanks anyway. Feel free to comment if you think I missed something somewhere, I'm always happy to learn ! :)


you can simplify this block a little:

for (let row of board) {
    for (let char of row) {
         map[counter] = char;
         counter++;
    }
}

into:

const map = board.flat();

You can generate matches pseudo-automatically which simultaneously improve readability

function generateMatches() {
     function simpleRange(upTo) {
          return new Array(upTo).fill(true).map((_, index) => index);
     }

     function customRange(start, step, length) {
          return simpleRange(length).map(index => start + index * step);
     }

     function horizontalRow(top) {
          return customRange(3 * top, 1, 3);
     }

     function verticalRow(left) {
          return customRange(left, 3, 3);
     }

     function progressingDiagonal() {
          return customRange(0, 4, 3);
     }

     function regressingDiagonal() {
          return customRange(2, 2, 3);
     }

     const matches = [];
     for (let top = 0; top < 3; ++top) {
          matches.push(horizontalRow(top));
     }
     for (let left = 0; left < 3; ++left) {
          matches.push(verticalRow(left));
     }
     matches.push(progressingDiagonal());
     matches.push(regressingDiagonal());
     return matches;
}

  Warning! I assumed starting at 0 index

Don't use console.log(...); in solve function. Try to return list of matches instead and use user interface API outside of it. It will allow you to write some automatic (for instance unit) tests for your code (using Motcha, Jasmine, etc... depending on your target technology)
General advices:

Use better names for variables: map -> flatBoard, arr -> row, arr2 -> reducedRow
Split your code into smaller functions for each step, for instance:

const arr2 = [...new Set(arr)].join("");

into:

function reduceRow(array) {
     return [...new Set(array)].join("");
}
const reducedRow = reduceRow(row);

Your original question is about performance. Let just start it now:

IMHO you don't need to convert Set into array into string to test its size. Use something like this instead:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/size

function rowDiversity(array) {
     return new Set(array).size;
}
const rowDiversity = rowDiversity(row);

Not sure if destructuring operator is needed at all at previous line too (most likely its performance impact is already neutral) But I would write this instead anyway:

function fetchRow(flattenBoard, match) {
     return match.map(index => flattenBoard[index]);
}
const row = fetchRow(flattenBoard, match);


Public Sub Main()
    Dim input = Console.ReadLine().Split(" ")
    'The variable name should describe what it is more specifically, "people" could mean
    '   a List(Of Person), or be a Boolean For If there are people, etc.
    'You don't need to explicitly state the data type.  I don't, it's a matter of
    '   personal (or company) style, i.e. no consensus either way.
    'Take note that you are setting the largest possible number of people or topics here
    '   to be <= Int32.MaxValue (2,147,483,647) by casting use CInt().  This is fine
    '   because your spec says it will be <= 500.  You could also use Int16
    '   (max of 32,767).  My point is that you should be somewhat aware of the sizes of
    '   data types you are using.
    Dim peopleCount = CInt(input(0))
    Dim topicsCount = CInt(input(1))

    'Arrays are great for low level or highly structured data, but this is neither.
    '   Lists provide many benefits over an array which we'll get to in a second.
    'The data is being input to you in a text representation of 0's and 1's, but the
    '   actual concept they represent is are they nowledgeable or not which is a Boolean.
    Dim peopleKnowledge As New List(Of List(Of Boolean))
    Dim maxScore As Integer = 0
    Dim teamsWithMaxScoreCount As Integer = 0

    For i = 0 To peopleCount - 1
        peopleKnowledge.Add(New List(Of Boolean))

        Dim CharArray = Console.ReadLine().ToCharArray()
        For Each ch In CharArray
            'Nowhere in your code was any validation that the only text input on the lines
            '   was 0, 1, Or CrLf (return) which is fine if you are the only person who
            '   will ever use it, but other users won't always remember rules like that.
            Dim IsKnowledgeable = If(ch = "1", True, False)
            peopleKnowledge(i).Add(IsKnowledgeable)
        Next

        'No need for the "i" in "Next i"
    Next

    'Lists allow us to use For Each which helps the developer not have to worry about
    '   getting the numbers in the loops right.
    'By starting i at 0 and j at 2, I assume you were trying (correctly) to prevent getting
    '   team scores for a team of the same person twice.  The way you had it set up though
    '   only prevented the very first person being added to itself.  Every other person did
    '   have a team score calculated for double their score.
    For Each PersonA In peopleKnowledge
        For Each PersonB In peopleKnowledge
            'This line prevents the getting a team score for a team of the same person twice.
            'PersonA and PersonB are both *references* to an object in peopleKnowledge.
            '   This comparison compares if they are pointing at the same object, not if
            '   the contents of their lists are the same.
            If PersonA Is PersonB Then Continue For

            Dim score = GetTeamScore(PersonA, PersonB)

            If score > maxScore Then
                maxScore = score
                teamsWithMaxScoreCount = 1
            ElseIf score = maxScore Then
                teamsWithMaxScoreCount += 1
            End If
        Next
    Next

    Console.WriteLine(maxScore)
    Console.WriteLine(teamsWithMaxScoreCount)
End Sub

Private Function GetTeamScore(PersonA As List(Of Boolean), PersonB As List(Of Boolean)) As Integer
    Dim score As Integer = 0

    'Nowhere in your code was any validation that every person's topic list of 1's and 0's
    '   were equal in length which is fine if you are the only person who will ever use it,
    '   but other users won't always remember rules like that.
    For i = 0 To PersonA.Count
        If PersonA(i) Or PersonB(i) Then
            score += 1
        End If
    Next

    Return score
End Function


Avoid getting a reference to the global object ("window") using this; it won't work in strict mode. If this is only meant to run in the browser, just use window; otherwise you can do this:

var root = (1,eval)('this');

Try to declare variables at the top of the function.
Regarding isArray: Favor feature detection. Does it need to have a length property? A push function?
Regarding return null: Just return. This will return undefined, which should be close enough 99.9% of the time.
typeof (precision) === 'undefined' can simply be !precision in this case.
all those early isNaN checks seem redundant, why not just do the checks in the main loop?  Or, better yet, leave out the checks entirely, let the calculation fail, and the function will return NaN by itself, which makes more sense than null or undefined.

Incidentally, these changes will remove the underscore.js dependency.

(function () {

    'use strict';

    var root = (1,eval)('this'),
        previousFin = root.Fin,
        Fin;

    root.Fin = Fin = {};

    Fin.VERSION = '0.0.1';
    Fin.PRECISION = 4; // floating point precision

    /*
    Runs Fin.js in noConflict mode and
    returns reference to this Fin object
    */
    Fin.noConflict = function () {
        root.Fin = previousFin;
        return this;
    };

    /*
    NPV - Net Present Value
    rate = the periodic discount rate
    example: If the discount rate is 10% enter 0.1, not 10.
    payments = an array or object (keys are the year numbers) of payments
    example: [-100, 50, 60] means an initial cash outflow of 100 at time 0,
    then cash inflows of 50 at the end of the period one, and 60 at
    the end of the period two.
    If you pass {0: -100, 2:50}, then the payment at the end of the
    year one is assumed to be 0.
    */
    Fin.npv = function (rate, payments, precision) {
        var i, npv = 0;
        if (!precision || isNaN(precision)) {
            precision = this.PRECISION;
        }
        for (i in payments) {
            if (payments.hasOwnProperty(i)) {
                // do the NaN check here if you want.
                // if (isNaN(payments[i])) return;
                npv += payments[i] / Math.pow((1 + rate), i);
            }
        }
        return npv.toFixed(precision);
    };
}());


You should avoid code duplication in constructors. For larger objects this practice can quickly spin out of control. Re-use existing constructors instead:

public AsyncCommand(Func<CancellationToken, Task> action) : this(action, () => true) {}

or use default parameters:

public AsyncCommand(Func<CancellationToken, Task> action, Func<bool> canExecute = null) : base(canExecute)
{
    if (action == null) throw new ArgumentNullException(nameof(action));
    _action = action;
}

public CommandBase(Func<bool> canExecute = null)
{
    //this also allows you to remove "_canExecute == null" check
    _canExecute = canExecute ?? () => true;
}

Also, public constructors in abstract class look weird. You should make those protected.

Another minor thing: you have public and private members mixed together in a way, that does not make much sense. Personally, I find code easier to follow, if it has members of the same access level grouped together. But you can use any other scheme (some people like to group ICommand property with related delegate, for example), as long as it does not look random and chaotic.

P.S. If I were to use this class, I would also want to have an overloaded constructor, which takes Action<CancellationToken>. I don't want to manually create tasks, I want you to do it for me. I'm lazy like that. :) I would also want the command to either implement IDisposable or have a public Cancel method, so I can stop async operation programmatically. I mean I could call AsyncCommand.CancelCommand.Execute(...) but it looks ugly.


Never assume that your user doesn't make mistakes.  I ran your program with no arguments ... error message, fine.  I ran it with a single argument of 4 ... error message, fine.  I ran it with two arguments, 4 and 5 ...:

Traceback (most recent call last):
  File "test.py", line 17, in <module>
    rate = checker(args.curency_for_convert, args.curency_converted_to)
  File "test.py", line 9, in checker
    rate = content["rates"][symbol.upper()]
KeyError: 'rates'

For debugging purposes, I put print content above that line and ran again:

{'error': 'Invalid base'}

If I run the program with a valid base, but an invalid symbol:

Traceback (most recent call last):
  File "test.py", line 16, in <module>
    rate = checker(args.curency_for_convert, args.curency_converted_to)
  File "test.py", line 8, in checker
    rate = content["rates"][symbol.upper()]
KeyError: '8'

You should catch these errors and display something that is a little more user-friendly.

I would recommend that you read PEP 8, the Python style guide.  There are a couple things you aren't following:

  Imports should usually be on separate lines, e.g.:

  Yes:

import os
import sys

  No:

import sys, os

  It's okay to say this though:

from subprocess import Popen, PIPE

  Don't use spaces around the = sign when used to indicate a keyword argument or a default parameter value.

Your whitespace is a little strange.  I would have at least one blank line above and below the function definition.  I would also put one after the if block and maybe even before it too.  You have " =", " = ", and "=" used in just three lines.  PEP 8 says that A Foolish Consistency is the Hobgoblin of Little Minds, but that doesn't mean never be consistent.  It is only the foolish consitency which is a hobgoblin.  In this case, you have nothing to lose.

Your naming is a little strange.  n even shows up in the help messages.  One-letter variable names are generally not recommended because they give very little idea of what the variable is for.  curency_for_convert and curency_converted_to, besides mis-spelling "currency", are ungrammatical.  You could say "for conversion" or "to convert", but "for convert"?  I would suggest "convert_from" and "convert_to".

if len(sys.argv) > 3:
    parser.add_argument("n", type =int, help = "Amount of curency_for_convert", default=1)

Instead of manually parsing an argument, make it optional with nargs='?'

print rate if len(sys.argv) <= 3 else rate*args.n

Since our argument will always be present (either with the default of 1 or with a user-supplied number), we can now do print rate * args.n.

Full Program

#!/usr/bin/env python
import argparse
import ast
import requests
import sys

def checker(base, symbol):
    url = "http://api.fixer.io/latest?base=%s" % base.upper()
    r = requests.get(url)
    content = ast.literal_eval(r.content)
    rate = content["rates"][symbol.upper()]
    return rate

parser = argparse.ArgumentParser(description=
    "Currency converter. For instance: to convert 100 USD to RUB, it would be "
    "100 USD RUB. If you need only the rate: USD RUB"
)

parser.add_argument("amount", type=int, help="Amount of currency to convert", default=1, nargs='?')
parser.add_argument('convert_from', type=str, help="Currency to convert")
parser.add_argument('convert_to', type=str, help = "Currency of converted")

args = parser.parse_args()

try:
    rate = checker(args.convert_from, args.convert_to)
except KeyError:
    print "Invalid argument(s)"
else:
    print rate*args.amount


Functions to count vowels and consonants in strings

char String[30];
    char choice;
    int Nvowels,Nconsonant;

Don't define a variable before it is needed. Doing so increases the cognitive load on readers that trace through your code and keep mental records of every variable, their possible values, and whether they've even been set. This artifact from older languages also encourages lazy reuse of variables beyond their original intent. Define variables as you need them and keep the scope of each variable as narrow as required.

Use descriptive names. The larger the scope in which a variable exists, the more important it is to give that variable a name that indicates to the reader what it represents. String \$\rightarrow\$ input_sentence. Nvowels \$\rightarrow\$ vowel_count.

    cin.getline(String ,30);

If a user inputs 30 or more characters, std::istream::getline will set the failbit. If end-of-file is reached before the delimiter is encountered, std::istream::getline will set the eofbit. You should check if std::cin is in a readable state and reset the state if it's not, otherwise you'll have an infinite loop when an error is encountered.

    cout<<"\nMENU"<<endl;
    cout<<" (A) Count the number of vowels in the string"<<endl;
    cout<<" (B) Count the number of Consonants in the string"<<endl;
    cout<<" (C) Count both the vowels and consonants in the string"<<endl;
    cout<<" (D) Enter another string"<<endl;
    cout<<" (E) Exit program"<<endl;

Whitespace is great for readability as they help separate operators and language constructs.

Avoid std::endl. If you need to explicitly flush the cache, then explicitly stream the manipulator std::flush and comment why a flush is necessary. If you simply need a end-of-line character, prefer '\n' or "\n".

Edward covered string concatenation via the compiler, but I'd like to also point out that C++11 introduced raw string literals.

    std::cout << R"(
MENU
 (A) Count the number of vowels in the string
 (B) Count the number of Consonants in the string
 (C) Count both the vowels and consonants in the string
 (D) Enter another string
 (E) Exit program
Enter Choice
");

    cin>>choice;

As with std::istream::getline, std::istream::operator>> needs to be checked to ensure a read was successful. If extraction failed, you should probably notify the user and attempt to recover.

    case 'A':
    //Function call to get number of Vowels
    case 'B':
    //Function call to get number of consonants
    //Outputting number of Consonants
    case 'C':
    //Function call to get number of Vowels

Keep comments crisp. Everything I need to know as far as what is being done is already there in the form of code to be compiled. Comments should be reserved for explaining why the code was written the way it was (the intent). Adding verbosity slows down understanding.

To assist with the readability, consider mapping the character inputs to enumerations. You can read up on enum serialization, but just to give you an idea of how it can help readability:

enum class Selected {
    count_vowels = 'A',
    count_consonants,
    count_both,
    reset_sentence,
    exit
};

std::istream& operator>>(std::istream& in, Selected op) {
    // exercise for the reader.
}

int main() {
    // ...
        Selected user_choice;
        std::cout << "Enter choice: ";
        std::cin >> user_choice;

        switch (user_choice) {
        case Selected::count_vowels:
            // ...
        case Selected::count_consonants:
            // ...
        case Selected::count_both:
            // ...
        case Selected::reset_sentence:
            // ...
        case Selected::exit:
            // ...
        case default:
            // Handle user-input error (out of range, end of file)

            fflush(stdin);

Using std::fflush on an input stream is undefined behavior. If you were trying to reset the buffer of std::cin, see std::cin::ignore.

        case 'E':
            exit(0);
            break;
        }
    } while (choice != 'E');

    system("pause");

Once the the program encounters exit(0), all of the remaining code (break; \$\rightarrow\$ while (choice != 'E') \$\rightarrow\$ system("pause");) is unreachable. If you intend to immediately return from a function (or in this case exit the program), you don't need to loop until choice is \$E\$. This is one of those times where while (true) is actually appropriate if you didn't have the restriction.

system("pause") is slow, platform-dependent, and insecure.  Consider re-evaluating your development environment, from having permanent access to a console or utilizing the breakpoint of a debugger.

int Consonant_count(char *str) {
    // ...
        if (*str != 'a' && *str != 'e' && *str != 'i' && *str != 'o' && *str != 'u')
              count++;
            str++;

Prefer scoping your single-line statement blocks with braces. Adding code in a hurry

if (condition)
    statement;
  statementIntendedToBeScoped???

or commenting

if (condition)
    // statement
statementThatIsNowScopedToCondition

can lead to errors. Scoping with braces addresses this issue.

if (condition) {
    statement
}
statementDefinitelyNotScoped

if (condition) {
    // statement
}
statementDefinitelyNotScoped

if (*str != 'a' && *str != 'e' && *str != 'i' && *str != 'o' && *str != 'u')

Keep in mind the various possible values a type can represent. A character (char) can represent the set of consonants and vowels (A-Z, a-z). It can also represent digits, punctuation, control characters, whitespace, etc. The conditional in Consonant_count is returning true or false if the current character is any ASCII character (not any alphabetic character) that is not any of aeiou. Clearly control structures, punctuation, and whitespaces are not consonants.

In both of your functions, how do you handle uppercase vowel inputs?

Rather than check each individual vowel, consider a lookup technique.  You could create a table (one for vowel, one for consonant) that maps each character to true or false.  There is also a bit mapping alternative that builds on the lookup table approach, where you exploit the layout of the ascii table to do very fast lookups via bit shifts and masks.

bool is_vowel(char ch) {
    auto lowercase_pos = (ch | 0x20) - 96;
    if (static_cast<unsigned char>(lowercase_pos) > 31) {
       return false;
    }
    constexpr std::uint32_t vowel_mask = (1 << 1) | (1 << 5) | (1 << 9) | (1 << 15) | (1 << 21);
    return (vowel_mask & (std::uint32_t{1} << lowercase_pos)) != 0;
}

specific_count(range)
    count = 0
    for each element in the range
        if element is what we're looking for
            count = count + 1
    return count

Learn the various <algorithm>s.  You'll notice that both your functions have the same structure as the pseudocode above.  It turns out, this is a common algorithm in C++ (std::count_if).  You should be aware of this library as you learn more about functions and specifically lambdas (objects that behave like functions and can be passed around into functions as arguments).


Determine the length of the largest contiguous segment

Code Review

PEP 8

PEP 8 recommends snake_case for variable names, so N, Q, A, L, R, and D all violate the guidelines.

A space should be used around operators: index - 1 and R - 1

Unused variables

N and testcase are never used, so should be replaced with the throwaway _ variable.

Variable naming

N, Q, A, L, R, and D are all "almost meaningless".  Yes, they are directly from the problem description, but you could do better naming them array_size, num_queries, array, left, right and difference.

Is count_length a count of lengths?  Doesn't seem to be; it is more like a max_length.

Is count_temp a count of temporaries?  Or is it more like a segment_length?

_, num_queries = [int(x) for x in input().split()]

array = list(map(int, input().split()))

for _ in range(num_queries):
    left, right, difference = [int(x) for x in input().split()]

    if left == right:
        print("1")
        continue

    max_length = 0
    segment_length = 0

    for index in range(left, right):
        if array[index] == array[index - 1] + difference:
            segment_length += 1
            if index == right - 1:
                segment_length += 1
                max_length = max(max_length, segment_length)

        else:
            segment_length += 1 # to include the first element of AP
            max_length = max(max_length, segment_length)
            segment_length = 0

    print(max_length)

Optimization

Without changing the Algorithm???

Ok, you're looking for just key-hole level optimizations.  Let's see what we can do.

    for index in range(left, right):
        if array[index] == array[index - 1] + difference:
            ...
        else:
            ...

The above is inefficient code.  Indexing into a list takes time, and you are doing it twice.  Moreover, subtraction by 1 takes time, and it was to get the value which was looked up on the previous iteration!

Compare the above code with:

    prev = array[left - 1]
    for curr in array[left:right]:
        if curr == prev + difference:
            ...
        else:
            ...
        prev = curr

The indexing has been replaced with iteration over an array slice, and the current value from one iteration is carried forward to as the previous value in the next iteration.  That should be a win, performance wise.

    segment_length = 0

    for ...:
        if ...:
            ...
            if ...:
                segment_length += 1
                max_length = max(max_length, segment_length)

        else:
            segment_length += 1 # to include the first element of AP
            max_length = ...
            segment_length = 0

Why are you starting the count from 0?  That means you need this segment_length += 1 to account for that first element all the time.  If you initialized segment_length = 1, you can skip that adjustment statement every time you reach the end of an arithmetic progression, saving another wee bit of time:

    segment_length = 1

    for ...:
        if ...:
            ...
            if ...:
                max_length = max(max_length, segment_length)

        else:
            max_length = ...
            segment_length = 1

Finally, the code I hate the most:

    for index in range(left, right):
        if ...:
            ...
            if index == right - 1:
                ...

        else:
            ...
        ...

When does the for loop end?  After index loops the final time with index = right - 1, of course.  So the only time this if condition will be true is during the last iteration of the loop.  During all of the remaining loop iterations, you are wasting time, subtraction 1 from right and comparing the result to index, when it can't possibly ever be true.  Simply move the code to follow the loop.

_, num_queries = [int(x) for x in input().split()]

array = list(map(int, input().split()))

for _ in range(num_queries):
    left, right, difference = [int(x) for x in input().split()]

    if left == right:
        print("1")
        continue

    max_length = 0
    segment_length = 1

    prev = array[left - 1]
    for curr in array[left:right]:
        if curr == prev + difference:
            segment_length += 1

        else:
            max_length = max(max_length, segment_length)
            segment_length = 1

        prev = curr

    max_length = max(max_length, segment_length)

    print(max_length)

With changing the Algorithm

You explicitly requested optimization without changing the algorithm, so I'll leave you to discover where there is an algorithmic improvement to be made.


Alright, let's see if we can simplifyabstract this for you. I'm not going to say simplify because often times abstracting something is far from simplifying it.

I think you can turn the method into something like this:

public void Method<T>(Context context, Action<T, Class> body, EventLog log = null)
{
    Class myClass = ConvertToMyClass();
    T apiCall = Activator.CreateInstance(typeof(T), new [] { context });
    if (log != null)
    {
        eventLog.WriteEntry("Starting");
    }

    try
    {
        body(apiCall, class);
        IsCallSuccess = true;
    }
    catch (Exception e)
    {
        if (log != null)
        {
            eventLog.WriteEntry("error");
        }

        IsCallSuccess = false;
        CallErrorMessage = e.Message;
    }
}

... then you should be able to call it like this:

// Method1
Method<ApiCall1>(
    yourContextInstance,
    (apiCall, myClass) =>
    {
        apiCall.Call1(myClass, null, false);
    },
    yourLogInstance);

// Method2
Method<ApiCall2>(
    yourContextInstance,
    (apiCall, myClass) =>
    {
        apiCall.Call1(myClass);
        NewItemID = myClass.ItemID;
    },
    yourLogInstance);

// Method3
Method<ApiCall3>(
    yourContextInstance,
    (apiCall, myClass) =>
    {
        apiCall.Call3(myClass, "param1");
        UpdatedItemID = myClass.UpdatedItemID;
    },
    yourLogInstance);

... one caveat is NewItemID and UpdatedItemID. If you're not making these calls from inside the class Method is defined in, you may need to modify this a tad to get the Method to return and integer instead.


you can chain the delay and switchClass to $elements and take the $("#container").find(".animation"); outside the function like this

function startAnimation($elements) {
$elements.switchClass("mc-ylw-blk", "mc-blk-ylw", 0)
      .delay(500).switchClass("mc-blk-ylw", "mc-ylw-blk", 0)
      .delay(250).switchClass("mc-ylw-blk", "mc-blk-ylw", 0)
      .delay(250).switchClass("mc-blk-ylw", "mc-ylw-blk", 0)
      .delay(500).promise().done(function () {
          startAnimation($elements);
      });
}
var $elements=$("#container").find(".animation");
if ($elements.length) {
    startAnimation($elements);
}

http://jsfiddle.net/Y95rU/1/


Iterate attributes of property, typecast and store info if found

Seems like ive found a great solution, my entire loop can be rewritten as this:

InvokeOnAttr<DisplayAttribute>(property, a => {
    Name = a.Name;
    Group = a.GroupName;
    Description = a.Description;
});

InvokeOnAttr<MinLengthAttribute>(property, a => {
    Validate.MinLength = a.Length;
});

InvokeOnAttr<MaxLengthAttribute>(property, a => {
    Validate.MaxLength = a.Length;
});

InvokeOnAttr<RegularExpressionAttribute>(property, a => {
    Validate.Regex = a.Pattern;
    Validate.RegexError = a.ErrorMessage;
});

If this method also is availible in the class (it takes a property, finds the attribute (of type TAttr provided), and if found executes the passed in action on it:

public void InvokeOnAttr<TAttr>(PropertyInfo p, Action<TAttr> action) where TAttr : Attribute {
    TAttr attr = p.GetCustomAttribute<TAttr>();
    if (attr is ValidationAttribute)
    {
        if (Validate == null) Validate = new MetaValidate();
    }
    if (attr != null) {
        action.Invoke(attr);
    }
}


Extract an abstract base class AbstractWordTable that implements the better-named interface WordTable by moving all code that's duplicated between Adjective and Animal (all but the table and column names). This is a major step in the DRY direction that will simplify your code.

I won't attempt to produce this code on my phone, but the key is for those concrete implementations to contain only unique code. The end result will be with a simple one-line constructor.

Another improvement would be to decouple reading the table contents from picking random words by splitting these functions between WordTable that reads words from a database table into an array and WordList that provides various ways to consume it, including choosing random words and subsets.


First, let's look at your answer with comments:

def speed_check(limits, speeds):
  # Explicit assignment of temporary variables
  i, j = 0, 0
  prev_limit_range, prev_speed_range = 0, 0
  # Assumption that speeds and limits will not change during iteration
  while j < len(speeds) and i < len(limits):
    # Multiple if statements make it so that we can't just swap lines of
    # code without breaking things.
    if limits[i][0] < speeds[j][0]: # speed > limit would be more readable
      return True
    # Operator precedence does not jump to the eye. Use parenthesis
    if limits[i][1] + prev_limit_range < speeds[j][1] + prev_speed_range:
      prev_limit_range += limits[i][1]
      i += 1
    elif limits[i][1] + prev_limit_range > speeds[j][1] + prev_speed_range:
      prev_speed_range += speeds[j][1]
      j += 1
    else:
    # Manual incrementation of local variables.
      prev_limit_range += limits[i][1]
      prev_speed_range += speeds[j][1]
      i += 1
      j += 1

  return False

Python-wise there are multiple parts of your implementation that could be tackled differently. Let's see what we could do.

If you think about this problem graphically, drawing an x-axis for distance and a y-axis for speed, then all you want is to check whether the curve for actual speed ever crosses the curve for speed limits.

You could break down your problem into subparts:

def get_graph(speedlist):
    """Generate a list of tuples into a flatten list as in:
    [(1,2), (3, 4)] -> [1, 1, 3, 3, 3, 3]
    """
    return [item for x in [y[1]*[y[0]] for y in speedlist] for item in x]

def check_exceeds(speeds, limits):
    speed_graph = get_graph(speeds)
    limits_graph = get_graph(limits)
    return any([x > y for x, y in zip(speed_graph, limits_graph)])

This approach avoids three issues I see in your implementation:  excess of if-statements, explicit indexing, and explicit iteration. Why are these issues? Well, it's easy to make mistakes when indexing and manually iterating, and it's easy to forget possible branches when using if/else clauses. Python offers a lot of tooling so that you don't have to do everything yourself, and it's considered good practice to leverage that tooling to make your code both more readable and safe.

For your assertions, there is also no need to compare to True nor False, in case your function is defined in such a way that it returns a boolean:

assert check_exceeds([(30, 15), (55, 20)], [(30, 15), (55, 20)])
assert not check_exceeds([(30, 15), (55, 20)], [(30, 14), (65, 20)])

(quick answer as I was answering the post in StackOverflow before it migrated)


I'll only look at the memory vs. speed trade-off.
Suppose that M is the key size we want to look up, and N is the number of words in the dictionary. If we start with a sorted dictionary, then the prefix can be found with binary search, so that is O(M * log N) lookup cost in terms of the dictionary size. A prefix tree has a lookup cost of O(M). But the "work" done to actually look things up is trivial, i.e. on modern CPUs there's no cost to doing the character comparisons and such, especially that you could use SIMD intrinsics to speed that up by a lot. The entire cost is in cacheline accesses.
To speak in concrete terms, let's use the alphanumeric word dictionary from https://github.com/dwyl/english-words, on x86-64 (i.e. 8-byte pointer size). Let's also assume that we're wishing to optimize for lookup efficiency (broadly defined).
First, some general statistics of this dictionary:

3,494,697 letters
370,103 words
1,027,815 nodes in a prefix tree
3 child nodes average branching factor.
9 letters median word length (also the average), 31 letters maximum word length
branching factors (for successive letters looked up):
1-26, 2-22, 3-8.6, 4-5.1, 5-2.7, 6-1.7, 7-1.1, 8-0.9, 9-0.8

So, if we stored the dictionary as a simple concatenation of null-terminated C strings, with no other optimizations, it'd take around 4MB of memory. This fits comfortably in the 6MB L3 cache of the CPU I'm trying this on (that cache can hold ~100k cachelines of 64 bytes each, in best case).
On the other hand, the question's implementation of the prefix tree takes ~220MB of RAM because the nodes are huge: 216 bytes. We'd have hoped that the prefix tree would have "compressed" our data, but instead it expands it by a factor of 55x. Each node fits in 4 cache lines (3.3 really).
Tree traversal using Node needs to pull up to two cachelines per Node (maybe 1.5 on average): one for the child node pointer, another for the value and the child pointer. Some of those cachelines will have to be misses, since the tree doesn't fit in the cache.
The L3 cache can fit around 30k nodes. Let's somewhat arbitrarily assume that about 10k of them will be "long lived hot nodes". The product of the first 5 branching factors is ~25k, so we can estimate that about 4 first characters of each word will be nodes that fit in L3. With average word being 9 letters long, we will miss 4-5 additional nodes, or 8-10 additional cachelines. That'd be the real cost of this implementation on this particular data set.
Now let's say our benchmark will be as follows: take a "lookup string" of all words in random order, concatenated into a long string of zero-terminated words. Iterating such a string is very fast, since the CPU will prefetch everything, so other than some cache pressure, the overhead of using such permuted word stream is very low. We use words from that string as lookup keys, and copy them to an output string as we perform each lookup. An exemplary benchmark takes about 120ms to look up all the 370k words in random order from the prefix tree, constructing the "output string". The function being timed is below, the assert is a no-op in release mode, and the nodes were all allocated from a contiguous memory block.
I wrote the examples below in C++, to make life a bit easier, but they could all be written in C without any loss of performance.
auto doLookup(Node *root, const std::string &lookupStream)
{
    std::string result, word;
    Node *node = root;
    result.clear();
    result.reserve(lookupStream.size());
    for (char ch : lookupStream) {
        if (ch) {
            node = node->children[ch - 'a'];
            word.push_back(ch);
        } else {
            node = root;
            result.append(word);
            result.push_back('\0');
            word.clear();
        }
    }
    assert(result == lookupStream);
    return std::make_pair(std::move(result), node);
}

Given this "standard" to compare with, let's do the "next most stupid thing": an equivalent lookup using just the dictionary, with zero-delimited words in ascending order, using a binary search, where each time we "throw a dart" in the dictionary, we have to scan back to find the beginning of the word.
The function being timed is below. It isn't particularly pretty but it does the job.
auto doLookup2(const std::string &dictionary, const std::string &lookupStream)
{
    assert(dictionary.front() == '\0');
    assert(dictionary.back() == '\0');
    assert(lookupStream.back() == '\0');
    std::string result, word;
    result.reserve(lookupStream.size());
    for (char ch : lookupStream) {
        if (ch)
            word.push_back(ch);
        else {
            const char *begin = &dictionary.front(), *end = &dictionary.back();
            const char *prevP = nullptr;
            for (;;) { // binary search
                const char *p = begin + (end - begin) / 2;
                const char *const p0 = p;
                assert(p0 != prevP); // otherwise we didn't find the word
                while (*p)
                    --p; // find start of the word
                p ++;
                int const cmp = strcmp(word.data(), p);
                if (cmp == 0) {
                    assert(word == p);
                    result.append(word);
                    result.push_back('\0');
                    word.clear();
                    break;
                }
                if (cmp < 0 /* word < p */) {
                    end = p0;
                } else { /* word > p */
                    begin = p0;
                }
                prevP = p0;
            }
        }
    }
    assert(result == lookupStream);
    return result;
}

This function takes about 170ms (vs. the tree's 120ms), and trades off 50% longer execution for 55x smaller memory use, although it doesn't find the first word with a given prefix, just some word - then one has to iterate backward. Doing that in the most rudimentary way adds some 10ms to the runtime (I'm not showing it above).
This trade-off may be acceptable as-is. But either approach could be micro-optimized. Cutting the tree size in half by replacing the node pointers with indices of nodes in the pool cuts about 10ms off the runtime - we don't expect a huge improvement, since the tree still doesn't fit in the cache.
But the tree approach seems promising, so let's try to reduce memory consumption further. Instead of allocating 26 child node pointers in each node, let's allocate only one, and double the pointer array size whenever we run out of space. There isn't a direct index-to-pointer mapping for child pointers anymore, but instead we can store a bit flag for each character, indicating whether the pointer is present or absent in the array. Furthermore, the leaf nodes can all be stored as stock nodes, since they are identical. The node looks as follows:
struct TreeNode
{
    uint32_t activeChildren;
    struct TreeNode *children[1]; // this is a dynamically sized array
} typedef TreeNode;

The activeChildren member also stores the end-of-word flag - access is provided via accessors.
This approach reduces the allocated memory size to 15MB, and the lookup benchmark takes about 140ms - only 20ms worse than the "reference" implementation. Only 750k nodes are individually allocated, the remaining 250k are all leaf nodes collected as the single stockLeafNode.
Retrieval of a child node looks as follows:
TreeNode **getChildNode(TreeNode *node, char ch)
{
    ch -= NODE_LOWEST_VALUE;
    uint32_t childrenBits = node->activeChildren;
    if (!bitIsSet(childrenBits, ch))
        return NULL;
    return node->children + numberOfSetBitsBelow(childrenBits, ch);
}

numberOfSetBitsBelow(bits, bit) returns the count of set bits ("1") in the bits paramer, but only the bits in positions lower than bit number bit. E.g. numberOfSetBitsBelow(0xFE, 3) == 2, because below bit 3 only bits 2 and 1 are set.
Using getChildNode, we have the following prefix lookup:
TreeNode *findNode(TreeNode *node, const char *word)
{
    for (char ch = *word++; ch; ch = *word++) {
        TreeNode *nextNode = *getChildNode(node, ch);
        if (!nextNode)
            break;
        node = nextNode;
    }
    return node;
}

Complete project is at https://github.com/KubaO/stackoverflown/tree/master/questions/cr-prefix-tree-252512


I think you're making this a lot more complicated than it needs to be. Forgive my rusty python, but you should be able to do something like

def viginere_encrypt(message, key):
    length = len(message)
    mnum = [0]*length
    for i in range(0, length):
        mnum[i] = letter_to_number(message[i])
    knum = [0]*len(key)
    for i in range(0, len(key)):
        knum[i] = letter_to_number(key[i]
    result = [0]*length
    for i in range(0, length):
        result[i] = number_to_letter(mnum[i] + knum[i % len(key])
    return result

def letter_to_num(letter):
    return ord(letter) - ord("a")

def number_to_letter(number):
    return chr(number%alpha + ord("a"))

Using list comprehensions, this can be shortened to

def viginere_encrypt(message, key):
    mnum = [letter_to_number(x) for x in message]
    knum = [letter_to_number(x) for x in key]
    return [number_to_letter(mnum[i] + knum[i%len(key)])for i in range(0, len(message)]

or even further to

def viginere_cipher(message, key):
    return [number_to_letter(letter_to_number(message[i]) + letter_to_number(key[i % len(key)])) for i in range(0, len(message)])

though that's probably too mushed together by now.

Also, I don't know python too well; there's probably a better way to convert between "a-z" and 0-25.

Anyways, functions are a Very Good Idea. Output can then be separated from business logic, so if, say, you need to use the cipher elsewhere in your code, you're not tied to the terminal. It also allows for much easier testing.


This got some discussion in the Ramda Gitter Room.  Although several people had different suggestions, my feeling -- and I believe the consensus -- was that this is very well done, and there's little to improve.

If you want it slightly more points-free, you could write divisibleBy like this:

var divisibleBy = R.curry(R.pipe(R.flip(R.modulo), R.equals(0)));

But, no, I don't think there is any more canonical way of doing this in Ramda.

BTW, I'm one of the original authors of Ramda, and as far as I've seen, yours is the very first Ramda fizzbuzz in existence!


Haskell function to error-diffuse a floating value to a list of integers

First I'd get rid of the dependency on num, since that's just a counter,
and you can use take num on an infinite list of errorDiffuses:

errorDiffuses :: Double -> Double -> [Int]
errorDiffuses v err = tv : errorDiffuses v (err + v - fromIntegral tv)
 where
  tv = truncate (v + err)

So we have:

errorDiffuse' :: Double -> Int -> Double -> [Int]
errorDiffuse' v num err = take num $ errorDiffuses v err

Then I'd think about generating the list of errorDiffuses differently.
Since we're trying to generate a list, that makes me think of unfolds,
which you can find in Data.List:

unfoldr :: (b -> Maybe (a, b)) -> b -> [a]

The unfold takes a function that, given a seed, produces the next
value in the outputted list, along with a new seed. The function
starts with an intitial seed, and keeps using those seeds, adding to the
list until the function returns Nothing.

The function we're looking for is the following:

nextErrorDiffuse :: Double -> Double -> Maybe (Int, Double)
nextErrorDiffuse v err = Just (tv, err + v - fromIntegral tv)
 where
  tv = truncate (v + err)

Our list is infinite, so we always return a Just value. The value that is output at each stage is tv, and the next "seed" is given by err + v - fromIntegral tv.

Putting things together we have:

errorDiffuse'' :: Double -> Int -> Double -> [Int]
errorDiffuse'' v num err = take num $ unfoldr (nextErrorDiffuse v) err


First off, you don't verify the data entered by the user. This is an absolute must, IMHO.
I'm no COBOL programmer, but do have some basic COBOL knowledge. Others may suggest better solutuions. Anyway, here are my thoughts:
You define data item 01 INP PIC A(14) but the user needs to input numbers and operators. Picture character A means *letter of the Latin alphabet or a space", You should use X, because you cannot tell what the user will enter, and that is why you need to add code to verify.
You define the data items to hold the input numbers as PIC 9(7), and PIC 9(15), resp., and the data item to hold the operation result as PIC 9(8). How did you come up with these lengths? Make sure the result fits into the corresponding data item.
You define the data item to hold the math operator as PIC A(2), but the operators are only one character (and not of type A). Again PIC X would be appropriate.
You're defining condition names for the operators, which is a good idea.
   01 NUM2 PIC A(2).
      88 PLU VALUE "+".
      88 AIDS VALUE "-".
      88 MULT VALUE "*".

However, you don't make user of them. You can use them in your IF statements, and in the (missing) logic to verify the input. So instead of
   IF NUM2 = "+" THEN
       ADD NUM1 NUM3 GIVING ANS
   ELSE ...

you could code
   IF PLU THEN
       ADD NUM1 NUM3 GIVING ANS
   ELSE ...

Instead of coding nested IF statements use other constructs the language of choice offers. In COBOL, you could make use of the EVALUATE statement as follows:
   EVALUATE TRUE
      WHEN PLU
         ADD NUM1 NUM3 GIVING ANS
      WHEN AIDS
         SUBTRACT NUM1 FROM NUM3 GIVING ANS
      WHEN MULT
         MULTIPLY NUM1 BY NUM3 GIVING ANS
      WHEN OTHER
         some error processing here....
    END-EVALUATE.