Before we look at how to improve performance, lets start by polishing your code.

Polishing

Dim Generar As Boolean = False
Dim N As Integer

Despite the fact that the .NET naming guidelines doesn't apply for internal and private fields the general consensus is to use English, descriptive and lower Camel case names.

I've renamed the variable and changed the initial value to True as "generate" (IMO) is referring to "columns".

The variable N is useless and should be removed as you already got a variable named c which you could use.

Dim generate As Boolean = True

For Each line As String In Clipboard.GetText.Split(vbNewLine)
    If Not line.Trim.ToString = "" Then
        Dim item() As String = line.Trim.Split(vbTab)

The first line "breaks" my compiler with the error BC30512 and correctly state that "Option Strict On disallows implicit conversions from 'String' to 'Char'". You should always make sure that the strict compiler option is set to On. I'm tempted to say that this is the most important thing you'll learn by reading this review. Oh, wait! I just did! ;)

The constants vbNewLine and vbTab (defined as String) are remnants from the past and should be regarded as obsolete. Many of the methods and classes inside the Microsoft.VisualBasic assembly were added to make the transition from VB6 to VB.NET more convenient. If there's a .NET equivalent, use it! However, in this case, we need a Char array so we create a few Char constants.

The Split method has an overload which allows us to pass an option to remove empty entries. We'll use this and remove the second line. But please note that a better alternative to your boolean expression would be to use the static method String.IsNullOrWhiteSpace. I've also renamed the variable item to values.

Const tab As Char = ChrW(9)
Const lineFeed As Char = ChrW(10)
Const carriageReturn As Char = ChrW(13)

For Each line As String In Clipboard.GetText.Split({lineFeed, carriageReturn}, StringSplitOptions.RemoveEmptyEntries)
    Dim values() As String = line.Trim.Split({tab})

For C = 0 To UBound(item)
    DGVLookUP.Columns.Add("C" + CStr(N), CStr(N))

Again, you're using an obsolete method, UBound. Just read the Length property of the array. (If you need to read the length of a give dimension, invoke GetLength.)

It's advisable to use & for string concatenation. And you ought to take advantage of all of the static methods the string type has to offer. I've also renamed the variable C to  cell.

For cell As Integer = 0 To (values.Length - 1)
    DGVLookUP.Columns.Add(String.Format("C{0}", cell), cell.ToString())

Performance

The complete code at this point looks like below. The great disadvantage with this code is that you add a new row in each iteration. Each call to Add will queue a bunch of messages all of which needs to be processed by the window. Do we really need to repaint the control 3000 times? The answer is of course NO. So we need to fix this.

Const tab As Char = ChrW(9)
Const lineFeed As Char = ChrW(10)
Const carriageReturn As Char = ChrW(13)

Dim generate As Boolean = True

For Each line As String In Clipboard.GetText.Split({lineFeed, carriageReturn}, StringSplitOptions.RemoveEmptyEntries)

    Dim values() As String = line.Trim.Split({tab})

    If (generate) Then
        For cell As Integer = 0 To (values.Length - 1)
            Me.DGVLookUP.Columns.Add(String.Format("C{0}", cell), cell.ToString())
        Next
        generate = False
    End If

    Me.DGVLookUP.Rows.Add(values)

Next

A much better option would be to first read the data into a data structure (we'll be using a DataTable) and then update the grid.

Const tab As Char = ChrW(9)
Const lineFeed As Char = ChrW(10)
Const carriageReturn As Char = ChrW(13)

Dim table As New DataTable()
Dim generate As Boolean = True

table.BeginLoadData()

For Each line As String In Clipboard.GetText.Split({lineFeed, carriageReturn}, StringSplitOptions.RemoveEmptyEntries)

    Dim values() As String = line.Trim.Split({tab})

    If (generate) Then
        For cell As Integer = 0 To (values.Length - 1)
            table.Columns.Add(String.Format("C{0}", cell))
        Next
        generate = False
    End If

    table.Rows.Add(values)

Next

table.EndLoadData()

Me.DGVLookUP.DataSource = table

To further increase the performance we'll need to write our own parser and scrap the split method. You might need to fine tune this if the data inside the excel cell contains a line feed and/or a carriage return.

Const tab As Char = ChrW(9)
Const lineFeed As Char = ChrW(10)
Const carriageReturn As Char = ChrW(13)

Dim data As String = Clipboard.GetText()
Dim table As New DataTable()
Dim generate As Boolean = True
Dim cursor As Integer = 0
Dim position As Integer = 0
Dim cell As Integer = 0
Dim row As DataRow = Nothing

table.BeginLoadData()

While (cursor < data.Length)

    Select Case data.Chars(cursor)

        Case tab, carriageReturn

            If (generate) Then
                table.Columns.Add(String.Format("C{0}", cell), GetType(String)).Caption = cell.ToString()
            End If

            If (cell = 0) Then
                row = table.NewRow()
            End If

            row.Item(cell) = data.Substring(position, (cursor - position))

            cell += 1
            cursor += 1
            position = cursor
            Continue While

        Case lineFeed

            If (Not row Is Nothing) Then
                table.Rows.Add(row)
                row = Nothing
            End If

            cell = 0
            cursor += 1
            position = cursor
            generate = False
            Continue While

        Case Else

            cursor += 1
            Continue While

    End Select

End While

table.EndLoadData()

Me.DGVLookUP.DataSource = table

Test

I've tested this with 3000 rows x 10 columns in release build and as you can see there's a distinct performance boost.

  Paste #1: count= 10, average= 3181.4678 ms
  Paste #2: count= 10, average= 1483.8070 ms
  Paste #3: count= 10, average= 1058.3944 ms

Option Strict On

Imports System.Text

Public Class Form1

    'Copy and paste the text below into each cell of the range A1:J3000
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas in convallis nunc, nec gravida sem. Praesent malesuada dignissim arcu, eu euismod enim. In non neque ut augue sodales dictum eu eget dui. Pellentesque dolor diam, vestibulum sit amet pulvinar et, sollicitudin nec mauris. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras sollicitudin metus vitae arcu faucibus, at posuere mauris dictum. Pellentesque in varius sem. Pellentesque molestie varius metus, a dignissim purus vulputate a. Cras venenatis orci et urna efficitur, vel fermentum dui eleifend. Pellentesque et malesuada mauris. Nulla eget nunc et turpis dictum pretium. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam porttitor diam nunc, ut dapibus felis porta at. Nunc non ante sit amet ipsum maximus imperdiet at vitae metus. Aliquam ut lacus in elit laoreet sodales et in eros.

    Private Class TestInfo
        Public Name As String
        Public Method As Action
        Public ReadOnly Results As New List(Of Double)
    End Class

    Private WithEvents input As New DataGridView With
    {
        .Dock = DockStyle.Fill
    }

    Private WithEvents output As New TextBox With
    {
        .Dock = DockStyle.Top,
        .Multiline = True,
        .Height = 100,
        .ReadOnly = True,
        .ScrollBars = ScrollBars.None,
        .Text = "Waiting for input..."
    }

    Private tests As TestInfo() = New TestInfo() _
    {
        New TestInfo With {.Name = "Paste #1", .Method = AddressOf Me.Paste1},
        New TestInfo With {.Name = "Paste #2", .Method = AddressOf Me.Paste2},
        New TestInfo With {.Name = "Paste #3", .Method = AddressOf Me.Paste3}
    }

    Private switch As Integer = 0

    Public Sub New()
        Me.Size = New Size(800, 600)
        Me.Text = "Test"
        Me.KeyPreview = True
        Me.Controls.AddRange({Me.input, Me.output})
    End Sub

    Private Sub HandleKeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown

        If (e.Control AndAlso (e.KeyCode = Keys.V)) Then

            If (Me.input.DataSource Is Nothing) Then
                Me.input.Rows.Clear()
                Me.input.Columns.Clear()
            Else
                Me.input.DataSource = Nothing
            End If

            Dim watch As New Stopwatch()
            Dim info As TestInfo = Me.tests(Me.switch)

            watch.Start()
            info.Method.Invoke()
            watch.Stop()
            info.Results.Add(watch.Elapsed.TotalMilliseconds)

            Dim builder As New StringBuilder()

            For Each info In Me.tests

                If (builder.Length > 0) Then
                    builder.AppendLine()
                End If

                Dim average As Double = 0

                If (info.Results.Count > 0) Then
                    average = info.Results.Average()
                End If

                builder.Append(String.Format("{0}: count= {1}, average= {2:F4} ms", info.Name, info.Results.Count, average))

            Next

            Me.output.Text = builder.ToString()
            Me.switch += 1

            If (Me.switch = Me.tests.Count) Then
                Me.switch = 0
            End If

        End If

    End Sub

    Private Sub Paste1()

        Const tab As Char = ChrW(9)
        Const lineFeed As Char = ChrW(10)
        Const carriageReturn As Char = ChrW(13)

        Dim generate As Boolean = True

        For Each line As String In Clipboard.GetText.Split({lineFeed, carriageReturn}, StringSplitOptions.RemoveEmptyEntries)

            Dim values() As String = line.Trim.Split({tab})

            If (generate) Then
                For cell As Integer = 0 To (values.Length - 1)
                    Me.input.Columns.Add(String.Format("C{0}", cell), cell.ToString())
                Next
                generate = False
            End If

            Me.input.Rows.Add(values)

        Next

    End Sub

    Private Sub Paste2()

        Const tab As Char = ChrW(9)
        Const lineFeed As Char = ChrW(10)
        Const carriageReturn As Char = ChrW(13)

        Dim table As New DataTable()
        Dim generate As Boolean = True

        table.BeginLoadData()

        For Each line As String In Clipboard.GetText.Split({lineFeed, carriageReturn}, StringSplitOptions.RemoveEmptyEntries)

            Dim values() As String = line.Trim.Split({tab})

            If (generate) Then
                For cell As Integer = 0 To (values.Length - 1)
                    table.Columns.Add(String.Format("C{0}", cell))
                Next
                generate = False
            End If

            table.Rows.Add(values)

        Next

        table.EndLoadData()

        Me.input.DataSource = table

    End Sub

    Private Sub Paste3()

        Const tab As Char = ChrW(9)
        Const lineFeed As Char = ChrW(10)
        Const carriageReturn As Char = ChrW(13)

        Dim data As String = Clipboard.GetText()
        Dim table As New DataTable()
        Dim generate As Boolean = True
        Dim cursor As Integer = 0
        Dim position As Integer = 0
        Dim cell As Integer = 0
        Dim row As DataRow = Nothing

        table.BeginLoadData()

        While (cursor < data.Length)

            Select Case data.Chars(cursor)

                Case tab, carriageReturn

                    If (generate) Then
                        table.Columns.Add(String.Format("C{0}", cell), GetType(String)).Caption = cell.ToString()
                    End If

                    If (cell = 0) Then
                        row = table.NewRow()
                    End If

                    row.Item(cell) = data.Substring(position, (cursor - position))

                    cell += 1
                    cursor += 1
                    position = cursor
                    Continue While

                Case lineFeed

                    If (Not row Is Nothing) Then
                        table.Rows.Add(row)
                        row = Nothing
                    End If

                    cell = 0
                    cursor += 1
                    position = cursor
                    generate = False
                    Continue While

                Case Else

                    cursor += 1
                    Continue While

            End Select

        End While

        table.EndLoadData()

        Me.input.DataSource = table

    End Sub

End Class


First of all, this is too big for one function. You have 7 levels of indentation. Split it up, or remove levels.
Second, you say "I think this is inefficient". Why? Have you timed it? How long does it take? How long do you think it should take? It is a bad idea to try to speed things up before measuring--maybe there is no problem. Maybe some other part of your program is the slow part.
If you are trying to figure out how to make your program efficient, you normally. only need to loop at the for loops:
for pattern in (horizontals + verticals + diagonals):
    for losing_pattern in losing_three:
        for i in range(9):

It should take (8 * 3 * 9)=216 iterations. Actually less, because you have if branches, but that's the maximum. You could make this smaller, yes (both of the two inner loops can be removed). But also, 216 iterations is just not that many--your computer executes a billion operations per second.
You should remove your third for loop, and every use of id, because it is confusing and hard to read, not because it's a loop.


Error and initial check

I recommend to substitute $1 with $@, so that if you ever forget to quote it will still print the complete message.

err ()
{
  echo "redo: error: $@"
  echo "redo: usage: redo <migration_name>"
  exit 1
}

I am not sure why you put the usage in that function, since if there is no database, this does not help anyone.

[[ -d ./db/migrate ]] || err "dir db/migrate not found"

You also may want to check if you have too few/many arguments.

[[ -z $1 ]] && err No argument!
[[ $# -gt 1 ]] && err Two many arguments!

Finding the migrations

I recommend not using sed to truncate your pathnames. I also think it is completely superfluous since your trapping a few things later on and can simply ignore the prefix. You also do not need to use grep, find should be able to do that on his own. Hence instead of

migrations=$(find './db/migrate' -name '*.rb' | grep "$1" | sed 's#^\./db/migrate/##')

simply use

migrations=$(find './db/migrate' -name "*$1*.rb")

At this point I would check if it actually found anything, too.

[[ -z $migrations ]] && err I don't know what you are talking about.

Note that I omitted the quotes to make the point raised above.

Creating the array

I recommend not using times as a variable name, because there is a built-in bash command of the same name.
You can use avoid that echo |sed construct by using the build-in regular expressions comparison operator =~.

Since I don't know the exact form how the migrations are written, I can only assume that a migration comes in the form ./db/migrate/YYYYMMDDHHmmSS_name.rb. Where the timestamp is obviously just numbers, but name can be anything.

declare -A migration_times
for select_migration in $migrations; do
    pattern="([0-9]+)_([^\.]+)\.rb"
    if  [[ $select_migration =~ $pattern ]]; then
        migration_times["${BASH_REMATCH[2]}"]="${BASH_REMATCH[1]}"
    fi
done

That shortens your code quite considerably and should make it more effective since you are not calling another program.

Executing command or listing migrations

If the array does only have one element then you don't need to read the whole pair, you can simply use the value the complete array evaluates to, saving you the lines with reassigning the names. You can also skip the exit 0 statement because that would overwrite the exit status of your external call. You can tie the listing with an else statement to the conditional.
I also used printf to give it a nicer look if the length of the names vary %-10s has to be adjusted to your needs.

if [[ ${#migration_times[@]} == 1 ]]; then
    echo "redo: executing 'bundle exec rake db:migrate:redo VERSION=${migration_times[*]}'"
    # bundle exec rake db:migrate:redo VERSION=${migration_times[*]}
else
    echo "redo: be more specific, candidates are:"
    for element in "${!migration_times[@]}"; do
        printf "%-10s : %s\n" $element ${migration_times[$element]}
    done
    exit 1
fi

I think you can also easily migrate the changes from your answer to this review.


Use standard #include guards, not the non-standard #pragma once.
Use standard data types, not DWORD.
Change

this:

static const int NO_ERR = 0;
static const int CAR_IS_BUSY = 1;
static const int DRIVER_IS_BUSY = 2;
static const int NO_DRIVER_FOUND = 3;
static const int CAR_IS_BROKEN = 4;

into an enum:

enum CarStatus { NO_ERROR, CAR_IS_BUSY, DRIVER_IS_BUSY, NO_DRIVER_FOUND, CAR_IS_BROKEN };

DoMainProcessing is a horrible name and sounds like a function that does way too much. (Update: Okay, that's part of the exercise. Oh, well.)
Consider typedef std::shared_ptr<Car> CarPtr or something, to make the code less cluttered.
Avoid bool in interfaces, as it leads to poor readability and is error prone.

Instead of:

int SetDriverStatus(DWORD driverID, bool onVacation, bool isSick);

Use an enum indicator (or a string) instead:

enum DriverStatus { /* ... */ };
void SetDriverStatus(DriverID driver, DriverStatus newStatus)
{
    // ...
}

The function should be void. (If you are currently returning the old state: Stop doing that, and have a separate function for that. If you are returning a status number to indicate success or not: Use exceptions instead.)

You should probably use the C++ threading library instead of your CreateMutex. (Update: Again, your exercise hinders you from doing the right thing.)
Your use of for_each should be substituted with a range-based for loop.
The exercise states:

  There must be some function, we call it DoMainProcessing, that periodically
  gets called by an external source using the emulator (for example, every second or two).
  It should detect when the driver made the carriage of the customer (depending
  distance and average speed) and is ready to perform the next one. Then, it should
  repair the broken car (subject of availability of sufficient
  number of funds).

The way I understand this, you should update the state of each of your cars and drivers in this function. You should probably record the time between each call, and add the distance traveled to a counter.

Very roughly something like this:

void TaxiPark::DoMainProcessing()
{
    // Use a real library for time, I'm just illustrating.
    Time now = getTime();
    TimeDiff time_difference = now - previous_processing_time;
    previous_processing_time = now;

    for (auto& driver : Drivers) {
        driver.update(time_difference);
    }

    // Updates for cars ...
}

Then, in Driver::update(), you should increase distance traveled based on speed and time difference. If the distance is greater than or equal to the distance of the current ride, the ride is done. Do other state updates as necessary.


Indeed the cases for delete can be reduced.

  public void delete(Node node) {
    Node prior = null;
    Node current = head;
    while (current != node && current != null) {
      prior = current;
      current = current.next;
    }
    if (current != null) {
      if (prior == null) {
        head = current.next;
      } else {
        prior.next = current.next;
      }
      --size;
      if (current == tail) {
        tail = prior;
      }
    }
  }

In general one would keep Node an internal non-public class, for instance one would not
like people to play with the next field. Hence I would propose:

  public void delete(int value) {
    Node prior = null;
    Node current = head;
    while (current != null && current.value != value) {
      prior = current;
      current = current.next;
    }
    if (current != null) {
      if (prior == null) {
        head = current.next;
      } else {
        prior.next = current.next;
      }
      --size;
      if (current == tail) {
        tail = prior;
      }
    }
  }

For the rest:

A tab of 4 spaces is still my favorite, probably still mainstream.
iterator is an unlucky naming, as there exist an Iterator in java, with a collection method iterator(). I used current.

And (as goodie) what about System.out.println(list);:

@Override
public String toString() {
    StringBuilder sb = new StringBuilder("[");
    Node current = head;
    while (current != null) {
      if (sb.length() >= 1) {
          sb.append(", ");
      }
      sb.append(current.value);
      current = current.next;
    }
    sb.append("]");
    return sb.toString();
}


1. Code review

There's no documentation. What do the functions do, what arguments do they take, and what do they return?
The code is not portable to Python 3.
The program has code at the top level, which makes it inconvenient to test from the interactive interpreter, because as soon as it imports the module the code runs. Better to encapsulate the top-level code within a function.
The program uses a global variable, pack_bag.max_weight. Global variables make code inconvenient to test, because you have to get the globals into the right state before running each test case. It is more convenient (and more robust) to encapsulate all the state inside a function or object.
item_efficiency doesn't use the name of the item. It's conventional to indicate unused values in tuple unpacking by using the name _. Alternatively, you could use a collections.namedtuple and then you'd be able to write item.weight and item.value.
Use sorted(..., reverse=True) rather than reversed(sorted(...)).
As noted by Janne Karila in comments, itertools.takewhile stops as soon as it encounters an item for which pack_bag returns False, but there might be (less efficient, but lighter) items which can still be packed. This could be fixed by using filter instead of takewhile.

2. Revised code

from collections import namedtuple

Item = namedtuple('Item', 'name weight value'.split())

ITEMS = [
    Item("map", 9, 150),
    Item("compass", 13, 35),
    Item("water", 153, 200),
    Item("sandwich", 50, 160),
    Item("glucose", 15, 60),
    Item("tin", 68, 45),
    Item("banana", 27, 60),
    Item("apple", 39, 40),
    Item("cheese", 23, 30),
    Item("beer", 52, 10),
    Item("suntan cream", 11, 70),
    Item("camera", 32, 30),
    Item("t-shirt", 24, 15),
    Item("trousers", 48, 10),
    Item("umbrella", 73, 40),
    Item("waterproof trousers", 42, 70),
    Item("waterproof overclothes", 43, 75),
    Item("note-case", 22, 80),
    Item("sunglasses", 7, 20),
    Item("towel", 18, 12),
    Item("socks", 4, 50),
    Item("book", 30, 10),
    ]

def efficiency(item):
    """Return efficiency of item (its value per unit weight)."""
    return float(item.value) / float(item.weight)

def packing(items=ITEMS, max_weight=400):
    """Return a list of items with the maximum value, subject to the
    constraint that their combined weight must not exceed max_weight.

    """
    def pack(item):
        # Attempt to pack item; return True if successful.
        if item.weight <= pack.max_weight:
            pack.max_weight -= item.weight
            return True
        else:
            return False

    pack.max_weight = max_weight
    return list(filter(pack, sorted(items, key=efficiency, reverse=True)))

Note that in order to allow pack to modify max_weight each time it is called, I've stored the value as an attribute. This is a slightly ugly workaround that's necessary in Python 2. In Python 3 one would just use a nonlocal statement to give the pack access to the variable max_weight.

3. Algorithm

Your program implements the well-known "greedy approximation algorithm" for the knapsack problem (first described by George Dantzig in 1957).

As the name says, this is an approximation algorithm: that is, it does not always return the best solution. For example, when max_weight=80 the greedy algorithm (as implemented above) picks the following items, with total value 430:

map                     9  150
glucose                15   60
suntan cream           11   70
note-case              22   80
sunglasses              7   20
socks                   4   50
TOTAL                  68  430

But the following choice of items has total value 445:

map                     9  150
compass                13   35
glucose                15   60
suntan cream           11   70
note-case              22   80
socks                   4   50
TOTAL                  74  445

So even in small examples like this, you really do need to use the tabular method (aka "dynamic programming") to get the best answer. See this answer for one way to implement it in Python.


Is there a better way to output a javascript array from ASP.net?

With a bit of help from System.Linq this becomes quite easy.

var array = [ <%=
    string.Join(",", items.Select(v => "'" + v.ToString() + "'").ToArray())
%> ];


the goal of this code is not to check if a document has a valid BSON syntax

But that's the first requirement of a formatter, understanding the syntax. For any formatter to work, it must understand the structure of the input. For instance, if I stick a { inside some random string, how would case "{": tell it apart from a structural {?

So in some form, your parser, no matter how simple, would need to know about some of these rules. You don't need to build a robust parser, you just need to know where the current character is based characters already encountered.

You can use JSON's flow diagrams as a guide to know when it's possible to encounter such characters. You just need to extend it for BSON. Also, here's a simple JS comment remover which removes comments from JS without having to understand the entire JS syntax. In a gist, it went through the string, checking the current character against the current state (i.e. am I in a string, a regexp, comment, etc.) then modifying the code accordingly as it went through.


Instead of var GameLoop = function() { ... };, you could just define a function the "natural" way.  Calling it gameLoop() would respect capitalization conventions better.

You neglected to use the var keyword when defining delta, so it becomes a global variable.

The GameLoop() function sets fps as a side-effect.  If you don't actually need fps anywhere else, then it should be local.  Furthermore, if you don't need fps, then there is no point in setting it to the reciprocal of delta.

I don't see much harm in initializing lastCalledTime right away, to eliminate the one-time-use special case inside GameLoop() — even if you technically didn't call GameLoop() at the time.

Calling getTime() twice is ugly.  If might also cause a tiny bit of clock skew.

var lastCalledTime = new Date().getTime();

function gameLoop() {
    var now = new Date().getTime();
    var delta = (now - lastCalledTime) / 1000;
    lastCalledTime = now;

    hp -= 0.5 * speed * delta;
};

Alternatively, if you would like lastCalledTime neatly tucked inside the gameLoop() function rather than dangling outside, you could write:

function gameLoop() {
    var now = new Date().getTime();
    if (!arguments.callee.lastCalledTime) {
        arguments.callee.lastCalledTime = now;
    }
    var delta = (now - arguments.callee.lastCalledTime) / 1000;
    arguments.callee.lastCalledTime = now;

    hp -= 0.5 * speed * delta;
};


One simple way to improve this is to package it in a function, and return (or throw an exception) after each $strErrMsg = ... line. This will flatten the function, and allow you to put the main functionality at the "top level" of the function.

Even better might be to move all the validation code to a separate function that throws an exception, and then handle it in the function that called it with the wrong parameters.


Instead of making a function that maps a number from 1 to 52 you can reduce your domain to 1 to 13, and use modulo 13 to every number. That will reduce 75% of your conditions. It is done with a bit of modulo math.
Then this function becomes quite short:

def getPoints(n):
    n = (n-1) % 13 + 1
    #the ace values
    if n == 1:
        return [1,11]
    #the regular card values
    if 2<=n<=10:
        return [n]
    if 11<=n<=13:
        return [10]


RadixSet - a growing-only radix/patricia tree

As Olzhas Zhumabek mentioned in the comments, the allocation and de-allocation is poorly done and cause undefined behavior, which will most likely cause a segmentation fault.

First, the allocation in the insert function: every time you insert, you're overwriting the previous node with the line node->children[c] = new radixset;, and it's a bug that your tests do not cover (happens in the case of inserting two words with the same prefix), so you haven't noticed it. Also, it would be better to allocate all the children upfront to avoid pointing to garbage; so, the insert function becomes:

void insert(std::string str) {
   radixset* node = this;
   for (unsigned char c : str) {
      if (node->children == nullptr) {
         node->children = new radixset*[256];
         for (auto i = 0; i < 256; i++) {
            node->children[i] = new radixset;
         }
      }
      node = node->children[c];
   }
   node->isword = true;
}

Then, the de-allocation. Whenever you allocate using new[] you must de-allocate using delete[], and not just delete. The allocations to the recursive radixset structure do not use the subscript allocation, so their delete also do not use the subscript.

~radixset() {
   if (children != nullptr) {
      for (auto i = 0; i < 256; i++) {
         delete children[i];
      }
      delete[] children;
   }
}

And don't forget to add the non-tested case to the test cases! (Note: I have changed the tests from cassert to GoogleTest).

TEST (RadixSetInsert, MatchingPrefixLongerFirst) {
   radixset r = radixset{};
   r.insert("abc");
   r.insert("ab");
   ASSERT_TRUE(r.contains("ab"));
   ASSERT_TRUE(r.contains("abc"));
}

TEST (RadixSetInsert, MatchingPrefixShorterFirst) {
   radixset r = radixset{};
   r.insert("ab");
   r.insert("abc");
   ASSERT_TRUE(r.contains("ab"));
   ASSERT_TRUE(r.contains("abc"));
}

Actually, the memory usage for sparse data sets is way too much in this implementation. To avoid allocating too much and still not pointing to garbage, point to nullptr and allocate as needed:

if (node->children == nullptr) {
    node->children = new radixset*[256];
    for (auto i = 0; i < 256; i++) {
        node->children[i] = nullptr;
    }
}
if (node->children[c] == nullptr) {
    node->children[c] = new radixset;
}

And check for nullptr properly when deleting the children members.


I don't want to sound harsh, but the code is useless. On top of that, the singleton seems to be slightly off in this situation. You should have a function which is a friend to the class and has static local variable and then simply return reference to it. The class itself should have private constructor, so that only the specified function can instantiate it.

Why?

Because it is not thread safe
Because it is singleton
Because only one message is supported at a time
No real way to retrieve the message as string (companies will need a person who looks at the monitor)
Memory leak

Alternative:

CustomStream& debugStream()
{
    static CustomStream stream;
    return stream;
}

where CustomStream is thread safe stream possibly inhertied from std::ostream. Do note that static variables are initialized in a thread safe way only from C++11 and forward (there might be some compiler extensions that allow it prior to C++11).


Block Allocation in Fixed-Size Block Allocator

These comments all have to do with optimization, not "logic holes."  Also, they are written without having tested them.  Obviously you'll want to both ensure correct function, and profile to see if they actually improve anything.

1) As an obvious first step:

xorq %rcx, %rcx

can be done as

xorq %ecx, %ecx

It produces the same effect, but it's 1 byte shorter.

2) It looks like you are using notw %dx (in 2 different places) to see if dx is 0xffff?  I might try cmp $0xffff, %dx instead.  It's 2 bytes longer, but you don't have to "put it back" if it's not (the extra notw %dx costs 3 bytes).

3) (Check me on this one) You are using movslq %edx, %rcx to move edx to rcx.  However because of how you populate edx, I believe it already clears the upper bits.  Such being the case, a simple movq %rdx, %rcx might suffice.

4) The __ZN10Superblock11alloc_blockEv.i_pubchalloc loop should probably have a pause inserted.  Perhaps something like this:

__ZN10Superblock11alloc_blockEv.i_pubchalloc2:
  pause
__ZN10Superblock11alloc_blockEv.i_pubchalloc:
  movq 16(%rdi), %rax
  // if this->last_publicly_freed_block == NULL
  testq %rax, %rax
  jz __ZN10Superblock11alloc_blockEv.i_pubchalloc2

See the docs on pause for why this is a good idea.

These are all pretty nitpicky.  Since there's only the 1 loop, there's just not that much to optimize.


Enable warnings

The -Wall on GCC leads to:

reverse.c:10:13: warning: unused variable ‘i’ [-Wunused-variable]

Do not repeat yourself

You check pos > MIN_CHAR in two places. This could be done only once:

    if (pos > MIN_CHAR)
    {
        if(isspace(input[pos])) // case when space is found
        {
            end = pos-SPACE;
            reverseword(start,end,input);
            start= pos+SPACE;
        }
        if(input[pos+NEXT]=='\0') // case for last world
        {
            end =pos;
            reverseword(start,end,input);
        }
    }

Be consistent in your code style

The code style seems a bit inconsistent. For instance, sometimes you have whitespaces before "=", sometimes after, sometimes both, sometimes none... You'll find various coding styles online and different tools to check you code compliancy.

Declare variables in smallest possible scope

I find it a good habit to define variable in the smallest scope in order to make things easier to track. In your case, temp could be declared inside the loop.

Getting rid of the your #define-d values

All your values (except for MAX) could be removed because the link between the name and the value is hard to understand at first.:w

So far, I've got:

#include<stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX 100

void reverseword(int start, int end, char *input)
{
    while (end > start)
    {
        char temp = input[start];
        input[start] = input[end];
        input[end] = temp;
        start++;
        end--;
    }
}

int main()
{
    // Updated for testing purposes
    //        char input[MAX];
    //        scanf("%[^\n]",input);
    char * original = "this is code review";
    char * input = strdup(original);
    printf("%s\n", input);
    int pos;
    int start = 0;
    for (pos = 0 ; input[pos] ; ++pos)
    {
        if (pos > 1)
        {
            if (isspace(input[pos])) // case when space is found
            {
                int end = pos-1;
                reverseword(start, end, input);
                start = pos + 1;
            }
            if (input[pos+1] == '\0') // case for last world
            {
                int end = pos;
                reverseword(start, end, input);
            }
        }
    }
    printf("%s\n", input);
}

Typo: You meant "word", not "world"

Not much to add here.

Handle the last word at the end

You can handle the final case the end. Then you can merge the condition check togetherin the loop.

Bug found

We have the following behaviors:

"a this is code review" -> "siht a si edoc weiver"
" a this is code review" -> "a  siht si edoc weiver"

I have to go, I'll try to continue asap.


Enhance the performance of the source code in Java

Exceptions used for control flow

inputFile = new File(args[0]);

Using exceptions for the control flow in your program is harmful for the speed of executing. When making a exception, much of the time is spent on constructing the stack trace.

if (args.length == 0) {
    System.out.println("Usage: java -jar program.jar <filename>");
    return;
}

Using unbuffered IO

FileReader reader = new FileReader(inputFile);
while((read = reader.read(charBuffer)) != -1) {

You are using unbuffered IO, this means for every call to the read() method, a call will be dispatched to the underlying file system to read 1 byte. Wrapping the FileReader in a BufferedReader increases the performance, and gives you access to prebuild methods such as nextLine

BufferedReader reader = new BufferedReader(new FileReader(inputFile));

You are trying to reimplement the wheel with your loop

while((read = reader.read(charBuffer)) != -1) {
        for (int i = 0; i < read; ++i) {
            char c = charBuffer[i];
            if (c == '\r' || c == '\n') {
                if (token.length() != 0) {
                    // read date
 ...
                }
            }
            else if (c == ' ') {
                // flush token
                if (tokenIndex == 0) {
                    // read name
                    name = token;
                    token = "";
                    tokenIndex++;
                }
                else if (tokenIndex == 1) {
                    // read amount
                    amount = token;
                    token = "";
                    tokenIndex++;
                }
            }
            else token = token + c;
        }

The above code is pretty inefficient duo to the large amount of stringbuilder and string object created, a better way is reading a whole line using BufferedReader.readLine() and splitting that on spaces:

String line;
while((line = reader.readLine()) != null) {
    int firstSpace = line.indexOf(' ');
    int secondSpace = line.indexOf(' ', firstSpace + 1);

    String name = line.subString(0, firstSpace);
    String amount = line.subString(firstSpace + 1, secondSpace);
    String date = line.subString(secondSpace + 1, line.length());

    year = Integer.parseInt(date.substring(0, 4));
    ...
}

This also decreases the size of the actual code

Don't declare variables until you actually need them

File inputFile;
...
int read;
String token = "";
...
String name = null;
int year = -1;
int month = -1;
int day = -1;
String amount = null;

While the performance impact of this isn't that high, it makes your code look better when seeing the variables declared on the point where it is used.

Not closing your IO streams

CLosing your IO streams is important to prevent the java program from getting errors for too many open files, closing can be done by calling reader.close(), or by using a try-with-resources block.

Fixed code

After applying all the steps above, you should get a code similar to the following:

public static void main(String[] args) throws IOException {
    if (args.length == 0) {
        System.out.println("Usage: java -jar program.jar <filename>");
        return;
    }

    File inputFile = new File(args[0]);
    long start = System.currentTimeMillis();

    try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
        String line;
        while((line = reader.readLine()) != null) {
            int firstSpace = line.indexOf(' ');
            int secondSpace = line.indexOf(' ', firstSpace + 1);

            String name = line.subString(0, firstSpace);
            String amount = line.subString(firstSpace + 1, secondSpace);
            String date = line.subString(secondSpace + 1, line.length());

            int year = Integer.parseInt(date.substring(0, 4));
            int month = Integer.parseInt(date.substring(5, 7));
            int day = Integer.parseInt(date.substring(8, 10));

            // flush line
            System.out.print(name.toUpperCase());
            System.out.print(" ");
            System.out.print(amount.indexOf('.') == -1 ? true : false);
            System.out.print(" ");
            System.out.print(day < 10 ? "0" + day : day);
            System.out.print("/");
            System.out.print(month < 10 ? "0" + month : month);
            System.out.print("/");
            System.out.print(year);
            System.out.println();
        }
    }
    System.out.println ("Time taken for String in if/else if :"+ (System.currentTimeMillis() - start));
}


Quickly find percentile with high precision

Use comprehensions

I understand that my_vals is not necessarily the real data and that you might have other means to generate them, but anyway building a list using append is often an antipattern. Use a list comprehension instead:

my_vals = [np.random.normal(0.05, 0.02) for _ in range(60000)]

Same for your actual computation, you basically want to count the amount of values lower than the threshold; use a generator expression and feed it to sum:

sum(1 if x <= threshold_val else 0 for x in my_vals)

This is still \$O(n)\$ and will compute the required value right away (after dividing by len(my_vals)).

Better is to use int(x <= threshold_val) instead of the ternary. Or even the comparison directly (even if more implicit) since True + True is 2.

Use functions

In order to improve reusability and testing.

This also means that you can wrap your demo code into bits that won't necessarily be called every time. For instance:

from scipy.optimize import minimize

def compute_percentile(values, threshold):
    count = sum(x <= threshold for x in values)
    percentage = 100. * count / len(values)
    # Improve precision of the percentile
    return minimize(lambda x: abs(np.percentile(values, x[0]) - threshold), percentage, bounds=[[0,100]], method='SLSQP', tol=10e-9).x[0]

if __name__ == "__main__" :
    demo_values = [np.random.normal(0.05, 0.02) for _ in range(60000)]
    print compute_percentile(demo_values, 0.065)


What you did well

Taking advantage of the shell to split your expression into tokens is smart.  It saves you from the trouble of having to write a tokenizer.

Beware, though, of a usability issue with Unix shells, where * and \ have special significance and need to be quoted or escaped.

Bugs

Compilation error: This was just carelessness.

getop.c:31:6: error: conflicting types for 'getOp'
char getOp(const char *op) {
     ^
./calc.h:3:5: note: previous declaration is here
int getOp(const char *s);
    ^
1 error generated.

Error handling: You treat errors like warnings.  If there's an error, I would expect the program to print nothing to stdout, and for the program to exit with a non-zero status code.  Error and warning messages should be printed to stderr instead of stdout.
Picky validation: In my opinion, this should successfully evaluate to 1:

$ ./expr 1
invalid call

By the way, if you find an insufficient number of command-line arguments, just return early.

int main(int argc, char *argv[]) {
    if (argc <= 1) {
        fprintf(stderr, "invalid call\n");
        return 1;
    }

    while (--argc) {
        …
    }
    printf("%g\n", pop());
    return 0;
}

Mishandling of negative numbers: I would expect the following calculation to yield -1:

$ ./expr 3 -4 +
warning: the stack is freewarning: the stack is free-3

Unconventional division operator: It is customary to use / for division.  I don't know why you use \ instead.
Division-by-zero paranoia: In contrast to integer arithmetic, where division by zero is undefined behaviour, division by zero in IEEE 754 floating point arithmetic should just return infinity.  Perhaps you could remove the check for division by zero.

Number parsing

I suggest the following implementation for getop.c, which is simpler and handles negative numbers.

#include <ctype.h>
#include "calc.h"

static int isNumber(const char *s) {
    if (*s == '-' || *s == '+') s++;
    if (*s == '\0') {
        return 0;
    }

    while (isdigit(*s)) s++;

    if (*s == '.') {
        s++;
        while (isdigit(*s)) s++;
    }

    if (*s == 'e' || *s == 'E') {
        s++;
        while (isdigit(*s)) s++;
    }

    return *s == '\0';
}

char getOp(const char *op) {
    return isNumber(op) ? NUMBER : *op;
}


Change a string into a function/def activator

There are quite a lot of things you should do differently.

Let's start with your function random_number. You should not overwrite the string module (even though it is only locally), which you imported. You should also use list comprehensions to build the string. To pretty print the number as a phone number, use str.format. Use the fact that random.randrange takes an implicit 0 as its first argument (just like range). And finally use tuple unpacking, instead of manually indexing the list.

def random_number():
    phone_number = [random.randrange(10) for _ in range(10)]
    return "({}{}{}){}{}{}-{}{}{}".format(*phone_number)

Next, your random_keyword function. You can vastly simplify the building of random_letter by using a list comprehension again, together with str.join, to avoid costly string addition.

Your while True loop also serves no purpose, since you break it in either case.

Also, what is the point of storing something in a dictionary (with \$\mathcal{O}(1)\$ lookup time if a key is in it) and then checking to see if something is in the values, which is a list and takes therefore \$\mathcal{O}(n)\$? At this point your dictionary is just a simple list. You can access its members with numbers from 0 to len(accepted_keywords). Instead have a list of your functions and have a dictionary with their names as keys (which you can build using a dictionary comprehension).

functions = [nothing, abc, deft, ghi, jkl, mno, pqrs, tuv, wxyz]
accepted_keywords = {f.__name__: f for f in functions}

def random_keyword():
    keyword = ''.join(random.choice(string.ascii_lowercase)
                      for _ in range(random.choice([3, 4])))
    print("keyword: {}".format(keyword))
    print("*Approved*\n" if keyword in accepted_keywords else "Denied\n")

Finally, Python has an official style-guide, PEP8. It recommends using ALL_CAPS for global constants (like accepted_keywords).

Python also has a docstring convention (written down in PEP257), which in its simplest form looks something like the following:

def random_number():
    """creates a random phone number"""
    ...

At this point you should also notice that that function name is not very descriptive, maybe something like random_phone_number instead?


Running validation procedures on a table

Iterating row by row

Assuming that you want to perform the validations on the files row by row, you shouldn't be using a temporary processed column to keep track of your progress.  The feature you should be using is cursors.

DECLARE validator_cursor CURSOR FOR
    SELECT PROC_NAME
        FROM Validations_List
        WHERE [ENABLED] = 'Y' AND [PROC_INDICATOR] = 'Y';
OPEN validator_cursor;

FETCH NEXT FROM validator_cursor INTO @procName;
WHILE @@FETCH_STATUS = 0
BEGIN
    DECLARE file_cursor CURSOR FOR
        SELECT DISTINCT Field1, Field2, Field3, Field4, Field5, Field6
            FROM [FILE]
            WHERE Field2 IS NOT NULL;
    OPEN file_cursor;

    FETCH NEXT FROM file_cursor INTO @file;
    WHILE @@FETCH_STATUS <> 0
    BEGIN
        EXECUTE sp_executesql @procName, N'@keyDataRow KeyData READONLY', @file;
        FETCH NEXT FROM file_cursor INTO @file;
    END

    CLOSE file_cursor;
    DEALLOCATE file_cursor;

    FETCH NEXT FROM validator_cursor INTO @procName;
END

CLOSE validator_cursor;
DEALLOCATE validator_cursor;

Forget procedures

Using procedures is still a poor approach, though.  SQL is designed to be used to work with data sets, operating on a significant portions of a table at a time.  Instead, I see a lot of one-value-at-a-time operations, in which you are working very hard to defeat the power and the purpose of SQL.

For example, the sp110_v1 validation should just be

INSERT INTO FailedValidations
    SELECT DISTINCT Field1, Field2, Field3, Field4, Field5, Field6, vl.Message
        FROM [FILE] wf, Validations_List vl
        WHERE
            vl.Validation_ID = 110
            AND vl.[ENABLED] = 'Y'
            AND wf.Field2 IS NOT NULL
            AND wf.RecordType = '04'
            AND ISNUMERIC(SUBSTRING(wf.Row, 108, 10)) <> 1;


Turning an array of words into a random license plate

A few suggestions, and then I'll get to how to test it:

Don't be afraid of whitespace -- your code is a little hard to read due to the lack of new lines.  Also, it's fairly standard to indent method names inside of classes.
Always use descriptive names: String[] a tells me nothing about what that parameter is.
When x is a bool, x == true is equivalent to x.

On an extremely picky note, contains seems like a more natural variable name for contain (grammatically anyway)

It doesn't really matter when there's only 4 characters (so 4 * A.length runs), but when doing a linear comparison, you should typically bail out of it with break or continue

Also, you might want to look into indexOf, contains and equalsIgnoreCase

Obviously this is just a little homework assignment, so it would be a bit overkill, but I would put the license plate generation in its own class in a real application.
I would also pass the banned words as a parameter to the constructor instead of to a method -- that allows your instance to carry around the words without any farther down consumers having to know what the words are

Imagine that you make a machine that's used in the DMV.  Imagine that this machine has a "generate license plate" button.  When pressed, a screen simply shows the plate.

Passing the words to the method is like having to key in the banned words every time the button is pressed -- the DMV employee shouldn't be responsible for knowing/controlling those words
Storing the words inside of an instance (whether set with a setBannedWords method or passed to the constructor) is like configuring the machine at creation.  The DMV employee no longer has to know what the words are, or be responsible for entering them.  Years could go by before an employee realized "Oh my, I just noticed that the machine has never output a cuss word!"
For completeness: A third option would be to not filter the words -- it would then be up to the employee to go "Hrmmm, 'FART 743' is probably a bad license plate."

Ok, so does this work?  Probably.  It looks correct to my rusty-with-Java-eye anyway.

The easiest way to test it would probably be to whittle down the set of possible characters from A-Z to A-D and then make ABC a bad word.  After a lot of test runs, you could be fairly certain that it was throwing out any ABCX or XABC.

This just made me realize: did your professor specify that the bad words would always be four characters?  If not, your code is wrong.

So how could this be tested more properly-ish?  Unfortunately it requires that the code become a lot longer.  Your professor would probably think you got a bit carried away if you truly made this testable.  Despite a fairly simple requirement, to test this with granularity would require breaking it down into quite a few pieces.

I can code this up if you want, but for the sake of brevity and time, I'll just describe it here.

The main problem with testing this is that all of the concerns are mixed together.  You have a few concerns:

Generating a license plate

Generating the text part
Generating the number part

Filtering a license plate

Note that separating this concerns allows you to test them independently.

"Does my class properly generate and filter license plates?" becomes "Does class X properly generate license plates?  Does class Y properly filter license plates?"

The second option is easier to test because it allows you to pass in a license plate generator that is rigged to generate bad words.

The text and number generation should arguably be separated.  That would allow for easily reusing generated numbers when a bad word is in the word part, but other than that, the added complexity would probably not be worth it.

One option would be to use an interface:

public interface LicensePlateGenerator {
    public String generateLicensePlate();
}

You could then have your classes implement it:

public class LicensePlateGeneratorRandom implements LicensePlateGenerator {

    private final lchar[] = {'A', 'B', 'C', ...};

    private final nchar[] = {'0', '1', '2', ...};

    public String generateLicensePlate() {

        //Randomly grab 4 lchars
        //Randomly grab 3 nchars

    }

}

public class LicensePlateGeneratorFiltered implements LicensePlateGenerator {

    private final LicensePlateGenerator gen;
    private final List<String> badWords;

    public LicensePlateGeneratorFiltered(LicensePlateGenerator generator, List<String> badWords) {

        this.gen = generator;
        this.badWords = badWords;

    }

    public String generateLicensePlate() {

        //It might be a good idea to test how many plates have already been generated
        //An infinite loop of generating could happen depending on the underlying generator
        //and what kind of badWords are defined

        String lp;

        do {
            lp = gen.generateLicensePlate();
        } while (isBad(lp));

        return lp;

    }

    private boolean isBad(String lp) {
        //Return false if lp contains any badWords
        //and true otherwise
    }

}

Note how this is transparent to any consuming class.  A consuming class doesn't need to know whether it has a LicensePlateGeneratorRandom or LicensePlateGeneratorFiltered; it just needs to know it has a LicensePlateGenerator.

Note that this allows you to test very easily.  Testing your random generator means just checking a few outputs.  Checking your filter could be done by rigging a generator:

(I would probably define this as an anonymous class in actual testing code, but my Java is too rusty to remember the syntax for that :p)

public class LicensePlateGeneratorFake implements LicensePlateGenerator {

    private final List<String> words;
    private Iterator<String> currentPos;

    public LicensePlateGeneratorFake(List<String> words) {
        this.words = words;
        currentPos = this.words.iterator();
    }

    public function generateLicensePlate() {
        if (!currentPos.hasNext()) {
            //Something should happen here...
            //could always just loop back around, or it
            //might also be worth considering having the interface
            //declare a certain exception as being possible in this method.
            //(That would also allow a way out of the infinite loop in the
            //(filter generator)
            //throw new LicensePlateGeneratorException("...");
            //(that could be the base class, and then a LicensePlateGeneratorInfiniteLoopException
            //could be thrown in the filter class)
        }
        //Obviously the end of the iterator should be checked, but I'm lazy
        return currentPos.next() + " 123";
    }

}

You then configure this fake generator to generate a certain stream of words ("ABCD", "DCBA", etc).  Then, you pass this fake generator to the filter, and give the filter a list of words you know that the fake generator will generate.

If you tell the fake generator to generate "ABCD" and you tell the filter to reject "ABCD", you can then test success by whether or not the filter generator returns "ABCD" in any of the generations.

An alternative approach would be to have the filter not be a generator.  Instead, your consuming code would be responsible for configuring its own filters and then generating plates until a suitable one is found.

Both designs have fairly strong pros and cons.

(Note: I completely bastardized the class names in my examples.  In a real application, namespaces should be used.  The code formatting on here makes namespaces a bit clumsy though, so I didn't use them.)


SearchActivity to search through an ArrayList

Once is enough of bundle.getParcelableArrayList("chords")

I'm not sure if bundle.getParcelableArrayList creates a new list every time it's called. If it doesn't, then repeated calls won't double the memory used so it won't really be a problem.
But in any case, you don't need to call it twice like this:

chords = bundle.getParcelableArrayList("chords");
filteredList = bundle.getParcelableArrayList("chords");

You can make filteredList reference chords:

filteredList = chords = bundle.getParcelableArrayList("chords");

Use interfaces in declarations

These fields would be better declared as List instead of ArrayList:

ArrayList<Accordo> chords;
ArrayList<Accordo> filteredList;

Just like you used List instead of ArrayList in the filter method.

Also, probably all fields of the activity should be private.

Reduce memory churn

Every time the query text changes,
you recreate a new list,
and re-link the adapter to the new list.
It might be more efficient to reuse the same list,
by clearing and re-adding elements instead of creating a new list.
However,
there is just one tricky point,
of the initial state when there is no filter yet.
The adapter could initially be linked to chords,
and then the first time a query text is entered,
re-link it to filteredList, for example:

@Override
public boolean onQueryTextChange(String newText) {
    if (filteredList == null) {
        // first time used
        filteredList = new ArrayList<>();
        adapter.setFilter(filteredList);
    }
    filter(newText);
    return true;
}

private void filter(String query) {
    query = query.toLowerCase();

    filteredList.clear();
    for (Accordo model : chords) {
        final String text = model.getName().toLowerCase();
        if (text.contains(query)) {
            filteredList.add(model);
        }
    }
}

Notice some other related changes:

I dropped the list parameter of filter: the filtering is always based on chords, which is a field, so the method has direct access to it, no need to pass as parameter
Made filter return void, as now it modifies filteredList in-place


Takes a string array and searches for two words that are anagrams of each other

In isAnagram one should start local variables with a small letter (just a convention).
Do not use if-else to return a boolean.

public static boolean isAnagram(String str1, String str2) {
    String s1 = str1.replaceAll("\\s", "");
    String s2 = str2.replaceAll("\\s", "");
    boolean status = true;
    if (s1.length() != s2.length()) {
        status = false;
    } else {
        char[] arrayS1 = s1.toLowerCase().toCharArray();
        char[] arrayS2 = s2.toLowerCase().toCharArray();
        Arrays.sort(arrayS1);
        Arrays.sort(arrayS2);
        status = Arrays.equals(arrayS1, arrayS2);
    }
    return status;
}

However if you think of an anagram as a form of sorted string, one could introduce either a type Anagram, or - here - a function deriving such a sorted string: here canonicalForm.

public static boolean isAnagram2(String str1, String str2) {
    return canonicalForm(str1).equals(canonicalForm(str2));
}

public static String canonicalForm(String s) {
    String cleaned = s.replaceAll("\\s", "");
    char[] chars = cleaned.toLowerCase().toCharArray();
    Arrays.sort(chars);
    return new String(chars);
}

Most important searching for anagrams can use a map from canonical value to string(s).
For ease of mapping to the original algorithm. the mapped-to value is a concatenation of anagrams:

public static String searchAnagram(String[] strings) {
    Map<String, String> canonicalToValue = new HashMap<>();
    for (String s : strings) {
        s = s.replace('\t', ' '); // Omit tabs, reserve them for our usage.
        String canonical = canonicalForm(s);
        canonicalToValue.merge(canonical, s, (oldS, s) -> oldS + "\t" + s);
    }
    return canonicalToValue.values().stream()
            .filter(s -> s.contains('\t'))
            .collect(Collectors.joining(", "));
}

I use a tab (\t) as it seems that spaces might occur in strings.
One could also use a slash (" / ").

Better yet would be to return a List<String> of anagrams, and keep a List<String> or Set<String> as map value. A TreeSet<String> would remove duplicates and is sorted.

Instead of isAnagram one only needs canonicalForm (better anagramForm?).

The complexity is reduced in code complexity, faster.
Your attempt to optimize sorting on length is just a partial optimizing, needing extra checks / not fitting entirely. By using a HashMap on the canonical form of a string,
one has exactly an immediate search result.

The solution could give "malmodera malordema marmelado melodrama, gasometro gasometro somertago".

No result as String would better be an empty String. Again a List seems more usable.


I think everything Sam Onela said is great. I'm gonna add a few more things.

Don't modify your state directly

In general, it's considered bad practice to directly modify your state object. According to the react docs:

  Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

Instead you should either

Pass setState an object with only what you want to change (I chose this)
Clone your state, modify the clone, then pass it to setState

Stop using index like that

Using index in your loops introduces another variable you don't need, and actually makes things slightly less correct.

Don't use index for key prop

The key prop should be a unique key to identify that element.
The most unique things we have about each of these checkboxes is the name that goes with them.
If we rearranged this list, we would want the same names to stay checked, not the same indexes in the list.

Don't use index as an id

At least not directly.
You want your ids to be unique on the page, and using the ids 1, 2, 3, etc. seems like not a good way to be unique. It would be better to use something like ${checkbox}-${key} so we get "checkbox-Sonia", "checkbox-Maria", etc.

It also used to be the case that ids needed to start with a letter and not a number, but I believe this is no longer the case.

You don't need an extra data layer in your state

It just adds needless comlexity. Just put the checkbox values right in your state, and only move them when you need to do more complex things with your state.

this.state = {
  Sonia: false,
  Maria: false,
  John: false,
  Michael: false
};

handleClick can be way simpler

One line in fact:

handleClick(key) {
    this.setState({ [key]: !this.state[key] });
}

Heck, it's so small that I would probably even put it inline, but different people might disagree on that.

Revised Version

Here's what my revised version of the code would look like:

class App extends React.Component {
  constructor(props) {
    super(props);
    // I guess you don't have props, so it doesn't really matter,
    // but you need to pass them to `super()` if you want them
    // to be available on `this.props`

    // Doesn't need the extra `data` layer
    this.state = {
      Sonia: false,
      Maria: false,
      John: false,
      Michael: false
    };
  }

  // handleClick was inlined

  render() {
    return (

        <form>
          {Object.keys(this.state.data).map((key) => (

              <input
                name={key}
                id={`checkbox-${key}`}
                type="checkbox"
                checked={this.state.data[key]}
                onChange={() => this.setState({ [key]: !this.state[key] })}
              />

                {/* Don't need a `key` prop here */}
                <label htmlFor={`checkbox-${key}`}>
                  {key}

          ))}
        </form>

Current State:

            {Object.keys(this.state).map(key => (

{`${key}: ${this.state.data[key]}`}

            ))}

    );
  }
}

Note that this does still use an arrow function and not a bound method.
I think that this lets to code be much more readable, and the possible performance loss wouldn't be realized until you have components that implement PureComponent deeper in the call chain receiving this function (currently it goes directly to an <input>.


Container that holds objects of various types, and can be searched for an object convertible to a given type

You said you implemented

  a container that can hold objects of various types, and look
  up an object convertible to a given type

This idea can be simplified and generalized: we want to

  look up an object convertible to a given a type in a sequence of variants

We can focus on the get function and strip everything else.  The container does not have to be a std::vector<std::variant> — we can use iterators:

template <typename T, typename ForIt>
T get_convertible(ForIt first, ForIt last);

In the code, you want to find an element that is convertible to T, and throw an exception if such an element is not found.  You used std::optional to conditionally return the visited element.  This overhead can be eliminated:

template <typename T, typename ForIt>
T get_convertible(ForIt first, ForIt last)
{
    auto it = std::find_if(first, last, [](const auto& variant) {
        return std::visit([](const auto& value) {
            using U = std::decay_t<decltype(value)>;
            return std::is_convertible_v<U, T>;
        }, variant);
    });

    if (it == last) {
        throw std::runtime_error{"..."};
    } else {
        return std::visit([](const auto& value) -> T {
            using U = std::decay_t<decltype(value)>;
            if constexpr (std::is_convertible_v<U, T>)
                return value;
        }, *it);
    }
}

(live demo, includes code to disable return warning)


Your insertionSort() is OK, but I would write:
template<std::forward_iterator Iter>
void insertion_sort(Iter first, Iter last) {
    for (Iter it = first; it != last; ++it)
        std::rotate(std::upper_bound(first, it, *it), it, std::next(it));
}

insertion_sort(v.begin(), v.end());

display() copys your vector, so make the parameter as const (lvalue) reference.
Use ranged-for loop for printing:
for (auto n : vec) {
    std::cout << n << ' ';
}
std::cout << '\n'; // don't use std::endl

Or you can use one-liner
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, ' '));


Python function to get numbers around another number

Your code seems really complicated, and so you should follow KISS and YAGNI.
max_num and min_num don't work the way I would expect them to.
The error goes against what I think is Pythonic. Just return the smaller set.

def get_numbers_around(number, size):
    return range(number - size, number + size)

If you then need to implement min_num and max_num create a filter:

def filter_between(values, minimum=float('-inf'), maximum=float('inf')):
    return (v for v in values if minimum <= v <= maximum)

>>> get_numbers_around(4, 5)
range(-1, 9)
>>> list(filter_between(_, 0))
[0, 1, 2, 3, 4, 5, 6, 7, 8]


If shape and number of polygons do not change (or at least not often), I would add an extra step (the new first step) to your algorithm.

Calculate the center and radius of the smallest surrounding circle for each polygon. This way you can calculate in a minimal and maximal distance of all vertices from the given position in one run without iterating through them.

If the minimum distance for a polygon is greater than the maximum of an other polygon, no vertex of that polygon can be the nearest => we can ignore this polygon.

Than proceed like you did before.

calculate distance to each polygon surrounding circle and eliminate all polygons which are too far away to be a match
Entity: performs a loop through all not eleminated polygons.
Polygon Loop: loops through ALL vertices of the polygon in the current iteration.
Vertex Loop: if the distance between the entity and the current vertex is lower than the distance between the entity and the previous vertex, save the current vertex and the ID of the polygon the vertex belongs to.
Once all loops are finished, take the nearest polygon/vertex and get the vertex of the polygon to the left and right of the nearest vertex.
Check the left and right vertices to see which is closest to the nearest vertex. Doing so, finds the nearest line of collision to the entity.


Extracting and mangling a parameter from a MySQL configuration file

Aside from not using a constant for RETURN_PATH (which is obviously wrong and will cause Ruby to warn you), it seems reasonable enough to me.


Converting a binary string to hexadecimal using Rust

A couple of things:

Any time you have a function which could fail, it should return an Option<T>.  Ask yourself, if someone calls convert_to_hex_from_binary("foobar") and gets back "", is that reasonable?  They will need to manually check that their input makes sense, or that the output makes sense every time.  Static checking of these errors is part of the joy of Rust.

With that it mind, change to_hex like so:

fn to_hex(b: &str) -> Option<&str> {
    match b {
        "0000" => Some("0"),
        "0001" => Some("1"),
        "0010" => Some("2"),
        "0011" => Some("3"),
        "0100" => Some("4"),
        "0101" => Some("5"),
        "0110" => Some("6"),
        "0111" => Some("7"),
        "1000" => Some("8"),
        "1001" => Some("9"),
        "1010" => Some("A"),
        "1011" => Some("B"),
        "1100" => Some("C"),
        "1101" => Some("D"),
        "1110" => Some("E"),
        "1111" => Some("F"),
        _ => None,
    }
}

You are iterating over a known range of values to get counter.  Instead of using a while loop, you can use a range.  Since you're now returning None from to_hex you can now shortcut returning if something is wrong with None.

Your inner loop now looks like this:

let mut hex_string = String::new();
for counter in (0..padded_binary.len()).step_by(4) {
    match to_hex(&padded_binary[counter..counter + 4])
    {
        Some(converted) => hex_string.push_str(converted),
        None => return None
    };
}

Your function signature and return type also need to match Option<String>:

fn convert_to_hex_from_binary(binary: &str) -> Option<String> {
    ...
    Some(hex_string)
}

Your padded_binary definition can be simplified, since repeating "0" zero times is exactly the same as not repeating it.

The definition is simply:

let padded_binary = ["0".repeat(padding_count), binary.to_string()].concat();

A couple of non Rust specific things:

Consider writing some tests.
String representation of binary numbers often begin with '0b'.  For example 0b1101 == 13.  You might want to consider checking for this prefix on the input string and trimming it.
You may have already thought about this, but consider if you want to trim whitespace or leave it to the function caller.


The code you show is explicit about what it does, easy to read and understand. I suppose you find the usage of the valid flag error-prone in case the logic gets deeper nested, or any sort of refactoring that might forget about that flag?

When you encounter an error, you are actually doing two things : setting the valid flag to False and printing an error. One simplification would be to make a list of error messages (no valid variable), and push error messages on it. You don't print anymore, and the list of errors becomes the valid flag.

def validation_function(item):
    errors = []

    try:
        if not test1:
            errors.append("Error on test 1 for item")
        if not test2:
            errors.append("Error on test 2 for item")
    except SomeException as e:
            errors.append("Exception on whatever for item")

    # change the return type to list of errors
    # reporting errors is responsability of caller.
    return errors

You could raise an exception from inside the validation_function but I see it as a low level validation routine which collects errors and returns them. The caller is responsible for handling (raise, print) the returned errors if any.

Also, your validate_ticketer_issue is actually harmonizing errors : it leads its own set of tests but also catches exceptions raised by functions it calls and translates that to a boolean + error messages. The above example preserves that behaviour which is all right as long as you are very specific about the exceptions you catch.

Finally you could see the function as a bunch of predicates with specific error messages run one after the other.

# List of predicates and messages. Predicates must have a
# harmonized api. Note: I'm using lambdas here but regular
# functions will work too.
PREDICATES = [
    (lambda item: some_logic_here, "Error on test 1 for item"),
    (lambda item: some_other_logic_here, "Error on test 2 for item")
]

def validation_function(item):
    errors = []

    try:
        for predicate, msg in PREDICATES:
            if not predicate(item):
                # here you have to harmonize you messages
                # so that they can be formatted using the
                # same argument.
                errors.append(msg.format(item=item))
    except SomeException as e:
            errors.append("Exception on whatever for item")

    # change the return type to list of errors
    # reporting errors is responsability of caller.
    return errors

This example might seem more scalable but for a small amount of predicates, it is probably overkill as understanding the code is not obvious, logic lives in other places, and some work has to be done to harmonize predicates and their messages.

These are the few ideas I have to improve the code so that it doesn't rely on the valid flag. The second step makes it perhaps more scalable at the expense of readability.


There is an End-of-data marker FF D9, but you can't scan for it blindly, because those bytes can also appear within a JPEG image. For example, if the JPEG contains a thumbnail, then FF D9 could mark the end of the thumbnail rather than of the whole image.  In fact, the FF D8 start-of-image marker can also appear within a JPEG image for the same reason.  Therefore, your technique is invalid.

To do a proper job, you must look for JPEG markers, most of which are followed by two bytes indicating the payload size, and advance the indicated number of bytes, until you hit the FF D9 marker.  It might even be faster, since you can advance in chunks rather than scanning every byte sequentially.


Function to censor single word in a sentence

As mentioned in the comments, you could use str.replace() to replace all occurrences of a certain substring:

def censor(text, word):
   return text.replace(word, "*"*len(word))

To ensure that only entire words are replaced, though, you should use regular expressions:

import re

def censor(text, word):
    pattern = r"\b" + re.escape(word) + r"\b"
    return re.sub(pattern, "*"*len(word), text)

Unlike your original code, the regular expression solution also handles words that have punctuation attached.

Some other things to think about:

Your else: continue statement can be omitted;
Your function does not have a docstring. If you plan on making it a public function (as part of an API, for example), you should explain what arguments it expects and what it returns. If you plan on using it internally, at the very least, provide a single-line docstring explaining what the function does.
range() assumes start is 0 if no explicit start is passed, thus you can change it to for i in range(len(text_list)):


You can sort each column separately (only move the transparent value to the top of the column) with a fast sorting algorithm like merge sort:

void mergeSortBlock(int *a, int index1, int index2, int size, int transparent){
    int *result;
    int resultIndex = 0;
    int mergeIndex1 = index1;
    int mergeIndex2 = index2;

    result = new int [size*2];

    while (mergeIndex1 <= (index1 + size -1) && mergeIndex2 <= (index2 + size -1)){
        if (a[mergeIndex2] == transparent) {  // check the transparency
            result[resultIndex] = a[mergeIndex2];
            resultIndex++;
            mergeIndex2++;
        }
        else {
            result[resultIndex] = a[mergeIndex1];
            resultIndex++;
            mergeIndex1++;
        }
    }

    if (mergeIndex2 <= (index2 + size - 1)) {
        for (int i = mergeIndex2 ; i< (index2 + size); i++) {
            result[resultIndex] = a[mergeIndex2];
            resultIndex++;
            mergeIndex2++;
        }
    }
    else{
        for (int i = mergeIndex1 ; i< (index1 + size); i++) {
            result[resultIndex] = a[mergeIndex1];
            resultIndex++;
            mergeIndex1++;
        }
    }

    // copy the result back
    for (int i=0; i < size*2; i++) {
        a[index1+i] = result[i];
    }
    delete [] result;
}

void mergeSort(int *a, int indexFront,int indexEnd, int transparent){
    int size = (indexEnd - indexFront +1)/2;
    if (size > 1){
        mergeSort(a, indexFront, indexFront + size - 1, transparent);
        mergeSort(a, indexFront + size, indexEnd, transparent);
    }
    mergeSortBlock(a, indexFront, indexFront + size, size, transparent);
}

As you can see, in the mergeSortBlock function, instead of examining a[mergeIndex1]>a[mergeIndex2] you check the transparency condition.

the indexFront is the index of the first element of your array and indexEnd is the index of the last element.

Now in your main, first you need to transpose the matrix so that the ith row of the transposed matrix (called result in this example) represents the ith column of your map matrix. then call the mergeSort function for each row of the transposed matrix, Result .

int  main()
    int result[5][5];
    int map[][5] =
    {
        {0, 2, 3, 2, 0},
        {0, 1, 4, 0, 1},
        {1, 2, 2, 0, 3},
        {2, 1, 0, 0, 4},
        {4, 3, 1, 1, 3}
    };

    //transpose map => map's ith column = result's ith row
    for (int i = 0; i<5; i++)
        for (int j = 0; j<5; j++)
            result[j][i] = map[i][j];

    for (int i=0; i<5; i++)
        mergeSort(result[i],0,4,0);

    //transpose reuslt => result's ith row = map's ith column
    for (int i = 0; i<5; i++)
        for (int j = 0; j<5; j++)
            map[j][i] = result[i][j];

    return 0;
}

At the end again we need to transpose the matrix result.

Note: The complexity of merge sort is O(n.logn). You have n columns. This makes the complexity of the matrix shifter O(n^2.logn). Thanks to the nature of your problem, you can still improve this by parallel programming (of course if you have multiple processors). The complexity of transpose is O(n^2). The complexity of your own algorithm is O(n^3).

Note2: You can modify mergeSort and mergeSortBlock functions to work directly with the columns of your matrix.


Selecting element from a collection based on bitwise-and result

to_handle actually varies, but the test_consts are all constant, so we can give the compiler a hint here

const uint32_t test_const1 = Constraint3::VAL1 + Constraint3::VAL2;
const uint32_t test_const2 = Constraint1::VAL2 + Constraint1::VAL4 + Constraint1::VAL8;
const uint32_t test_const3 = Constraint2::VAL1 +  Constraint2::VAL2 + Constraint2::VAL4;

uint32_t to_handle = test_const1;
for(ConstraintsContainer_t::iterator it = constraints_.begin(); it != constraints_.end(); ++it) {

EDIT

I've just seen from the linked code that the posted code is completely wrong. So, the remainder of this answer is unlikely to be helpful.

I will however observe that you're timing both the operations you sort-of show above, but also the formatted output. Are you sure you're timing the right thing?

now, we de-reference your iterator a lot in this loop. I don't know how easily the compiler can handle it here, but IMO this is more readable:

    auto &item = it->get();

(if you don't have C++11 auto, just put the actual type in - I don't know what it is here)

    if( (item & to_handle) == item &&
        (item & test_const2) == item &&
        (item & test_const3) == item ) {
        choosen_.push_back((*it));
        to_handle -= item;
    }
}

Now, the second two conditions in your if never vary, and they simply test that all the set bits of item are inside both masks test_const2=0x0E and test_const3=0x07. That is, none of the set bits are outside test_const2 & test_const3, so

const uint32_t fail_test = ~(test_const2 & test_const3);

//...

    if( (item & to_handle) == item &&
        (item & fail_test) == 0) {
        choosen_.push_back((*it));
        to_handle -= item;
    }

again, the optimizer might have figured that out already, but this version is anyway more expressive.


How can I make this better? Python Web scraping

Naming

Variable names should be snake_case, and should represent what they are containing. I would also use req instead of r. The extra two characters aren't going to cause a heartache.

Constants

You have the same headers dict in four different places. I would instead define it once at the top of the file in UPPER_CASE, then just use that wherever you need headers. I would do the same for site.

List Comprehension

I would go about collecting categories in this way:

categories = [link['href'] for link in soup.findAll(href=re.compile(r'/category/\w+$'))]

It's shorter and utilizes a quirk in the python language. Of course, if you want to print out each one, then add this just after:

for category in categories:
    print(category)

Also, it seems like you assign category_link to the last element in the list, so that can go just outside the list comprehension.

Save your assignments

Instead of assigning the result of soup.find to a variable, then using it in a loop, simply put that soup.find in the loop. Take a look:

for articles in soup.findAll(class_="chapter-chs"):
    for chapters in articles.findAll("a"):
        ....

As a result of the above changes, you code would look something like this:

from requests import get
from bs4 import BeautifulSoup
import re

HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"}
SITE = "https://readlightnovel.org/"

req = get(SITE, headers=HEADERS)
soup = BeautifulSoup(req.text, "lxml")
category = soup.findAll(class_="search-by-genre")

categories = [link['href'] for link in soup.findAll(href=re.compile(r'/category/\w+$'))]
category_link = categories[-1]

# Getting all Novel Headers
for category in categories:
    req = get(category_link, headers=HEADERS)
    soup = BeautifulSoup(req.text, "lxml")
    novels_header = soup.findAll(class_="top-novel-header")

    # Getting Novels' Title and Link
    for novel_names in novels_header:
        print("Novel:", novel_names.text.strip())

        novel_link = novel_names.find('a')['href']

        # Getting Novel's Info
        req = get(novel_link, headers=HEADERS)
        soup = BeautifulSoup(req.text, "lxml")

        # Novel Chapters
        for articles in soup.findAll(class_="chapter-chs"):
            for chapters in articles.findAll("a"):
                ch = chapters["href"]

                # Getting article
                req = get(ch, headers=HEADERS)
                soup = BeautifulSoup(req.content, "lxml")
                title = soup.find(class_="block-title")
                print(title.text.strip())
                full_article = soup.find("div", {"class": "desc"})

                # remove ads inside the text:
                for ads in full_article.select('center, small, a'):
                    ads.extract()

                print(full_article.get_text(strip=True, separator='\n'))


Build string by generating random characters step by step

Extract magic numbers into constants

For instance, what do 126 and 32 represent in the following line?

return String.fromCharCode(Math.floor(Math.random() * (126 - 32 + 1)) + 32)

It is much better to extract magic numbers into constants, i.e. to annotate them with a semantically meaningful name:

const HIGHEST_ASCII_PRINTABLE_CHARACTER = 126;
const LOWEST_ASCII_PRINTABLE_CHARACTER = 32;

But even when you replace the numbers by their constant's name, it isn't immediately clear what you're doing with -32, +32, Math.random() and Math.floor() there. Even if you are accustomed to random number generation, a dedicated function call is more readable with less redundancy and in fact is easier to reason about:

return String.fromCharCode(getRandomInt(LOWEST_ASCII_PRINTABLE_CHARACTER, HIGHEST_ASCII_PRINTABLE_CHARACTER));

Especially, with your old code, I had to look up Math.random() on MDN to make really sure that is produces a uniform distribution. Now you can just add a docblock comment to getRandomInt indicating that property.
await sleep(1000 / 16) also features magic numbers.

Miscellaneous remarks

Using async-await for waiting after each loop iteration is a good use case and really makes the code cleaner!
Extracting only a single property with the object destructuring syntax (const {length} = builtWord) seems a bit unidiomatic to me as opposed to const length = builtWord.length.
Apart from that, you are using length only once anyway, so I would drop that variable all together.
Try to avoid global variables and interdependencies.

For example, builtWord as well as targetWord are shared (and the former even modified!) by main and updateWord. I would suggest making updateWord accepting both as arguments and returning the possibly newly built word:

function tryUpdateWord(currentBuiltWord, targetWord) {
    // This is a good moment to introduce a sanity check as well
    if (currentBuildWord.length >= targetWord.length) {
      throw new Error('<todo>');
    }

    const nextChar = getRandomChar()
    process.stdout.write('\r')
    process.stdout.write(currentBuiltWord)
    process.stdout.write(nextChar)
    if (targetWord[currentBuildWord.length] === nextChar) {
        return currentBuiltWord + nextChar
    }
    else {
        return currentBuiltWord;
    }
}

Since the interdependencies have now been eliminiated, I would also move the part reading the process arguments into main():

async function main() {
    const targetWord = process.args[2]
    let builtWord = ''

    const SLEEP_PER_ITERATION = 1000 / 16;
    while (true) {
        builtWord = tryUpdateWord(builtWord, targetWord)
        if (builtWord === targetWord) {
            break
        }
        await sleep(SLEEP_PER_ITERATION)
    }
}


Python script to download adult comics from 8muses

There's no reason to use selenium here. Instead of reaching for selenium, first try the easier path. Load the page without javascript and see if you can find any helpful information about how the images get there. There must be something (perhaps AJAX) that gets the URLs for them. They don't just magically appear!

It turns out if you do this, you'll see there isn't any fancy JS stuff. The images are there, they just look like this:

This means, you can extract all these URLs with a single line of BeautifulSoup:

urls = [img['data-src'] for img in doc.find_all('img', class_='lazyload')]

Now some comments about your code:

PEP8 it! Your spacing is inconsistent. Make good use of vertical whitespace. Phrase things like you would paragraphs. That makes things much easier to read.
You don't need selenium, but you definitely shouldn't hard code a driver path in a project that you open source. How many people have a selenium driver exactly at C:\Users\NH\PycharmProjects\SeleniumTest\drivers\chromedriver.exe on their computer?
Nice use of functions to separate concerns
You should probably use BeautifulSoup(page, 'html5lib') instead of lxml
Your construction of image_url is a bit sloppy. Typically, we'd reach for urllib.path to build paths instead of just doing string concatenation.
Use pathlib instead of os.path
'Mozilla/5.0' isn't a User-Agent that's going to fool anybody. If you're really trying to stay under the radar, use a real UA
But none of that matters, because you appear to request pages as fast as possible. Add sleep()s in between downloading. Throttle your scraper.
threading is a bit useless in Python. This is somewhat of an I/O bound task (for which threads are well suited), but the HTML parsing and extraction could definitely be done concurrently with web requests (but threading doesn't allow this). You almost always want to reach for multiprocessing.
Use the context manager of a pool instead of manually calling close() and join():

with Pool() as pool:
    pool.imap_unorderd(fetch_image_url, pages)

Also, don't pass a parameter to Pool. It defaults to the number of CPU cores, which is almost always what you want
starmap is ordered and blocking. It only can process things in order. This is okay in this case, because you aren't actually returning anything, but if you were say doing math you probably want imap_unordered which yields results as they arrive (likely out of order).
Don't print from a separate process. You want a single process writing to stdout, otherwise you can have write contention (which you'll luck out and probably never run into because your strings probably fit inside the stdout buffer, but it's possible they may not under certain circumstances).

But this all culminates in the following advice: don't use Python to download things!

Especially since this scraping doesn't appear to be useful as a library (instead, it seems like you just are providing a CLI utility for a human to download these things). Given this, it's much smarter and safer to not reinvent the wheel. There are tools that already do jobs like this well: namely, wget (it appears that you're on windows, you can and should use the Ubuntu subsystem, which will have wget). wget is particularly suited for this job and has tons of builtin functionality which will be super useful to you. This includes:

Not redownloading things
Throttling (including random delays)
Restarting after a catastrophic (program crashing) failure
Retrying requests per HTTP spec

All of these are things that your script doesn't do currently. In particular, in python it's very easy to do something like this:

pages = download_hundreds_of_pages()  # takes hours...
for page in paages:  # oops, this NameErrors and you lose everything you've downloaded
  pass

Mistakes like this are too easy to make. You can completely avoid them with the following workflow:

Build up a list of urls you want to download (perhaps with python)
Use wget -nc -i urls.txt to download them
Repeat as necessary

For you, that would involve making a list of urls containing the images. Then do wget -nc -i pages.txt. That will download all of the pages to the current directory. Then you can make a Python script which uses beautiful soup (and the line I mentioned above) to extract the image urls: python3 extract_image_urls.py > image_urls.txt. Then to download them do wget -nc -i image_urls.txt. If your python script fails at any point, you don't lose all of the downloads you've already done. You can wrap all of this in a convenient bash script.


Run several Python programs and check for errors

allitems = open('allitems.txt').read().splitlines()

You're putting all of those lines into a list, but you don't need them as a list.  All that you do with them later is iterate, so you should just say allitems = open('allitems.txt').  That will mean that the newline characters will be at the end of each line, but you can fix that by adding item = item.strip() in your loop. You should also always use a with statement when opening files.

kind, chapter_c, number_c = itemparser.match(item).groups()

What if the item doesn't match?  You'll have a very ugly error that won't make sense to whoever uses your program.  You should have some error handling added:

item = item.strip()
match = itemparser.match(item):
if not match or len(match.groups()) != 3:
    print("Invalid item: {}".format(item), file=sys.stderr)
    continue

If you want, you could throw an error instead, but your error would hopefully be more helpful to the user.

number = int(number_c)

Again, no error handling.

status = 'Success'
...
status = 'Failed'
...
status = 'Not implemented'

Those are hard-coded values.  What would happen if you had just one slight typo?  It could throw you off with something completely unexpected and it would be very difficult to debug.  You should define constants at the beginning of the file for the different status codes:

SUCCESS = 'Success'
FAILED = 'Failed'

Well, you don't really need to define one for 'Not implemented' because NotImplemented already exists as a built-in constant.  You could even use True, False, and NotImplemented.  In that case, the variable might be success instead of status.

sys.exit(statuscounter['Failed'])

I like that.  You exit with success if nothing failed, but the error exit codes make sense.


Selecting results as a comma-separated string

Using one of the below queries removes the need to iterate over the result sets to construct the CSV strings. When a single result is expected, a ->fetch() instead of ->fetchAll() would do.

Conclusion: implode goes away, while and for loops go away the only iteration needed would be in case of multiple CSV result sets.

SELECT GROUP_CONCAT(columnName) FROM Table1; # for single column

SELECT CONCAT(columnA,",",columnB) from Table2; # for multi cols

You might have issues creating prepared statements for this; I don't know.

example for the first query:

<?php

$conn = new PDO("mysql:host=localhost;dbname=test", "root", "");

$stmt = $conn->query("SELECT GROUP_CONCAT(columnName) FROM Table1");

$result = $stmt->fetch(PDO::FETCH_ASSOC);

var_dump($result);


Codechef Deforestation problem: Finding maximum rope length between trees

There appears to be a bug in your program. In particular, I think this line is wrong:

if (h[l] > x[l])

Starting from location j, the question is not whether h[l] > x[l] but whether h[l] - h[j] > x[l] - x[j]. The 45 degree angle will be relative to the start-point of the line, not the origin, I think.

That said, your loop over l is duplicating the results of looping over k. I think you could profit by keeping a running total of lossage during your k loop, and just adding it in when appropriate.

Viz:

for (j...)
    auto hj = h[j], xj = x[j];

    for (k...)
        auto dx = x[k] - xj;
        auto dh = h[k] - hj;

        auto over_height = dh - dx;

        if (over_height > 0) deforestation += over_height;

        if (over_height == 0) {
            // this k is a candidate
            rope_len = sqrt(...) - deforestation;

        }


Spending a target sum, preferably split equally

You have still some work to do to get correct results in all cases. Consider M=3 and prizes [2,1,4,3]. Your algorithm sorts the list, splits it in two and considers pairs where one item is from the left half and the other from the right. You will not find the sum 1+2 because both numbers will be in the left half.


There is missing code so I'm assuming that ER_ID and CPS are strings. If not, you can easily sub the data type.

Since the only difference between the blocks of code is which string (or other data type) to use (ER_ID vs. CPS), you can make a member function of EMRMgr that has the same block of code but subbing the string to use with a parameter.

Unless I've overlooked something, this should work.

bool EMRMgr::DoTheThing(std::string str)
    {
        mcIOstructObj.lpszValueName = (LPWSTR)str;
        memset(szValue, 0, MAX_PATH);
        mcIOstructObj.lpData = (LPBYTE)&szValue[0];
        lRes = m_cIOManager.ReadValue(mcStorageTypeObj, mcIOstructObj);
        value.clear();
        if ((LPWSTR)mcIOstructObj.lpData == nullptr)
        {
            value.assign(L"");
        }
        else
        {
            value.assign((LPWSTR)mcIOstructObj.lpData);
        }

        m_fileParams.insert({ (std::wstring) str, value });

    }


Finding the perfect numbers between 1 - 1000

If you're trying to shorten it, there are only 3 perfect numbers up to 1000: just list 6, 28, and 496.

If you're trying to speed it up, an array of 1000 numbers is small enough to stay reasonably cache-resident: you can compute all divisor sums together faster than you can compute each of them one at a time.  This is similar to how you can sieve a long interval for primes much faster than you can test each number individually for primality.  Code fragment:

for(int i=1; i<=n/2; i++) {
  for(int x=2*i; x<=n; x+=i) {
    divisor_sum[x] += i;
  }
}

The length of the inner loop is O(n/i), which gets small very quickly, making the total cost O(n log n), whereas your double loop is O(n^2).


Reading and returning the HTML content from a specified URL

There are a couple of minor technical issues:

The content variable is unnecessary, because you can simply return html_page.read() directly. (And you could as well return urlopen(req, timeout=10).read() directly...) When the max attempts are reached, you could return "" instead of relying on that content was initialized to "". And how about returning None? Then you could simply omit the return statement to the same effect.
In the exception handling, there are multiple if statements with conditions that are mutually exclusive, only one can match at a time. In such situation you should chain them together with elif.
Instead of doing a single except statement with multiple error types and then using conditionals to identify the correct one, it would be better to use multiple except statements each with a single error type.
You could iterate using range for slightly more compact code.

Like this:

def get_html_content(url, max_attempt = 3):
    req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

    for attempt in range(max_attempt):
        try:
            return urlopen(req, timeout=10).read()
        except HTTPError as e:
            print("The server couldn\'t fulfill the request....attempt {}/{}".format(attempt + 1, max_attempt))
            print('Error code: ', e.code)
        except URLError as e:
            print("We failed to reach a server....attempt {}/{}".format(attempt + 1, max_attempt))
            print('Reason: ', e.reason)
        except timeout as e:
            print('timeout...attempt {}/{}'.format(attempt + 1, max_attempt))